Couchbase Lite C++
Couchbase Lite C++ API
Loading...
Searching...
No Matches
Collection.hh
Go to the documentation of this file.
1//
2// Collection.hh
3//
4// Copyright (c) 2022 Couchbase, Inc All rights reserved.
5//
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17//
18
19#pragma once
20#include "cbl++/Base.hh"
21#include "cbl++/Database.hh"
22#include "cbl/CBLCollection.h"
23#include "cbl/CBLScope.h"
24#include "fleece/Mutable.hh"
25#include <functional>
26#include <string>
27#include <vector>
28
29
31
32namespace cbl {
33 class Document;
34 class MutableDocument;
35 class CollectionChange;
36 class DocumentChange;
37 class QueryIndex;
39
41 using CollectionConflictHandler = std::function<bool(MutableDocument documentBeingSaved,
42 Document conflictingDocument)>;
59
64
68 std::string expressions;
69
74
86 std::string language;
87
91 std::string where;
92 };
93
99
104 std::string path;
105
111 std::string expressions;
112 };
113
131 class Collection : private RefCounted {
132 public:
133 // Accessors:
134
136 std::string name() const {return internal::asString(CBLCollection_Name(ref()));}
137
139 std::string fullName() const {return internal::asString(CBLCollection_FullName(ref()));}
140
142 std::string scopeName() const {
143 auto scope = CBLCollection_Scope(ref());
144 auto scopeName = internal::asString(CBLScope_Name(scope));
145 CBLScope_Release(scope);
146 return scopeName;
147 }
148
151
153 uint64_t count() const {return CBLCollection_Count(ref());}
154
155 // Documents:
156
163 inline Document getDocument(std::string_view docID) const;
164
171 inline MutableDocument getMutableDocument(std::string_view docID) const;
172
179 inline void saveDocument(MutableDocument &doc);
180
190 inline bool saveDocument(MutableDocument &doc, CBLConcurrencyControl concurrency);
191
198 inline bool saveDocument(MutableDocument &doc, CollectionConflictHandler handler);
199
202 inline void deleteDocument(Document &doc);
203
209 inline bool deleteDocument(Document &doc, CBLConcurrencyControl concurrency);
210
216 inline void purgeDocument(Document &doc);
217
221 bool purgeDocument(std::string_view docID) {
222 CBLError error;
223 bool purged = CBLCollection_PurgeDocumentByID(ref(), slice(docID), &error);
224 if ( !purged && !(error.domain == kCBLDomain && error.code == kCBLErrorNotFound) )
225 internal::check(false, error);
226 return purged;
227 }
228
235 time_t getDocumentExpiration(std::string_view docID) const {
236 CBLError error;
237 time_t exp = CBLCollection_GetDocumentExpiration(ref(), slice(docID), &error);
238 internal::check(exp >= 0, error);
239 return exp;
240 }
241
246 void setDocumentExpiration(std::string_view docID, time_t expiration) {
247 CBLError error;
248 internal::check(CBLCollection_SetDocumentExpiration(ref(), slice(docID), expiration, &error), error);
249 }
250
251 // Indexes:
252
259 void createValueIndex(std::string_view name, ValueIndexConfiguration config) {
260 CBLError error;
261 internal::check(CBLCollection_CreateValueIndex(ref(), slice(name), {
262 config.expressionLanguage,
263 slice(config.expressions),
264 slice(config.where)
265 }, &error), error);
266 }
267
274 void createFullTextIndex(std::string_view name, FullTextIndexConfiguration config) {
275 CBLError error;
276 internal::check(CBLCollection_CreateFullTextIndex(ref(), slice(name), {
277 config.expressionLanguage,
278 slice(config.expressions),
279 config.ignoreAccents,
280 slice(config.language),
281 slice(config.where)
282 }, &error), error);
283 }
284
291 void createArrayIndex(std::string_view name, ArrayIndexConfiguration config) {
292 CBLError error;
293 internal::check(CBLCollection_CreateArrayIndex(ref(), slice(name), {
294 config.expressionLanguage,
295 slice(config.path),
296 slice(config.expressions)
297 }, &error), error);
298 }
299
300#ifdef COUCHBASE_ENTERPRISE
307 inline void createVectorIndex(std::string_view name, VectorIndexConfiguration config);
308#endif
309
311 void deleteIndex(std::string_view name) {
312 CBLError error;
313 internal::check(CBLCollection_DeleteIndex(ref(), slice(name), &error), error);
314 }
315
317 fleece::RetainedArray getIndexNames() {
318 CBLError error{};
320 internal::check(error.code == 0, error);
321 fleece::RetainedArray names(flNames);
322 FLArray_Release(flNames);
323 return names;
324 }
325
327 inline QueryIndex getIndex(std::string_view name);
328
329 // Listeners:
330
333
339 auto l = CollectionChangeListener(callback);
340 l.setToken( CBLCollection_AddChangeListener(ref(), &_callListener, l.context()) );
341 return l;
342 }
343
346
354 {
355 auto l = CollectionDocumentChangeListener(callback);
356 l.setToken( CBLCollection_AddDocumentChangeListener(ref(), slice(docID), &_callDocListener, l.context()) );
357 return l;
358 }
359
360 protected:
361
363 internal::check(d != nullptr || error->code == 0, *error);
364 Collection col;
365 col._ref = (CBLRefCounted*)d;
366 return col;
367 }
368
369 friend class Database;
370 friend class Document;
371 friend class QueryIndex;
372
374
375 private:
376
377 static void _callListener(void* _cbl_nullable context, const CBLCollectionChange* change);
378
379 static void _callDocListener(void* _cbl_nullable context, const CBLDocumentChange* change);
380 };
381
384 public:
386 Collection& collection() {return _collection;}
387
389 std::vector<slice>& docIDs() {return _docIDs;}
390
393 :_collection(std::move(collection))
394 ,_docIDs(std::move(docIDs))
395 { }
396
397 private:
398
399 Collection _collection;
400 std::vector<slice> _docIDs;
401 };
402
405 public:
407 Collection& collection() {return _collection;}
408
410 slice& docID() {return _docID;}
411
414 :_collection(std::move(collection))
415 ,_docID(slice(docID))
416 { }
417
418 private:
419
420 Collection _collection;
421 slice _docID;
422 };
423
424 // Database method bodies:
425
426 inline Collection Database::getCollection(std::string_view collectionName, std::optional<std::string_view> optScopeName) const {
427 CBLError error {};
428 slice scopeName = optScopeName.value_or(slice(kCBLDefaultScopeName));
429 return Collection::adopt(CBLDatabase_Collection(ref(), slice(collectionName), slice(scopeName), &error), &error) ;
430 }
431
432 inline Collection Database::createCollection(std::string_view collectionName, std::optional<std::string_view> optScopeName) {
433 CBLError error {};
434 slice scopeName = optScopeName.value_or(slice(kCBLDefaultScopeName));
435 return Collection::adopt(CBLDatabase_CreateCollection(ref(), slice(collectionName), scopeName, &error), &error) ;
436 }
437
439 CBLError error {};
440 return Collection::adopt(CBLDatabase_DefaultCollection(ref(), &error), &error) ;
441 }
442
443 // Collection method bodies:
444
445 inline void Collection::_callListener(void* _cbl_nullable context, const CBLCollectionChange* change) {
447 std::vector<slice> docIDs((slice*)&change->docIDs[0], (slice*)&change->docIDs[change->numDocs]);
448 auto ch = std::make_unique<CollectionChange>(col, docIDs);
449 CollectionChangeListener::call(context, ch.get());
450 }
451
452 inline void Collection::_callDocListener(void* _cbl_nullable context, const CBLDocumentChange* change) {
454 slice docID = change->docID;
455 auto ch = std::make_unique<DocumentChange>(col, docID);
457 }
458}
459
461template<> struct std::hash<cbl::Collection> {
462 std::size_t operator() (cbl::Collection const& col) const {
463 auto name = CBLCollection_Name(col.ref());
464 auto scope = CBLCollection_Scope(col.ref());
465 std::size_t hash = fleece::slice(name).hash() ^ fleece::slice(CBLScope_Name(scope)).hash();
466 CBLScope_Release(scope);
467 return hash;
468 }
469};
470
#define CBL_REFCOUNTED_BOILERPLATE(CLASS, SUPER, C_TYPE)
Definition Base.hh:160
#define _cbl_nullable
#define CBL_ASSUME_NONNULL_END
#define CBL_ASSUME_NONNULL_BEGIN
#define _cbl_warn_unused
Collection change info notified to the collection change listener's callback.
Definition Collection.hh:383
Collection & collection()
The collection.
Definition Collection.hh:386
CollectionChange(Collection collection, std::vector< slice > docIDs)
Internal API.
Definition Collection.hh:392
std::vector< slice > & docIDs()
The IDs of the changed documents.
Definition Collection.hh:389
A Collection is a container for documents within a database.
Definition Collection.hh:131
MutableDocument getMutableDocument(std::string_view docID) const
Reads a document from the collection in mutable form that can be updated and saved.
Definition Document.hh:192
CBLCollection *_Nullable ref() const
Returns a pointer to the underlying C object (CBLCollection), or NULL if this is a null reference.
Definition Collection.hh:373
CollectionChangeListener addChangeListener(CollectionChangeListener::Callback callback)
Registers a collection change listener callback.
Definition Collection.hh:338
Collection() noexcept
Constructs a null reference (one that points to no object).
Definition Collection.hh:373
std::string name() const
The collection's name.
Definition Collection.hh:136
CollectionDocumentChangeListener addDocumentChangeListener(std::string_view docID, CollectionDocumentChangeListener::Callback callback)
Registers a document change listener callback.
Definition Collection.hh:352
void setDocumentExpiration(std::string_view docID, time_t expiration)
Sets or clears the expiration time of a document in the collection.
Definition Collection.hh:246
fleece::RetainedArray getIndexNames()
Returns the names of the indexes in the collection, as a Fleece array of strings.
Definition Collection.hh:317
void saveDocument(MutableDocument &doc)
Saves a (mutable) document to the collection.
Definition Document.hh:197
void deleteIndex(std::string_view name)
Deletes an index given its name from the collection.
Definition Collection.hh:311
void purgeDocument(Document &doc)
Purges a document from the collection.
Definition Document.hh:229
static Collection adopt(const CBLCollection *_Nullable d, CBLError *error)
Definition Collection.hh:362
QueryIndex getIndex(std::string_view name)
Get an index by name.
Definition QueryIndex.hh:134
void createArrayIndex(std::string_view name, ArrayIndexConfiguration config)
Creates an array index for use with UNNEST queries in the collection.
Definition Collection.hh:291
cbl::ListenerToken< CollectionChange * > CollectionChangeListener
Collection Change Listener Token.
Definition Collection.hh:332
bool purgeDocument(std::string_view docID)
Purges a document by its ID from the collection.
Definition Collection.hh:221
std::string fullName() const
The collection's fully qualified name in the '<scope-name>.
Definition Collection.hh:139
Document getDocument(std::string_view docID) const
Reads a document from the collection in an immutable form.
Definition Document.hh:187
Database database() const
The collection's database.
Definition Collection.hh:150
friend class Database
Definition Collection.hh:369
friend class QueryIndex
Definition Collection.hh:371
time_t getDocumentExpiration(std::string_view docID) const
Returns the time, if any, at which a given document in the collection will expire and be purged.
Definition Collection.hh:235
void deleteDocument(Document &doc)
Deletes a document from the collection.
Definition Document.hh:219
friend class Document
Definition Collection.hh:370
void createVectorIndex(std::string_view name, VectorIndexConfiguration config)
Creates a vector index in the collection.
Definition VectorIndex.hh:189
cbl::ListenerToken< DocumentChange * > CollectionDocumentChangeListener
Document Change Listener Token.
Definition Collection.hh:345
uint64_t count() const
The number of documents in the collection.
Definition Collection.hh:153
void createFullTextIndex(std::string_view name, FullTextIndexConfiguration config)
Creates a full-text index in the collection.
Definition Collection.hh:274
void createValueIndex(std::string_view name, ValueIndexConfiguration config)
Creates a value index in the collection.
Definition Collection.hh:259
std::string scopeName() const
The scope's name.
Definition Collection.hh:142
CBLDatabase *_Nullable ref() const
Returns a pointer to the underlying C object (CBLDatabase), or NULL if this is a null reference.
Definition Database.hh:411
Collection getDefaultCollection() const
Returns the default collection.
Definition Collection.hh:438
Collection getCollection(std::string_view collectionName, std::optional< std::string_view > scopeName=std::nullopt) const
Returns the existing collection with the given name and scope.
Definition Collection.hh:426
Collection createCollection(std::string_view collectionName, std::optional< std::string_view > scopeName=std::nullopt)
Create a new collection.
Definition Collection.hh:432
friend class Collection
Definition Database.hh:408
Document change info notified to the document change listener's callback.
Definition Collection.hh:404
slice & docID()
The ID of the changed document.
Definition Collection.hh:410
DocumentChange(Collection collection, std::string_view docID)
Internal API.
Definition Collection.hh:413
Collection & collection()
The collection.
Definition Collection.hh:407
An immutable, in-memory copy of a document read from a collection.
Definition Document.hh:33
A token representing a registered listener; instances are returned from the various methods that regi...
Definition Base.hh:177
static void call(void *_Nullable context, Args... args)
Definition Base.hh:228
std::function< void(Args...)> Callback
Definition Base.hh:180
A mutable document, whose properties can be modified and saved to a collection.
Definition Document.hh:104
Represents an existing index in a collection.
Definition QueryIndex.hh:33
Configuration for creating a vector index, which enables searching documents by vector similarity.
Definition VectorIndex.hh:82
void FLArray_Release(FLArray FL_NULLABLE v)
CBLCollection *_cbl_nullable CBLDatabase_DefaultCollection(const CBLDatabase *db, CBLError *_cbl_nullable outError)
_cbl_warn_unused FLMutableArray _cbl_nullable CBLCollection_GetIndexNames(CBLCollection *collection, CBLError *_cbl_nullable outError)
bool CBLCollection_SetDocumentExpiration(CBLCollection *collection, FLSlice docID, CBLTimestamp expiration, CBLError *_cbl_nullable outError)
uint64_t CBLCollection_Count(const CBLCollection *collection)
bool CBLCollection_DeleteIndex(CBLCollection *collection, FLString name, CBLError *_cbl_nullable outError)
bool CBLCollection_CreateValueIndex(CBLCollection *collection, FLString name, CBLValueIndexConfiguration config, CBLError *_cbl_nullable outError)
CBLDatabase * CBLCollection_Database(const CBLCollection *collection)
CBLCollection *_cbl_nullable CBLDatabase_Collection(const CBLDatabase *db, FLString collectionName, FLString scopeName, CBLError *_cbl_nullable outError)
bool CBLCollection_CreateFullTextIndex(CBLCollection *collection, FLString name, CBLFullTextIndexConfiguration config, CBLError *_cbl_nullable outError)
bool CBLCollection_PurgeDocumentByID(CBLCollection *collection, FLString docID, CBLError *_cbl_nullable outError)
_cbl_warn_unused CBLListenerToken * CBLCollection_AddChangeListener(const CBLCollection *collection, CBLCollectionChangeListener listener, void *_cbl_nullable context)
CBLCollection *_cbl_nullable CBLDatabase_CreateCollection(CBLDatabase *db, FLString collectionName, FLString scopeName, CBLError *_cbl_nullable outError)
_cbl_warn_unused CBLListenerToken * CBLCollection_AddDocumentChangeListener(const CBLCollection *collection, FLString docID, CBLCollectionDocumentChangeListener listener, void *_cbl_nullable context)
bool CBLCollection_CreateArrayIndex(CBLCollection *collection, FLString name, CBLArrayIndexConfiguration config, CBLError *_cbl_nullable outError)
FLString CBLCollection_Name(const CBLCollection *collection)
CBLScope * CBLCollection_Scope(const CBLCollection *collection)
struct CBLCollection CBLCollection
CBLTimestamp CBLCollection_GetDocumentExpiration(CBLCollection *collection, FLSlice docID, CBLError *_cbl_nullable outError)
FLString CBLCollection_FullName(const CBLCollection *collection)
CBLConcurrencyControl
kCBLDomain
kCBLErrorNotFound
struct CBLRefCounted CBLRefCounted
FLString CBLScope_Name(const CBLScope *scope)
CBLINLINE void CBLScope_Release(const CBLScope *_cbl_nullable t)
CBL_PUBLIC const FLString kCBLDefaultScopeName
struct _FLArray * FLMutableArray
Definition Base.hh:46
fleece::slice slice
Convenience alias for fleece::slice, a non-owning view of a byte range.
Definition Base.hh:49
std::function< bool(MutableDocument documentBeingSaved, Document conflictingDocument)> CollectionConflictHandler
Conflict handler used when saving a document.
Definition Collection.hh:41
CBLQueryLanguage QueryLanguage
Definition Base.hh:53
const CBLCollection * collection
const CBLCollection * collection
CBLErrorDomain domain
Array Index Configuration for indexing property values within arrays in documents,...
Definition Collection.hh:96
std::string path
Path to the array, which can be nested to be indexed (Required).
Definition Collection.hh:104
QueryLanguage expressionLanguage
The language used in the expressions (Required).
Definition Collection.hh:98
std::string expressions
Optional expressions representing the values within the array to be indexed.
Definition Collection.hh:111
Configuration for creating a full-text index, which enables full-text search in queries.
Definition Collection.hh:61
std::string where
A predicate expression defining conditions for indexing documents.
Definition Collection.hh:91
std::string expressions
The expressions describing each coloumn of the index (Required).
Definition Collection.hh:68
QueryLanguage expressionLanguage
The language used in the expressions (Required).
Definition Collection.hh:63
bool ignoreAccents
Should diacritical marks (accents) be ignored?
Definition Collection.hh:73
std::string language
The dominant language.
Definition Collection.hh:86
Configuration for creating a value index, which indexes the values of one or more document properties...
Definition Collection.hh:45
std::string where
A predicate expression defining conditions for indexing documents.
Definition Collection.hh:57
QueryLanguage expressionLanguage
The language used in the expressions (Required).
Definition Collection.hh:47
std::string expressions
The expressions describing each column of the index (Required).
Definition Collection.hh:52