diff --git a/.gitignore b/.gitignore index ca98cd9..64284a2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ /target/ Cargo.lock + +.vscode diff --git a/Cargo.toml b/Cargo.toml index 7dd9a5a..4652557 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,8 @@ [package] name = "couchbase_lite" -version = "3.1.10-0" +version = "3.2.1-0" # The first three numbers correspond to the Couchbase Lite C release, the fourth number corresponds to the Doctolib release +edition = "2021" [dependencies] enum_primitive = "*" diff --git a/c_playground/.gitignore b/c_playground/.gitignore new file mode 100644 index 0000000..04c1afc --- /dev/null +++ b/c_playground/.gitignore @@ -0,0 +1,6 @@ +CMakeCache.txt +CMakeFiles +Makefile +cmake_install.cmake + +Main diff --git a/c_playground/CMakeLists.txt b/c_playground/CMakeLists.txt new file mode 100644 index 0000000..1c6f9b9 --- /dev/null +++ b/c_playground/CMakeLists.txt @@ -0,0 +1,9 @@ +cmake_minimum_required(VERSION 3.15) + +project(c_playground) + +include_directories(${CMAKE_SOURCE_DIR}/../libcblite/include) + +add_executable(Main main.c) + +target_link_libraries(Main PUBLIC ${CMAKE_SOURCE_DIR}/../libcblite/lib/macos/libcblite.3.dylib) diff --git a/c_playground/README.md b/c_playground/README.md new file mode 100644 index 0000000..0161268 --- /dev/null +++ b/c_playground/README.md @@ -0,0 +1,33 @@ +## Purpose of the c_playground + +Couchbase does not provide support for Rust bindings, so we cannot communicate code from this repo in support tickets. + +With the c_playground, you can code whatever you want in C with full access to the couchbase-lite-C API. + +## How to use it + +The code in main.c will be compiled. + +In the c_payground repository, you need to run the command once: + +``` +cmake CMakeLists.txt +``` + +You will then be able to compile the code anytime you want with the command: + +``` +make +``` + +The file Main is the executable, do not forget to set the execution right for yourself: + +``` +chmod u+x ./Main +``` + +Execute your code: + +``` +./Main +``` diff --git a/c_playground/doc.json b/c_playground/doc.json new file mode 100644 index 0000000..9513470 --- /dev/null +++ b/c_playground/doc.json @@ -0,0 +1,22 @@ +{ + "name":"Sam", + "contacts":[ + { + "type":"primary", + "address":{"street":"1 St","city":"San Pedro","state":"CA"}, + "phones":[ + {"type":"home","number":"310-123-4567"}, + {"type":"mobile","number":"310-123-6789"} + ] + }, + { + "type":"secondary", + "address":{"street":"5 St","city":"Seattle","state":"WA"}, + "phones":[ + {"type":"home","number":"206-123-4567"}, + {"type":"mobile","number":"206-123-6789"} + ] + } + ], + "likes":["soccer","travel"] +} \ No newline at end of file diff --git a/c_playground/main.c b/c_playground/main.c new file mode 100644 index 0000000..21bc5f2 --- /dev/null +++ b/c_playground/main.c @@ -0,0 +1,144 @@ +#include +#include +#include + +#include +#include +#include +#include +#include + +const char* DOMAINS[] = { "Database", "Query", "Replicator", "Network" }; +const char* LEVEL_PREFIX[] = { "((", "_", "", "WARNING: ", "***ERROR: " }; +const char* LEVEL_SUFFIX[] = { "))", "_", "", "", " ***" }; + +void log_callback(CBLLogDomain domain, CBLLogLevel level, FLString message) { + printf( + "CBL %s: %s%s%s\n", + DOMAINS[domain], + LEVEL_PREFIX[level], + (char*) message.buf, + LEVEL_SUFFIX[level] + ); +} + +int main(void) { + CBLLog_SetCallbackLevel(kCBLLogVerbose); + CBLLog_SetConsoleLevel(kCBLLogVerbose); + CBLLog_SetCallback(log_callback); + + // Open database + CBLError error; + CBLDatabaseConfiguration config = {FLSTR("/tmp")}; + CBLDatabase* db = CBLDatabase_Open(FLSTR("my_db"), &config, &error); + assert(db); + + CBLCollection* default_collection = CBLDatabase_DefaultCollection(db, &error); + assert(default_collection); + + // Create a document + CBLDocument* doc = CBLDocument_Create(); + + FILE* fp = fopen("doc.json", "r"); + + char json_format[4096]; + int len = fread(json_format, 1, 4096, fp); + + fclose(fp); + + FLString json = {}; + json.buf = &json_format; + json.size = len; + bool set_doc_content = CBLDocument_SetJSON(doc, json, &error); + + // Save the document + bool saved = CBLDatabase_SaveDocument(db, doc, &error); + assert(saved); + + CBLDocument_Release(doc); + + // Simple array index + CBLArrayIndexConfiguration array_index_config = {}; + array_index_config.expressionLanguage = kCBLN1QLLanguage; + array_index_config.path = FLSTR("likes"); + array_index_config.expressions = FLSTR(""); + + bool array_index_created = CBLCollection_CreateArrayIndex( + default_collection, + FLSTR("one_level"), + array_index_config, + &error + ); + assert(array_index_created); + + int error_pos = 0; + CBLQuery* query = CBLDatabase_CreateQuery( + db, + kCBLN1QLLanguage, + FLSTR("SELECT _.name, _like FROM _ UNNEST _.likes as _like WHERE _like = 'travel'"), + &error_pos, + &error + ); + assert(query); + + FLSliceResult explain_result = CBLQuery_Explain(query); + assert(strstr(explain_result.buf, "USING INDEX one_level")); + + CBLResultSet* query_result = CBLQuery_Execute(query, &error); + assert(query_result); + + assert(CBLResultSet_Next(query_result)); + + FLArray row = CBLResultSet_ResultArray(query_result); + FLValue name = FLArray_Get(row, 0); + assert(strcmp(FLValue_AsString(name).buf, "Sam") == 0); + + assert(!CBLResultSet_Next(query_result)); + + CBLResultSet_Release(query_result); + CBLQuery_Release(query); + + // Complex array index + array_index_config.expressionLanguage = kCBLN1QLLanguage; + array_index_config.path = FLSTR("contacts[].phones"); + array_index_config.expressions = FLSTR("type"); + + array_index_created = CBLCollection_CreateArrayIndex( + default_collection, + FLSTR("two_level"), + array_index_config, + &error + ); + assert(array_index_created); + + query = CBLDatabase_CreateQuery( + db, + kCBLN1QLLanguage, + FLSTR("SELECT _.name, contact.type, phone.number FROM _ UNNEST _.contacts as contact UNNEST contact.phones as phone WHERE phone.type = 'mobile'"), + &error_pos, + &error + ); + assert(query); + + explain_result = CBLQuery_Explain(query); + assert(strstr(explain_result.buf, "USING INDEX two_level")); + + query_result = CBLQuery_Execute(query, &error); + assert(query_result); + + assert(CBLResultSet_Next(query_result)); + + row = CBLResultSet_ResultArray(query_result); + name = FLArray_Get(row, 0); + assert(strcmp(FLValue_AsString(name).buf, "Sam") == 0); + + assert(CBLResultSet_Next(query_result)); + assert(!CBLResultSet_Next(query_result)); + + CBLResultSet_Release(query_result); + CBLQuery_Release(query); + + // Cleanup + bool closed = CBLDatabase_Delete(db, &error); + assert(closed); +} diff --git a/libcblite-3.0.3/.DS_Store b/libcblite-3.0.3/.DS_Store index 0a84613..cef7795 100644 Binary files a/libcblite-3.0.3/.DS_Store and b/libcblite-3.0.3/.DS_Store differ diff --git a/libcblite-3.0.3/include/.DS_Store b/libcblite-3.0.3/include/.DS_Store index 63198da..9f73b72 100644 Binary files a/libcblite-3.0.3/include/.DS_Store and b/libcblite-3.0.3/include/.DS_Store differ diff --git a/libcblite-3.0.3/include/cbl++/Base.hh b/libcblite-3.0.3/include/cbl++/Base.hh index b876102..d425f5d 100644 --- a/libcblite-3.0.3/include/cbl++/Base.hh +++ b/libcblite-3.0.3/include/cbl++/Base.hh @@ -91,6 +91,7 @@ namespace cbl { CBLRefCounted* _cbl_nullable _ref; + friend class Extension; friend class Transaction; }; diff --git a/libcblite-3.0.3/include/cbl++/Collection.hh b/libcblite-3.0.3/include/cbl++/Collection.hh index 65de32a..b199bbb 100644 --- a/libcblite-3.0.3/include/cbl++/Collection.hh +++ b/libcblite-3.0.3/include/cbl++/Collection.hh @@ -18,6 +18,7 @@ #pragma once #include "cbl++/Base.hh" +#include "cbl++/Database.hh" #include "cbl/CBLCollection.h" #include "cbl/CBLScope.h" #include "fleece/Mutable.hh" @@ -35,6 +36,8 @@ namespace cbl { class MutableDocument; class CollectionChange; class DocumentChange; + class QueryIndex; + class VectorIndexConfiguration; /** Conflict handler used when saving a document. */ using CollectionConflictHandler = std::function.' format. */ + std::string fullName() const {return asString(CBLCollection_FullName(ref()));} + + /** The scope's name. */ std::string scopeName() const { auto scope = CBLCollection_Scope(ref()); auto scopeName = asString(CBLScope_Name(scope)); @@ -72,8 +78,11 @@ namespace cbl { return scopeName; } + /** The collection's database. */ + Database database() const {return Database(CBLCollection_Database(ref()));} + /** The number of documents in the collection. */ - uint64_t count() const {return CBLCollection_Count(ref());} + uint64_t count() const {return CBLCollection_Count(ref());} // Documents: @@ -190,6 +199,28 @@ namespace cbl { CBLError error; check(CBLCollection_CreateFullTextIndex(ref(), name, config, &error), error); } + + /** Creates an array index for use with UNNEST queries in the collection. + Indexes are persistent. + If an identical index with that name already exists, nothing happens (and no error is returned.) + If a non-identical index with that name already exists, it is deleted and re-created. + @param name The index name. + @param config The array index config. */ + void createArrayIndex(slice name, CBLArrayIndexConfiguration config) { + CBLError error; + check(CBLCollection_CreateArrayIndex(ref(), name, config, &error), error); + } + +#ifdef COUCHBASE_ENTERPRISE + /** ENTERPRISE EDITION ONLY + + Creatres a vector index in the collection. + If an identical index with that name already exists, nothing happens (and no error is returned.) + If a non-identical index with that name already exists, it is deleted and re-created. + @param name The index name. + @param config The vector index config. */ + inline void createVectorIndex(slice name, const VectorIndexConfiguration &config); +#endif /** Deletes an index given its name from the collection. */ void deleteIndex(slice name) { @@ -207,6 +238,9 @@ namespace cbl { return names; } + /** Get an index by name. If the index doesn't exist, the NULL QueryIndex object will be returned. */ + inline QueryIndex getIndex(slice name); + // Listeners: /** Collection Change Listener Token */ @@ -250,6 +284,7 @@ namespace cbl { friend class Database; friend class Document; + friend class QueryIndex; CBL_REFCOUNTED_BOILERPLATE(Collection, RefCounted, CBLCollection); @@ -311,6 +346,23 @@ namespace cbl { Collection _collection; slice _docID; }; + + // Database method bodies: + + inline Collection Database::getCollection(slice collectionName, slice scopeName) const { + CBLError error {}; + return Collection::adopt(CBLDatabase_Collection(ref(), collectionName, scopeName, &error), &error) ; + } + + inline Collection Database::createCollection(slice collectionName, slice scopeName) { + CBLError error {}; + return Collection::adopt(CBLDatabase_CreateCollection(ref(), collectionName, scopeName, &error), &error) ; + } + + inline Collection Database::getDefaultCollection() const { + CBLError error {}; + return Collection::adopt(CBLDatabase_DefaultCollection(ref(), &error), &error) ; + } } /** Hash function for Collection. */ diff --git a/libcblite-3.0.3/include/cbl++/CouchbaseLite.hh b/libcblite-3.0.3/include/cbl++/CouchbaseLite.hh index 9b4981f..cd1f635 100644 --- a/libcblite-3.0.3/include/cbl++/CouchbaseLite.hh +++ b/libcblite-3.0.3/include/cbl++/CouchbaseLite.hh @@ -24,5 +24,8 @@ #include "Collection.hh" #include "Database.hh" #include "Document.hh" +#include "Prediction.hh" #include "Query.hh" +#include "QueryIndex.hh" #include "Replicator.hh" +#include "VectorIndex.hh" diff --git a/libcblite-3.0.3/include/cbl++/Database.hh b/libcblite-3.0.3/include/cbl++/Database.hh index 6d09638..ab0b9f2 100644 --- a/libcblite-3.0.3/include/cbl++/Database.hh +++ b/libcblite-3.0.3/include/cbl++/Database.hh @@ -45,6 +45,24 @@ namespace cbl { using ConflictHandler = std::function; + +#ifdef COUCHBASE_ENTERPRISE + /** ENTERPRISE EDITION ONLY + + Couchbase Lite Extension. */ + class Extension { + public: + /** Enables Vector Search extension by specifying the extension path to search for the Vector Search extension library. + This function must be called before opening a database that intends to use the vector search extension. + @param path The file system path of the directory that contains the Vector Search extension library. + @note Must be called before opening a database that intends to use the vector search extension. */ + static void enableVectorSearch(slice path) { + CBLError error {}; + RefCounted::check(CBL_EnableVectorSearch(path, &error), error); + } + }; +#endif + /** Couchbase Lite Database. */ class Database : private RefCounted { public: @@ -186,10 +204,7 @@ namespace cbl { @param collectionName The name of the collection. @param scopeName The name of the scope. @return A \ref Collection instance, or NULL if the collection doesn't exist, or throws if an error occurred. */ - inline Collection getCollection(slice collectionName, slice scopeName =kCBLDefaultScopeName) const { - CBLError error {}; - return Collection::adopt(CBLDatabase_Collection(ref(), collectionName, scopeName, &error), &error) ; - } + inline Collection getCollection(slice collectionName, slice scopeName =kCBLDefaultScopeName) const; /** Create a new collection. The naming rules of the collections and scopes are as follows: @@ -201,10 +216,7 @@ namespace cbl { @param collectionName The name of the collection. @param scopeName The name of the scope. @return A \ref Collection instance, or throws if an error occurred. */ - inline Collection createCollection(slice collectionName, slice scopeName =kCBLDefaultScopeName) { - CBLError error {}; - return Collection::adopt(CBLDatabase_CreateCollection(ref(), collectionName, scopeName, &error), &error) ; - } + inline Collection createCollection(slice collectionName, slice scopeName =kCBLDefaultScopeName); /** Delete an existing collection. @note The default collection cannot be deleted. @@ -216,10 +228,7 @@ namespace cbl { } /** Returns the default collection. */ - inline Collection getDefaultCollection() const { - CBLError error {}; - return Collection::adopt(CBLDatabase_DefaultCollection(ref(), &error), &error) ; - } + inline Collection getDefaultCollection() const; // Documents: @@ -446,6 +455,12 @@ namespace cbl { ~Database() { clear(); } + + protected: + friend class Collection; + friend class Scope; + + CBL_REFCOUNTED_WITHOUT_COPY_MOVE_BOILERPLATE(Database, RefCounted, CBLDatabase) private: void open(slice& name, const CBLDatabaseConfiguration* _cbl_nullable config) { @@ -492,8 +507,6 @@ namespace cbl { std::shared_ptr _notificationReadyCallbackAccess; - CBL_REFCOUNTED_WITHOUT_COPY_MOVE_BOILERPLATE(Database, RefCounted, CBLDatabase) - public: Database(const Database &other) noexcept :RefCounted(other) @@ -573,7 +586,6 @@ namespace cbl { CBLDatabase* _cbl_nullable _db = nullptr; }; - } CBL_ASSUME_NONNULL_END diff --git a/libcblite-3.0.3/include/cbl++/Document.hh b/libcblite-3.0.3/include/cbl++/Document.hh index d28e37e..365c7b6 100644 --- a/libcblite-3.0.3/include/cbl++/Document.hh +++ b/libcblite-3.0.3/include/cbl++/Document.hh @@ -71,6 +71,10 @@ namespace cbl { inline MutableDocument mutableCopy() const; protected: + friend class Collection; + friend class Database; + friend class Replicator; + Document(CBLRefCounted* r) :RefCounted(r) { } static Document adopt(const CBLDocument* _cbl_nullable d, CBLError *error) { @@ -89,11 +93,7 @@ namespace cbl { else throw error; } - - friend class Collection; - friend class Database; - friend class Replicator; - + CBL_REFCOUNTED_BOILERPLATE(Document, RefCounted, const CBLDocument) }; diff --git a/libcblite-3.0.3/include/cbl++/Prediction.hh b/libcblite-3.0.3/include/cbl++/Prediction.hh new file mode 100644 index 0000000..f8d0302 --- /dev/null +++ b/libcblite-3.0.3/include/cbl++/Prediction.hh @@ -0,0 +1,88 @@ +// +// Prediction.hh +// +// Copyright (c) 2024 Couchbase, Inc All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +// VOLATILE API: Couchbase Lite C++ API is not finalized, and may change in +// future releases. + +#ifdef COUCHBASE_ENTERPRISE + +#pragma once +#include "cbl++/Base.hh" +#include "cbl/CBLPrediction.h" +#include +#include + +// VOLATILE API: Couchbase Lite C++ API is not finalized, and may change in +// future releases. + +CBL_ASSUME_NONNULL_BEGIN + +namespace cbl { + /** ENTERPRISE EDITION ONLY + + The PredictiveModel that allows to integrate machine learning model + into queries via invoking query's PREDICTION() function. + + @note The predictive index feature is not supported by Couchbase Lite for C. + The Predictive Model is currently for creating vector indexes using the PREDICTION() function, + which will call the specified predictive model for computing the vectors. */ + class PredictiveModel { + public: + /** Predicts and returns a mutable dictionary based on the input dictionary. + Override this function for the implementation. + @param input The input dictionary corresponding to the input dictionary expression given in the query's PREDICTION() function + @return The output dictionary. + - To create a new dictionary for returning, use fleece::MutableDict::newDict(). + - To create a null result to evaluate as MISSING, use fleece::MutableDict(). */ + virtual fleece::MutableDict prediction(fleece::Dict input) noexcept = 0; + + virtual ~PredictiveModel() = default; + }; + + static std::unordered_map> _sPredictiveModels; + + /** Predictive Model Registation + This class provides static methods to register and unregister predictive models. */ + class Prediction { + public: + /** Registers a predictive model with the given name. */ + static void registerModel(slice name, std::unique_ptr model) { + auto prediction = [](void* context, FLDict input) { + auto m = (PredictiveModel*)context; + return FLMutableDict_Retain((FLMutableDict) m->prediction(input)); + }; + + CBLPredictiveModel config { }; + config.context = model.get(); + config.prediction = prediction; + CBL_RegisterPredictiveModel(name, config); + + _sPredictiveModels[name] = std::move(model); + } + + /** Unregisters the predictive model with the given name. */ + static void unregisterModel(slice name) { + CBL_UnregisterPredictiveModel(name); + _sPredictiveModels.erase(name); + } + }; +} + +CBL_ASSUME_NONNULL_END + +#endif diff --git a/libcblite-3.0.3/include/cbl++/QueryIndex.hh b/libcblite-3.0.3/include/cbl++/QueryIndex.hh new file mode 100644 index 0000000..e2dc2d9 --- /dev/null +++ b/libcblite-3.0.3/include/cbl++/QueryIndex.hh @@ -0,0 +1,144 @@ +// +// QueryIndex.hh +// +// Copyright (c) 2024 Couchbase, Inc All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +// VOLATILE API: Couchbase Lite C++ API is not finalized, and may change in +// future releases. + +#pragma once +#include "cbl++/Base.hh" +#include "cbl++/Collection.hh" +#include "cbl/CBLQueryIndex.h" + +CBL_ASSUME_NONNULL_BEGIN + +namespace cbl { +#ifdef COUCHBASE_ENTERPRISE + class IndexUpdater; +#endif + + /** QueryIndex object representing an existing index in the collection. */ + class QueryIndex : private RefCounted { + public: + // Accessors: + + /** The index's name. */ + std::string name() const {return asString(CBLQueryIndex_Name(ref()));} + + /** A index's collection. */ + Collection collection() const {return Collection(CBLQueryIndex_Collection(ref()));} + +#ifdef COUCHBASE_ENTERPRISE + // Index Updater: + + /** ENTERPRISE EDITION ONLY + + Finds new or updated documents for which vectors need to be (re)computed and returns an \ref IndexUpdater object + for setting the computed vectors to update the index. If the index is not lazy, an error will be returned. + @note For updating lazy vector indexes only. + @param limit The maximum number of vectors to be computed. + @return An \ref IndexUpdater object for setting the computed vectors to update the index, + or NULL if the index is up-to-date. */ + inline IndexUpdater beginUpdate(size_t limit); +#endif + + protected: + friend class Collection; + + static QueryIndex adopt(const CBLQueryIndex* _cbl_nullable i, CBLError *error) { + if (!i && error->code != 0) + throw *error; + QueryIndex index; + index._ref = (CBLRefCounted*)i; + return index; + } + + CBL_REFCOUNTED_BOILERPLATE(QueryIndex, RefCounted, CBLQueryIndex) + }; + +#ifdef COUCHBASE_ENTERPRISE + + /** ENTERPRISE EDITION ONLY + + IndexUpdater is used for updating the index in lazy mode. Currently, the vector index is the only index type + that can be updated lazily. */ + class IndexUpdater : private RefCounted { + public: + /** The total number of vectors to compute and set for updating the index. */ + size_t count() const {return CBLIndexUpdater_Count(ref());} + + /** Get the value at the given index for computing the vector. + @param index The zero-based index. + @return The value. */ + fleece::Value value(size_t index) const { + return CBLIndexUpdater_Value(ref(), index); + } + + /** Sets the vector for the value corresponding to the given index. + Setting NULL vector means that there is no vector for the value, and any existing vector + will be removed when the \ref IndexUpdater::finish is called. + @param index The zero-based index. + @param vector A pointer to the vector which is an array of floats, or NULL if there is no vector. + @param dimension The dimension of `vector`. Must be equal to the dimension value set in the vector index config. */ + void setVector(unsigned index, const float* _cbl_nullable vector, size_t dimension) { + CBLError error; + check(CBLIndexUpdater_SetVector(ref(), index, vector, dimension, &error), error); + } + + /** Skip setting the vector for the value corresponding to the index. + The vector will be required to compute and set again when the \ref QueryIndex::beginUpdate is later called. + @param index The zero-based index. */ + void skipVector(size_t index) { + CBLIndexUpdater_SkipVector(ref(), index); + } + + /** Updates the index with the computed vectors and removes any index rows for which null vector was given. + If there are any indexes that do not have their vector value set or are skipped, a error will be returned. + @note Before calling \ref IndexUpdater::finish, the set vectors are kept in the memory. + @warning The index updater cannot be used after calling \ref IndexUpdater::finish. */ + void finish() { + CBLError error; + check(CBLIndexUpdater_Finish(ref(), &error), error); + } + + protected: + static IndexUpdater adopt(const CBLIndexUpdater* _cbl_nullable i, CBLError *error) { + if (!i && error->code != 0) + throw *error; + IndexUpdater updater; + updater._ref = (CBLRefCounted*)i; + return updater; + } + + friend class QueryIndex; + CBL_REFCOUNTED_BOILERPLATE(IndexUpdater, RefCounted, CBLIndexUpdater) + }; + + IndexUpdater QueryIndex::beginUpdate(size_t limit) { + CBLError error {}; + auto updater = CBLQueryIndex_BeginUpdate(ref(), limit, &error); + return IndexUpdater::adopt(updater, &error); + } +#endif + + QueryIndex Collection::getIndex(slice name) { + CBLError error {}; + return QueryIndex::adopt(CBLCollection_GetIndex(ref(), name, &error), &error); + } +} + +CBL_ASSUME_NONNULL_END diff --git a/libcblite-3.0.3/include/cbl++/Replicator.hh b/libcblite-3.0.3/include/cbl++/Replicator.hh index 3fd2286..c37c390 100644 --- a/libcblite-3.0.3/include/cbl++/Replicator.hh +++ b/libcblite-3.0.3/include/cbl++/Replicator.hh @@ -403,6 +403,7 @@ namespace cbl { } /** Starts a replicator, asynchronously. Does nothing if it's already started. + @note Replicators cannot be started from within a database's transaction. @param resetCheckpoint If true, the persistent saved state ("checkpoint") for this replication will be discarded, causing it to re-scan all documents. This significantly increases time and bandwidth (redundant docs are not transferred, but their diff --git a/libcblite-3.0.3/include/cbl++/VectorIndex.hh b/libcblite-3.0.3/include/cbl++/VectorIndex.hh new file mode 100644 index 0000000..6f32110 --- /dev/null +++ b/libcblite-3.0.3/include/cbl++/VectorIndex.hh @@ -0,0 +1,189 @@ +// +// VectorIndex.hh +// +// Copyright (c) 2024 Couchbase, Inc All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +// VOLATILE API: Couchbase Lite C++ API is not finalized, and may change in +// future releases. + +#ifdef COUCHBASE_ENTERPRISE + +#pragma once +#include "cbl++/Base.hh" +#include "cbl++/Collection.hh" +#include "cbl/CBLQueryIndexTypes.h" + +CBL_ASSUME_NONNULL_BEGIN + +namespace cbl { + /** ENTERPRISE EDITION ONLY + + Vector Encoding Type*/ + class VectorEncoding { + public: + /** Creates a no-encoding type to use in VectorIndexConfiguration; 4 bytes per dimension, no data loss. + @return A None encoding object. */ + static VectorEncoding none() { + return VectorEncoding(CBLVectorEncoding_CreateNone()); + } + + /** Creates a Scalar Quantizer encoding type to use in VectorIndexConfiguration. + @param type Scalar Quantizer Type. + @return A Scalar Quantizer encoding object. */ + static VectorEncoding scalarQuantizer(CBLScalarQuantizerType type) { + return VectorEncoding(CBLVectorEncoding_CreateScalarQuantizer(type)); + } + + /** Creates a Product Quantizer encoding type to use in VectorIndexConfiguration. + @param subquantizers Number of subquantizers. Must be > 1 and a factor of vector dimensions. + @param bits Number of bits. Must be >= 4 and <= 12. + @return A Product Quantizer encoding object. */ + static VectorEncoding productQuantizer(unsigned int subquantizers, unsigned int bits) { + return VectorEncoding(CBLVectorEncoding_CreateProductQuantizer(subquantizers, bits)); + } + + VectorEncoding() = delete; + + protected: + friend class VectorIndexConfiguration; + + CBLVectorEncoding* ref() const {return _ref.get();} + + private: + VectorEncoding(CBLVectorEncoding* ref) { + _ref = std::shared_ptr(ref, [](auto r) { + CBLVectorEncoding_Free(r); + }); + } + + std::shared_ptr _ref; + }; + + /** ENTERPRISE EDITION ONLY + + Vector Index Configuration. */ + class VectorIndexConfiguration { + public: + /** Creates the VectorIndexConfiguration. + @param expressionLanguage The language used in the expressions. + @param expression The expression could be specified in a JSON Array or in N1QL syntax depending on + the expressionLanguage. + - For non-lazy indexes, an expression returning either a vector, which is an array of 32-bit + floating-point numbers, or a Base64 string representing an array of 32-bit floating-point + numbers in little-endian order. + - For lazy indexex, an expression returning a value for computing a vector lazily when using + \ref IndexUpdater to add or update the vector into the index. + @param dimensions The number of vector dimensions. + @note The maximum number of vector dimensions supported is 4096. + @param centroids The number of centroids which is the number buckets to partition the vectors in the index. + @note The recommended number of centroids is the square root of the number of vectors to be indexed, + and the maximum number of centroids supported is 64,000. */ + VectorIndexConfiguration(CBLQueryLanguage expressionLanguage, slice expression, + unsigned dimensions, unsigned centroids) + :_exprLang(expressionLanguage) + ,_expr(expression) + ,_dimensions(dimensions) + ,_centroids(centroids) + { } + + //-- Accessors: + + /** The language used in the expressions. */ + CBLQueryLanguage expressionLanguage() const {return _exprLang;} + + /** The expression. */ + slice expression() const {return _expr;} + + /** The number of vector dimensions. */ + unsigned dimensions() const {return _dimensions;} + + /** The number of centroids. */ + unsigned centroids() const {return _centroids;} + + /** The boolean flag indicating that index is lazy or not. The default value is false. + + If the index is lazy, it will not be automatically updated when the documents in the collection are changed, + except when the documents are deleted or purged. + + When configuring the index to be lazy, the expression set to the config is the expression that returns + a value used for computing the vector. + + To update the lazy index, use a CBLIndexUpdater object, which can be obtained + from a \ref QueryIndex object. To get a \ref QueryIndex object, call \ref Collection::getIndex. */ + bool isLazy = false; + + /** Vector encoding type. The default value is 8-bits Scalar Quantizer. */ + VectorEncoding encoding = VectorEncoding::scalarQuantizer(kCBLSQ8); + + /** Distance Metric type. The default value is squared euclidean distance. */ + CBLDistanceMetric metric = kCBLDistanceMetricEuclideanSquared; + + /** The minimum number of vectors for training the index. + The default value is zero, meaning that minTrainingSize will be determined based on + the number of centroids, encoding types, and the encoding parameters. + + @note The training will occur at or before the APPROX_VECTOR_DISANCE query is + executed, provided there is enough data at that time, and consequently, if + training is triggered during a query, the query may take longer to return + results. + + @note If a query is executed against the index before it is trained, a full + scan of the vectors will be performed. If there are insufficient vectors + in the database for training, a warning message will be logged, + indicating the required number of vectors. */ + unsigned minTrainingSize = 0; + + /** The maximum number of vectors used for training the index. + The default value is zero, meaning that the maxTrainingSize will be determined based on + the number of centroids, encoding types, and encoding parameters. */ + unsigned maxTrainingSize = 0; + + /** The number of centroids that will be scanned during a query. + The default value is zero, meaning that the numProbes will be determined based on + the number of centroids. */ + unsigned numProbes = 0; + + protected: + friend Collection; + + /** To CBLVectorIndexConfiguration */ + operator CBLVectorIndexConfiguration() const { + CBLVectorIndexConfiguration config { _exprLang, _expr, _dimensions, _centroids }; + config.isLazy = isLazy; + config.encoding = encoding.ref(); + config.metric = metric; + config.minTrainingSize = minTrainingSize; + config.maxTrainingSize = maxTrainingSize; + config.numProbes = numProbes; + return config; + } + + private: + CBLQueryLanguage _exprLang; + slice _expr; + unsigned _dimensions; + unsigned _centroids; + }; + + void Collection::createVectorIndex(slice name, const VectorIndexConfiguration &config) { + CBLError error {}; + check(CBLCollection_CreateVectorIndex(ref(), name, config, &error), error); + } +} + +CBL_ASSUME_NONNULL_END + +#endif diff --git a/libcblite-3.0.3/include/cbl/CBLBase.h b/libcblite-3.0.3/include/cbl/CBLBase.h index f7d9ef0..4590ad7 100644 --- a/libcblite-3.0.3/include/cbl/CBLBase.h +++ b/libcblite-3.0.3/include/cbl/CBLBase.h @@ -209,7 +209,7 @@ typedef struct CBLDocument CBLDocument; typedef struct CBLBlob CBLBlob; /** @} */ -/** \defgroup queries Queries +/** \defgroup query Query @{ */ /** A compiled database query. */ typedef struct CBLQuery CBLQuery; @@ -218,6 +218,16 @@ typedef struct CBLQuery CBLQuery; typedef struct CBLResultSet CBLResultSet; /** @} */ +/** \defgroup index Index + @{ */ +/** A query index. */ +typedef struct CBLQueryIndex CBLQueryIndex; + +#ifdef COUCHBASE_ENTERPRISE +typedef struct CBLIndexUpdater CBLIndexUpdater; +#endif +/** @} */ + /** \defgroup replication Replication @{ */ /** A background task that syncs a \ref CBLDatabase with a remote server or peer. */ diff --git a/libcblite-3.0.3/include/cbl/CBLCollection.h b/libcblite-3.0.3/include/cbl/CBLCollection.h index 9ea61f0..de90101 100644 --- a/libcblite-3.0.3/include/cbl/CBLCollection.h +++ b/libcblite-3.0.3/include/cbl/CBLCollection.h @@ -19,7 +19,8 @@ #pragma once #include "CBLBase.h" #include "CBLDocument.h" -#include "CBLQuery.h" +#include "CBLQueryIndexTypes.h" +#include "CBLQueryTypes.h" CBL_CAPI_BEGIN @@ -154,12 +155,10 @@ CBLScope* CBLDatabase_DefaultScope(const CBLDatabase* db, CBLError* _cbl_nullable outError) CBLAPI; /** Returns the default collection. - @note The default collection may not exist if it was deleted. - Also, the default collection cannot be recreated after being deleted. @note You are responsible for releasing the returned collection. @param db The database. @param outError On failure, the error will be written here. - @return A \ref CBLCollection instance, or NULL if the default collection doesn't exist or an error occurred. */ + @return A \ref CBLCollection instance, or NULL if an error occurred. */ CBLCollection* _cbl_nullable CBLDatabase_DefaultCollection(const CBLDatabase* db, CBLError* _cbl_nullable outError) CBLAPI; @@ -170,17 +169,28 @@ CBLCollection* _cbl_nullable CBLDatabase_DefaultCollection(const CBLDatabase* db Getting information about a collection. */ -/** Returns the scope of the collection. +/** Returns the collection's scope. @note You are responsible for releasing the returned scope. @param collection The collection. - @return A \ref CBLScope instance. */ + @return The scope of the collection. */ CBLScope* CBLCollection_Scope(const CBLCollection* collection) CBLAPI; -/** Returns the collection name. +/** Returns the collection's name. @param collection The collection. @return The name of the collection. */ FLString CBLCollection_Name(const CBLCollection* collection) CBLAPI; +/** Returns the collection's fully qualified name in the '.' format. + @param collection The collection. + @return The fully qualified name of the collection. */ +FLString CBLCollection_FullName(const CBLCollection* collection) CBLAPI; + +/** Returns the collection's database. + @note The database object is owned by the collection object; you do not need to release it. + @param collection The collection. + @return The database of the collection. */ +CBLDatabase* CBLCollection_Database(const CBLCollection* collection) CBLAPI; + /** Returns the number of documents in the collection. @param collection The collection. @return the number of documents in the collection. */ @@ -371,6 +381,33 @@ bool CBLCollection_CreateFullTextIndex(CBLCollection *collection, CBLFullTextIndexConfiguration config, CBLError* _cbl_nullable outError) CBLAPI; +/** Creates an array index for use with UNNEST queries in the collection. + If an identical index with that name already exists, nothing happens (and no error is returned.) + If a non-identical index with that name already exists, it is deleted and re-created. + @param collection The collection. + @param name The name of the index. + @param config The index configuration. + @param outError On failure, an error is written here. + @return True on success, false on failure. */ +bool CBLCollection_CreateArrayIndex(CBLCollection *collection, + FLString name, + CBLArrayIndexConfiguration config, + CBLError* _cbl_nullable outError) CBLAPI; + +#ifdef COUCHBASE_ENTERPRISE +/** ENTERPRISE EDITION ONLY + + Creatres a vector index in the collection. + If an identical index with that name already exists, nothing happens (and no error is returned.) + If a non-identical index with that name already exists, it is deleted and re-created. + */ +bool CBLCollection_CreateVectorIndex(CBLCollection *collection, + FLString name, + CBLVectorIndexConfiguration config, + CBLError* _cbl_nullable outError) CBLAPI; + +#endif + /** Deletes an index in the collection by name. @param collection The collection. @param name The name of the index. @@ -389,6 +426,17 @@ _cbl_warn_unused FLMutableArray _cbl_nullable CBLCollection_GetIndexNames(CBLCollection *collection, CBLError* _cbl_nullable outError) CBLAPI; +/** Returns an index object representing an existing index in the collection. + @note You are responsible for releasing the returned index object. + @param collection The collection. + @param name The name of the index. + @param outError On failure, an error is written here. + @return A \ref CBLQueryIndex instance if the index exists, or NULL if the index doesn't exist or an error occurred. */ +_cbl_warn_unused +CBLQueryIndex* _cbl_nullable CBLCollection_GetIndex(CBLCollection* collection, + FLString name, + CBLError* _cbl_nullable outError) CBLAPI; + /** @} */ /** \name Change Listeners diff --git a/libcblite-3.0.3/include/cbl/CBLDatabase.h b/libcblite-3.0.3/include/cbl/CBLDatabase.h index d4d5071..394db68 100644 --- a/libcblite-3.0.3/include/cbl/CBLDatabase.h +++ b/libcblite-3.0.3/include/cbl/CBLDatabase.h @@ -18,6 +18,7 @@ #pragma once #include "CBLBase.h" +#include "CBLQueryIndexTypes.h" CBL_CAPI_BEGIN @@ -26,6 +27,29 @@ CBL_CAPI_BEGIN A \ref CBLDatabase is both a filesystem object and a container for documents. */ +#ifdef COUCHBASE_ENTERPRISE + +#ifdef __APPLE__ +#pragma mark - Database Extension +#endif + +/** \name Database Extension + @{ */ + +/** ENTERPRISE EDITION ONLY + + Enables Vector Search extension by specifying the extension path to search for the Vector Search extension library. + This function must be called before opening a database that intends to use the vector search extension. + @param path The file system path of the directory that contains the Vector Search extension library. + @param outError On return, will be set to the error that occurred. + @return True on success, false if there was an error. + @note Must be called before opening a database that intends to use the vector search extension. */ +bool CBL_EnableVectorSearch(FLString path, CBLError* _cbl_nullable outError) CBLAPI; + +/** @} */ + +#endif + #ifdef __APPLE__ #pragma mark - CONFIGURATION #endif @@ -68,6 +92,13 @@ typedef struct { power failure will not cause the loss of any data. FULL synchronous is very safe but it is also dramatically slower. */ bool fullSync; + + /** + Disable memory-mapped I/O. By default, memory-mapped I/O is enabled. + Disabling it may affect database performance. Typically, there is no need to modify this setting. + @note Memory-mapped I/O is always disabled on macOS to prevent database corruption, + so setting mmapDisabled value has no effect on the macOS platform. */ + bool mmapDisabled; } CBLDatabaseConfiguration; /** Returns the default database configuration. */ @@ -219,7 +250,6 @@ bool CBLDatabase_PerformMaintenance(CBLDatabase* db, /** @} */ - #ifdef __APPLE__ #pragma mark - ACCESSORS #endif @@ -244,6 +274,45 @@ const CBLDatabaseConfiguration CBLDatabase_Config(const CBLDatabase*) CBLAPI; /** @} */ +/** \name Query Indexes + @{ + Query Index Management + */ + +/** Creates a value index. + Indexes are persistent. + If an identical index with that name already exists, nothing happens (and no error is returned.) + If a non-identical index with that name already exists, it is deleted and re-created. + @warning Deprecated : Use CBLCollection_CreateValueIndex on the default collection instead. */ +bool CBLDatabase_CreateValueIndex(CBLDatabase *db, + FLString name, + CBLValueIndexConfiguration config, + CBLError* _cbl_nullable outError) CBLAPI; + +/** Creates a full-text index. + Indexes are persistent. + If an identical index with that name already exists, nothing happens (and no error is returned.) + If a non-identical index with that name already exists, it is deleted and re-created. + @warning Deprecated : Use CBLCollection_CreateFullTextIndex on the default collection instead. */ +bool CBLDatabase_CreateFullTextIndex(CBLDatabase *db, + FLString name, + CBLFullTextIndexConfiguration config, + CBLError* _cbl_nullable outError) CBLAPI; + +/** Deletes an index given its name. + @warning Deprecated : Use CBLCollection_DeleteIndex on the default collection instead. */ +bool CBLDatabase_DeleteIndex(CBLDatabase *db, + FLString name, + CBLError* _cbl_nullable outError) CBLAPI; + +/** Returns the names of the indexes on this database, as a Fleece array of strings. + @note You are responsible for releasing the returned Fleece array. + @warning Deprecated : Use CBLCollection_GetIndexNames on the default collection instead. */ +_cbl_warn_unused +FLArray CBLDatabase_GetIndexNames(CBLDatabase *db) CBLAPI; + + +/** @} */ #ifdef __APPLE__ #pragma mark - LISTENERS diff --git a/libcblite-3.0.3/include/cbl/CBLDefaults.h b/libcblite-3.0.3/include/cbl/CBLDefaults.h index 2ab890d..696e648 100644 --- a/libcblite-3.0.3/include/cbl/CBLDefaults.h +++ b/libcblite-3.0.3/include/cbl/CBLDefaults.h @@ -2,7 +2,7 @@ // CBLDefaults.h // CouchbaseLite // -// Copyright (c) 2023-present Couchbase, Inc All rights reserved. +// Copyright (c) 2024-present Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ #pragma once #include "CBL_Compat.h" #include "CBLReplicator.h" +#include "CBLQueryIndexTypes.h" CBL_CAPI_BEGIN @@ -33,11 +34,27 @@ CBL_CAPI_BEGIN Constants for default configuration values. */ +/** \name CBLDatabaseConfiguration + @{ +*/ + +/** [false] Full sync is off by default because the performance hit is seldom worth the benefit */ +CBL_PUBLIC extern const bool kCBLDefaultDatabaseFullSync; + +/** [false] Memory mapped database files are enabled by default */ +CBL_PUBLIC extern const bool kCBLDefaultDatabaseMmapDisabled; + +/** @} */ + /** \name CBLLogFileConfiguration @{ */ /** [false] Plaintext is not used, and instead binary encoding is used in log files */ +CBL_PUBLIC extern const bool kCBLDefaultLogFileUsePlaintext; + +/** [false] Plaintext is not used, and instead binary encoding is used in log files + @warning Deprecated : Use kCBLDefaultLogFileUsePlaintext instead. */ CBL_PUBLIC extern const bool kCBLDefaultLogFileUsePlainText; /** [524288] 512 KiB for the size of a log file */ @@ -46,7 +63,6 @@ CBL_PUBLIC extern const size_t kCBLDefaultLogFileMaxSize; /** [1] 1 rotated file present (2 total, including the currently active log file) */ CBL_PUBLIC extern const uint32_t kCBLDefaultLogFileMaxRotateCount; - /** @} */ /** \name CBLFullTextIndexConfiguration @@ -56,7 +72,6 @@ CBL_PUBLIC extern const uint32_t kCBLDefaultLogFileMaxRotateCount; /** [false] Accents and ligatures are not ignored when indexing via full text search */ CBL_PUBLIC extern const bool kCBLDefaultFullTextIndexIgnoreAccents; - /** @} */ /** \name CBLReplicatorConfiguration @@ -79,6 +94,10 @@ CBL_PUBLIC extern const unsigned kCBLDefaultReplicatorMaxAttemptsSingleShot; CBL_PUBLIC extern const unsigned kCBLDefaultReplicatorMaxAttemptsContinuous; /** [300] Max wait time between retry attempts in seconds */ +CBL_PUBLIC extern const unsigned kCBLDefaultReplicatorMaxAttemptsWaitTime; + +/** [300] Max wait time between retry attempts in seconds + @warning Deprecated : Use kCBLDefaultReplicatorMaxAttemptsWaitTime instead. */ CBL_PUBLIC extern const unsigned kCBLDefaultReplicatorMaxAttemptWaitTime; /** [false] Purge documents when a user loses access */ @@ -89,6 +108,31 @@ CBL_PUBLIC extern const bool kCBLDefaultReplicatorAcceptParentCookies; /** @} */ +#ifdef COUCHBASE_ENTERPRISE + +/** \name CBLVectorIndexConfiguration + @{ +*/ + +/** [false] Vectors are not lazily indexed, by default */ +CBL_PUBLIC extern const bool kCBLDefaultVectorIndexLazy; + +/** [kCBLDistanceMetricEuclideanSquared] By default, vectors are compared using Squared Euclidean metric. */ +CBL_PUBLIC extern const CBLDistanceMetric kCBLDefaultVectorIndexDistanceMetric; + +/** [0] By default, the value will be determined based on the number of centroids, encoding types, and the encoding parameters. */ +CBL_PUBLIC extern const unsigned kCBLDefaultVectorIndexMinTrainingSize; + +/** [0] By default, the value will be determined based on the number of centroids, encoding types, and the encoding parameters */ +CBL_PUBLIC extern const unsigned kCBLDefaultVectorIndexMaxTrainingSize; + +/** [0] By default, the value will be determined based on the number of centroids. */ +CBL_PUBLIC extern const unsigned kCBLDefaultVectorIndexNumProbes; + +/** @} */ + +#endif + /** @} */ CBL_CAPI_END diff --git a/libcblite-3.0.3/include/cbl/CBLLog.h b/libcblite-3.0.3/include/cbl/CBLLog.h index 1792734..25b53f9 100644 --- a/libcblite-3.0.3/include/cbl/CBLLog.h +++ b/libcblite-3.0.3/include/cbl/CBLLog.h @@ -128,7 +128,7 @@ typedef struct { size_t maxSize; /** Whether or not to log in plaintext (as opposed to binary.) Plaintext logging is slower and bigger. - The default is \ref kCBLDefaultLogFileUsePlainText. */ + The default is \ref kCBLDefaultLogFileUsePlaintext. */ bool usePlaintext; } CBLLogFileConfiguration; diff --git a/libcblite-3.0.3/include/cbl/CBLPrediction.h b/libcblite-3.0.3/include/cbl/CBLPrediction.h new file mode 100644 index 0000000..cba35ce --- /dev/null +++ b/libcblite-3.0.3/include/cbl/CBLPrediction.h @@ -0,0 +1,57 @@ +// +// CBLPrediction.h +// +// Copyright (c) 2024 Couchbase, Inc All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#pragma once +#include "CBLBase.h" + +#ifdef COUCHBASE_ENTERPRISE + +CBL_CAPI_BEGIN + +/** Predictive Model */ +typedef struct { + /** A pointer to any external data needed by the `prediction` callback, which will receive this as its first parameter. */ + void* _cbl_nullable context; + + /** Prediction callback, called from within a query (or document indexing) to run the prediction. + @param context The value of the CBLPredictiveModel's `context` field. + @param input The input dictionary from the query. + @return The output of the prediction function as an FLMutableDict, or NULL if there is no output. + @note The output FLMutableDict will be automatically released after the prediction callback is called. + @warning This function must be "pure": given the same input parameters it must always + produce the same output (otherwise indexes or queries may be messed up). + It MUST NOT alter the database or any documents, nor run a query: either of + those are very likely to cause a crash. */ + FLMutableDict _cbl_nullable (* _cbl_nonnull prediction)(void* _cbl_nullable context, FLDict input); + + /** Unregistered callback, called if the model is unregistered, so it can release resources. */ + void (*_cbl_nullable unregistered)(void* context); +} CBLPredictiveModel; + +/** Registers a predictive model. + @param name The name. + @param model The predictive model. */ +void CBL_RegisterPredictiveModel(FLString name, CBLPredictiveModel model) CBLAPI; + +/** Unregisters the predictive model. + @param name The name of the registered predictive model. */ +void CBL_UnregisterPredictiveModel(FLString name) CBLAPI; + +CBL_CAPI_END + +#endif diff --git a/libcblite-3.0.3/include/cbl/CBLQuery.h b/libcblite-3.0.3/include/cbl/CBLQuery.h index ee26c79..ad6f602 100644 --- a/libcblite-3.0.3/include/cbl/CBLQuery.h +++ b/libcblite-3.0.3/include/cbl/CBLQuery.h @@ -18,33 +18,26 @@ #pragma once #include "CBLBase.h" +#include "CBLQueryTypes.h" CBL_CAPI_BEGIN - -/** \defgroup queries Queries +/** \defgroup query Query @{ A CBLQuery represents a compiled database query. The query language is a large subset of the [N1QL](https://www.couchbase.com/products/n1ql) language from Couchbase Server, which you can think of as "SQL for JSON" or "SQL++". - Queries may be given either in - [N1QL syntax](https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/index.html), - or in JSON using a - [schema](https://github.com/couchbase/couchbase-lite-core/wiki/JSON-Query-Schema) - that resembles a parse tree of N1QL. The JSON syntax is harder for humans, but much more + Supported Query languages: + [N1QL](https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/index.html) + + [JSON](https://github.com/couchbase/couchbase-lite-core/wiki/JSON-Query-Schema) + + JSON language resembles a parse tree of N1QL. The JSON syntax is harder for humans, but much more amenable to machine generation, if you need to create queries programmatically or translate them from some other form. */ - -/** Query languages */ -typedef CBL_ENUM(uint32_t, CBLQueryLanguage) { - kCBLJSONLanguage, ///< [JSON query schema](https://github.com/couchbase/couchbase-lite-core/wiki/JSON-Query-Schema) - kCBLN1QLLanguage ///< [N1QL syntax](https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/index.html) -}; - - /** \name Query objects @{ */ @@ -150,16 +143,16 @@ bool CBLResultSet_Next(CBLResultSet*) CBLAPI; /** Returns the value of a column of the current result, given its (zero-based) numeric index. This may return a NULL pointer, indicating `MISSING`, if the value doesn't exist, e.g. if the column is a property that doesn't exist in the document. */ -FLValue CBLResultSet_ValueAtIndex(const CBLResultSet*, - unsigned index) CBLAPI; +FLValue _cbl_nullable CBLResultSet_ValueAtIndex(const CBLResultSet*, + unsigned index) CBLAPI; /** Returns the value of a column of the current result, given its name. This may return a NULL pointer, indicating `MISSING`, if the value doesn't exist, e.g. if the column is a property that doesn't exist in the document. (Or, of course, if the key is not a column name in this query.) @note See \ref CBLQuery_ColumnName for a discussion of column names. */ -FLValue CBLResultSet_ValueForKey(const CBLResultSet*, - FLString key) CBLAPI; +FLValue _cbl_nullable CBLResultSet_ValueForKey(const CBLResultSet*, + FLString key) CBLAPI; /** Returns the current result as an array of column values. @warning The array reference is only valid until the result-set is advanced or released. @@ -179,7 +172,6 @@ CBL_REFCOUNTED(CBLResultSet*, ResultSet); /** @} */ - /** \name Change listener @{ Adding a change listener to a query turns it into a "live query". When changes are made to @@ -233,106 +225,6 @@ CBLResultSet* _cbl_nullable CBLQuery_CopyCurrentResults(const CBLQuery* query, /** @} */ - - -/** \name Database Indexes - @{ - Indexes are used to speed up queries by allowing fast -- O(log n) -- lookup of documents - that have specific values or ranges of values. The values may be properties, or expressions - based on properties. - - An index will speed up queries that use the expression it indexes, but it takes up space in - the database file, and it slows down document saves slightly because it needs to be kept up - to date when documents change. - - Tuning a database with indexes can be a tricky task. Fortunately, a lot has been written about - it in the relational-database (SQL) realm, and much of that advice holds for Couchbase Lite. - You may find SQLite's documentation particularly helpful since Couchbase Lite's querying is - based on SQLite. - - Two types of indexes are currently supported: - * Value indexes speed up queries by making it possible to look up property (or expression) - values without scanning every document. They're just like regular indexes in SQL or N1QL. - Multiple expressions are supported; the first is the primary key, second is secondary. - Expressions must evaluate to scalar types (boolean, number, string). - * Full-Text Search (FTS) indexes enable fast search of natural-language words or phrases - by using the `MATCH` operator in a query. A FTS index is **required** for full-text - search: a query with a `MATCH` operator will fail to compile unless there is already a - FTS index for the property/expression being matched. Only a single expression is - currently allowed, and it must evaluate to a string. */ - -/** Value Index Configuration. */ -typedef struct { - /** The language used in the expressions. */ - CBLQueryLanguage expressionLanguage; - - /** The expressions describing each coloumn of the index. The expressions could be specified - in a JSON Array or in N1QL syntax using comma delimiter. */ - FLString expressions; -} CBLValueIndexConfiguration; - -/** Creates a value index. - Indexes are persistent. - If an identical index with that name already exists, nothing happens (and no error is returned.) - If a non-identical index with that name already exists, it is deleted and re-created. - @warning Deprecated : Use CBLCollection_CreateValueIndex on the default collection instead. */ -bool CBLDatabase_CreateValueIndex(CBLDatabase *db, - FLString name, - CBLValueIndexConfiguration config, - CBLError* _cbl_nullable outError) CBLAPI; - - -/** Full-Text Index Configuration. */ -typedef struct { - /** The language used in the expressions (Required). */ - CBLQueryLanguage expressionLanguage; - - /** The expressions describing each coloumn of the index. The expressions could be specified - in a JSON Array or in N1QL syntax using comma delimiter. (Required) */ - FLString expressions; - - /** Should diacritical marks (accents) be ignored? - Defaults to \ref kCBLDefaultFullTextIndexIgnoreAccents. - Generally this should be left `false` for non-English text. */ - bool ignoreAccents; - - /** The dominant language. Setting this enables word stemming, i.e. - matching different cases of the same word ("big" and "bigger", for instance) and ignoring - common "stop-words" ("the", "a", "of", etc.) - - Can be an ISO-639 language code or a lowercase (English) language name; supported - languages are: da/danish, nl/dutch, en/english, fi/finnish, fr/french, de/german, - hu/hungarian, it/italian, no/norwegian, pt/portuguese, ro/romanian, ru/russian, - es/spanish, sv/swedish, tr/turkish. - - If left null, or set to an unrecognized language, no language-specific behaviors - such as stemming and stop-word removal occur. */ - FLString language; -} CBLFullTextIndexConfiguration; - -/** Creates a full-text index. - Indexes are persistent. - If an identical index with that name already exists, nothing happens (and no error is returned.) - If a non-identical index with that name already exists, it is deleted and re-created. - @warning Deprecated : Use CBLCollection_CreateFullTextIndex on the default collection instead. */ -bool CBLDatabase_CreateFullTextIndex(CBLDatabase *db, - FLString name, - CBLFullTextIndexConfiguration config, - CBLError* _cbl_nullable outError) CBLAPI; - -/** Deletes an index given its name. - @warning Deprecated : Use CBLCollection_DeleteIndex on the default collection instead. */ -bool CBLDatabase_DeleteIndex(CBLDatabase *db, - FLString name, - CBLError* _cbl_nullable outError) CBLAPI; - -/** Returns the names of the indexes on this database, as a Fleece array of strings. - @note You are responsible for releasing the returned Fleece array. - @warning Deprecated : Use CBLCollection_GetIndexNames on the default collection instead. */ -_cbl_warn_unused -FLArray CBLDatabase_GetIndexNames(CBLDatabase *db) CBLAPI; - -/** @} */ /** @} */ CBL_CAPI_END diff --git a/libcblite-3.0.3/include/cbl/CBLQueryIndex.h b/libcblite-3.0.3/include/cbl/CBLQueryIndex.h new file mode 100644 index 0000000..2779f6a --- /dev/null +++ b/libcblite-3.0.3/include/cbl/CBLQueryIndex.h @@ -0,0 +1,161 @@ +// +// CBLQueryIndex.h +// +// Copyright (c) 2024 Couchbase, Inc All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#pragma once +#include "CBLBase.h" +#include "CBLQueryTypes.h" + +CBL_CAPI_BEGIN + +/** \defgroup index Index + @{ + Indexes are used to speed up queries by allowing fast -- O(log n) -- lookup of documents + that have specific values or ranges of values. The values may be properties, or expressions + based on properties. + + An index will speed up queries that use the expression it indexes, but it takes up space in + the database file, and it slows down document saves slightly because it needs to be kept up + to date when documents change. + + Tuning a database with indexes can be a tricky task. Fortunately, a lot has been written about + it in the relational-database (SQL) realm, and much of that advice holds for Couchbase Lite. + You may find SQLite's documentation particularly helpful since Couchbase Lite's querying is + based on SQLite. + + Supported index types: + * Value indexes speed up queries by making it possible to look up property (or expression) + values without scanning every document. They're just like regular indexes in SQL or N1QL. + Multiple expressions are supported; the first is the primary key, second is secondary. + Expressions must evaluate to scalar types (boolean, number, string). + + * Full-Text Search (FTS) indexes enable fast search of natural-language words or phrases + by using the `MATCH()` function in a query. A FTS index is **required** for full-text + search: a query with a `MATCH()` function will fail to compile unless there is already a + FTS index for the property/expression being matched. + + * (Enterprise Edition Only) Vector indexes allows efficient search of ML vectors by using + the `VECTOR_MATCH()` function in a query. The `CouchbaseLiteVectorSearch` + extension library is **required** to use the functionality. Use \ref CBL_EnableVectorSearch + function to set the directoary path containing the extension library. */ + +/** \name CBLQueryIndex + @{ + CBLQueryIndex represents an existing index in a collection. + + Available in the enterprise edition, the \ref CBLQueryIndex can be used to obtain + a \ref CBLIndexUpdater object for updating the vector index in lazy mode. */ +CBL_REFCOUNTED(CBLQueryIndex*, QueryIndex); + +/** Returns the index's name. + @param index The index. + @return The name of the index. */ +FLString CBLQueryIndex_Name(const CBLQueryIndex* index) CBLAPI; + +/** Returns the collection that the index belongs to. + @param index The index. + @return A \ref CBLCollection instance that the index belongs to. */ +CBLCollection* CBLQueryIndex_Collection(const CBLQueryIndex* index) CBLAPI; + +#ifdef COUCHBASE_ENTERPRISE + +CBL_REFCOUNTED(CBLIndexUpdater*, IndexUpdater); + +/** ENTERPRISE EDITION ONLY + + Finds new or updated documents for which vectors need to be (re)computed and returns an \ref CBLIndexUpdater object + for setting the computed vectors to update the index. If the index is not lazy, an error will be returned. + @note For updating lazy vector indexes only. + @note You are responsible for releasing the returned A \ref CBLIndexUpdater object. + @param index The index. + @param limit The maximum number of vectors to be computed. + @param outError On failure, an error is written here. + @return A \ref CBLIndexUpdater object for setting the computed vectors to update the index, + or NULL if the index is up-to-date or an error occurred. */ +_cbl_warn_unused +CBLIndexUpdater* _cbl_nullable CBLQueryIndex_BeginUpdate(CBLQueryIndex* index, + size_t limit, + CBLError* _cbl_nullable outError) CBLAPI; + +/** @} */ + +/** \name IndexUpdater + @{ + CBLIndexUpdater used for updating the index in lazy mode. Currently, the vector index is the only index type that + can be updated lazily. + */ + +/** ENTERPRISE EDITION ONLY + + Returns the total number of vectors to compute and set for updating the index. + @param updater The index updater. + @return The total number of vectors to compute and set for updating the index. */ +size_t CBLIndexUpdater_Count(const CBLIndexUpdater* updater) CBLAPI; + +/** ENTERPRISE EDITION ONLY + + Returns the valut at the given index to compute a vector from. + @note The returned Fleece value is valid unilt its \ref CBLIndexUpdater is released. + If you want to keep it longer, retain it with `FLRetain`. + @param updater The index updater. + @param index The zero-based index. + @return A Fleece value of the index's evaluated expression at the given index. */ +FLValue CBLIndexUpdater_Value(CBLIndexUpdater* updater, size_t index) CBLAPI; + +/** ENTERPRISE EDITION ONLY + + Sets the vector for the value corresponding to the given index. + Setting null vector means that there is no vector for the value, and any existing vector + will be removed when the `CBLIndexUpdater_Finish` is called. + @param updater The index updater. + @param index The zero-based index. + @param vector A pointer to the vector which is an array of floats, or NULL if there is no vector. + @param dimension The dimension of `vector`. Must be equal to the dimension value set in the vector index config. + @param outError On failure, an error is written here. + @return True if success, or False if an error occurred. */ +bool CBLIndexUpdater_SetVector(CBLIndexUpdater* updater, + size_t index, + const float vector[_cbl_nullable], + size_t dimension, + CBLError* _cbl_nullable outError) CBLAPI; + +/** ENTERPRISE EDITION ONLY + + Skip setting the vector for the value corresponding to the index. + The vector will be required to compute and set again when the `CBLQueryIndex_BeginUpdate` is later called. + @param updater The index updater. + @param index The zero-based index. */ +void CBLIndexUpdater_SkipVector(CBLIndexUpdater* updater, size_t index) CBLAPI; + +/** ENTERPRISE EDITION ONLY + + Updates the index with the computed vectors and removes any index rows for which null vector was given. + If there are any indexes that do not have their vector value set or are skipped, a error will be returned. + @note Before calling `CBLIndexUpdater_Finish`, the set vectors are kept in the memory. + @warning The index updater cannot be used after calling `CBLIndexUpdater_Finish`. + @param updater The index updater. + @param outError On failure, an error is written here. + @return True if success, or False if an error occurred. */ +bool CBLIndexUpdater_Finish(CBLIndexUpdater* updater, CBLError* _cbl_nullable outError) CBLAPI; + +#endif + +/** @} */ + +/** @} */ + +CBL_CAPI_END diff --git a/libcblite-3.0.3/include/cbl/CBLQueryIndexTypes.h b/libcblite-3.0.3/include/cbl/CBLQueryIndexTypes.h new file mode 100644 index 0000000..48d6e66 --- /dev/null +++ b/libcblite-3.0.3/include/cbl/CBLQueryIndexTypes.h @@ -0,0 +1,206 @@ +// +// CBLQueryIndexTypes.h +// +// Copyright (c) 2024 Couchbase, Inc All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#pragma once +#include "CBLBase.h" +#include "CBLQueryTypes.h" + +CBL_CAPI_BEGIN + +/** \defgroup index Index + @{ */ + +/** \name Index Configuration + @{ */ + +/** Value Index Configuration. */ +typedef struct { + /** The language used in the expressions. */ + CBLQueryLanguage expressionLanguage; + + /** The expressions describing each coloumn of the index. The expressions could be specified + in a JSON Array or in N1QL syntax using comma delimiter. */ + FLString expressions; +} CBLValueIndexConfiguration; + +/** Full-Text Index Configuration. */ +typedef struct { + /** The language used in the expressions (Required). */ + CBLQueryLanguage expressionLanguage; + + /** The expressions describing each coloumn of the index. The expressions could be specified + in a JSON Array or in N1QL syntax using comma delimiter. (Required) */ + FLString expressions; + + /** Should diacritical marks (accents) be ignored? + Defaults to \ref kCBLDefaultFullTextIndexIgnoreAccents. + Generally this should be left `false` for non-English text. */ + bool ignoreAccents; + + /** The dominant language. Setting this enables word stemming, i.e. + matching different cases of the same word ("big" and "bigger", for instance) and ignoring + common "stop-words" ("the", "a", "of", etc.) + + Can be an ISO-639 language code or a lowercase (English) language name; supported + languages are: da/danish, nl/dutch, en/english, fi/finnish, fr/french, de/german, + hu/hungarian, it/italian, no/norwegian, pt/portuguese, ro/romanian, ru/russian, + es/spanish, sv/swedish, tr/turkish. + + If left null, or set to an unrecognized language, no language-specific behaviors + such as stemming and stop-word removal occur. */ + FLString language; +} CBLFullTextIndexConfiguration; + +/** Array Index Configuration for indexing property values within arrays + in documents, intended for use with the UNNEST query. */ +typedef struct { + /** The language used in the expressions (Required). */ + CBLQueryLanguage expressionLanguage; + + /** Path to the array, which can be nested to be indexed (Required). + Use "[]" to represent a property that is an array of each nested array level. + For a single array or the last level array, the "[]" is optional. For instance, + use "contacts[].phones" to specify an array of phones within each contact. */ + FLString path; + + /** Optional expressions representing the values within the array to be + indexed. The expressions could be specified in a JSON Array or in N1QL syntax + using comma delimiter. If the array specified by the path contains scalar values, + the expressions should be left unset or set to null. */ + FLString expressions; +} CBLArrayIndexConfiguration; + +#ifdef COUCHBASE_ENTERPRISE + +/** An opaque object representing vector encoding type to use in CBLVectorIndexConfiguration. */ +typedef struct CBLVectorEncoding CBLVectorEncoding; + +/** Creates a no-encoding type to use in CBLVectorIndexConfiguration; 4 bytes per dimension, no data loss. + @return A None encoding object. */ +_cbl_warn_unused +CBLVectorEncoding* CBLVectorEncoding_CreateNone(void) CBLAPI; + +/** Scalar Quantizer encoding type */ +typedef CBL_ENUM(uint32_t, CBLScalarQuantizerType) { + kCBLSQ4 = 4, ///< 4 bits per dimension + kCBLSQ6 = 6, ///< 6 bits per dimension + kCBLSQ8 = 8 ///< 8 bits per dimension +}; + +/** Creates a Scalar Quantizer encoding to use in CBLVectorIndexConfiguration. + @param type Scalar Quantizer Type. + @return A Scalar Quantizer encoding object. */ +_cbl_warn_unused +CBLVectorEncoding* CBLVectorEncoding_CreateScalarQuantizer(CBLScalarQuantizerType type) CBLAPI; + +/** Creates a Product Quantizer encoding to use in CBLVectorIndexConfiguration. + @param subquantizers Number of subquantizers. Must be > 1 and a factor of vector dimensions. + @param bits Number of bits. Must be >= 4 and <= 12. + @return A Product Quantizer encoding object. */ +_cbl_warn_unused +CBLVectorEncoding* CBLVectorEncoding_CreateProductQuantizer(unsigned subquantizers, unsigned bits) CBLAPI; + +/** Frees a CBLVectorEncoding object. The encoding object can be freed after the index is created. */ +void CBLVectorEncoding_Free(CBLVectorEncoding* _cbl_nullable) CBLAPI; + +/** Distance metric to use in CBLVectorIndexConfiguration. */ +typedef CBL_ENUM(uint32_t, CBLDistanceMetric) { + kCBLDistanceMetricEuclideanSquared = 1, ///< Squared Euclidean distance (AKA Squared L2) + kCBLDistanceMetricCosine, ///< Cosine distance (1.0 - Cosine Similarity) + kCBLDistanceMetricEuclidean, ///< Euclidean distance (AKA L2) + kCBLDistanceMetricDot ///< Dot-product distance (Negative of dot-product) +}; + +/** ENTERPRISE EDITION ONLY + + Vector Index Configuration. */ +typedef struct { + /** The language used in the expressions (Required). */ + CBLQueryLanguage expressionLanguage; + + /** The expression could be specified in a JSON Array or in N1QL syntax depending on + the expressionLanguage. (Required) + + For non-lazy indexes, an expression returning either a vector, which is an array of 32-bit + floating-point numbers, or a Base64 string representing an array of 32-bit floating-point + numbers in little-endian order. + + For lazy indexex, an expression returning a value for computing a vector lazily when using + \ref CBLIndexUpdater to add or update the vector into the index. */ + FLString expression; + + /** The number of vector dimensions. (Required) + @note The maximum number of vector dimensions supported is 4096. */ + unsigned dimensions; + + /** The number of centroids which is the number buckets to partition the vectors in the index. (Required) + @note The recommended number of centroids is the square root of the number of vectors to be indexed, + and the maximum number of centroids supported is 64,000.*/ + unsigned centroids; + + /** The boolean flag indicating that index is lazy or not. The default value is false. + + If the index is lazy, it will not be automatically updated when the documents in the collection are changed, + except when the documents are deleted or purged. + + When configuring the index to be lazy, the expression set to the config is the expression that returns + a value used for computing the vector. + + To update the lazy index, use a CBLIndexUpdater object, which can be obtained + from a CBLQueryIndex object. To get a CBLQueryIndex object, call CBLCollection_GetIndex. */ + bool isLazy; + + /** Vector encoding type. The default value is 8-bits Scalar Quantizer. */ + CBLVectorEncoding* encoding; + + /** Distance Metric type. The default value is euclidean distance. */ + CBLDistanceMetric metric; + + /** The minimum number of vectors for training the index. + The default value is zero, meaning that minTrainingSize will be determined based on + the number of centroids, encoding types, and the encoding parameters. + + @note The training will occur at or before the APPROX_VECTOR_DISANCE query is + executed, provided there is enough data at that time, and consequently, if + training is triggered during a query, the query may take longer to return + results. + + @note If a query is executed against the index before it is trained, a full + scan of the vectors will be performed. If there are insufficient vectors + in the database for training, a warning message will be logged, + indicating the required number of vectors. */ + unsigned minTrainingSize; + + /** The maximum number of vectors used for training the index. + The default value is zero, meaning that the maxTrainingSize will be determined based on + the number of centroids, encoding types, and encoding parameters. */ + unsigned maxTrainingSize; + + /** The number of centroids that will be scanned during a query. + The default value is zero, meaning that the numProbes will be determined based on + the number of centroids. */ + unsigned numProbes; +} CBLVectorIndexConfiguration; + +#endif + +/** @} */ + +/** @} */ + +CBL_CAPI_END diff --git a/libcblite-3.0.3/include/cbl/CBLQueryTypes.h b/libcblite-3.0.3/include/cbl/CBLQueryTypes.h new file mode 100644 index 0000000..4082451 --- /dev/null +++ b/libcblite-3.0.3/include/cbl/CBLQueryTypes.h @@ -0,0 +1,35 @@ +// +// CBLQueryTypes.h +// +// Copyright (c) 2024 Couchbase, Inc All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#pragma once +#include "CBLBase.h" + +CBL_CAPI_BEGIN + +/** \defgroup queries Queries + @{ */ + +/** Supported Query languages */ +typedef CBL_ENUM(uint32_t, CBLQueryLanguage) { + kCBLJSONLanguage, ///< [JSON query schema](https://github.com/couchbase/couchbase-lite-core/wiki/JSON-Query-Schema) + kCBLN1QLLanguage ///< [N1QL syntax](https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/index.html) +}; + +/** @} */ + +CBL_CAPI_END diff --git a/libcblite-3.0.3/include/cbl/CBLReplicator.h b/libcblite-3.0.3/include/cbl/CBLReplicator.h index 8492550..bffcb64 100644 --- a/libcblite-3.0.3/include/cbl/CBLReplicator.h +++ b/libcblite-3.0.3/include/cbl/CBLReplicator.h @@ -343,7 +343,7 @@ typedef struct { unsigned maxAttempts; /** Max wait time between retry attempts in seconds. - The default value \ref kCBLDefaultReplicatorMaxAttemptWaitTime. */ + The default value \ref kCBLDefaultReplicatorMaxAttemptsWaitTime. */ unsigned maxAttemptWaitTime; //-- WebSocket: @@ -418,8 +418,11 @@ typedef struct { @warning Deprecated : Use documentPropertyDecryptor instead. */ CBLPropertyDecryptor _cbl_nullable propertyDecryptor; - CBLDocumentPropertyEncryptor _cbl_nullable documentPropertyEncryptor; ///< Optional callback to encrypt \ref CBLEncryptable values. - CBLDocumentPropertyDecryptor _cbl_nullable documentPropertyDecryptor; ///< Optional callback to decrypt encrypted \ref CBLEncryptable values. + /** Optional callback to encrypt \ref CBLEncryptable values. */ + CBLDocumentPropertyEncryptor _cbl_nullable documentPropertyEncryptor; + + /** Optional callback to decrypt encrypted \ref CBLEncryptable values. */ + CBLDocumentPropertyDecryptor _cbl_nullable documentPropertyDecryptor; #endif /** The collections to replicate with the target's endpoint (Required if the database is not set). */ @@ -459,6 +462,7 @@ CBLReplicator* _cbl_nullable CBLReplicator_Create(const CBLReplicatorConfigurati const CBLReplicatorConfiguration* CBLReplicator_Config(CBLReplicator*) CBLAPI; /** Starts a replicator, asynchronously. Does nothing if it's already started. + @note Replicators cannot be started from within a database's transaction. @param replicator The replicator instance. @param resetCheckpoint If true, the persistent saved state ("checkpoint") for this replication will be discarded, causing it to re-scan all documents. This significantly diff --git a/libcblite-3.0.3/include/cbl/CBLScope.h b/libcblite-3.0.3/include/cbl/CBLScope.h index d0b7c7d..10f9124 100644 --- a/libcblite-3.0.3/include/cbl/CBLScope.h +++ b/libcblite-3.0.3/include/cbl/CBLScope.h @@ -58,6 +58,12 @@ CBL_PUBLIC extern const FLString kCBLDefaultScopeName; @return The name of the scope. */ FLString CBLScope_Name(const CBLScope* scope) CBLAPI; +/** Returns the scope's database. + @note The database object is owned by the scope object; you do not need to release it. + @param scope The scope. + @return The database of the scope. */ +CBLDatabase* CBLScope_Database(const CBLScope* scope) CBLAPI; + /** @} */ /** \name Collections diff --git a/libcblite-3.0.3/include/cbl/CBL_Edition.h b/libcblite-3.0.3/include/cbl/CBL_Edition.h index ed2bf41..833d9b5 100644 --- a/libcblite-3.0.3/include/cbl/CBL_Edition.h +++ b/libcblite-3.0.3/include/cbl/CBL_Edition.h @@ -20,8 +20,8 @@ #define COUCHBASE_ENTERPRISE #endif -#define CBLITE_VERSION "3.1.10" -#define CBLITE_VERSION_NUMBER 3001010 -#define CBLITE_BUILD_NUMBER 52760 -#define CBLITE_SOURCE_ID "036da58+f7cfc38" -#define CBLITE_BUILD_TIMESTAMP "2024-09-30T21:11:23Z" +#define CBLITE_VERSION "3.2.1" +#define CBLITE_VERSION_NUMBER 3002001 +#define CBLITE_BUILD_NUMBER 9 +#define CBLITE_SOURCE_ID "6728898+e322f9b" +#define CBLITE_BUILD_TIMESTAMP "2024-10-30T14:17:35Z" diff --git a/libcblite-3.0.3/include/cbl/CouchbaseLite.h b/libcblite-3.0.3/include/cbl/CouchbaseLite.h index 80f2dd5..180e5fb 100644 --- a/libcblite-3.0.3/include/cbl/CouchbaseLite.h +++ b/libcblite-3.0.3/include/cbl/CouchbaseLite.h @@ -26,6 +26,10 @@ #include "CBLEncryptable.h" #include "CBLLog.h" #include "CBLPlatform.h" +#include "CBLPrediction.h" #include "CBLQuery.h" +#include "CBLQueryIndex.h" +#include "CBLQueryIndexTypes.h" +#include "CBLQueryTypes.h" #include "CBLReplicator.h" #include "CBLScope.h" diff --git a/libcblite-3.0.3/include/fleece/CompilerSupport.h b/libcblite-3.0.3/include/fleece/CompilerSupport.h index 8098543..382b19b 100644 --- a/libcblite-3.0.3/include/fleece/CompilerSupport.h +++ b/libcblite-3.0.3/include/fleece/CompilerSupport.h @@ -14,7 +14,7 @@ #ifndef _FLEECE_COMPILER_SUPPORT_H #define _FLEECE_COMPILER_SUPPORT_H -// The __has_xxx() macros are only(?) implemented by Clang. (Except GCC has __has_attribute...) +// The __has_xxx() macros are supported by [at least] Clang and GCC. // Define them to return 0 on other compilers. // https://clang.llvm.org/docs/AttributeReference.html // https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html @@ -36,24 +36,37 @@ #endif -#if defined(__clang__) || defined(__GNUC__) - // Tells the optimizer that a function's return value is never NULL. - #define RETURNS_NONNULL __attribute__((returns_nonnull)) +// Tells the optimizer that a function's return value is never NULL. +#if __has_attribute(returns_nonnull) +# define RETURNS_NONNULL __attribute__((returns_nonnull)) +#else +# define RETURNS_NONNULL +#endif - // Triggers a compile error if a call to the function ignores the returned value. - // Typically this is because the return value is something that must be released/freed. - #define MUST_USE_RESULT __attribute__((warn_unused_result)) +// deprecated; use NODISCARD instead +#if __has_attribute(returns_nonnull) +# define MUST_USE_RESULT __attribute__((warn_unused_result)) +#else +# define MUST_USE_RESULT +#endif - // These have no effect on behavior, but they hint to the optimizer which branch of an 'if' - // statement to make faster. - #define _usuallyTrue(VAL) __builtin_expect(VAL, true) - #define _usuallyFalse(VAL) __builtin_expect(VAL, false) +// NODISCARD expands to the C++17/C23 `[[nodiscard]]` attribute, or else MUST_USE_RESULT. +// (We can't just redefine MUST_USE_RESULT as `[[nodiscard]]` unfortunately, because the former is +// already in use in positions where `[[nodiscard]]` isn't valid, like at the end of a declaration.) +#if (__cplusplus >= 201700L) || (__STDC_VERSION__ >= 202000) +# define NODISCARD [[nodiscard]] #else - #define RETURNS_NONNULL - #define MUST_USE_RESULT +# define NODISCARD MUST_USE_RESULT +#endif - #define _usuallyTrue(VAL) (VAL) - #define _usuallyFalse(VAL) (VAL) +// These have no effect on behavior, but they hint to the optimizer which branch of an 'if' +// statement to make faster. +#if __has_builtin(__builtin_expect) +#define _usuallyTrue(VAL) __builtin_expect(VAL, true) +#define _usuallyFalse(VAL) __builtin_expect(VAL, false) +#else +#define _usuallyTrue(VAL) (VAL) +#define _usuallyFalse(VAL) (VAL) #endif @@ -83,10 +96,10 @@ // GCC also has an attribute with this name, but it's incompatible: it can't be applied to a // parameter, it has to come after the function and list parameters by number. Oh well. // TODO: Replace this with the better nullability annotations above. -#ifdef __clang__ - #define NONNULL __attribute__((nonnull)) +#if __has_attribute(nonnull) +# define NONNULL __attribute__((nonnull)) #else - #define NONNULL +# define NONNULL #endif @@ -104,10 +117,10 @@ // declared with the pure attribute can safely read any non-volatile objects, and modify the value // of objects in a way that does not affect their return value or the observable state of the // program." -- GCC manual -#if defined(__GNUC__) || __has_attribute(__pure__) - #define FLPURE __attribute__((__pure__)) +#if __has_attribute(__pure__) +# define FLPURE __attribute__((__pure__)) #else - #define FLPURE +# define FLPURE #endif // FLCONST is even stricter than FLPURE. The function cannot access memory at all (except for @@ -126,10 +139,10 @@ // "In general, since a function cannot distinguish data that might change from data that cannot, // const functions should never take pointer or, in C++, reference arguments. Likewise, a function // that calls a non-const function usually must not be const itself." -- GCC manual -#if defined(__GNUC__) || __has_attribute(__const__) - #define FLCONST __attribute__((__const__)) +#if __has_attribute(__const__) +# define FLCONST __attribute__((__const__)) #else - #define FLCONST +# define FLCONST #endif diff --git a/libcblite-3.0.3/include/fleece/Expert.hh b/libcblite-3.0.3/include/fleece/Expert.hh index 8350b67..14109b8 100644 --- a/libcblite-3.0.3/include/fleece/Expert.hh +++ b/libcblite-3.0.3/include/fleece/Expert.hh @@ -78,9 +78,11 @@ namespace fleece { static inline alloc_slice create(Value old, Value nuu); static inline bool create(Value old, Value nuu, Encoder &jsonEncoder); - static inline alloc_slice apply(Value old, - slice jsonDelta, - FLError* FL_NULLABLE error); + [[nodiscard]] static inline alloc_slice apply(Value old, + slice jsonDelta, + FLError* FL_NULLABLE error); + /// Writes patched Fleece to the Encoder. + /// On failure, returns false and sets the Encoder's error property. static inline bool apply(Value old, slice jsonDelta, Encoder &encoder); @@ -105,11 +107,12 @@ namespace fleece { static SharedKeys create() {return SharedKeys(FLSharedKeys_New(), 1);} static inline SharedKeys create(slice state); bool loadState(slice data) {return FLSharedKeys_LoadStateData(_sk, data);} - bool loadState(Value state) {return FLSharedKeys_LoadState(_sk, state);} + [[nodiscard]] bool loadState(Value state) {return FLSharedKeys_LoadState(_sk, state);} alloc_slice stateData() const {return FLSharedKeys_GetStateData(_sk);} inline void writeState(const Encoder &enc); unsigned count() const {return FLSharedKeys_Count(_sk);} void revertToCount(unsigned count) {FLSharedKeys_RevertToCount(_sk, count);} + void disableCaching() {if (_sk) FLSharedKeys_DisableCaching(_sk);} operator FLSharedKeys FL_NULLABLE () const {return _sk;} bool operator== (SharedKeys other) const {return _sk == other._sk;} diff --git a/libcblite-3.0.3/include/fleece/FLCollections.h b/libcblite-3.0.3/include/fleece/FLCollections.h index 3ed1822..146e94e 100644 --- a/libcblite-3.0.3/include/fleece/FLCollections.h +++ b/libcblite-3.0.3/include/fleece/FLCollections.h @@ -48,7 +48,7 @@ extern "C" { FLEECE_PUBLIC bool FLArray_IsEmpty(FLArray FL_NULLABLE) FLAPI FLPURE; /** If the array is mutable, returns it cast to FLMutableArray, else NULL. */ - FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLArray_AsMutable(FLArray FL_NULLABLE) FLAPI FLPURE; + NODISCARD FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLArray_AsMutable(FLArray FL_NULLABLE) FLAPI FLPURE; /** Returns an value at an array index, or NULL if the index is out of range. */ FLEECE_PUBLIC FLValue FL_NULLABLE FLArray_Get(FLArray FL_NULLABLE, uint32_t index) FLAPI FLPURE; @@ -80,10 +80,11 @@ while (NULL != (value = FLArrayIterator_GetValue(&iter))) { } FLArrayIterator; /** Initializes a FLArrayIterator struct to iterate over an array. - Call FLArrayIteratorGetValue to get the first item, then FLArrayIteratorNext. */ + Call FLArrayIteratorGetValue to get the first item, then as long as the item is not NULL, + call FLArrayIterator_Next to advance. */ FLEECE_PUBLIC void FLArrayIterator_Begin(FLArray FL_NULLABLE, FLArrayIterator*) FLAPI; - /** Returns the current value being iterated over. */ + /** Returns the current value being iterated over, or NULL at the end. */ FLEECE_PUBLIC FLValue FL_NULLABLE FLArrayIterator_GetValue(const FLArrayIterator*) FLAPI FLPURE; /** Returns a value in the array at the given offset from the current value. */ @@ -92,7 +93,9 @@ while (NULL != (value = FLArrayIterator_GetValue(&iter))) { /** Returns the number of items remaining to be iterated, including the current one. */ FLEECE_PUBLIC uint32_t FLArrayIterator_GetCount(const FLArrayIterator*) FLAPI FLPURE; - /** Advances the iterator to the next value, or returns false if at the end. */ + /** Advances the iterator to the next value. + @warning It is illegal to call this when the iterator is already at the end. + In particular, calling this when the array is empty is always illegal. */ FLEECE_PUBLIC bool FLArrayIterator_Next(FLArrayIterator*) FLAPI; /** @} */ @@ -153,22 +156,26 @@ while (NULL != (value = FLDictIterator_GetValue(&iter))) { /** Initializes a FLDictIterator struct to iterate over a dictionary. Call FLDictIterator_GetKey and FLDictIterator_GetValue to get the first item, - then FLDictIterator_Next. */ + then as long as the item is not NULL, call FLDictIterator_Next to advance. */ FLEECE_PUBLIC void FLDictIterator_Begin(FLDict FL_NULLABLE, FLDictIterator*) FLAPI; - /** Returns the current key being iterated over. This Value will be a string or an integer. */ + /** Returns the current key being iterated over. + This Value will be a string or an integer, or NULL when there are no more keys. */ FLEECE_PUBLIC FLValue FL_NULLABLE FLDictIterator_GetKey(const FLDictIterator*) FLAPI FLPURE; - /** Returns the current key's string value. */ + /** Returns the current key's string value, or NULL when there are no more keys. */ FLEECE_PUBLIC FLString FLDictIterator_GetKeyString(const FLDictIterator*) FLAPI; - /** Returns the current value being iterated over. */ + /** Returns the current value being iterated over. + Returns NULL when there are no more values. */ FLEECE_PUBLIC FLValue FL_NULLABLE FLDictIterator_GetValue(const FLDictIterator*) FLAPI FLPURE; /** Returns the number of items remaining to be iterated, including the current one. */ FLEECE_PUBLIC uint32_t FLDictIterator_GetCount(const FLDictIterator*) FLAPI FLPURE; - /** Advances the iterator to the next value, or returns false if at the end. */ + /** Advances the iterator to the next value. + @warning It is illegal to call this when the iterator is already at the end. + In particular, calling this when the dict is empty is always illegal. */ FLEECE_PUBLIC bool FLDictIterator_Next(FLDictIterator*) FLAPI; /** Cleans up after an iterator. Only needed if (a) the dictionary is a delta, and diff --git a/libcblite-3.0.3/include/fleece/FLDoc.h b/libcblite-3.0.3/include/fleece/FLDoc.h index 2292ec0..b62d8f3 100644 --- a/libcblite-3.0.3/include/fleece/FLDoc.h +++ b/libcblite-3.0.3/include/fleece/FLDoc.h @@ -37,7 +37,7 @@ extern "C" { /** Creates an FLDoc from Fleece-encoded data that's been returned as a result from FLSlice_Copy or other API. The resulting document retains the data, so you don't need to worry about it remaining valid. */ - FLEECE_PUBLIC FLDoc FLDoc_FromResultData(FLSliceResult data, FLTrust, + NODISCARD FLEECE_PUBLIC FLDoc FLDoc_FromResultData(FLSliceResult data, FLTrust, FLSharedKeys FL_NULLABLE, FLSlice externData) FLAPI; /** Releases a reference to an FLDoc. This must be called once to free an FLDoc you created. */ @@ -61,7 +61,7 @@ extern "C" { /** Looks up the Doc containing the Value, or NULL if there is none. @note Caller must release the FLDoc reference!! */ - FLEECE_PUBLIC FLDoc FL_NULLABLE FLValue_FindDoc(FLValue FL_NULLABLE) FLAPI FLPURE; + NODISCARD FLEECE_PUBLIC FLDoc FL_NULLABLE FLValue_FindDoc(FLValue FL_NULLABLE) FLAPI FLPURE; /** Associates an arbitrary pointer value with a document, and thus its contained values. Allows client code to associate its own pointer with this FLDoc and its Values, diff --git a/libcblite-3.0.3/include/fleece/FLEncoder.h b/libcblite-3.0.3/include/fleece/FLEncoder.h index f3fefc6..b92d17d 100644 --- a/libcblite-3.0.3/include/fleece/FLEncoder.h +++ b/libcblite-3.0.3/include/fleece/FLEncoder.h @@ -48,7 +48,7 @@ extern "C" { /** Creates a new encoder, for generating Fleece data. Call FLEncoder_Free when done. */ - FLEECE_PUBLIC FLEncoder FLEncoder_New(void) FLAPI; + NODISCARD FLEECE_PUBLIC FLEncoder FLEncoder_New(void) FLAPI; /** Creates a new encoder, allowing some options to be customized. @param format The output format to generate (Fleece, JSON, or JSON5.) @@ -57,12 +57,12 @@ extern "C" { as a single shared value. This saves space but makes encoding slightly slower. You should only turn this off if you know you're going to be writing large numbers of non-repeated strings. (Default is true) */ - FLEECE_PUBLIC FLEncoder FLEncoder_NewWithOptions(FLEncoderFormat format, + NODISCARD FLEECE_PUBLIC FLEncoder FLEncoder_NewWithOptions(FLEncoderFormat format, size_t reserveSize, bool uniqueStrings) FLAPI; /** Creates a new Fleece encoder that writes to a file, not to memory. */ - FLEECE_PUBLIC FLEncoder FLEncoder_NewWritingToFile(FILE*, bool uniqueStrings) FLAPI; + NODISCARD FLEECE_PUBLIC FLEncoder FLEncoder_NewWritingToFile(FILE*, bool uniqueStrings) FLAPI; /** Frees the space used by an encoder. */ FLEECE_PUBLIC void FLEncoder_Free(FLEncoder FL_NULLABLE) FLAPI; @@ -201,12 +201,12 @@ extern "C" { /** Ends encoding; if there has been no error, it returns the encoded Fleece data packaged in an FLDoc. (This function does not support JSON encoding.) This does not free the FLEncoder; call FLEncoder_Free (or FLEncoder_Reset) next. */ - MUST_USE_RESULT + NODISCARD FLEECE_PUBLIC FLDoc FL_NULLABLE FLEncoder_FinishDoc(FLEncoder, FLError* FL_NULLABLE outError) FLAPI; /** Ends encoding; if there has been no error, it returns the encoded data, else null. This does not free the FLEncoder; call FLEncoder_Free (or FLEncoder_Reset) next. */ - MUST_USE_RESULT + NODISCARD FLEECE_PUBLIC FLSliceResult FLEncoder_Finish(FLEncoder, FLError* FL_NULLABLE outError) FLAPI; /** @} */ diff --git a/libcblite-3.0.3/include/fleece/FLExpert.h b/libcblite-3.0.3/include/fleece/FLExpert.h index 00d8c97..5536f2c 100644 --- a/libcblite-3.0.3/include/fleece/FLExpert.h +++ b/libcblite-3.0.3/include/fleece/FLExpert.h @@ -31,6 +31,12 @@ extern "C" { /** \defgroup Obscure Rarely-needed or advanced functions @{ */ + /** For use with \ref FLDoc_FromResultData. This option prevents the function from parsing the + data at all; you are responsible for locating the FLValues in it. + This is for the case where you have trusted data in a custom format that contains Fleece- + encoded data within it. You still need an FLDoc to access the data safely (especially to + retain FLValues), but it can't be parsed as-is. */ + #define kFLTrustedDontParse FLTrust(-1) /** \name Delta Compression @{ @@ -48,7 +54,7 @@ extern "C" { @param nuu A value that's typically the new/changed state of the `old` data. @return JSON data representing the changes from `old` to `nuu`, or NULL on (extremely unlikely) failure. */ - FLEECE_PUBLIC FLSliceResult FLCreateJSONDelta(FLValue FL_NULLABLE old, + NODISCARD FLEECE_PUBLIC FLSliceResult FLCreateJSONDelta(FLValue FL_NULLABLE old, FLValue FL_NULLABLE nuu) FLAPI; /** Writes JSON that describes the changes to turn the value `old` into `nuu`. @@ -58,7 +64,7 @@ extern "C" { @param jsonEncoder An encoder to write the JSON to. Must have been created using `FLEncoder_NewWithOptions`, with JSON or JSON5 format. @return True on success, false on (extremely unlikely) failure. */ - FLEECE_PUBLIC bool FLEncodeJSONDelta(FLValue FL_NULLABLE old, + NODISCARD FLEECE_PUBLIC bool FLEncodeJSONDelta(FLValue FL_NULLABLE old, FLValue FL_NULLABLE nuu, FLEncoder jsonEncoder) FLAPI; @@ -71,7 +77,7 @@ extern "C" { @param jsonDelta A JSON-encoded delta created by `FLCreateJSONDelta` or `FLEncodeJSONDelta`. @param outError On failure, error information will be stored where this points, if non-null. @return The corresponding `nuu` value, encoded as Fleece, or null if an error occurred. */ - FLEECE_PUBLIC FLSliceResult FLApplyJSONDelta(FLValue FL_NULLABLE old, + NODISCARD FLEECE_PUBLIC FLSliceResult FLApplyJSONDelta(FLValue FL_NULLABLE old, FLSlice jsonDelta, FLError* FL_NULLABLE outError) FLAPI; @@ -110,17 +116,18 @@ extern "C" { */ /** Creates a new empty FLSharedKeys object, which must eventually be released. */ - FLEECE_PUBLIC FLSharedKeys FLSharedKeys_New(void) FLAPI; + NODISCARD FLEECE_PUBLIC FLSharedKeys FLSharedKeys_New(void) FLAPI; typedef bool (*FLSharedKeysReadCallback)(void* FL_NULLABLE context, FLSharedKeys); - FLEECE_PUBLIC FLSharedKeys FLSharedKeys_NewWithRead(FLSharedKeysReadCallback, + NODISCARD FLEECE_PUBLIC FLSharedKeys FLSharedKeys_NewWithRead(FLSharedKeysReadCallback, void* FL_NULLABLE context) FLAPI; /** Returns a data blob containing the current state (all the keys and their integers.) */ - FLEECE_PUBLIC FLSliceResult FLSharedKeys_GetStateData(FLSharedKeys) FLAPI; + NODISCARD FLEECE_PUBLIC FLSliceResult FLSharedKeys_GetStateData(FLSharedKeys) FLAPI; - /** Updates an FLSharedKeys with saved state data created by \ref FLSharedKeys_GetStateData. */ + /** Updates an FLSharedKeys with saved state data created by \ref FLSharedKeys_GetStateData. + Returns true if new keys were added, false if not. */ FLEECE_PUBLIC bool FLSharedKeys_LoadStateData(FLSharedKeys, FLSlice) FLAPI; /** Writes the current state to a Fleece encoder as a single value, @@ -129,7 +136,7 @@ extern "C" { /** Updates an FLSharedKeys object with saved state, a Fleece value previously written by \ref FLSharedKeys_WriteState. */ - FLEECE_PUBLIC bool FLSharedKeys_LoadState(FLSharedKeys, FLValue) FLAPI; + NODISCARD FLEECE_PUBLIC bool FLSharedKeys_LoadState(FLSharedKeys, FLValue) FLAPI; /** Maps a key string to a number in the range [0...2047], or returns -1 if it isn't mapped. If the key doesn't already have a mapping, and the `add` flag is true, @@ -148,8 +155,11 @@ extern "C" { /** Reverts an FLSharedKeys by "forgetting" any keys added since it had the count `oldCount`. */ FLEECE_PUBLIC void FLSharedKeys_RevertToCount(FLSharedKeys, unsigned oldCount) FLAPI; + /** Disable caching of the SharedKeys.. */ + FLEECE_PUBLIC void FLSharedKeys_DisableCaching(FLSharedKeys) FLAPI; + /** Increments the reference count of an FLSharedKeys. */ - FLEECE_PUBLIC FLSharedKeys FL_NULLABLE FLSharedKeys_Retain(FLSharedKeys FL_NULLABLE) FLAPI; + NODISCARD FLEECE_PUBLIC FLSharedKeys FL_NULLABLE FLSharedKeys_Retain(FLSharedKeys FL_NULLABLE) FLAPI; /** Decrements the reference count of an FLSharedKeys, freeing it when it reaches zero. */ FLEECE_PUBLIC void FLSharedKeys_Release(FLSharedKeys FL_NULLABLE) FLAPI; @@ -159,7 +169,7 @@ extern "C" { /** Registers a range of memory containing Fleece data that uses the given shared keys. This allows Dict accessors to look up the values of shared keys. */ - FLEECE_PUBLIC FLSharedKeyScope FLSharedKeyScope_WithRange(FLSlice range, FLSharedKeys) FLAPI; + NODISCARD FLEECE_PUBLIC FLSharedKeyScope FLSharedKeyScope_WithRange(FLSlice range, FLSharedKeys) FLAPI; /** Unregisters a scope created by \ref FLSharedKeyScope_WithRange. */ FLEECE_PUBLIC void FLSharedKeyScope_Free(FLSharedKeyScope FL_NULLABLE) FLAPI; @@ -203,14 +213,14 @@ extern "C" { will be stored here (if it's not NULL.) @param outError On failure, the error code will be stored here (if it's not NULL.) @return The converted JSON. */ - FLEECE_PUBLIC FLStringResult FLJSON5_ToJSON(FLString json5, + NODISCARD FLEECE_PUBLIC FLStringResult FLJSON5_ToJSON(FLString json5, FLStringResult* FL_NULLABLE outErrorMessage, size_t* FL_NULLABLE outErrorPos, FLError* FL_NULLABLE outError) FLAPI; /** Directly converts JSON data to Fleece-encoded data. Not commonly needed. Prefer \ref FLDoc_FromJSON instead. */ - FLEECE_PUBLIC FLSliceResult FLData_ConvertJSON(FLSlice json, FLError* FL_NULLABLE outError) FLAPI; + NODISCARD FLEECE_PUBLIC FLSliceResult FLData_ConvertJSON(FLSlice json, FLError* FL_NULLABLE outError) FLAPI; /** @} */ @@ -246,24 +256,28 @@ extern "C" { (Due to internal buffering, this is not the same as FLEncoder_BytesWritten.) */ FLEECE_PUBLIC size_t FLEncoder_GetNextWritePos(FLEncoder) FLAPI; + #define kFLNoWrittenValue INTPTR_MIN + /** Returns an opaque reference to the last complete value written to the encoder, if possible. - Fails (returning 0) if nothing has been written, or if the value is inline and can't be - referenced this way -- that only happens with small scalars or empty collections. */ + Fails (returning kFLNoWrittenValue) if nothing has been written, or if the value is inline + and can't be referenced this way -- that only happens with small scalars or empty + collections. */ FLEECE_PUBLIC intptr_t FLEncoder_LastValueWritten(FLEncoder) FLAPI; /** Writes another reference (a "pointer") to an already-written value, given a reference previously returned from \ref FLEncoder_LastValueWritten. The effect is exactly the same as if you wrote the - entire value again, except that the size of the encoded data only grows by 4 bytes. */ - FLEECE_PUBLIC void FLEncoder_WriteValueAgain(FLEncoder, intptr_t preWrittenValue) FLAPI; + entire value again, except that the size of the encoded data only grows by 4 bytes. + Returns false if the reference couldn't be written. */ + FLEECE_PUBLIC bool FLEncoder_WriteValueAgain(FLEncoder, intptr_t preWrittenValue) FLAPI; /** Returns the data written so far as a standalone Fleece document, whose root is the last value written. You can continue writing, and the final output returned by \ref FLEncoder_Finish will consist of everything after this point. That second part can be used in the future by loading it as an `FLDoc` with the first part as its `extern` reference. */ - FLEECE_PUBLIC FLSliceResult FLEncoder_Snip(FLEncoder) FLAPI; + NODISCARD FLEECE_PUBLIC FLSliceResult FLEncoder_Snip(FLEncoder) FLAPI; /** Finishes encoding the current item, and returns its offset in the output data. */ - FLEECE_PUBLIC size_t FLEncoder_FinishItem(FLEncoder) FLAPI; + NODISCARD FLEECE_PUBLIC size_t FLEncoder_FinishItem(FLEncoder) FLAPI; /** In a JSON encoder, adds a newline ('\n') and prepares to start encoding another top-level object. The encoder MUST be not be within an array or dict. diff --git a/libcblite-3.0.3/include/fleece/FLJSON.h b/libcblite-3.0.3/include/fleece/FLJSON.h index 91e7d52..67c5e93 100644 --- a/libcblite-3.0.3/include/fleece/FLJSON.h +++ b/libcblite-3.0.3/include/fleece/FLJSON.h @@ -59,15 +59,15 @@ extern "C" { /** Creates an FLDoc from JSON-encoded data. The data is first encoded into Fleece, and the Fleece data is kept by the doc; the input JSON data is no longer needed after this function returns. */ - FLEECE_PUBLIC FLDoc FLDoc_FromJSON(FLSlice json, FLError* FL_NULLABLE outError) FLAPI; + NODISCARD FLEECE_PUBLIC FLDoc FLDoc_FromJSON(FLSlice json, FLError* FL_NULLABLE outError) FLAPI; /** Creates a new mutable Array from JSON. It is an error if the JSON is not an array. Its initial ref-count is 1, so a call to FLMutableArray_Release will free it. */ - FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLMutableArray_NewFromJSON(FLString json, FLError* FL_NULLABLE outError) FLAPI; + NODISCARD FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLMutableArray_NewFromJSON(FLString json, FLError* FL_NULLABLE outError) FLAPI; /** Creates a new mutable Dict from json. It is an error if the JSON is not a dictionary/object. Its initial ref-count is 1, so a call to FLMutableDict_Release will free it. */ - FLEECE_PUBLIC FLMutableDict FL_NULLABLE FLMutableDict_NewFromJSON(FLString json, FLError* FL_NULLABLE outError) FLAPI; + NODISCARD FLEECE_PUBLIC FLMutableDict FL_NULLABLE FLMutableDict_NewFromJSON(FLString json, FLError* FL_NULLABLE outError) FLAPI; /** Parses JSON data and writes the value(s) to the encoder as their Fleece equivalents. (This acts as a single write, like WriteInt; it's just that the value written is likely to diff --git a/libcblite-3.0.3/include/fleece/FLKeyPath.h b/libcblite-3.0.3/include/fleece/FLKeyPath.h index 84fb3cf..cd91877 100644 --- a/libcblite-3.0.3/include/fleece/FLKeyPath.h +++ b/libcblite-3.0.3/include/fleece/FLKeyPath.h @@ -37,8 +37,7 @@ extern "C" { A leading JSONPath-like `$.` is allowed but ignored. - A '\' can be used to escape a special character ('.', '[' or '$') at the start of a - property name (but not yet in the middle of a name.) + A '\' can be used to escape a special character ('.', '[' or '$'). */ #ifndef FL_IMPL @@ -46,24 +45,24 @@ extern "C" { #endif /** Creates a new FLKeyPath object by compiling a path specifier string. */ - FLEECE_PUBLIC FLKeyPath FL_NULLABLE FLKeyPath_New(FLSlice specifier, + NODISCARD FLEECE_PUBLIC FLKeyPath FL_NULLABLE FLKeyPath_New(FLSlice specifier, FLError* FL_NULLABLE outError) FLAPI; /** Frees a compiled FLKeyPath object. (It's ok to pass NULL.) */ FLEECE_PUBLIC void FLKeyPath_Free(FLKeyPath FL_NULLABLE) FLAPI; /** Evaluates a compiled key-path for a given Fleece root object. */ - FLEECE_PUBLIC FLValue FL_NULLABLE FLKeyPath_Eval(FLKeyPath, + NODISCARD FLEECE_PUBLIC FLValue FL_NULLABLE FLKeyPath_Eval(FLKeyPath, FLValue root) FLAPI; /** Evaluates a key-path from a specifier string, for a given Fleece root object. If you only need to evaluate the path once, this is a bit faster than creating an FLKeyPath object, evaluating, then freeing it. */ - FLEECE_PUBLIC FLValue FL_NULLABLE FLKeyPath_EvalOnce(FLSlice specifier, FLValue root, + NODISCARD FLEECE_PUBLIC FLValue FL_NULLABLE FLKeyPath_EvalOnce(FLSlice specifier, FLValue root, FLError* FL_NULLABLE outError) FLAPI; /** Returns a path in string form. */ - FLEECE_PUBLIC FLStringResult FLKeyPath_ToString(FLKeyPath path) FLAPI; + NODISCARD FLEECE_PUBLIC FLStringResult FLKeyPath_ToString(FLKeyPath path) FLAPI; /** Equality test. */ FLEECE_PUBLIC bool FLKeyPath_Equals(FLKeyPath path1, FLKeyPath path2) FLAPI; diff --git a/libcblite-3.0.3/include/fleece/FLMutable.h b/libcblite-3.0.3/include/fleece/FLMutable.h index 58971c1..d2f1d93 100644 --- a/libcblite-3.0.3/include/fleece/FLMutable.h +++ b/libcblite-3.0.3/include/fleece/FLMutable.h @@ -55,12 +55,12 @@ extern "C" { also set, immutable values are also copied, recursively. If the source Array is NULL, then NULL is returned. */ - FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLArray_MutableCopy(FLArray FL_NULLABLE, + NODISCARD FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLArray_MutableCopy(FLArray FL_NULLABLE, FLCopyFlags) FLAPI; /** Creates a new empty mutable Array. Its initial ref-count is 1, so a call to FLMutableArray_Release will free it. */ - FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLMutableArray_New(void) FLAPI; + NODISCARD FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLMutableArray_New(void) FLAPI; /** Increments the ref-count of a mutable Array. */ static inline FLMutableArray FL_NULLABLE FLMutableArray_Retain(FLMutableArray FL_NULLABLE d) { @@ -108,7 +108,7 @@ extern "C" { - If the value is a mutable array, returns it. - If the value is an immutable array, this function makes a mutable copy, assigns the copy as the property value, and returns the copy. */ - FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLMutableArray_GetMutableArray(FLMutableArray FL_NULLABLE, + NODISCARD FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLMutableArray_GetMutableArray(FLMutableArray FL_NULLABLE, uint32_t index) FLAPI; /** Convenience function for getting an array-valued property in mutable form. @@ -116,7 +116,7 @@ extern "C" { - If the value is a mutable array, returns it. - If the value is an immutable array, this function makes a mutable copy, assigns the copy as the property value, and returns the copy. */ - FLEECE_PUBLIC FLMutableDict FL_NULLABLE FLMutableArray_GetMutableDict(FLMutableArray FL_NULLABLE, + NODISCARD FLEECE_PUBLIC FLMutableDict FL_NULLABLE FLMutableArray_GetMutableDict(FLMutableArray FL_NULLABLE, uint32_t index) FLAPI; @@ -303,21 +303,21 @@ extern "C" { You store a value to it by calling one of the nine `FLSlot_Set...` functions. \warning You should immediately store a value into the `FLSlot`. Do not keep it around; any changes to the array invalidate it.*/ - MUST_USE_RESULT + NODISCARD FLEECE_PUBLIC FLSlot FLMutableArray_Set(FLMutableArray, uint32_t index) FLAPI; /** Appends a null value to the array and returns an \ref FLSlot that refers to that position. You store a value to it by calling one of the nine `FLSlot_Set...` functions. \warning You should immediately store a value into the `FLSlot`. Do not keep it around; any changes to the array invalidate it.*/ - MUST_USE_RESULT + NODISCARD FLEECE_PUBLIC FLSlot FLMutableArray_Append(FLMutableArray) FLAPI; /** Returns an \ref FLSlot that refers to the given key/value pair of the given dictionary. You store a value to it by calling one of the nine `FLSlot_Set...` functions. \warning You should immediately store a value into the `FLSlot`. Do not keep it around; any changes to the dictionary invalidate it.*/ - MUST_USE_RESULT + NODISCARD FLEECE_PUBLIC FLSlot FLMutableDict_Set(FLMutableDict, FLString key) FLAPI; diff --git a/libcblite-3.0.3/include/fleece/FLSlice.h b/libcblite-3.0.3/include/fleece/FLSlice.h index 7ac3d9a..04e9720 100644 --- a/libcblite-3.0.3/include/fleece/FLSlice.h +++ b/libcblite-3.0.3/include/fleece/FLSlice.h @@ -60,7 +60,7 @@ typedef struct FLSlice { a `FLSliceResult` return value is to construct an `alloc_slice` from it, which will adopt the reference, and release it in its destructor. For example: `alloc_slice foo( CopyFoo() );` */ -typedef struct FLSliceResult { +struct NODISCARD FLSliceResult { const void* FL_NULLABLE buf; size_t size; @@ -69,7 +69,8 @@ typedef struct FLSliceResult { explicit operator FLSlice () const {return {buf, size};} inline explicit operator std::string() const; #endif -} FLSliceResult; +}; +typedef struct FLSliceResult FLSliceResult; /** A heap-allocated, reference-counted slice. This type is really just a hint in an API diff --git a/libcblite-3.0.3/include/fleece/Fleece+CoreFoundation.h b/libcblite-3.0.3/include/fleece/Fleece+CoreFoundation.h index d4a4214..216c47b 100644 --- a/libcblite-3.0.3/include/fleece/Fleece+CoreFoundation.h +++ b/libcblite-3.0.3/include/fleece/Fleece+CoreFoundation.h @@ -29,16 +29,16 @@ extern "C" { /** Writes a Core Foundation (or Objective-C) object to an Encoder. Supports all the JSON types, as well as CFData. */ - FLEECE_PUBLIC bool FLEncoder_WriteCFObject(FLEncoder, CFTypeRef) FLAPI; + NODISCARD FLEECE_PUBLIC bool FLEncoder_WriteCFObject(FLEncoder, CFTypeRef) FLAPI; /** Returns a Value as a corresponding CoreFoundation object. Caller must CFRelease the result. */ - FLEECE_PUBLIC CFTypeRef FLValue_CopyCFObject(FLValue FL_NULLABLE) FLAPI; + NODISCARD FLEECE_PUBLIC CFTypeRef FLValue_CopyCFObject(FLValue FL_NULLABLE) FLAPI; /** Same as FLDictGet, but takes the key as a CFStringRef. */ - FLEECE_PUBLIC FLValue FLDict_GetWithCFString(FLDict FL_NULLABLE, CFStringRef) FLAPI; + NODISCARD FLEECE_PUBLIC FLValue FLDict_GetWithCFString(FLDict FL_NULLABLE, CFStringRef) FLAPI; #ifdef __OBJC__ diff --git a/libcblite-3.0.3/include/fleece/Fleece.hh b/libcblite-3.0.3/include/fleece/Fleece.hh index b024464..5a0cffd 100644 --- a/libcblite-3.0.3/include/fleece/Fleece.hh +++ b/libcblite-3.0.3/include/fleece/Fleece.hh @@ -121,7 +121,7 @@ namespace fleece { static Array emptyArray() {return Array(kFLEmptyArray);} inline uint32_t count() const; - inline bool empty() const; + [[nodiscard]] inline bool empty() const; inline Value get(uint32_t index) const; inline Value operator[] (int index) const {return get(index);} @@ -131,9 +131,9 @@ namespace fleece { Array& operator= (std::nullptr_t) {_val = nullptr; return *this;} Value& operator= (Value v) =delete; - inline MutableArray asMutable() const; + [[nodiscard]] inline MutableArray asMutable() const; - inline MutableArray mutableCopy(FLCopyFlags =kFLDefaultCopy) const; + [[nodiscard]] inline MutableArray mutableCopy(FLCopyFlags =kFLDefaultCopy) const; class iterator : private FLArrayIterator { @@ -175,7 +175,7 @@ namespace fleece { static Dict emptyDict() {return Dict(kFLEmptyDict);} inline uint32_t count() const; - inline bool empty() const; + [[nodiscard]] inline bool empty() const; inline Value get(slice_NONNULL key) const; @@ -189,9 +189,9 @@ namespace fleece { Dict& operator= (std::nullptr_t) {_val = nullptr; return *this;} Value& operator= (Value v) =delete; - inline MutableDict asMutable() const; + [[nodiscard]] inline MutableDict asMutable() const; - inline MutableDict mutableCopy(FLCopyFlags =kFLDefaultCopy) const; + [[nodiscard]] inline MutableDict mutableCopy(FLCopyFlags =kFLDefaultCopy) const; /** An efficient key for a Dict. */ class Key { @@ -437,8 +437,8 @@ namespace fleece { template inline void write(slice_NONNULL key, T value) {writeKey(key); *this << value;} - inline Doc finishDoc(FLError* FL_NULLABLE =nullptr); - inline alloc_slice finish(FLError* FL_NULLABLE =nullptr); + [[nodiscard]] inline Doc finishDoc(FLError* FL_NULLABLE =nullptr); + [[nodiscard]] inline alloc_slice finish(FLError* FL_NULLABLE =nullptr); inline void reset(); inline FLError error() const; diff --git a/libcblite-3.0.3/include/fleece/Mutable.hh b/libcblite-3.0.3/include/fleece/Mutable.hh index 1fb285c..036aa55 100644 --- a/libcblite-3.0.3/include/fleece/Mutable.hh +++ b/libcblite-3.0.3/include/fleece/Mutable.hh @@ -22,7 +22,7 @@ namespace fleece { // (this is a mostly-internal type that acts as a reference to an item of a MutableArray or // MutableDict, and allows a value to be stored in it. It decouples dereferencing the collection // from setting the value, which simplifies the code.) - class Slot { + class [[nodiscard]] Slot { public: void setNull() {FLSlot_SetNull(_slot);} void operator= (Null) {FLSlot_SetNull(_slot);} @@ -60,7 +60,7 @@ namespace fleece { // (this is an internal type used to make `MutableArray` and `MutableDict`'s `operator[]` // act idiomatically, supporting assignment. It's not used directly.) template - class keyref : public Value { + class [[nodiscard]] keyref : public Value { public: keyref(Collection &coll, Key key) :Value(coll.get(key)), _coll(coll), _key(key) { } template diff --git a/libcblite-3.0.3/include/fleece/PlatformCompat.hh b/libcblite-3.0.3/include/fleece/PlatformCompat.hh index 38874ea..477f9f6 100644 --- a/libcblite-3.0.3/include/fleece/PlatformCompat.hh +++ b/libcblite-3.0.3/include/fleece/PlatformCompat.hh @@ -41,14 +41,16 @@ #else // Suppresses "unused function" warnings - #ifdef __APPLE__ - #define LITECORE_UNUSED __unused - #else - #define LITECORE_UNUSED __attribute__((unused)) + #if __has_attribute(unused) + # define LITECORE_UNUSED __attribute__((unused)) #endif // Disables inlining a function. Use when the space savings are worth more than speed. - #define NOINLINE __attribute((noinline)) + #if __has_attribute(noinline) + # define NOINLINE __attribute((noinline)) + #else + # define NOINLINE + #endif // Forces function to be inlined. Use with care for speed-critical code. #if __has_attribute(always_inline) @@ -69,8 +71,9 @@ // Declares this function takes a printf-like format string, and the subsequent args should // be type-checked against it. - #ifndef __printflike - #define __printflike(fmtarg, firstvararg) __attribute__((__format__ (__printf__, fmtarg, firstvararg))) + #if __has_attribute(__format__) && !defined(__printflike) + # define __printflike(fmtarg, firstvararg) \ + __attribute__((__format__ (__printf__, fmtarg, firstvararg))) #endif // Windows has underscore prefixes before these function names, so define a common name diff --git a/libcblite-3.0.3/include/fleece/RefCounted.hh b/libcblite-3.0.3/include/fleece/RefCounted.hh index 635fb39..a719575 100644 --- a/libcblite-3.0.3/include/fleece/RefCounted.hh +++ b/libcblite-3.0.3/include/fleece/RefCounted.hh @@ -147,6 +147,7 @@ namespace fleece { /// Converts a Retained into a raw pointer with a +1 reference that must be released. /// Used in C++ functions that bridge to C and return C references. + [[nodiscard]] T* detach() && noexcept {auto r = _ref; _ref = nullptr; return r;} // The operator below is often a dangerous mistake, so it's deliberately made impossible. @@ -228,6 +229,7 @@ namespace fleece { return *this; } + [[nodiscard]] const T* detach() && noexcept {auto r = _ref; _ref = nullptr; return r;} operator const T* () const && =delete; // Usually a mistake; see above under Retained @@ -239,13 +241,13 @@ namespace fleece { /** Easy instantiation of a ref-counted object: `auto f = retained(new Foo());`*/ template - inline Retained retained(REFCOUNTED *r) noexcept { + [[nodiscard]] inline Retained retained(REFCOUNTED *r) noexcept { return Retained(r); } /** Easy instantiation of a const ref-counted object: `auto f = retained(new Foo());`*/ template - inline RetainedConst retained(const REFCOUNTED *r) noexcept { + [[nodiscard]] inline RetainedConst retained(const REFCOUNTED *r) noexcept { return RetainedConst(r); } @@ -253,7 +255,7 @@ namespace fleece { This has no effect on the object's ref-count; the existing +1 ref will be released when the Retained destructs. */ template - inline Retained adopt(REFCOUNTED *r) noexcept { + [[nodiscard]] inline Retained adopt(REFCOUNTED *r) noexcept { return Retained(r, false); } @@ -262,7 +264,7 @@ namespace fleece { /** make_retained(...) is equivalent to `std::make_unique` and `std::make_shared`. It constructs a new RefCounted object, passing params to the constructor, returning a `Retained`. */ template - static inline Retained + [[nodiscard]] static inline Retained make_retained(_Args&&... __args) { return Retained(new T(std::forward<_Args>(__args)...)); } @@ -271,13 +273,14 @@ namespace fleece { /** Extracts the pointer from a Retained. It must later be released via `release`. This is used in bridging functions that return a direct pointer for a C API. */ template - ALWAYS_INLINE REFCOUNTED* retain(Retained &&retained) noexcept { + [[nodiscard]] ALWAYS_INLINE REFCOUNTED* retain(Retained &&retained) noexcept { return std::move(retained).detach(); } /** Extracts the pointer from a RetainedConst. It must later be released via `release`. This is used in bridging functions that return a direct pointer for a C API. */ template + [[nodiscard]] ALWAYS_INLINE const REFCOUNTED* retain(RetainedConst &&retained) noexcept { return std::move(retained).detach(); } diff --git a/libcblite-3.0.3/include/fleece/slice.hh b/libcblite-3.0.3/include/fleece/slice.hh index 3e3797d..88d5d5c 100644 --- a/libcblite-3.0.3/include/fleece/slice.hh +++ b/libcblite-3.0.3/include/fleece/slice.hh @@ -84,12 +84,12 @@ namespace fleece { } /** Subtracts the 2nd pointer from the 1st, returning the difference in addresses. */ - constexpr inline ptrdiff_t _pointerDiff(const void* FL_NULLABLE a, const void* FL_NULLABLE b) noexcept { + FLCONST constexpr inline ptrdiff_t _pointerDiff(const void* FL_NULLABLE a, const void* FL_NULLABLE b) noexcept { return (uint8_t*)a - (uint8_t*)b; } /** Subtracts the 2nd pointer from the 1st, returning the difference in addresses. */ - constexpr inline ptrdiff_t pointerDiff(const void* a, const void* b) noexcept { + FLCONST constexpr inline ptrdiff_t pointerDiff(const void* a, const void* b) noexcept { return _pointerDiff(a, b); } @@ -342,7 +342,7 @@ namespace fleece { #pragma mark - ALLOC_SLICE: /** A \ref slice that owns a heap-allocated, ref-counted block of memory. */ - struct alloc_slice : public pure_slice { + struct [[nodiscard]] alloc_slice : public pure_slice { constexpr alloc_slice() noexcept STEPOVER {} constexpr alloc_slice(std::nullptr_t) noexcept STEPOVER {} constexpr alloc_slice(nullslice_t) noexcept STEPOVER {} @@ -418,7 +418,7 @@ namespace fleece { explicit alloc_slice(CFStringRef FL_NULLABLE); /** Creates a CFDataDataRef. The data is not copied: the CFDataRef points to the same bytes as this alloc_slice, which is retained until the CFDataRef is freed. */ - CFDataRef createCFData() const; + [[nodiscard]] CFDataRef createCFData() const; # ifdef __OBJC__ explicit alloc_slice(NSData* FL_NULLABLE data); /** Creates an NSData using initWithBytesNoCopy and a deallocator that releases this diff --git a/libcblite-3.0.3/lib/.DS_Store b/libcblite-3.0.3/lib/.DS_Store index d35da3c..97a94cc 100644 Binary files a/libcblite-3.0.3/lib/.DS_Store and b/libcblite-3.0.3/lib/.DS_Store differ diff --git a/libcblite-3.0.3/lib/aarch64-linux-android/libcblite.so b/libcblite-3.0.3/lib/aarch64-linux-android/libcblite.so index 397be82..ce78937 100644 Binary files a/libcblite-3.0.3/lib/aarch64-linux-android/libcblite.so and b/libcblite-3.0.3/lib/aarch64-linux-android/libcblite.so differ diff --git a/libcblite-3.0.3/lib/aarch64-linux-android/libcblite.stripped.so b/libcblite-3.0.3/lib/aarch64-linux-android/libcblite.stripped.so index 5c8f190..8793334 100755 Binary files a/libcblite-3.0.3/lib/aarch64-linux-android/libcblite.stripped.so and b/libcblite-3.0.3/lib/aarch64-linux-android/libcblite.stripped.so differ diff --git a/libcblite-3.0.3/lib/arm-linux-androideabi/libcblite.so b/libcblite-3.0.3/lib/arm-linux-androideabi/libcblite.so index 3d51a41..02a6ed1 100644 Binary files a/libcblite-3.0.3/lib/arm-linux-androideabi/libcblite.so and b/libcblite-3.0.3/lib/arm-linux-androideabi/libcblite.so differ diff --git a/libcblite-3.0.3/lib/arm-linux-androideabi/libcblite.stripped.so b/libcblite-3.0.3/lib/arm-linux-androideabi/libcblite.stripped.so index 67c9811..fed0fdb 100755 Binary files a/libcblite-3.0.3/lib/arm-linux-androideabi/libcblite.stripped.so and b/libcblite-3.0.3/lib/arm-linux-androideabi/libcblite.stripped.so differ diff --git a/libcblite-3.0.3/lib/i686-linux-android/libcblite.so b/libcblite-3.0.3/lib/i686-linux-android/libcblite.so index 1e06bf0..2c0f6e9 100644 Binary files a/libcblite-3.0.3/lib/i686-linux-android/libcblite.so and b/libcblite-3.0.3/lib/i686-linux-android/libcblite.so differ diff --git a/libcblite-3.0.3/lib/i686-linux-android/libcblite.stripped.so b/libcblite-3.0.3/lib/i686-linux-android/libcblite.stripped.so index 693e540..11a351e 100755 Binary files a/libcblite-3.0.3/lib/i686-linux-android/libcblite.stripped.so and b/libcblite-3.0.3/lib/i686-linux-android/libcblite.stripped.so differ diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/Info.plist b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/Info.plist index 15c418a..6079b74 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/Info.plist +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/Info.plist @@ -8,32 +8,32 @@ DebugSymbolsPath dSYMs LibraryIdentifier - ios-arm64_x86_64-simulator + ios-arm64 LibraryPath CouchbaseLite.framework SupportedArchitectures arm64 - x86_64 SupportedPlatform ios - SupportedPlatformVariant - simulator DebugSymbolsPath dSYMs LibraryIdentifier - ios-arm64 + ios-arm64_x86_64-simulator LibraryPath CouchbaseLite.framework SupportedArchitectures arm64 + x86_64 SupportedPlatform ios + SupportedPlatformVariant + simulator CFBundlePackageType diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/CouchbaseLite b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/CouchbaseLite index 9912fc6..16f85da 100755 Binary files a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/CouchbaseLite and b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/CouchbaseLite differ diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLBase.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLBase.h index 5da21cd..d7866eb 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLBase.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLBase.h @@ -209,7 +209,7 @@ typedef struct CBLDocument CBLDocument; typedef struct CBLBlob CBLBlob; /** @} */ -/** \defgroup queries Queries +/** \defgroup query Query @{ */ /** A compiled database query. */ typedef struct CBLQuery CBLQuery; @@ -218,6 +218,16 @@ typedef struct CBLQuery CBLQuery; typedef struct CBLResultSet CBLResultSet; /** @} */ +/** \defgroup index Index + @{ */ +/** A query index. */ +typedef struct CBLQueryIndex CBLQueryIndex; + +#ifdef COUCHBASE_ENTERPRISE +typedef struct CBLIndexUpdater CBLIndexUpdater; +#endif +/** @} */ + /** \defgroup replication Replication @{ */ /** A background task that syncs a \ref CBLDatabase with a remote server or peer. */ diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLCollection.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLCollection.h index 6e91d27..35941b5 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLCollection.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLCollection.h @@ -19,7 +19,8 @@ #pragma once #include #include -#include +#include +#include CBL_CAPI_BEGIN @@ -154,12 +155,10 @@ CBLScope* CBLDatabase_DefaultScope(const CBLDatabase* db, CBLError* _cbl_nullable outError) CBLAPI; /** Returns the default collection. - @note The default collection may not exist if it was deleted. - Also, the default collection cannot be recreated after being deleted. @note You are responsible for releasing the returned collection. @param db The database. @param outError On failure, the error will be written here. - @return A \ref CBLCollection instance, or NULL if the default collection doesn't exist or an error occurred. */ + @return A \ref CBLCollection instance, or NULL if an error occurred. */ CBLCollection* _cbl_nullable CBLDatabase_DefaultCollection(const CBLDatabase* db, CBLError* _cbl_nullable outError) CBLAPI; @@ -170,17 +169,28 @@ CBLCollection* _cbl_nullable CBLDatabase_DefaultCollection(const CBLDatabase* db Getting information about a collection. */ -/** Returns the scope of the collection. +/** Returns the collection's scope. @note You are responsible for releasing the returned scope. @param collection The collection. - @return A \ref CBLScope instance. */ + @return The scope of the collection. */ CBLScope* CBLCollection_Scope(const CBLCollection* collection) CBLAPI; -/** Returns the collection name. +/** Returns the collection's name. @param collection The collection. @return The name of the collection. */ FLString CBLCollection_Name(const CBLCollection* collection) CBLAPI; +/** Returns the collection's fully qualified name in the '.' format. + @param collection The collection. + @return The fully qualified name of the collection. */ +FLString CBLCollection_FullName(const CBLCollection* collection) CBLAPI; + +/** Returns the collection's database. + @note The database object is owned by the collection object; you do not need to release it. + @param collection The collection. + @return The database of the collection. */ +CBLDatabase* CBLCollection_Database(const CBLCollection* collection) CBLAPI; + /** Returns the number of documents in the collection. @param collection The collection. @return the number of documents in the collection. */ @@ -371,6 +381,33 @@ bool CBLCollection_CreateFullTextIndex(CBLCollection *collection, CBLFullTextIndexConfiguration config, CBLError* _cbl_nullable outError) CBLAPI; +/** Creates an array index for use with UNNEST queries in the collection. + If an identical index with that name already exists, nothing happens (and no error is returned.) + If a non-identical index with that name already exists, it is deleted and re-created. + @param collection The collection. + @param name The name of the index. + @param config The index configuration. + @param outError On failure, an error is written here. + @return True on success, false on failure. */ +bool CBLCollection_CreateArrayIndex(CBLCollection *collection, + FLString name, + CBLArrayIndexConfiguration config, + CBLError* _cbl_nullable outError) CBLAPI; + +#ifdef COUCHBASE_ENTERPRISE +/** ENTERPRISE EDITION ONLY + + Creatres a vector index in the collection. + If an identical index with that name already exists, nothing happens (and no error is returned.) + If a non-identical index with that name already exists, it is deleted and re-created. + */ +bool CBLCollection_CreateVectorIndex(CBLCollection *collection, + FLString name, + CBLVectorIndexConfiguration config, + CBLError* _cbl_nullable outError) CBLAPI; + +#endif + /** Deletes an index in the collection by name. @param collection The collection. @param name The name of the index. @@ -389,6 +426,17 @@ _cbl_warn_unused FLMutableArray _cbl_nullable CBLCollection_GetIndexNames(CBLCollection *collection, CBLError* _cbl_nullable outError) CBLAPI; +/** Returns an index object representing an existing index in the collection. + @note You are responsible for releasing the returned index object. + @param collection The collection. + @param name The name of the index. + @param outError On failure, an error is written here. + @return A \ref CBLQueryIndex instance if the index exists, or NULL if the index doesn't exist or an error occurred. */ +_cbl_warn_unused +CBLQueryIndex* _cbl_nullable CBLCollection_GetIndex(CBLCollection* collection, + FLString name, + CBLError* _cbl_nullable outError) CBLAPI; + /** @} */ /** \name Change Listeners diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLDatabase.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLDatabase.h index 09e794b..071c1d3 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLDatabase.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLDatabase.h @@ -18,6 +18,7 @@ #pragma once #include +#include CBL_CAPI_BEGIN @@ -26,6 +27,29 @@ CBL_CAPI_BEGIN A \ref CBLDatabase is both a filesystem object and a container for documents. */ +#ifdef COUCHBASE_ENTERPRISE + +#ifdef __APPLE__ +#pragma mark - Database Extension +#endif + +/** \name Database Extension + @{ */ + +/** ENTERPRISE EDITION ONLY + + Enables Vector Search extension by specifying the extension path to search for the Vector Search extension library. + This function must be called before opening a database that intends to use the vector search extension. + @param path The file system path of the directory that contains the Vector Search extension library. + @param outError On return, will be set to the error that occurred. + @return True on success, false if there was an error. + @note Must be called before opening a database that intends to use the vector search extension. */ +bool CBL_EnableVectorSearch(FLString path, CBLError* _cbl_nullable outError) CBLAPI; + +/** @} */ + +#endif + #ifdef __APPLE__ #pragma mark - CONFIGURATION #endif @@ -68,6 +92,13 @@ typedef struct { power failure will not cause the loss of any data. FULL synchronous is very safe but it is also dramatically slower. */ bool fullSync; + + /** + Disable memory-mapped I/O. By default, memory-mapped I/O is enabled. + Disabling it may affect database performance. Typically, there is no need to modify this setting. + @note Memory-mapped I/O is always disabled on macOS to prevent database corruption, + so setting mmapDisabled value has no effect on the macOS platform. */ + bool mmapDisabled; } CBLDatabaseConfiguration; /** Returns the default database configuration. */ @@ -219,7 +250,6 @@ bool CBLDatabase_PerformMaintenance(CBLDatabase* db, /** @} */ - #ifdef __APPLE__ #pragma mark - ACCESSORS #endif @@ -244,6 +274,45 @@ const CBLDatabaseConfiguration CBLDatabase_Config(const CBLDatabase*) CBLAPI; /** @} */ +/** \name Query Indexes + @{ + Query Index Management + */ + +/** Creates a value index. + Indexes are persistent. + If an identical index with that name already exists, nothing happens (and no error is returned.) + If a non-identical index with that name already exists, it is deleted and re-created. + @warning Deprecated : Use CBLCollection_CreateValueIndex on the default collection instead. */ +bool CBLDatabase_CreateValueIndex(CBLDatabase *db, + FLString name, + CBLValueIndexConfiguration config, + CBLError* _cbl_nullable outError) CBLAPI; + +/** Creates a full-text index. + Indexes are persistent. + If an identical index with that name already exists, nothing happens (and no error is returned.) + If a non-identical index with that name already exists, it is deleted and re-created. + @warning Deprecated : Use CBLCollection_CreateFullTextIndex on the default collection instead. */ +bool CBLDatabase_CreateFullTextIndex(CBLDatabase *db, + FLString name, + CBLFullTextIndexConfiguration config, + CBLError* _cbl_nullable outError) CBLAPI; + +/** Deletes an index given its name. + @warning Deprecated : Use CBLCollection_DeleteIndex on the default collection instead. */ +bool CBLDatabase_DeleteIndex(CBLDatabase *db, + FLString name, + CBLError* _cbl_nullable outError) CBLAPI; + +/** Returns the names of the indexes on this database, as a Fleece array of strings. + @note You are responsible for releasing the returned Fleece array. + @warning Deprecated : Use CBLCollection_GetIndexNames on the default collection instead. */ +_cbl_warn_unused +FLArray CBLDatabase_GetIndexNames(CBLDatabase *db) CBLAPI; + + +/** @} */ #ifdef __APPLE__ #pragma mark - LISTENERS diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLDefaults.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLDefaults.h index d115a35..d1c39a9 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLDefaults.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLDefaults.h @@ -2,7 +2,7 @@ // CBLDefaults.h // CouchbaseLite // -// Copyright (c) 2023-present Couchbase, Inc All rights reserved. +// Copyright (c) 2024-present Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ #pragma once #include #include +#include CBL_CAPI_BEGIN @@ -33,11 +34,27 @@ CBL_CAPI_BEGIN Constants for default configuration values. */ +/** \name CBLDatabaseConfiguration + @{ +*/ + +/** [false] Full sync is off by default because the performance hit is seldom worth the benefit */ +CBL_PUBLIC extern const bool kCBLDefaultDatabaseFullSync; + +/** [false] Memory mapped database files are enabled by default */ +CBL_PUBLIC extern const bool kCBLDefaultDatabaseMmapDisabled; + +/** @} */ + /** \name CBLLogFileConfiguration @{ */ /** [false] Plaintext is not used, and instead binary encoding is used in log files */ +CBL_PUBLIC extern const bool kCBLDefaultLogFileUsePlaintext; + +/** [false] Plaintext is not used, and instead binary encoding is used in log files + @warning Deprecated : Use kCBLDefaultLogFileUsePlaintext instead. */ CBL_PUBLIC extern const bool kCBLDefaultLogFileUsePlainText; /** [524288] 512 KiB for the size of a log file */ @@ -46,7 +63,6 @@ CBL_PUBLIC extern const size_t kCBLDefaultLogFileMaxSize; /** [1] 1 rotated file present (2 total, including the currently active log file) */ CBL_PUBLIC extern const uint32_t kCBLDefaultLogFileMaxRotateCount; - /** @} */ /** \name CBLFullTextIndexConfiguration @@ -56,7 +72,6 @@ CBL_PUBLIC extern const uint32_t kCBLDefaultLogFileMaxRotateCount; /** [false] Accents and ligatures are not ignored when indexing via full text search */ CBL_PUBLIC extern const bool kCBLDefaultFullTextIndexIgnoreAccents; - /** @} */ /** \name CBLReplicatorConfiguration @@ -79,6 +94,10 @@ CBL_PUBLIC extern const unsigned kCBLDefaultReplicatorMaxAttemptsSingleShot; CBL_PUBLIC extern const unsigned kCBLDefaultReplicatorMaxAttemptsContinuous; /** [300] Max wait time between retry attempts in seconds */ +CBL_PUBLIC extern const unsigned kCBLDefaultReplicatorMaxAttemptsWaitTime; + +/** [300] Max wait time between retry attempts in seconds + @warning Deprecated : Use kCBLDefaultReplicatorMaxAttemptsWaitTime instead. */ CBL_PUBLIC extern const unsigned kCBLDefaultReplicatorMaxAttemptWaitTime; /** [false] Purge documents when a user loses access */ @@ -89,6 +108,31 @@ CBL_PUBLIC extern const bool kCBLDefaultReplicatorAcceptParentCookies; /** @} */ +#ifdef COUCHBASE_ENTERPRISE + +/** \name CBLVectorIndexConfiguration + @{ +*/ + +/** [false] Vectors are not lazily indexed, by default */ +CBL_PUBLIC extern const bool kCBLDefaultVectorIndexLazy; + +/** [kCBLDistanceMetricEuclideanSquared] By default, vectors are compared using Squared Euclidean metric. */ +CBL_PUBLIC extern const CBLDistanceMetric kCBLDefaultVectorIndexDistanceMetric; + +/** [0] By default, the value will be determined based on the number of centroids, encoding types, and the encoding parameters. */ +CBL_PUBLIC extern const unsigned kCBLDefaultVectorIndexMinTrainingSize; + +/** [0] By default, the value will be determined based on the number of centroids, encoding types, and the encoding parameters */ +CBL_PUBLIC extern const unsigned kCBLDefaultVectorIndexMaxTrainingSize; + +/** [0] By default, the value will be determined based on the number of centroids. */ +CBL_PUBLIC extern const unsigned kCBLDefaultVectorIndexNumProbes; + +/** @} */ + +#endif + /** @} */ CBL_CAPI_END diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLLog.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLLog.h index 6298efa..2c2c1b9 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLLog.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLLog.h @@ -128,7 +128,7 @@ typedef struct { size_t maxSize; /** Whether or not to log in plaintext (as opposed to binary.) Plaintext logging is slower and bigger. - The default is \ref kCBLDefaultLogFileUsePlainText. */ + The default is \ref kCBLDefaultLogFileUsePlaintext. */ bool usePlaintext; } CBLLogFileConfiguration; diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLPrediction.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLPrediction.h new file mode 100644 index 0000000..625e736 --- /dev/null +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLPrediction.h @@ -0,0 +1,57 @@ +// +// CBLPrediction.h +// +// Copyright (c) 2024 Couchbase, Inc All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#pragma once +#include + +#ifdef COUCHBASE_ENTERPRISE + +CBL_CAPI_BEGIN + +/** Predictive Model */ +typedef struct { + /** A pointer to any external data needed by the `prediction` callback, which will receive this as its first parameter. */ + void* _cbl_nullable context; + + /** Prediction callback, called from within a query (or document indexing) to run the prediction. + @param context The value of the CBLPredictiveModel's `context` field. + @param input The input dictionary from the query. + @return The output of the prediction function as an FLMutableDict, or NULL if there is no output. + @note The output FLMutableDict will be automatically released after the prediction callback is called. + @warning This function must be "pure": given the same input parameters it must always + produce the same output (otherwise indexes or queries may be messed up). + It MUST NOT alter the database or any documents, nor run a query: either of + those are very likely to cause a crash. */ + FLMutableDict _cbl_nullable (* _cbl_nonnull prediction)(void* _cbl_nullable context, FLDict input); + + /** Unregistered callback, called if the model is unregistered, so it can release resources. */ + void (*_cbl_nullable unregistered)(void* context); +} CBLPredictiveModel; + +/** Registers a predictive model. + @param name The name. + @param model The predictive model. */ +void CBL_RegisterPredictiveModel(FLString name, CBLPredictiveModel model) CBLAPI; + +/** Unregisters the predictive model. + @param name The name of the registered predictive model. */ +void CBL_UnregisterPredictiveModel(FLString name) CBLAPI; + +CBL_CAPI_END + +#endif diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLQuery.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLQuery.h index a4e10f1..321b424 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLQuery.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLQuery.h @@ -18,33 +18,26 @@ #pragma once #include +#include CBL_CAPI_BEGIN - -/** \defgroup queries Queries +/** \defgroup query Query @{ A CBLQuery represents a compiled database query. The query language is a large subset of the [N1QL](https://www.couchbase.com/products/n1ql) language from Couchbase Server, which you can think of as "SQL for JSON" or "SQL++". - Queries may be given either in - [N1QL syntax](https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/index.html), - or in JSON using a - [schema](https://github.com/couchbase/couchbase-lite-core/wiki/JSON-Query-Schema) - that resembles a parse tree of N1QL. The JSON syntax is harder for humans, but much more + Supported Query languages: + [N1QL](https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/index.html) + + [JSON](https://github.com/couchbase/couchbase-lite-core/wiki/JSON-Query-Schema) + + JSON language resembles a parse tree of N1QL. The JSON syntax is harder for humans, but much more amenable to machine generation, if you need to create queries programmatically or translate them from some other form. */ - -/** Query languages */ -typedef CBL_ENUM(uint32_t, CBLQueryLanguage) { - kCBLJSONLanguage, ///< [JSON query schema](https://github.com/couchbase/couchbase-lite-core/wiki/JSON-Query-Schema) - kCBLN1QLLanguage ///< [N1QL syntax](https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/index.html) -}; - - /** \name Query objects @{ */ @@ -150,16 +143,16 @@ bool CBLResultSet_Next(CBLResultSet*) CBLAPI; /** Returns the value of a column of the current result, given its (zero-based) numeric index. This may return a NULL pointer, indicating `MISSING`, if the value doesn't exist, e.g. if the column is a property that doesn't exist in the document. */ -FLValue CBLResultSet_ValueAtIndex(const CBLResultSet*, - unsigned index) CBLAPI; +FLValue _cbl_nullable CBLResultSet_ValueAtIndex(const CBLResultSet*, + unsigned index) CBLAPI; /** Returns the value of a column of the current result, given its name. This may return a NULL pointer, indicating `MISSING`, if the value doesn't exist, e.g. if the column is a property that doesn't exist in the document. (Or, of course, if the key is not a column name in this query.) @note See \ref CBLQuery_ColumnName for a discussion of column names. */ -FLValue CBLResultSet_ValueForKey(const CBLResultSet*, - FLString key) CBLAPI; +FLValue _cbl_nullable CBLResultSet_ValueForKey(const CBLResultSet*, + FLString key) CBLAPI; /** Returns the current result as an array of column values. @warning The array reference is only valid until the result-set is advanced or released. @@ -179,7 +172,6 @@ CBL_REFCOUNTED(CBLResultSet*, ResultSet); /** @} */ - /** \name Change listener @{ Adding a change listener to a query turns it into a "live query". When changes are made to @@ -233,106 +225,6 @@ CBLResultSet* _cbl_nullable CBLQuery_CopyCurrentResults(const CBLQuery* query, /** @} */ - - -/** \name Database Indexes - @{ - Indexes are used to speed up queries by allowing fast -- O(log n) -- lookup of documents - that have specific values or ranges of values. The values may be properties, or expressions - based on properties. - - An index will speed up queries that use the expression it indexes, but it takes up space in - the database file, and it slows down document saves slightly because it needs to be kept up - to date when documents change. - - Tuning a database with indexes can be a tricky task. Fortunately, a lot has been written about - it in the relational-database (SQL) realm, and much of that advice holds for Couchbase Lite. - You may find SQLite's documentation particularly helpful since Couchbase Lite's querying is - based on SQLite. - - Two types of indexes are currently supported: - * Value indexes speed up queries by making it possible to look up property (or expression) - values without scanning every document. They're just like regular indexes in SQL or N1QL. - Multiple expressions are supported; the first is the primary key, second is secondary. - Expressions must evaluate to scalar types (boolean, number, string). - * Full-Text Search (FTS) indexes enable fast search of natural-language words or phrases - by using the `MATCH` operator in a query. A FTS index is **required** for full-text - search: a query with a `MATCH` operator will fail to compile unless there is already a - FTS index for the property/expression being matched. Only a single expression is - currently allowed, and it must evaluate to a string. */ - -/** Value Index Configuration. */ -typedef struct { - /** The language used in the expressions. */ - CBLQueryLanguage expressionLanguage; - - /** The expressions describing each coloumn of the index. The expressions could be specified - in a JSON Array or in N1QL syntax using comma delimiter. */ - FLString expressions; -} CBLValueIndexConfiguration; - -/** Creates a value index. - Indexes are persistent. - If an identical index with that name already exists, nothing happens (and no error is returned.) - If a non-identical index with that name already exists, it is deleted and re-created. - @warning Deprecated : Use CBLCollection_CreateValueIndex on the default collection instead. */ -bool CBLDatabase_CreateValueIndex(CBLDatabase *db, - FLString name, - CBLValueIndexConfiguration config, - CBLError* _cbl_nullable outError) CBLAPI; - - -/** Full-Text Index Configuration. */ -typedef struct { - /** The language used in the expressions (Required). */ - CBLQueryLanguage expressionLanguage; - - /** The expressions describing each coloumn of the index. The expressions could be specified - in a JSON Array or in N1QL syntax using comma delimiter. (Required) */ - FLString expressions; - - /** Should diacritical marks (accents) be ignored? - Defaults to \ref kCBLDefaultFullTextIndexIgnoreAccents. - Generally this should be left `false` for non-English text. */ - bool ignoreAccents; - - /** The dominant language. Setting this enables word stemming, i.e. - matching different cases of the same word ("big" and "bigger", for instance) and ignoring - common "stop-words" ("the", "a", "of", etc.) - - Can be an ISO-639 language code or a lowercase (English) language name; supported - languages are: da/danish, nl/dutch, en/english, fi/finnish, fr/french, de/german, - hu/hungarian, it/italian, no/norwegian, pt/portuguese, ro/romanian, ru/russian, - es/spanish, sv/swedish, tr/turkish. - - If left null, or set to an unrecognized language, no language-specific behaviors - such as stemming and stop-word removal occur. */ - FLString language; -} CBLFullTextIndexConfiguration; - -/** Creates a full-text index. - Indexes are persistent. - If an identical index with that name already exists, nothing happens (and no error is returned.) - If a non-identical index with that name already exists, it is deleted and re-created. - @warning Deprecated : Use CBLCollection_CreateFullTextIndex on the default collection instead. */ -bool CBLDatabase_CreateFullTextIndex(CBLDatabase *db, - FLString name, - CBLFullTextIndexConfiguration config, - CBLError* _cbl_nullable outError) CBLAPI; - -/** Deletes an index given its name. - @warning Deprecated : Use CBLCollection_DeleteIndex on the default collection instead. */ -bool CBLDatabase_DeleteIndex(CBLDatabase *db, - FLString name, - CBLError* _cbl_nullable outError) CBLAPI; - -/** Returns the names of the indexes on this database, as a Fleece array of strings. - @note You are responsible for releasing the returned Fleece array. - @warning Deprecated : Use CBLCollection_GetIndexNames on the default collection instead. */ -_cbl_warn_unused -FLArray CBLDatabase_GetIndexNames(CBLDatabase *db) CBLAPI; - -/** @} */ /** @} */ CBL_CAPI_END diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLQueryIndex.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLQueryIndex.h new file mode 100644 index 0000000..79bed5a --- /dev/null +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLQueryIndex.h @@ -0,0 +1,161 @@ +// +// CBLQueryIndex.h +// +// Copyright (c) 2024 Couchbase, Inc All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#pragma once +#include +#include + +CBL_CAPI_BEGIN + +/** \defgroup index Index + @{ + Indexes are used to speed up queries by allowing fast -- O(log n) -- lookup of documents + that have specific values or ranges of values. The values may be properties, or expressions + based on properties. + + An index will speed up queries that use the expression it indexes, but it takes up space in + the database file, and it slows down document saves slightly because it needs to be kept up + to date when documents change. + + Tuning a database with indexes can be a tricky task. Fortunately, a lot has been written about + it in the relational-database (SQL) realm, and much of that advice holds for Couchbase Lite. + You may find SQLite's documentation particularly helpful since Couchbase Lite's querying is + based on SQLite. + + Supported index types: + * Value indexes speed up queries by making it possible to look up property (or expression) + values without scanning every document. They're just like regular indexes in SQL or N1QL. + Multiple expressions are supported; the first is the primary key, second is secondary. + Expressions must evaluate to scalar types (boolean, number, string). + + * Full-Text Search (FTS) indexes enable fast search of natural-language words or phrases + by using the `MATCH()` function in a query. A FTS index is **required** for full-text + search: a query with a `MATCH()` function will fail to compile unless there is already a + FTS index for the property/expression being matched. + + * (Enterprise Edition Only) Vector indexes allows efficient search of ML vectors by using + the `VECTOR_MATCH()` function in a query. The `CouchbaseLiteVectorSearch` + extension library is **required** to use the functionality. Use \ref CBL_EnableVectorSearch + function to set the directoary path containing the extension library. */ + +/** \name CBLQueryIndex + @{ + CBLQueryIndex represents an existing index in a collection. + + Available in the enterprise edition, the \ref CBLQueryIndex can be used to obtain + a \ref CBLIndexUpdater object for updating the vector index in lazy mode. */ +CBL_REFCOUNTED(CBLQueryIndex*, QueryIndex); + +/** Returns the index's name. + @param index The index. + @return The name of the index. */ +FLString CBLQueryIndex_Name(const CBLQueryIndex* index) CBLAPI; + +/** Returns the collection that the index belongs to. + @param index The index. + @return A \ref CBLCollection instance that the index belongs to. */ +CBLCollection* CBLQueryIndex_Collection(const CBLQueryIndex* index) CBLAPI; + +#ifdef COUCHBASE_ENTERPRISE + +CBL_REFCOUNTED(CBLIndexUpdater*, IndexUpdater); + +/** ENTERPRISE EDITION ONLY + + Finds new or updated documents for which vectors need to be (re)computed and returns an \ref CBLIndexUpdater object + for setting the computed vectors to update the index. If the index is not lazy, an error will be returned. + @note For updating lazy vector indexes only. + @note You are responsible for releasing the returned A \ref CBLIndexUpdater object. + @param index The index. + @param limit The maximum number of vectors to be computed. + @param outError On failure, an error is written here. + @return A \ref CBLIndexUpdater object for setting the computed vectors to update the index, + or NULL if the index is up-to-date or an error occurred. */ +_cbl_warn_unused +CBLIndexUpdater* _cbl_nullable CBLQueryIndex_BeginUpdate(CBLQueryIndex* index, + size_t limit, + CBLError* _cbl_nullable outError) CBLAPI; + +/** @} */ + +/** \name IndexUpdater + @{ + CBLIndexUpdater used for updating the index in lazy mode. Currently, the vector index is the only index type that + can be updated lazily. + */ + +/** ENTERPRISE EDITION ONLY + + Returns the total number of vectors to compute and set for updating the index. + @param updater The index updater. + @return The total number of vectors to compute and set for updating the index. */ +size_t CBLIndexUpdater_Count(const CBLIndexUpdater* updater) CBLAPI; + +/** ENTERPRISE EDITION ONLY + + Returns the valut at the given index to compute a vector from. + @note The returned Fleece value is valid unilt its \ref CBLIndexUpdater is released. + If you want to keep it longer, retain it with `FLRetain`. + @param updater The index updater. + @param index The zero-based index. + @return A Fleece value of the index's evaluated expression at the given index. */ +FLValue CBLIndexUpdater_Value(CBLIndexUpdater* updater, size_t index) CBLAPI; + +/** ENTERPRISE EDITION ONLY + + Sets the vector for the value corresponding to the given index. + Setting null vector means that there is no vector for the value, and any existing vector + will be removed when the `CBLIndexUpdater_Finish` is called. + @param updater The index updater. + @param index The zero-based index. + @param vector A pointer to the vector which is an array of floats, or NULL if there is no vector. + @param dimension The dimension of `vector`. Must be equal to the dimension value set in the vector index config. + @param outError On failure, an error is written here. + @return True if success, or False if an error occurred. */ +bool CBLIndexUpdater_SetVector(CBLIndexUpdater* updater, + size_t index, + const float vector[_cbl_nullable], + size_t dimension, + CBLError* _cbl_nullable outError) CBLAPI; + +/** ENTERPRISE EDITION ONLY + + Skip setting the vector for the value corresponding to the index. + The vector will be required to compute and set again when the `CBLQueryIndex_BeginUpdate` is later called. + @param updater The index updater. + @param index The zero-based index. */ +void CBLIndexUpdater_SkipVector(CBLIndexUpdater* updater, size_t index) CBLAPI; + +/** ENTERPRISE EDITION ONLY + + Updates the index with the computed vectors and removes any index rows for which null vector was given. + If there are any indexes that do not have their vector value set or are skipped, a error will be returned. + @note Before calling `CBLIndexUpdater_Finish`, the set vectors are kept in the memory. + @warning The index updater cannot be used after calling `CBLIndexUpdater_Finish`. + @param updater The index updater. + @param outError On failure, an error is written here. + @return True if success, or False if an error occurred. */ +bool CBLIndexUpdater_Finish(CBLIndexUpdater* updater, CBLError* _cbl_nullable outError) CBLAPI; + +#endif + +/** @} */ + +/** @} */ + +CBL_CAPI_END diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLQueryIndexTypes.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLQueryIndexTypes.h new file mode 100644 index 0000000..b26350e --- /dev/null +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLQueryIndexTypes.h @@ -0,0 +1,206 @@ +// +// CBLQueryIndexTypes.h +// +// Copyright (c) 2024 Couchbase, Inc All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#pragma once +#include +#include + +CBL_CAPI_BEGIN + +/** \defgroup index Index + @{ */ + +/** \name Index Configuration + @{ */ + +/** Value Index Configuration. */ +typedef struct { + /** The language used in the expressions. */ + CBLQueryLanguage expressionLanguage; + + /** The expressions describing each coloumn of the index. The expressions could be specified + in a JSON Array or in N1QL syntax using comma delimiter. */ + FLString expressions; +} CBLValueIndexConfiguration; + +/** Full-Text Index Configuration. */ +typedef struct { + /** The language used in the expressions (Required). */ + CBLQueryLanguage expressionLanguage; + + /** The expressions describing each coloumn of the index. The expressions could be specified + in a JSON Array or in N1QL syntax using comma delimiter. (Required) */ + FLString expressions; + + /** Should diacritical marks (accents) be ignored? + Defaults to \ref kCBLDefaultFullTextIndexIgnoreAccents. + Generally this should be left `false` for non-English text. */ + bool ignoreAccents; + + /** The dominant language. Setting this enables word stemming, i.e. + matching different cases of the same word ("big" and "bigger", for instance) and ignoring + common "stop-words" ("the", "a", "of", etc.) + + Can be an ISO-639 language code or a lowercase (English) language name; supported + languages are: da/danish, nl/dutch, en/english, fi/finnish, fr/french, de/german, + hu/hungarian, it/italian, no/norwegian, pt/portuguese, ro/romanian, ru/russian, + es/spanish, sv/swedish, tr/turkish. + + If left null, or set to an unrecognized language, no language-specific behaviors + such as stemming and stop-word removal occur. */ + FLString language; +} CBLFullTextIndexConfiguration; + +/** Array Index Configuration for indexing property values within arrays + in documents, intended for use with the UNNEST query. */ +typedef struct { + /** The language used in the expressions (Required). */ + CBLQueryLanguage expressionLanguage; + + /** Path to the array, which can be nested to be indexed (Required). + Use "[]" to represent a property that is an array of each nested array level. + For a single array or the last level array, the "[]" is optional. For instance, + use "contacts[].phones" to specify an array of phones within each contact. */ + FLString path; + + /** Optional expressions representing the values within the array to be + indexed. The expressions could be specified in a JSON Array or in N1QL syntax + using comma delimiter. If the array specified by the path contains scalar values, + the expressions should be left unset or set to null. */ + FLString expressions; +} CBLArrayIndexConfiguration; + +#ifdef COUCHBASE_ENTERPRISE + +/** An opaque object representing vector encoding type to use in CBLVectorIndexConfiguration. */ +typedef struct CBLVectorEncoding CBLVectorEncoding; + +/** Creates a no-encoding type to use in CBLVectorIndexConfiguration; 4 bytes per dimension, no data loss. + @return A None encoding object. */ +_cbl_warn_unused +CBLVectorEncoding* CBLVectorEncoding_CreateNone(void) CBLAPI; + +/** Scalar Quantizer encoding type */ +typedef CBL_ENUM(uint32_t, CBLScalarQuantizerType) { + kCBLSQ4 = 4, ///< 4 bits per dimension + kCBLSQ6 = 6, ///< 6 bits per dimension + kCBLSQ8 = 8 ///< 8 bits per dimension +}; + +/** Creates a Scalar Quantizer encoding to use in CBLVectorIndexConfiguration. + @param type Scalar Quantizer Type. + @return A Scalar Quantizer encoding object. */ +_cbl_warn_unused +CBLVectorEncoding* CBLVectorEncoding_CreateScalarQuantizer(CBLScalarQuantizerType type) CBLAPI; + +/** Creates a Product Quantizer encoding to use in CBLVectorIndexConfiguration. + @param subquantizers Number of subquantizers. Must be > 1 and a factor of vector dimensions. + @param bits Number of bits. Must be >= 4 and <= 12. + @return A Product Quantizer encoding object. */ +_cbl_warn_unused +CBLVectorEncoding* CBLVectorEncoding_CreateProductQuantizer(unsigned subquantizers, unsigned bits) CBLAPI; + +/** Frees a CBLVectorEncoding object. The encoding object can be freed after the index is created. */ +void CBLVectorEncoding_Free(CBLVectorEncoding* _cbl_nullable) CBLAPI; + +/** Distance metric to use in CBLVectorIndexConfiguration. */ +typedef CBL_ENUM(uint32_t, CBLDistanceMetric) { + kCBLDistanceMetricEuclideanSquared = 1, ///< Squared Euclidean distance (AKA Squared L2) + kCBLDistanceMetricCosine, ///< Cosine distance (1.0 - Cosine Similarity) + kCBLDistanceMetricEuclidean, ///< Euclidean distance (AKA L2) + kCBLDistanceMetricDot ///< Dot-product distance (Negative of dot-product) +}; + +/** ENTERPRISE EDITION ONLY + + Vector Index Configuration. */ +typedef struct { + /** The language used in the expressions (Required). */ + CBLQueryLanguage expressionLanguage; + + /** The expression could be specified in a JSON Array or in N1QL syntax depending on + the expressionLanguage. (Required) + + For non-lazy indexes, an expression returning either a vector, which is an array of 32-bit + floating-point numbers, or a Base64 string representing an array of 32-bit floating-point + numbers in little-endian order. + + For lazy indexex, an expression returning a value for computing a vector lazily when using + \ref CBLIndexUpdater to add or update the vector into the index. */ + FLString expression; + + /** The number of vector dimensions. (Required) + @note The maximum number of vector dimensions supported is 4096. */ + unsigned dimensions; + + /** The number of centroids which is the number buckets to partition the vectors in the index. (Required) + @note The recommended number of centroids is the square root of the number of vectors to be indexed, + and the maximum number of centroids supported is 64,000.*/ + unsigned centroids; + + /** The boolean flag indicating that index is lazy or not. The default value is false. + + If the index is lazy, it will not be automatically updated when the documents in the collection are changed, + except when the documents are deleted or purged. + + When configuring the index to be lazy, the expression set to the config is the expression that returns + a value used for computing the vector. + + To update the lazy index, use a CBLIndexUpdater object, which can be obtained + from a CBLQueryIndex object. To get a CBLQueryIndex object, call CBLCollection_GetIndex. */ + bool isLazy; + + /** Vector encoding type. The default value is 8-bits Scalar Quantizer. */ + CBLVectorEncoding* encoding; + + /** Distance Metric type. The default value is euclidean distance. */ + CBLDistanceMetric metric; + + /** The minimum number of vectors for training the index. + The default value is zero, meaning that minTrainingSize will be determined based on + the number of centroids, encoding types, and the encoding parameters. + + @note The training will occur at or before the APPROX_VECTOR_DISANCE query is + executed, provided there is enough data at that time, and consequently, if + training is triggered during a query, the query may take longer to return + results. + + @note If a query is executed against the index before it is trained, a full + scan of the vectors will be performed. If there are insufficient vectors + in the database for training, a warning message will be logged, + indicating the required number of vectors. */ + unsigned minTrainingSize; + + /** The maximum number of vectors used for training the index. + The default value is zero, meaning that the maxTrainingSize will be determined based on + the number of centroids, encoding types, and encoding parameters. */ + unsigned maxTrainingSize; + + /** The number of centroids that will be scanned during a query. + The default value is zero, meaning that the numProbes will be determined based on + the number of centroids. */ + unsigned numProbes; +} CBLVectorIndexConfiguration; + +#endif + +/** @} */ + +/** @} */ + +CBL_CAPI_END diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLQueryTypes.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLQueryTypes.h new file mode 100644 index 0000000..25ad9aa --- /dev/null +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLQueryTypes.h @@ -0,0 +1,35 @@ +// +// CBLQueryTypes.h +// +// Copyright (c) 2024 Couchbase, Inc All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#pragma once +#include + +CBL_CAPI_BEGIN + +/** \defgroup queries Queries + @{ */ + +/** Supported Query languages */ +typedef CBL_ENUM(uint32_t, CBLQueryLanguage) { + kCBLJSONLanguage, ///< [JSON query schema](https://github.com/couchbase/couchbase-lite-core/wiki/JSON-Query-Schema) + kCBLN1QLLanguage ///< [N1QL syntax](https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/index.html) +}; + +/** @} */ + +CBL_CAPI_END diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLReplicator.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLReplicator.h index 9d2a627..1c61c87 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLReplicator.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLReplicator.h @@ -343,7 +343,7 @@ typedef struct { unsigned maxAttempts; /** Max wait time between retry attempts in seconds. - The default value \ref kCBLDefaultReplicatorMaxAttemptWaitTime. */ + The default value \ref kCBLDefaultReplicatorMaxAttemptsWaitTime. */ unsigned maxAttemptWaitTime; //-- WebSocket: @@ -418,8 +418,11 @@ typedef struct { @warning Deprecated : Use documentPropertyDecryptor instead. */ CBLPropertyDecryptor _cbl_nullable propertyDecryptor; - CBLDocumentPropertyEncryptor _cbl_nullable documentPropertyEncryptor; ///< Optional callback to encrypt \ref CBLEncryptable values. - CBLDocumentPropertyDecryptor _cbl_nullable documentPropertyDecryptor; ///< Optional callback to decrypt encrypted \ref CBLEncryptable values. + /** Optional callback to encrypt \ref CBLEncryptable values. */ + CBLDocumentPropertyEncryptor _cbl_nullable documentPropertyEncryptor; + + /** Optional callback to decrypt encrypted \ref CBLEncryptable values. */ + CBLDocumentPropertyDecryptor _cbl_nullable documentPropertyDecryptor; #endif /** The collections to replicate with the target's endpoint (Required if the database is not set). */ @@ -459,6 +462,7 @@ CBLReplicator* _cbl_nullable CBLReplicator_Create(const CBLReplicatorConfigurati const CBLReplicatorConfiguration* CBLReplicator_Config(CBLReplicator*) CBLAPI; /** Starts a replicator, asynchronously. Does nothing if it's already started. + @note Replicators cannot be started from within a database's transaction. @param replicator The replicator instance. @param resetCheckpoint If true, the persistent saved state ("checkpoint") for this replication will be discarded, causing it to re-scan all documents. This significantly diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLScope.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLScope.h index 591ce66..ab93483 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLScope.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBLScope.h @@ -58,6 +58,12 @@ CBL_PUBLIC extern const FLString kCBLDefaultScopeName; @return The name of the scope. */ FLString CBLScope_Name(const CBLScope* scope) CBLAPI; +/** Returns the scope's database. + @note The database object is owned by the scope object; you do not need to release it. + @param scope The scope. + @return The database of the scope. */ +CBLDatabase* CBLScope_Database(const CBLScope* scope) CBLAPI; + /** @} */ /** \name Collections diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBL_Edition.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBL_Edition.h index 8d1fcf7..7c5c504 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBL_Edition.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CBL_Edition.h @@ -20,8 +20,8 @@ #define COUCHBASE_ENTERPRISE #endif -#define CBLITE_VERSION "3.1.10" -#define CBLITE_VERSION_NUMBER 3001010 -#define CBLITE_BUILD_NUMBER 52760 -#define CBLITE_SOURCE_ID "036da58+f7cfc38" -#define CBLITE_BUILD_TIMESTAMP "2024-09-30T21:15:22Z" +#define CBLITE_VERSION "3.2.1" +#define CBLITE_VERSION_NUMBER 3002001 +#define CBLITE_BUILD_NUMBER 9 +#define CBLITE_SOURCE_ID "6728898+e322f9b" +#define CBLITE_BUILD_TIMESTAMP "2024-10-30T14:23:54Z" diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CompilerSupport.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CompilerSupport.h index 8098543..382b19b 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CompilerSupport.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CompilerSupport.h @@ -14,7 +14,7 @@ #ifndef _FLEECE_COMPILER_SUPPORT_H #define _FLEECE_COMPILER_SUPPORT_H -// The __has_xxx() macros are only(?) implemented by Clang. (Except GCC has __has_attribute...) +// The __has_xxx() macros are supported by [at least] Clang and GCC. // Define them to return 0 on other compilers. // https://clang.llvm.org/docs/AttributeReference.html // https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html @@ -36,24 +36,37 @@ #endif -#if defined(__clang__) || defined(__GNUC__) - // Tells the optimizer that a function's return value is never NULL. - #define RETURNS_NONNULL __attribute__((returns_nonnull)) +// Tells the optimizer that a function's return value is never NULL. +#if __has_attribute(returns_nonnull) +# define RETURNS_NONNULL __attribute__((returns_nonnull)) +#else +# define RETURNS_NONNULL +#endif - // Triggers a compile error if a call to the function ignores the returned value. - // Typically this is because the return value is something that must be released/freed. - #define MUST_USE_RESULT __attribute__((warn_unused_result)) +// deprecated; use NODISCARD instead +#if __has_attribute(returns_nonnull) +# define MUST_USE_RESULT __attribute__((warn_unused_result)) +#else +# define MUST_USE_RESULT +#endif - // These have no effect on behavior, but they hint to the optimizer which branch of an 'if' - // statement to make faster. - #define _usuallyTrue(VAL) __builtin_expect(VAL, true) - #define _usuallyFalse(VAL) __builtin_expect(VAL, false) +// NODISCARD expands to the C++17/C23 `[[nodiscard]]` attribute, or else MUST_USE_RESULT. +// (We can't just redefine MUST_USE_RESULT as `[[nodiscard]]` unfortunately, because the former is +// already in use in positions where `[[nodiscard]]` isn't valid, like at the end of a declaration.) +#if (__cplusplus >= 201700L) || (__STDC_VERSION__ >= 202000) +# define NODISCARD [[nodiscard]] #else - #define RETURNS_NONNULL - #define MUST_USE_RESULT +# define NODISCARD MUST_USE_RESULT +#endif - #define _usuallyTrue(VAL) (VAL) - #define _usuallyFalse(VAL) (VAL) +// These have no effect on behavior, but they hint to the optimizer which branch of an 'if' +// statement to make faster. +#if __has_builtin(__builtin_expect) +#define _usuallyTrue(VAL) __builtin_expect(VAL, true) +#define _usuallyFalse(VAL) __builtin_expect(VAL, false) +#else +#define _usuallyTrue(VAL) (VAL) +#define _usuallyFalse(VAL) (VAL) #endif @@ -83,10 +96,10 @@ // GCC also has an attribute with this name, but it's incompatible: it can't be applied to a // parameter, it has to come after the function and list parameters by number. Oh well. // TODO: Replace this with the better nullability annotations above. -#ifdef __clang__ - #define NONNULL __attribute__((nonnull)) +#if __has_attribute(nonnull) +# define NONNULL __attribute__((nonnull)) #else - #define NONNULL +# define NONNULL #endif @@ -104,10 +117,10 @@ // declared with the pure attribute can safely read any non-volatile objects, and modify the value // of objects in a way that does not affect their return value or the observable state of the // program." -- GCC manual -#if defined(__GNUC__) || __has_attribute(__pure__) - #define FLPURE __attribute__((__pure__)) +#if __has_attribute(__pure__) +# define FLPURE __attribute__((__pure__)) #else - #define FLPURE +# define FLPURE #endif // FLCONST is even stricter than FLPURE. The function cannot access memory at all (except for @@ -126,10 +139,10 @@ // "In general, since a function cannot distinguish data that might change from data that cannot, // const functions should never take pointer or, in C++, reference arguments. Likewise, a function // that calls a non-const function usually must not be const itself." -- GCC manual -#if defined(__GNUC__) || __has_attribute(__const__) - #define FLCONST __attribute__((__const__)) +#if __has_attribute(__const__) +# define FLCONST __attribute__((__const__)) #else - #define FLCONST +# define FLCONST #endif diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CouchbaseLite.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CouchbaseLite.h index 6802407..bce263b 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CouchbaseLite.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/CouchbaseLite.h @@ -26,6 +26,10 @@ #include #include #include +#include #include +#include +#include +#include #include #include diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLCollections.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLCollections.h index f621c6b..5e2489e 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLCollections.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLCollections.h @@ -48,7 +48,7 @@ extern "C" { FLEECE_PUBLIC bool FLArray_IsEmpty(FLArray FL_NULLABLE) FLAPI FLPURE; /** If the array is mutable, returns it cast to FLMutableArray, else NULL. */ - FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLArray_AsMutable(FLArray FL_NULLABLE) FLAPI FLPURE; + NODISCARD FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLArray_AsMutable(FLArray FL_NULLABLE) FLAPI FLPURE; /** Returns an value at an array index, or NULL if the index is out of range. */ FLEECE_PUBLIC FLValue FL_NULLABLE FLArray_Get(FLArray FL_NULLABLE, uint32_t index) FLAPI FLPURE; @@ -80,10 +80,11 @@ while (NULL != (value = FLArrayIterator_GetValue(&iter))) { } FLArrayIterator; /** Initializes a FLArrayIterator struct to iterate over an array. - Call FLArrayIteratorGetValue to get the first item, then FLArrayIteratorNext. */ + Call FLArrayIteratorGetValue to get the first item, then as long as the item is not NULL, + call FLArrayIterator_Next to advance. */ FLEECE_PUBLIC void FLArrayIterator_Begin(FLArray FL_NULLABLE, FLArrayIterator*) FLAPI; - /** Returns the current value being iterated over. */ + /** Returns the current value being iterated over, or NULL at the end. */ FLEECE_PUBLIC FLValue FL_NULLABLE FLArrayIterator_GetValue(const FLArrayIterator*) FLAPI FLPURE; /** Returns a value in the array at the given offset from the current value. */ @@ -92,7 +93,9 @@ while (NULL != (value = FLArrayIterator_GetValue(&iter))) { /** Returns the number of items remaining to be iterated, including the current one. */ FLEECE_PUBLIC uint32_t FLArrayIterator_GetCount(const FLArrayIterator*) FLAPI FLPURE; - /** Advances the iterator to the next value, or returns false if at the end. */ + /** Advances the iterator to the next value. + @warning It is illegal to call this when the iterator is already at the end. + In particular, calling this when the array is empty is always illegal. */ FLEECE_PUBLIC bool FLArrayIterator_Next(FLArrayIterator*) FLAPI; /** @} */ @@ -153,22 +156,26 @@ while (NULL != (value = FLDictIterator_GetValue(&iter))) { /** Initializes a FLDictIterator struct to iterate over a dictionary. Call FLDictIterator_GetKey and FLDictIterator_GetValue to get the first item, - then FLDictIterator_Next. */ + then as long as the item is not NULL, call FLDictIterator_Next to advance. */ FLEECE_PUBLIC void FLDictIterator_Begin(FLDict FL_NULLABLE, FLDictIterator*) FLAPI; - /** Returns the current key being iterated over. This Value will be a string or an integer. */ + /** Returns the current key being iterated over. + This Value will be a string or an integer, or NULL when there are no more keys. */ FLEECE_PUBLIC FLValue FL_NULLABLE FLDictIterator_GetKey(const FLDictIterator*) FLAPI FLPURE; - /** Returns the current key's string value. */ + /** Returns the current key's string value, or NULL when there are no more keys. */ FLEECE_PUBLIC FLString FLDictIterator_GetKeyString(const FLDictIterator*) FLAPI; - /** Returns the current value being iterated over. */ + /** Returns the current value being iterated over. + Returns NULL when there are no more values. */ FLEECE_PUBLIC FLValue FL_NULLABLE FLDictIterator_GetValue(const FLDictIterator*) FLAPI FLPURE; /** Returns the number of items remaining to be iterated, including the current one. */ FLEECE_PUBLIC uint32_t FLDictIterator_GetCount(const FLDictIterator*) FLAPI FLPURE; - /** Advances the iterator to the next value, or returns false if at the end. */ + /** Advances the iterator to the next value. + @warning It is illegal to call this when the iterator is already at the end. + In particular, calling this when the dict is empty is always illegal. */ FLEECE_PUBLIC bool FLDictIterator_Next(FLDictIterator*) FLAPI; /** Cleans up after an iterator. Only needed if (a) the dictionary is a delta, and diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLDoc.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLDoc.h index c2f631b..49f4747 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLDoc.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLDoc.h @@ -37,7 +37,7 @@ extern "C" { /** Creates an FLDoc from Fleece-encoded data that's been returned as a result from FLSlice_Copy or other API. The resulting document retains the data, so you don't need to worry about it remaining valid. */ - FLEECE_PUBLIC FLDoc FLDoc_FromResultData(FLSliceResult data, FLTrust, + NODISCARD FLEECE_PUBLIC FLDoc FLDoc_FromResultData(FLSliceResult data, FLTrust, FLSharedKeys FL_NULLABLE, FLSlice externData) FLAPI; /** Releases a reference to an FLDoc. This must be called once to free an FLDoc you created. */ @@ -61,7 +61,7 @@ extern "C" { /** Looks up the Doc containing the Value, or NULL if there is none. @note Caller must release the FLDoc reference!! */ - FLEECE_PUBLIC FLDoc FL_NULLABLE FLValue_FindDoc(FLValue FL_NULLABLE) FLAPI FLPURE; + NODISCARD FLEECE_PUBLIC FLDoc FL_NULLABLE FLValue_FindDoc(FLValue FL_NULLABLE) FLAPI FLPURE; /** Associates an arbitrary pointer value with a document, and thus its contained values. Allows client code to associate its own pointer with this FLDoc and its Values, diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLEncoder.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLEncoder.h index 7aa1368..7ce213e 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLEncoder.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLEncoder.h @@ -48,7 +48,7 @@ extern "C" { /** Creates a new encoder, for generating Fleece data. Call FLEncoder_Free when done. */ - FLEECE_PUBLIC FLEncoder FLEncoder_New(void) FLAPI; + NODISCARD FLEECE_PUBLIC FLEncoder FLEncoder_New(void) FLAPI; /** Creates a new encoder, allowing some options to be customized. @param format The output format to generate (Fleece, JSON, or JSON5.) @@ -57,12 +57,12 @@ extern "C" { as a single shared value. This saves space but makes encoding slightly slower. You should only turn this off if you know you're going to be writing large numbers of non-repeated strings. (Default is true) */ - FLEECE_PUBLIC FLEncoder FLEncoder_NewWithOptions(FLEncoderFormat format, + NODISCARD FLEECE_PUBLIC FLEncoder FLEncoder_NewWithOptions(FLEncoderFormat format, size_t reserveSize, bool uniqueStrings) FLAPI; /** Creates a new Fleece encoder that writes to a file, not to memory. */ - FLEECE_PUBLIC FLEncoder FLEncoder_NewWritingToFile(FILE*, bool uniqueStrings) FLAPI; + NODISCARD FLEECE_PUBLIC FLEncoder FLEncoder_NewWritingToFile(FILE*, bool uniqueStrings) FLAPI; /** Frees the space used by an encoder. */ FLEECE_PUBLIC void FLEncoder_Free(FLEncoder FL_NULLABLE) FLAPI; @@ -201,12 +201,12 @@ extern "C" { /** Ends encoding; if there has been no error, it returns the encoded Fleece data packaged in an FLDoc. (This function does not support JSON encoding.) This does not free the FLEncoder; call FLEncoder_Free (or FLEncoder_Reset) next. */ - MUST_USE_RESULT + NODISCARD FLEECE_PUBLIC FLDoc FL_NULLABLE FLEncoder_FinishDoc(FLEncoder, FLError* FL_NULLABLE outError) FLAPI; /** Ends encoding; if there has been no error, it returns the encoded data, else null. This does not free the FLEncoder; call FLEncoder_Free (or FLEncoder_Reset) next. */ - MUST_USE_RESULT + NODISCARD FLEECE_PUBLIC FLSliceResult FLEncoder_Finish(FLEncoder, FLError* FL_NULLABLE outError) FLAPI; /** @} */ diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLExpert.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLExpert.h index b52b77c..9dd697f 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLExpert.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLExpert.h @@ -31,6 +31,12 @@ extern "C" { /** \defgroup Obscure Rarely-needed or advanced functions @{ */ + /** For use with \ref FLDoc_FromResultData. This option prevents the function from parsing the + data at all; you are responsible for locating the FLValues in it. + This is for the case where you have trusted data in a custom format that contains Fleece- + encoded data within it. You still need an FLDoc to access the data safely (especially to + retain FLValues), but it can't be parsed as-is. */ + #define kFLTrustedDontParse FLTrust(-1) /** \name Delta Compression @{ @@ -48,7 +54,7 @@ extern "C" { @param nuu A value that's typically the new/changed state of the `old` data. @return JSON data representing the changes from `old` to `nuu`, or NULL on (extremely unlikely) failure. */ - FLEECE_PUBLIC FLSliceResult FLCreateJSONDelta(FLValue FL_NULLABLE old, + NODISCARD FLEECE_PUBLIC FLSliceResult FLCreateJSONDelta(FLValue FL_NULLABLE old, FLValue FL_NULLABLE nuu) FLAPI; /** Writes JSON that describes the changes to turn the value `old` into `nuu`. @@ -58,7 +64,7 @@ extern "C" { @param jsonEncoder An encoder to write the JSON to. Must have been created using `FLEncoder_NewWithOptions`, with JSON or JSON5 format. @return True on success, false on (extremely unlikely) failure. */ - FLEECE_PUBLIC bool FLEncodeJSONDelta(FLValue FL_NULLABLE old, + NODISCARD FLEECE_PUBLIC bool FLEncodeJSONDelta(FLValue FL_NULLABLE old, FLValue FL_NULLABLE nuu, FLEncoder jsonEncoder) FLAPI; @@ -71,7 +77,7 @@ extern "C" { @param jsonDelta A JSON-encoded delta created by `FLCreateJSONDelta` or `FLEncodeJSONDelta`. @param outError On failure, error information will be stored where this points, if non-null. @return The corresponding `nuu` value, encoded as Fleece, or null if an error occurred. */ - FLEECE_PUBLIC FLSliceResult FLApplyJSONDelta(FLValue FL_NULLABLE old, + NODISCARD FLEECE_PUBLIC FLSliceResult FLApplyJSONDelta(FLValue FL_NULLABLE old, FLSlice jsonDelta, FLError* FL_NULLABLE outError) FLAPI; @@ -110,17 +116,18 @@ extern "C" { */ /** Creates a new empty FLSharedKeys object, which must eventually be released. */ - FLEECE_PUBLIC FLSharedKeys FLSharedKeys_New(void) FLAPI; + NODISCARD FLEECE_PUBLIC FLSharedKeys FLSharedKeys_New(void) FLAPI; typedef bool (*FLSharedKeysReadCallback)(void* FL_NULLABLE context, FLSharedKeys); - FLEECE_PUBLIC FLSharedKeys FLSharedKeys_NewWithRead(FLSharedKeysReadCallback, + NODISCARD FLEECE_PUBLIC FLSharedKeys FLSharedKeys_NewWithRead(FLSharedKeysReadCallback, void* FL_NULLABLE context) FLAPI; /** Returns a data blob containing the current state (all the keys and their integers.) */ - FLEECE_PUBLIC FLSliceResult FLSharedKeys_GetStateData(FLSharedKeys) FLAPI; + NODISCARD FLEECE_PUBLIC FLSliceResult FLSharedKeys_GetStateData(FLSharedKeys) FLAPI; - /** Updates an FLSharedKeys with saved state data created by \ref FLSharedKeys_GetStateData. */ + /** Updates an FLSharedKeys with saved state data created by \ref FLSharedKeys_GetStateData. + Returns true if new keys were added, false if not. */ FLEECE_PUBLIC bool FLSharedKeys_LoadStateData(FLSharedKeys, FLSlice) FLAPI; /** Writes the current state to a Fleece encoder as a single value, @@ -129,7 +136,7 @@ extern "C" { /** Updates an FLSharedKeys object with saved state, a Fleece value previously written by \ref FLSharedKeys_WriteState. */ - FLEECE_PUBLIC bool FLSharedKeys_LoadState(FLSharedKeys, FLValue) FLAPI; + NODISCARD FLEECE_PUBLIC bool FLSharedKeys_LoadState(FLSharedKeys, FLValue) FLAPI; /** Maps a key string to a number in the range [0...2047], or returns -1 if it isn't mapped. If the key doesn't already have a mapping, and the `add` flag is true, @@ -148,8 +155,11 @@ extern "C" { /** Reverts an FLSharedKeys by "forgetting" any keys added since it had the count `oldCount`. */ FLEECE_PUBLIC void FLSharedKeys_RevertToCount(FLSharedKeys, unsigned oldCount) FLAPI; + /** Disable caching of the SharedKeys.. */ + FLEECE_PUBLIC void FLSharedKeys_DisableCaching(FLSharedKeys) FLAPI; + /** Increments the reference count of an FLSharedKeys. */ - FLEECE_PUBLIC FLSharedKeys FL_NULLABLE FLSharedKeys_Retain(FLSharedKeys FL_NULLABLE) FLAPI; + NODISCARD FLEECE_PUBLIC FLSharedKeys FL_NULLABLE FLSharedKeys_Retain(FLSharedKeys FL_NULLABLE) FLAPI; /** Decrements the reference count of an FLSharedKeys, freeing it when it reaches zero. */ FLEECE_PUBLIC void FLSharedKeys_Release(FLSharedKeys FL_NULLABLE) FLAPI; @@ -159,7 +169,7 @@ extern "C" { /** Registers a range of memory containing Fleece data that uses the given shared keys. This allows Dict accessors to look up the values of shared keys. */ - FLEECE_PUBLIC FLSharedKeyScope FLSharedKeyScope_WithRange(FLSlice range, FLSharedKeys) FLAPI; + NODISCARD FLEECE_PUBLIC FLSharedKeyScope FLSharedKeyScope_WithRange(FLSlice range, FLSharedKeys) FLAPI; /** Unregisters a scope created by \ref FLSharedKeyScope_WithRange. */ FLEECE_PUBLIC void FLSharedKeyScope_Free(FLSharedKeyScope FL_NULLABLE) FLAPI; @@ -203,14 +213,14 @@ extern "C" { will be stored here (if it's not NULL.) @param outError On failure, the error code will be stored here (if it's not NULL.) @return The converted JSON. */ - FLEECE_PUBLIC FLStringResult FLJSON5_ToJSON(FLString json5, + NODISCARD FLEECE_PUBLIC FLStringResult FLJSON5_ToJSON(FLString json5, FLStringResult* FL_NULLABLE outErrorMessage, size_t* FL_NULLABLE outErrorPos, FLError* FL_NULLABLE outError) FLAPI; /** Directly converts JSON data to Fleece-encoded data. Not commonly needed. Prefer \ref FLDoc_FromJSON instead. */ - FLEECE_PUBLIC FLSliceResult FLData_ConvertJSON(FLSlice json, FLError* FL_NULLABLE outError) FLAPI; + NODISCARD FLEECE_PUBLIC FLSliceResult FLData_ConvertJSON(FLSlice json, FLError* FL_NULLABLE outError) FLAPI; /** @} */ @@ -246,24 +256,28 @@ extern "C" { (Due to internal buffering, this is not the same as FLEncoder_BytesWritten.) */ FLEECE_PUBLIC size_t FLEncoder_GetNextWritePos(FLEncoder) FLAPI; + #define kFLNoWrittenValue INTPTR_MIN + /** Returns an opaque reference to the last complete value written to the encoder, if possible. - Fails (returning 0) if nothing has been written, or if the value is inline and can't be - referenced this way -- that only happens with small scalars or empty collections. */ + Fails (returning kFLNoWrittenValue) if nothing has been written, or if the value is inline + and can't be referenced this way -- that only happens with small scalars or empty + collections. */ FLEECE_PUBLIC intptr_t FLEncoder_LastValueWritten(FLEncoder) FLAPI; /** Writes another reference (a "pointer") to an already-written value, given a reference previously returned from \ref FLEncoder_LastValueWritten. The effect is exactly the same as if you wrote the - entire value again, except that the size of the encoded data only grows by 4 bytes. */ - FLEECE_PUBLIC void FLEncoder_WriteValueAgain(FLEncoder, intptr_t preWrittenValue) FLAPI; + entire value again, except that the size of the encoded data only grows by 4 bytes. + Returns false if the reference couldn't be written. */ + FLEECE_PUBLIC bool FLEncoder_WriteValueAgain(FLEncoder, intptr_t preWrittenValue) FLAPI; /** Returns the data written so far as a standalone Fleece document, whose root is the last value written. You can continue writing, and the final output returned by \ref FLEncoder_Finish will consist of everything after this point. That second part can be used in the future by loading it as an `FLDoc` with the first part as its `extern` reference. */ - FLEECE_PUBLIC FLSliceResult FLEncoder_Snip(FLEncoder) FLAPI; + NODISCARD FLEECE_PUBLIC FLSliceResult FLEncoder_Snip(FLEncoder) FLAPI; /** Finishes encoding the current item, and returns its offset in the output data. */ - FLEECE_PUBLIC size_t FLEncoder_FinishItem(FLEncoder) FLAPI; + NODISCARD FLEECE_PUBLIC size_t FLEncoder_FinishItem(FLEncoder) FLAPI; /** In a JSON encoder, adds a newline ('\n') and prepares to start encoding another top-level object. The encoder MUST be not be within an array or dict. diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLJSON.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLJSON.h index 5dbc78c..677d3e4 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLJSON.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLJSON.h @@ -59,15 +59,15 @@ extern "C" { /** Creates an FLDoc from JSON-encoded data. The data is first encoded into Fleece, and the Fleece data is kept by the doc; the input JSON data is no longer needed after this function returns. */ - FLEECE_PUBLIC FLDoc FLDoc_FromJSON(FLSlice json, FLError* FL_NULLABLE outError) FLAPI; + NODISCARD FLEECE_PUBLIC FLDoc FLDoc_FromJSON(FLSlice json, FLError* FL_NULLABLE outError) FLAPI; /** Creates a new mutable Array from JSON. It is an error if the JSON is not an array. Its initial ref-count is 1, so a call to FLMutableArray_Release will free it. */ - FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLMutableArray_NewFromJSON(FLString json, FLError* FL_NULLABLE outError) FLAPI; + NODISCARD FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLMutableArray_NewFromJSON(FLString json, FLError* FL_NULLABLE outError) FLAPI; /** Creates a new mutable Dict from json. It is an error if the JSON is not a dictionary/object. Its initial ref-count is 1, so a call to FLMutableDict_Release will free it. */ - FLEECE_PUBLIC FLMutableDict FL_NULLABLE FLMutableDict_NewFromJSON(FLString json, FLError* FL_NULLABLE outError) FLAPI; + NODISCARD FLEECE_PUBLIC FLMutableDict FL_NULLABLE FLMutableDict_NewFromJSON(FLString json, FLError* FL_NULLABLE outError) FLAPI; /** Parses JSON data and writes the value(s) to the encoder as their Fleece equivalents. (This acts as a single write, like WriteInt; it's just that the value written is likely to diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLKeyPath.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLKeyPath.h index b448d77..9ed12e3 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLKeyPath.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLKeyPath.h @@ -37,8 +37,7 @@ extern "C" { A leading JSONPath-like `$.` is allowed but ignored. - A '\' can be used to escape a special character ('.', '[' or '$') at the start of a - property name (but not yet in the middle of a name.) + A '\' can be used to escape a special character ('.', '[' or '$'). */ #ifndef FL_IMPL @@ -46,24 +45,24 @@ extern "C" { #endif /** Creates a new FLKeyPath object by compiling a path specifier string. */ - FLEECE_PUBLIC FLKeyPath FL_NULLABLE FLKeyPath_New(FLSlice specifier, + NODISCARD FLEECE_PUBLIC FLKeyPath FL_NULLABLE FLKeyPath_New(FLSlice specifier, FLError* FL_NULLABLE outError) FLAPI; /** Frees a compiled FLKeyPath object. (It's ok to pass NULL.) */ FLEECE_PUBLIC void FLKeyPath_Free(FLKeyPath FL_NULLABLE) FLAPI; /** Evaluates a compiled key-path for a given Fleece root object. */ - FLEECE_PUBLIC FLValue FL_NULLABLE FLKeyPath_Eval(FLKeyPath, + NODISCARD FLEECE_PUBLIC FLValue FL_NULLABLE FLKeyPath_Eval(FLKeyPath, FLValue root) FLAPI; /** Evaluates a key-path from a specifier string, for a given Fleece root object. If you only need to evaluate the path once, this is a bit faster than creating an FLKeyPath object, evaluating, then freeing it. */ - FLEECE_PUBLIC FLValue FL_NULLABLE FLKeyPath_EvalOnce(FLSlice specifier, FLValue root, + NODISCARD FLEECE_PUBLIC FLValue FL_NULLABLE FLKeyPath_EvalOnce(FLSlice specifier, FLValue root, FLError* FL_NULLABLE outError) FLAPI; /** Returns a path in string form. */ - FLEECE_PUBLIC FLStringResult FLKeyPath_ToString(FLKeyPath path) FLAPI; + NODISCARD FLEECE_PUBLIC FLStringResult FLKeyPath_ToString(FLKeyPath path) FLAPI; /** Equality test. */ FLEECE_PUBLIC bool FLKeyPath_Equals(FLKeyPath path1, FLKeyPath path2) FLAPI; diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLMutable.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLMutable.h index 7aea9f5..1072e64 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLMutable.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLMutable.h @@ -55,12 +55,12 @@ extern "C" { also set, immutable values are also copied, recursively. If the source Array is NULL, then NULL is returned. */ - FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLArray_MutableCopy(FLArray FL_NULLABLE, + NODISCARD FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLArray_MutableCopy(FLArray FL_NULLABLE, FLCopyFlags) FLAPI; /** Creates a new empty mutable Array. Its initial ref-count is 1, so a call to FLMutableArray_Release will free it. */ - FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLMutableArray_New(void) FLAPI; + NODISCARD FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLMutableArray_New(void) FLAPI; /** Increments the ref-count of a mutable Array. */ static inline FLMutableArray FL_NULLABLE FLMutableArray_Retain(FLMutableArray FL_NULLABLE d) { @@ -108,7 +108,7 @@ extern "C" { - If the value is a mutable array, returns it. - If the value is an immutable array, this function makes a mutable copy, assigns the copy as the property value, and returns the copy. */ - FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLMutableArray_GetMutableArray(FLMutableArray FL_NULLABLE, + NODISCARD FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLMutableArray_GetMutableArray(FLMutableArray FL_NULLABLE, uint32_t index) FLAPI; /** Convenience function for getting an array-valued property in mutable form. @@ -116,7 +116,7 @@ extern "C" { - If the value is a mutable array, returns it. - If the value is an immutable array, this function makes a mutable copy, assigns the copy as the property value, and returns the copy. */ - FLEECE_PUBLIC FLMutableDict FL_NULLABLE FLMutableArray_GetMutableDict(FLMutableArray FL_NULLABLE, + NODISCARD FLEECE_PUBLIC FLMutableDict FL_NULLABLE FLMutableArray_GetMutableDict(FLMutableArray FL_NULLABLE, uint32_t index) FLAPI; @@ -303,21 +303,21 @@ extern "C" { You store a value to it by calling one of the nine `FLSlot_Set...` functions. \warning You should immediately store a value into the `FLSlot`. Do not keep it around; any changes to the array invalidate it.*/ - MUST_USE_RESULT + NODISCARD FLEECE_PUBLIC FLSlot FLMutableArray_Set(FLMutableArray, uint32_t index) FLAPI; /** Appends a null value to the array and returns an \ref FLSlot that refers to that position. You store a value to it by calling one of the nine `FLSlot_Set...` functions. \warning You should immediately store a value into the `FLSlot`. Do not keep it around; any changes to the array invalidate it.*/ - MUST_USE_RESULT + NODISCARD FLEECE_PUBLIC FLSlot FLMutableArray_Append(FLMutableArray) FLAPI; /** Returns an \ref FLSlot that refers to the given key/value pair of the given dictionary. You store a value to it by calling one of the nine `FLSlot_Set...` functions. \warning You should immediately store a value into the `FLSlot`. Do not keep it around; any changes to the dictionary invalidate it.*/ - MUST_USE_RESULT + NODISCARD FLEECE_PUBLIC FLSlot FLMutableDict_Set(FLMutableDict, FLString key) FLAPI; diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLSlice.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLSlice.h index 2850115..9713584 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLSlice.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/FLSlice.h @@ -60,7 +60,7 @@ typedef struct FLSlice { a `FLSliceResult` return value is to construct an `alloc_slice` from it, which will adopt the reference, and release it in its destructor. For example: `alloc_slice foo( CopyFoo() );` */ -typedef struct FLSliceResult { +struct NODISCARD FLSliceResult { const void* FL_NULLABLE buf; size_t size; @@ -69,7 +69,8 @@ typedef struct FLSliceResult { explicit operator FLSlice () const {return {buf, size};} inline explicit operator std::string() const; #endif -} FLSliceResult; +}; +typedef struct FLSliceResult FLSliceResult; /** A heap-allocated, reference-counted slice. This type is really just a hint in an API diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/Fleece+CoreFoundation.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/Fleece+CoreFoundation.h index 585c528..ce14e29 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/Fleece+CoreFoundation.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Headers/Fleece+CoreFoundation.h @@ -29,16 +29,16 @@ extern "C" { /** Writes a Core Foundation (or Objective-C) object to an Encoder. Supports all the JSON types, as well as CFData. */ - FLEECE_PUBLIC bool FLEncoder_WriteCFObject(FLEncoder, CFTypeRef) FLAPI; + NODISCARD FLEECE_PUBLIC bool FLEncoder_WriteCFObject(FLEncoder, CFTypeRef) FLAPI; /** Returns a Value as a corresponding CoreFoundation object. Caller must CFRelease the result. */ - FLEECE_PUBLIC CFTypeRef FLValue_CopyCFObject(FLValue FL_NULLABLE) FLAPI; + NODISCARD FLEECE_PUBLIC CFTypeRef FLValue_CopyCFObject(FLValue FL_NULLABLE) FLAPI; /** Same as FLDictGet, but takes the key as a CFStringRef. */ - FLEECE_PUBLIC FLValue FLDict_GetWithCFString(FLDict FL_NULLABLE, CFStringRef) FLAPI; + NODISCARD FLEECE_PUBLIC FLValue FLDict_GetWithCFString(FLDict FL_NULLABLE, CFStringRef) FLAPI; #ifdef __OBJC__ diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Info.plist b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Info.plist index d18d326..9ae8222 100644 Binary files a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Info.plist and b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Info.plist differ diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Modules/module.modulemap b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Modules/module.modulemap index 157018d..42fd88e 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Modules/module.modulemap +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/Modules/module.modulemap @@ -11,7 +11,11 @@ framework module CouchbaseLite { header "CBLEncryptable.h" header "CBLLog.h" header "CBLPlatform.h" + header "CBLPrediction.h" header "CBLQuery.h" + header "CBLQueryIndex.h" + header "CBLQueryIndexTypes.h" + header "CBLQueryTypes.h" header "CBLReplicator.h" header "CBLScope.h" diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/PrivacyInfo.xcprivacy b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/PrivacyInfo.xcprivacy index fe840a0..6cb5e91 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/PrivacyInfo.xcprivacy +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/CouchbaseLite.framework/PrivacyInfo.xcprivacy @@ -1,17 +1,23 @@ - - NSPrivacyAccessedAPITypes - - - NSPrivacyAccessedAPIType - NSPrivacyAccessedAPICategoryFileTimestamp - NSPrivacyAccessedAPITypeReasons - - C617.1 - - - - + + NSPrivacyTracking + + NSPrivacyTrackingDomains + + NSPrivacyCollectedDataTypes + + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryFileTimestamp + NSPrivacyAccessedAPITypeReasons + + C617.1 + + + + diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/dSYMs/CouchbaseLite.framework.dSYM/Contents/Info.plist b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/dSYMs/CouchbaseLite.framework.dSYM/Contents/Info.plist index f5bf4bc..dedf43b 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/dSYMs/CouchbaseLite.framework.dSYM/Contents/Info.plist +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/dSYMs/CouchbaseLite.framework.dSYM/Contents/Info.plist @@ -13,8 +13,8 @@ CFBundleSignature ???? CFBundleShortVersionString - 3.1.10 + 3.2.1 CFBundleVersion - 52760 + 9 diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/dSYMs/CouchbaseLite.framework.dSYM/Contents/Resources/DWARF/CouchbaseLite b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/dSYMs/CouchbaseLite.framework.dSYM/Contents/Resources/DWARF/CouchbaseLite index fe5921b..473e588 100644 Binary files a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/dSYMs/CouchbaseLite.framework.dSYM/Contents/Resources/DWARF/CouchbaseLite and b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64/dSYMs/CouchbaseLite.framework.dSYM/Contents/Resources/DWARF/CouchbaseLite differ diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/CouchbaseLite b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/CouchbaseLite index a57dfba..578fb25 100755 Binary files a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/CouchbaseLite and b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/CouchbaseLite differ diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLBase.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLBase.h index 5da21cd..d7866eb 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLBase.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLBase.h @@ -209,7 +209,7 @@ typedef struct CBLDocument CBLDocument; typedef struct CBLBlob CBLBlob; /** @} */ -/** \defgroup queries Queries +/** \defgroup query Query @{ */ /** A compiled database query. */ typedef struct CBLQuery CBLQuery; @@ -218,6 +218,16 @@ typedef struct CBLQuery CBLQuery; typedef struct CBLResultSet CBLResultSet; /** @} */ +/** \defgroup index Index + @{ */ +/** A query index. */ +typedef struct CBLQueryIndex CBLQueryIndex; + +#ifdef COUCHBASE_ENTERPRISE +typedef struct CBLIndexUpdater CBLIndexUpdater; +#endif +/** @} */ + /** \defgroup replication Replication @{ */ /** A background task that syncs a \ref CBLDatabase with a remote server or peer. */ diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLCollection.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLCollection.h index 6e91d27..35941b5 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLCollection.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLCollection.h @@ -19,7 +19,8 @@ #pragma once #include #include -#include +#include +#include CBL_CAPI_BEGIN @@ -154,12 +155,10 @@ CBLScope* CBLDatabase_DefaultScope(const CBLDatabase* db, CBLError* _cbl_nullable outError) CBLAPI; /** Returns the default collection. - @note The default collection may not exist if it was deleted. - Also, the default collection cannot be recreated after being deleted. @note You are responsible for releasing the returned collection. @param db The database. @param outError On failure, the error will be written here. - @return A \ref CBLCollection instance, or NULL if the default collection doesn't exist or an error occurred. */ + @return A \ref CBLCollection instance, or NULL if an error occurred. */ CBLCollection* _cbl_nullable CBLDatabase_DefaultCollection(const CBLDatabase* db, CBLError* _cbl_nullable outError) CBLAPI; @@ -170,17 +169,28 @@ CBLCollection* _cbl_nullable CBLDatabase_DefaultCollection(const CBLDatabase* db Getting information about a collection. */ -/** Returns the scope of the collection. +/** Returns the collection's scope. @note You are responsible for releasing the returned scope. @param collection The collection. - @return A \ref CBLScope instance. */ + @return The scope of the collection. */ CBLScope* CBLCollection_Scope(const CBLCollection* collection) CBLAPI; -/** Returns the collection name. +/** Returns the collection's name. @param collection The collection. @return The name of the collection. */ FLString CBLCollection_Name(const CBLCollection* collection) CBLAPI; +/** Returns the collection's fully qualified name in the '.' format. + @param collection The collection. + @return The fully qualified name of the collection. */ +FLString CBLCollection_FullName(const CBLCollection* collection) CBLAPI; + +/** Returns the collection's database. + @note The database object is owned by the collection object; you do not need to release it. + @param collection The collection. + @return The database of the collection. */ +CBLDatabase* CBLCollection_Database(const CBLCollection* collection) CBLAPI; + /** Returns the number of documents in the collection. @param collection The collection. @return the number of documents in the collection. */ @@ -371,6 +381,33 @@ bool CBLCollection_CreateFullTextIndex(CBLCollection *collection, CBLFullTextIndexConfiguration config, CBLError* _cbl_nullable outError) CBLAPI; +/** Creates an array index for use with UNNEST queries in the collection. + If an identical index with that name already exists, nothing happens (and no error is returned.) + If a non-identical index with that name already exists, it is deleted and re-created. + @param collection The collection. + @param name The name of the index. + @param config The index configuration. + @param outError On failure, an error is written here. + @return True on success, false on failure. */ +bool CBLCollection_CreateArrayIndex(CBLCollection *collection, + FLString name, + CBLArrayIndexConfiguration config, + CBLError* _cbl_nullable outError) CBLAPI; + +#ifdef COUCHBASE_ENTERPRISE +/** ENTERPRISE EDITION ONLY + + Creatres a vector index in the collection. + If an identical index with that name already exists, nothing happens (and no error is returned.) + If a non-identical index with that name already exists, it is deleted and re-created. + */ +bool CBLCollection_CreateVectorIndex(CBLCollection *collection, + FLString name, + CBLVectorIndexConfiguration config, + CBLError* _cbl_nullable outError) CBLAPI; + +#endif + /** Deletes an index in the collection by name. @param collection The collection. @param name The name of the index. @@ -389,6 +426,17 @@ _cbl_warn_unused FLMutableArray _cbl_nullable CBLCollection_GetIndexNames(CBLCollection *collection, CBLError* _cbl_nullable outError) CBLAPI; +/** Returns an index object representing an existing index in the collection. + @note You are responsible for releasing the returned index object. + @param collection The collection. + @param name The name of the index. + @param outError On failure, an error is written here. + @return A \ref CBLQueryIndex instance if the index exists, or NULL if the index doesn't exist or an error occurred. */ +_cbl_warn_unused +CBLQueryIndex* _cbl_nullable CBLCollection_GetIndex(CBLCollection* collection, + FLString name, + CBLError* _cbl_nullable outError) CBLAPI; + /** @} */ /** \name Change Listeners diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLDatabase.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLDatabase.h index 09e794b..071c1d3 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLDatabase.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLDatabase.h @@ -18,6 +18,7 @@ #pragma once #include +#include CBL_CAPI_BEGIN @@ -26,6 +27,29 @@ CBL_CAPI_BEGIN A \ref CBLDatabase is both a filesystem object and a container for documents. */ +#ifdef COUCHBASE_ENTERPRISE + +#ifdef __APPLE__ +#pragma mark - Database Extension +#endif + +/** \name Database Extension + @{ */ + +/** ENTERPRISE EDITION ONLY + + Enables Vector Search extension by specifying the extension path to search for the Vector Search extension library. + This function must be called before opening a database that intends to use the vector search extension. + @param path The file system path of the directory that contains the Vector Search extension library. + @param outError On return, will be set to the error that occurred. + @return True on success, false if there was an error. + @note Must be called before opening a database that intends to use the vector search extension. */ +bool CBL_EnableVectorSearch(FLString path, CBLError* _cbl_nullable outError) CBLAPI; + +/** @} */ + +#endif + #ifdef __APPLE__ #pragma mark - CONFIGURATION #endif @@ -68,6 +92,13 @@ typedef struct { power failure will not cause the loss of any data. FULL synchronous is very safe but it is also dramatically slower. */ bool fullSync; + + /** + Disable memory-mapped I/O. By default, memory-mapped I/O is enabled. + Disabling it may affect database performance. Typically, there is no need to modify this setting. + @note Memory-mapped I/O is always disabled on macOS to prevent database corruption, + so setting mmapDisabled value has no effect on the macOS platform. */ + bool mmapDisabled; } CBLDatabaseConfiguration; /** Returns the default database configuration. */ @@ -219,7 +250,6 @@ bool CBLDatabase_PerformMaintenance(CBLDatabase* db, /** @} */ - #ifdef __APPLE__ #pragma mark - ACCESSORS #endif @@ -244,6 +274,45 @@ const CBLDatabaseConfiguration CBLDatabase_Config(const CBLDatabase*) CBLAPI; /** @} */ +/** \name Query Indexes + @{ + Query Index Management + */ + +/** Creates a value index. + Indexes are persistent. + If an identical index with that name already exists, nothing happens (and no error is returned.) + If a non-identical index with that name already exists, it is deleted and re-created. + @warning Deprecated : Use CBLCollection_CreateValueIndex on the default collection instead. */ +bool CBLDatabase_CreateValueIndex(CBLDatabase *db, + FLString name, + CBLValueIndexConfiguration config, + CBLError* _cbl_nullable outError) CBLAPI; + +/** Creates a full-text index. + Indexes are persistent. + If an identical index with that name already exists, nothing happens (and no error is returned.) + If a non-identical index with that name already exists, it is deleted and re-created. + @warning Deprecated : Use CBLCollection_CreateFullTextIndex on the default collection instead. */ +bool CBLDatabase_CreateFullTextIndex(CBLDatabase *db, + FLString name, + CBLFullTextIndexConfiguration config, + CBLError* _cbl_nullable outError) CBLAPI; + +/** Deletes an index given its name. + @warning Deprecated : Use CBLCollection_DeleteIndex on the default collection instead. */ +bool CBLDatabase_DeleteIndex(CBLDatabase *db, + FLString name, + CBLError* _cbl_nullable outError) CBLAPI; + +/** Returns the names of the indexes on this database, as a Fleece array of strings. + @note You are responsible for releasing the returned Fleece array. + @warning Deprecated : Use CBLCollection_GetIndexNames on the default collection instead. */ +_cbl_warn_unused +FLArray CBLDatabase_GetIndexNames(CBLDatabase *db) CBLAPI; + + +/** @} */ #ifdef __APPLE__ #pragma mark - LISTENERS diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLDefaults.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLDefaults.h index d115a35..d1c39a9 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLDefaults.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLDefaults.h @@ -2,7 +2,7 @@ // CBLDefaults.h // CouchbaseLite // -// Copyright (c) 2023-present Couchbase, Inc All rights reserved. +// Copyright (c) 2024-present Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ #pragma once #include #include +#include CBL_CAPI_BEGIN @@ -33,11 +34,27 @@ CBL_CAPI_BEGIN Constants for default configuration values. */ +/** \name CBLDatabaseConfiguration + @{ +*/ + +/** [false] Full sync is off by default because the performance hit is seldom worth the benefit */ +CBL_PUBLIC extern const bool kCBLDefaultDatabaseFullSync; + +/** [false] Memory mapped database files are enabled by default */ +CBL_PUBLIC extern const bool kCBLDefaultDatabaseMmapDisabled; + +/** @} */ + /** \name CBLLogFileConfiguration @{ */ /** [false] Plaintext is not used, and instead binary encoding is used in log files */ +CBL_PUBLIC extern const bool kCBLDefaultLogFileUsePlaintext; + +/** [false] Plaintext is not used, and instead binary encoding is used in log files + @warning Deprecated : Use kCBLDefaultLogFileUsePlaintext instead. */ CBL_PUBLIC extern const bool kCBLDefaultLogFileUsePlainText; /** [524288] 512 KiB for the size of a log file */ @@ -46,7 +63,6 @@ CBL_PUBLIC extern const size_t kCBLDefaultLogFileMaxSize; /** [1] 1 rotated file present (2 total, including the currently active log file) */ CBL_PUBLIC extern const uint32_t kCBLDefaultLogFileMaxRotateCount; - /** @} */ /** \name CBLFullTextIndexConfiguration @@ -56,7 +72,6 @@ CBL_PUBLIC extern const uint32_t kCBLDefaultLogFileMaxRotateCount; /** [false] Accents and ligatures are not ignored when indexing via full text search */ CBL_PUBLIC extern const bool kCBLDefaultFullTextIndexIgnoreAccents; - /** @} */ /** \name CBLReplicatorConfiguration @@ -79,6 +94,10 @@ CBL_PUBLIC extern const unsigned kCBLDefaultReplicatorMaxAttemptsSingleShot; CBL_PUBLIC extern const unsigned kCBLDefaultReplicatorMaxAttemptsContinuous; /** [300] Max wait time between retry attempts in seconds */ +CBL_PUBLIC extern const unsigned kCBLDefaultReplicatorMaxAttemptsWaitTime; + +/** [300] Max wait time between retry attempts in seconds + @warning Deprecated : Use kCBLDefaultReplicatorMaxAttemptsWaitTime instead. */ CBL_PUBLIC extern const unsigned kCBLDefaultReplicatorMaxAttemptWaitTime; /** [false] Purge documents when a user loses access */ @@ -89,6 +108,31 @@ CBL_PUBLIC extern const bool kCBLDefaultReplicatorAcceptParentCookies; /** @} */ +#ifdef COUCHBASE_ENTERPRISE + +/** \name CBLVectorIndexConfiguration + @{ +*/ + +/** [false] Vectors are not lazily indexed, by default */ +CBL_PUBLIC extern const bool kCBLDefaultVectorIndexLazy; + +/** [kCBLDistanceMetricEuclideanSquared] By default, vectors are compared using Squared Euclidean metric. */ +CBL_PUBLIC extern const CBLDistanceMetric kCBLDefaultVectorIndexDistanceMetric; + +/** [0] By default, the value will be determined based on the number of centroids, encoding types, and the encoding parameters. */ +CBL_PUBLIC extern const unsigned kCBLDefaultVectorIndexMinTrainingSize; + +/** [0] By default, the value will be determined based on the number of centroids, encoding types, and the encoding parameters */ +CBL_PUBLIC extern const unsigned kCBLDefaultVectorIndexMaxTrainingSize; + +/** [0] By default, the value will be determined based on the number of centroids. */ +CBL_PUBLIC extern const unsigned kCBLDefaultVectorIndexNumProbes; + +/** @} */ + +#endif + /** @} */ CBL_CAPI_END diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLLog.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLLog.h index 6298efa..2c2c1b9 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLLog.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLLog.h @@ -128,7 +128,7 @@ typedef struct { size_t maxSize; /** Whether or not to log in plaintext (as opposed to binary.) Plaintext logging is slower and bigger. - The default is \ref kCBLDefaultLogFileUsePlainText. */ + The default is \ref kCBLDefaultLogFileUsePlaintext. */ bool usePlaintext; } CBLLogFileConfiguration; diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLPrediction.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLPrediction.h new file mode 100644 index 0000000..625e736 --- /dev/null +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLPrediction.h @@ -0,0 +1,57 @@ +// +// CBLPrediction.h +// +// Copyright (c) 2024 Couchbase, Inc All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#pragma once +#include + +#ifdef COUCHBASE_ENTERPRISE + +CBL_CAPI_BEGIN + +/** Predictive Model */ +typedef struct { + /** A pointer to any external data needed by the `prediction` callback, which will receive this as its first parameter. */ + void* _cbl_nullable context; + + /** Prediction callback, called from within a query (or document indexing) to run the prediction. + @param context The value of the CBLPredictiveModel's `context` field. + @param input The input dictionary from the query. + @return The output of the prediction function as an FLMutableDict, or NULL if there is no output. + @note The output FLMutableDict will be automatically released after the prediction callback is called. + @warning This function must be "pure": given the same input parameters it must always + produce the same output (otherwise indexes or queries may be messed up). + It MUST NOT alter the database or any documents, nor run a query: either of + those are very likely to cause a crash. */ + FLMutableDict _cbl_nullable (* _cbl_nonnull prediction)(void* _cbl_nullable context, FLDict input); + + /** Unregistered callback, called if the model is unregistered, so it can release resources. */ + void (*_cbl_nullable unregistered)(void* context); +} CBLPredictiveModel; + +/** Registers a predictive model. + @param name The name. + @param model The predictive model. */ +void CBL_RegisterPredictiveModel(FLString name, CBLPredictiveModel model) CBLAPI; + +/** Unregisters the predictive model. + @param name The name of the registered predictive model. */ +void CBL_UnregisterPredictiveModel(FLString name) CBLAPI; + +CBL_CAPI_END + +#endif diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLQuery.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLQuery.h index a4e10f1..321b424 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLQuery.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLQuery.h @@ -18,33 +18,26 @@ #pragma once #include +#include CBL_CAPI_BEGIN - -/** \defgroup queries Queries +/** \defgroup query Query @{ A CBLQuery represents a compiled database query. The query language is a large subset of the [N1QL](https://www.couchbase.com/products/n1ql) language from Couchbase Server, which you can think of as "SQL for JSON" or "SQL++". - Queries may be given either in - [N1QL syntax](https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/index.html), - or in JSON using a - [schema](https://github.com/couchbase/couchbase-lite-core/wiki/JSON-Query-Schema) - that resembles a parse tree of N1QL. The JSON syntax is harder for humans, but much more + Supported Query languages: + [N1QL](https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/index.html) + + [JSON](https://github.com/couchbase/couchbase-lite-core/wiki/JSON-Query-Schema) + + JSON language resembles a parse tree of N1QL. The JSON syntax is harder for humans, but much more amenable to machine generation, if you need to create queries programmatically or translate them from some other form. */ - -/** Query languages */ -typedef CBL_ENUM(uint32_t, CBLQueryLanguage) { - kCBLJSONLanguage, ///< [JSON query schema](https://github.com/couchbase/couchbase-lite-core/wiki/JSON-Query-Schema) - kCBLN1QLLanguage ///< [N1QL syntax](https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/index.html) -}; - - /** \name Query objects @{ */ @@ -150,16 +143,16 @@ bool CBLResultSet_Next(CBLResultSet*) CBLAPI; /** Returns the value of a column of the current result, given its (zero-based) numeric index. This may return a NULL pointer, indicating `MISSING`, if the value doesn't exist, e.g. if the column is a property that doesn't exist in the document. */ -FLValue CBLResultSet_ValueAtIndex(const CBLResultSet*, - unsigned index) CBLAPI; +FLValue _cbl_nullable CBLResultSet_ValueAtIndex(const CBLResultSet*, + unsigned index) CBLAPI; /** Returns the value of a column of the current result, given its name. This may return a NULL pointer, indicating `MISSING`, if the value doesn't exist, e.g. if the column is a property that doesn't exist in the document. (Or, of course, if the key is not a column name in this query.) @note See \ref CBLQuery_ColumnName for a discussion of column names. */ -FLValue CBLResultSet_ValueForKey(const CBLResultSet*, - FLString key) CBLAPI; +FLValue _cbl_nullable CBLResultSet_ValueForKey(const CBLResultSet*, + FLString key) CBLAPI; /** Returns the current result as an array of column values. @warning The array reference is only valid until the result-set is advanced or released. @@ -179,7 +172,6 @@ CBL_REFCOUNTED(CBLResultSet*, ResultSet); /** @} */ - /** \name Change listener @{ Adding a change listener to a query turns it into a "live query". When changes are made to @@ -233,106 +225,6 @@ CBLResultSet* _cbl_nullable CBLQuery_CopyCurrentResults(const CBLQuery* query, /** @} */ - - -/** \name Database Indexes - @{ - Indexes are used to speed up queries by allowing fast -- O(log n) -- lookup of documents - that have specific values or ranges of values. The values may be properties, or expressions - based on properties. - - An index will speed up queries that use the expression it indexes, but it takes up space in - the database file, and it slows down document saves slightly because it needs to be kept up - to date when documents change. - - Tuning a database with indexes can be a tricky task. Fortunately, a lot has been written about - it in the relational-database (SQL) realm, and much of that advice holds for Couchbase Lite. - You may find SQLite's documentation particularly helpful since Couchbase Lite's querying is - based on SQLite. - - Two types of indexes are currently supported: - * Value indexes speed up queries by making it possible to look up property (or expression) - values without scanning every document. They're just like regular indexes in SQL or N1QL. - Multiple expressions are supported; the first is the primary key, second is secondary. - Expressions must evaluate to scalar types (boolean, number, string). - * Full-Text Search (FTS) indexes enable fast search of natural-language words or phrases - by using the `MATCH` operator in a query. A FTS index is **required** for full-text - search: a query with a `MATCH` operator will fail to compile unless there is already a - FTS index for the property/expression being matched. Only a single expression is - currently allowed, and it must evaluate to a string. */ - -/** Value Index Configuration. */ -typedef struct { - /** The language used in the expressions. */ - CBLQueryLanguage expressionLanguage; - - /** The expressions describing each coloumn of the index. The expressions could be specified - in a JSON Array or in N1QL syntax using comma delimiter. */ - FLString expressions; -} CBLValueIndexConfiguration; - -/** Creates a value index. - Indexes are persistent. - If an identical index with that name already exists, nothing happens (and no error is returned.) - If a non-identical index with that name already exists, it is deleted and re-created. - @warning Deprecated : Use CBLCollection_CreateValueIndex on the default collection instead. */ -bool CBLDatabase_CreateValueIndex(CBLDatabase *db, - FLString name, - CBLValueIndexConfiguration config, - CBLError* _cbl_nullable outError) CBLAPI; - - -/** Full-Text Index Configuration. */ -typedef struct { - /** The language used in the expressions (Required). */ - CBLQueryLanguage expressionLanguage; - - /** The expressions describing each coloumn of the index. The expressions could be specified - in a JSON Array or in N1QL syntax using comma delimiter. (Required) */ - FLString expressions; - - /** Should diacritical marks (accents) be ignored? - Defaults to \ref kCBLDefaultFullTextIndexIgnoreAccents. - Generally this should be left `false` for non-English text. */ - bool ignoreAccents; - - /** The dominant language. Setting this enables word stemming, i.e. - matching different cases of the same word ("big" and "bigger", for instance) and ignoring - common "stop-words" ("the", "a", "of", etc.) - - Can be an ISO-639 language code or a lowercase (English) language name; supported - languages are: da/danish, nl/dutch, en/english, fi/finnish, fr/french, de/german, - hu/hungarian, it/italian, no/norwegian, pt/portuguese, ro/romanian, ru/russian, - es/spanish, sv/swedish, tr/turkish. - - If left null, or set to an unrecognized language, no language-specific behaviors - such as stemming and stop-word removal occur. */ - FLString language; -} CBLFullTextIndexConfiguration; - -/** Creates a full-text index. - Indexes are persistent. - If an identical index with that name already exists, nothing happens (and no error is returned.) - If a non-identical index with that name already exists, it is deleted and re-created. - @warning Deprecated : Use CBLCollection_CreateFullTextIndex on the default collection instead. */ -bool CBLDatabase_CreateFullTextIndex(CBLDatabase *db, - FLString name, - CBLFullTextIndexConfiguration config, - CBLError* _cbl_nullable outError) CBLAPI; - -/** Deletes an index given its name. - @warning Deprecated : Use CBLCollection_DeleteIndex on the default collection instead. */ -bool CBLDatabase_DeleteIndex(CBLDatabase *db, - FLString name, - CBLError* _cbl_nullable outError) CBLAPI; - -/** Returns the names of the indexes on this database, as a Fleece array of strings. - @note You are responsible for releasing the returned Fleece array. - @warning Deprecated : Use CBLCollection_GetIndexNames on the default collection instead. */ -_cbl_warn_unused -FLArray CBLDatabase_GetIndexNames(CBLDatabase *db) CBLAPI; - -/** @} */ /** @} */ CBL_CAPI_END diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLQueryIndex.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLQueryIndex.h new file mode 100644 index 0000000..79bed5a --- /dev/null +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLQueryIndex.h @@ -0,0 +1,161 @@ +// +// CBLQueryIndex.h +// +// Copyright (c) 2024 Couchbase, Inc All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#pragma once +#include +#include + +CBL_CAPI_BEGIN + +/** \defgroup index Index + @{ + Indexes are used to speed up queries by allowing fast -- O(log n) -- lookup of documents + that have specific values or ranges of values. The values may be properties, or expressions + based on properties. + + An index will speed up queries that use the expression it indexes, but it takes up space in + the database file, and it slows down document saves slightly because it needs to be kept up + to date when documents change. + + Tuning a database with indexes can be a tricky task. Fortunately, a lot has been written about + it in the relational-database (SQL) realm, and much of that advice holds for Couchbase Lite. + You may find SQLite's documentation particularly helpful since Couchbase Lite's querying is + based on SQLite. + + Supported index types: + * Value indexes speed up queries by making it possible to look up property (or expression) + values without scanning every document. They're just like regular indexes in SQL or N1QL. + Multiple expressions are supported; the first is the primary key, second is secondary. + Expressions must evaluate to scalar types (boolean, number, string). + + * Full-Text Search (FTS) indexes enable fast search of natural-language words or phrases + by using the `MATCH()` function in a query. A FTS index is **required** for full-text + search: a query with a `MATCH()` function will fail to compile unless there is already a + FTS index for the property/expression being matched. + + * (Enterprise Edition Only) Vector indexes allows efficient search of ML vectors by using + the `VECTOR_MATCH()` function in a query. The `CouchbaseLiteVectorSearch` + extension library is **required** to use the functionality. Use \ref CBL_EnableVectorSearch + function to set the directoary path containing the extension library. */ + +/** \name CBLQueryIndex + @{ + CBLQueryIndex represents an existing index in a collection. + + Available in the enterprise edition, the \ref CBLQueryIndex can be used to obtain + a \ref CBLIndexUpdater object for updating the vector index in lazy mode. */ +CBL_REFCOUNTED(CBLQueryIndex*, QueryIndex); + +/** Returns the index's name. + @param index The index. + @return The name of the index. */ +FLString CBLQueryIndex_Name(const CBLQueryIndex* index) CBLAPI; + +/** Returns the collection that the index belongs to. + @param index The index. + @return A \ref CBLCollection instance that the index belongs to. */ +CBLCollection* CBLQueryIndex_Collection(const CBLQueryIndex* index) CBLAPI; + +#ifdef COUCHBASE_ENTERPRISE + +CBL_REFCOUNTED(CBLIndexUpdater*, IndexUpdater); + +/** ENTERPRISE EDITION ONLY + + Finds new or updated documents for which vectors need to be (re)computed and returns an \ref CBLIndexUpdater object + for setting the computed vectors to update the index. If the index is not lazy, an error will be returned. + @note For updating lazy vector indexes only. + @note You are responsible for releasing the returned A \ref CBLIndexUpdater object. + @param index The index. + @param limit The maximum number of vectors to be computed. + @param outError On failure, an error is written here. + @return A \ref CBLIndexUpdater object for setting the computed vectors to update the index, + or NULL if the index is up-to-date or an error occurred. */ +_cbl_warn_unused +CBLIndexUpdater* _cbl_nullable CBLQueryIndex_BeginUpdate(CBLQueryIndex* index, + size_t limit, + CBLError* _cbl_nullable outError) CBLAPI; + +/** @} */ + +/** \name IndexUpdater + @{ + CBLIndexUpdater used for updating the index in lazy mode. Currently, the vector index is the only index type that + can be updated lazily. + */ + +/** ENTERPRISE EDITION ONLY + + Returns the total number of vectors to compute and set for updating the index. + @param updater The index updater. + @return The total number of vectors to compute and set for updating the index. */ +size_t CBLIndexUpdater_Count(const CBLIndexUpdater* updater) CBLAPI; + +/** ENTERPRISE EDITION ONLY + + Returns the valut at the given index to compute a vector from. + @note The returned Fleece value is valid unilt its \ref CBLIndexUpdater is released. + If you want to keep it longer, retain it with `FLRetain`. + @param updater The index updater. + @param index The zero-based index. + @return A Fleece value of the index's evaluated expression at the given index. */ +FLValue CBLIndexUpdater_Value(CBLIndexUpdater* updater, size_t index) CBLAPI; + +/** ENTERPRISE EDITION ONLY + + Sets the vector for the value corresponding to the given index. + Setting null vector means that there is no vector for the value, and any existing vector + will be removed when the `CBLIndexUpdater_Finish` is called. + @param updater The index updater. + @param index The zero-based index. + @param vector A pointer to the vector which is an array of floats, or NULL if there is no vector. + @param dimension The dimension of `vector`. Must be equal to the dimension value set in the vector index config. + @param outError On failure, an error is written here. + @return True if success, or False if an error occurred. */ +bool CBLIndexUpdater_SetVector(CBLIndexUpdater* updater, + size_t index, + const float vector[_cbl_nullable], + size_t dimension, + CBLError* _cbl_nullable outError) CBLAPI; + +/** ENTERPRISE EDITION ONLY + + Skip setting the vector for the value corresponding to the index. + The vector will be required to compute and set again when the `CBLQueryIndex_BeginUpdate` is later called. + @param updater The index updater. + @param index The zero-based index. */ +void CBLIndexUpdater_SkipVector(CBLIndexUpdater* updater, size_t index) CBLAPI; + +/** ENTERPRISE EDITION ONLY + + Updates the index with the computed vectors and removes any index rows for which null vector was given. + If there are any indexes that do not have their vector value set or are skipped, a error will be returned. + @note Before calling `CBLIndexUpdater_Finish`, the set vectors are kept in the memory. + @warning The index updater cannot be used after calling `CBLIndexUpdater_Finish`. + @param updater The index updater. + @param outError On failure, an error is written here. + @return True if success, or False if an error occurred. */ +bool CBLIndexUpdater_Finish(CBLIndexUpdater* updater, CBLError* _cbl_nullable outError) CBLAPI; + +#endif + +/** @} */ + +/** @} */ + +CBL_CAPI_END diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLQueryIndexTypes.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLQueryIndexTypes.h new file mode 100644 index 0000000..b26350e --- /dev/null +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLQueryIndexTypes.h @@ -0,0 +1,206 @@ +// +// CBLQueryIndexTypes.h +// +// Copyright (c) 2024 Couchbase, Inc All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#pragma once +#include +#include + +CBL_CAPI_BEGIN + +/** \defgroup index Index + @{ */ + +/** \name Index Configuration + @{ */ + +/** Value Index Configuration. */ +typedef struct { + /** The language used in the expressions. */ + CBLQueryLanguage expressionLanguage; + + /** The expressions describing each coloumn of the index. The expressions could be specified + in a JSON Array or in N1QL syntax using comma delimiter. */ + FLString expressions; +} CBLValueIndexConfiguration; + +/** Full-Text Index Configuration. */ +typedef struct { + /** The language used in the expressions (Required). */ + CBLQueryLanguage expressionLanguage; + + /** The expressions describing each coloumn of the index. The expressions could be specified + in a JSON Array or in N1QL syntax using comma delimiter. (Required) */ + FLString expressions; + + /** Should diacritical marks (accents) be ignored? + Defaults to \ref kCBLDefaultFullTextIndexIgnoreAccents. + Generally this should be left `false` for non-English text. */ + bool ignoreAccents; + + /** The dominant language. Setting this enables word stemming, i.e. + matching different cases of the same word ("big" and "bigger", for instance) and ignoring + common "stop-words" ("the", "a", "of", etc.) + + Can be an ISO-639 language code or a lowercase (English) language name; supported + languages are: da/danish, nl/dutch, en/english, fi/finnish, fr/french, de/german, + hu/hungarian, it/italian, no/norwegian, pt/portuguese, ro/romanian, ru/russian, + es/spanish, sv/swedish, tr/turkish. + + If left null, or set to an unrecognized language, no language-specific behaviors + such as stemming and stop-word removal occur. */ + FLString language; +} CBLFullTextIndexConfiguration; + +/** Array Index Configuration for indexing property values within arrays + in documents, intended for use with the UNNEST query. */ +typedef struct { + /** The language used in the expressions (Required). */ + CBLQueryLanguage expressionLanguage; + + /** Path to the array, which can be nested to be indexed (Required). + Use "[]" to represent a property that is an array of each nested array level. + For a single array or the last level array, the "[]" is optional. For instance, + use "contacts[].phones" to specify an array of phones within each contact. */ + FLString path; + + /** Optional expressions representing the values within the array to be + indexed. The expressions could be specified in a JSON Array or in N1QL syntax + using comma delimiter. If the array specified by the path contains scalar values, + the expressions should be left unset or set to null. */ + FLString expressions; +} CBLArrayIndexConfiguration; + +#ifdef COUCHBASE_ENTERPRISE + +/** An opaque object representing vector encoding type to use in CBLVectorIndexConfiguration. */ +typedef struct CBLVectorEncoding CBLVectorEncoding; + +/** Creates a no-encoding type to use in CBLVectorIndexConfiguration; 4 bytes per dimension, no data loss. + @return A None encoding object. */ +_cbl_warn_unused +CBLVectorEncoding* CBLVectorEncoding_CreateNone(void) CBLAPI; + +/** Scalar Quantizer encoding type */ +typedef CBL_ENUM(uint32_t, CBLScalarQuantizerType) { + kCBLSQ4 = 4, ///< 4 bits per dimension + kCBLSQ6 = 6, ///< 6 bits per dimension + kCBLSQ8 = 8 ///< 8 bits per dimension +}; + +/** Creates a Scalar Quantizer encoding to use in CBLVectorIndexConfiguration. + @param type Scalar Quantizer Type. + @return A Scalar Quantizer encoding object. */ +_cbl_warn_unused +CBLVectorEncoding* CBLVectorEncoding_CreateScalarQuantizer(CBLScalarQuantizerType type) CBLAPI; + +/** Creates a Product Quantizer encoding to use in CBLVectorIndexConfiguration. + @param subquantizers Number of subquantizers. Must be > 1 and a factor of vector dimensions. + @param bits Number of bits. Must be >= 4 and <= 12. + @return A Product Quantizer encoding object. */ +_cbl_warn_unused +CBLVectorEncoding* CBLVectorEncoding_CreateProductQuantizer(unsigned subquantizers, unsigned bits) CBLAPI; + +/** Frees a CBLVectorEncoding object. The encoding object can be freed after the index is created. */ +void CBLVectorEncoding_Free(CBLVectorEncoding* _cbl_nullable) CBLAPI; + +/** Distance metric to use in CBLVectorIndexConfiguration. */ +typedef CBL_ENUM(uint32_t, CBLDistanceMetric) { + kCBLDistanceMetricEuclideanSquared = 1, ///< Squared Euclidean distance (AKA Squared L2) + kCBLDistanceMetricCosine, ///< Cosine distance (1.0 - Cosine Similarity) + kCBLDistanceMetricEuclidean, ///< Euclidean distance (AKA L2) + kCBLDistanceMetricDot ///< Dot-product distance (Negative of dot-product) +}; + +/** ENTERPRISE EDITION ONLY + + Vector Index Configuration. */ +typedef struct { + /** The language used in the expressions (Required). */ + CBLQueryLanguage expressionLanguage; + + /** The expression could be specified in a JSON Array or in N1QL syntax depending on + the expressionLanguage. (Required) + + For non-lazy indexes, an expression returning either a vector, which is an array of 32-bit + floating-point numbers, or a Base64 string representing an array of 32-bit floating-point + numbers in little-endian order. + + For lazy indexex, an expression returning a value for computing a vector lazily when using + \ref CBLIndexUpdater to add or update the vector into the index. */ + FLString expression; + + /** The number of vector dimensions. (Required) + @note The maximum number of vector dimensions supported is 4096. */ + unsigned dimensions; + + /** The number of centroids which is the number buckets to partition the vectors in the index. (Required) + @note The recommended number of centroids is the square root of the number of vectors to be indexed, + and the maximum number of centroids supported is 64,000.*/ + unsigned centroids; + + /** The boolean flag indicating that index is lazy or not. The default value is false. + + If the index is lazy, it will not be automatically updated when the documents in the collection are changed, + except when the documents are deleted or purged. + + When configuring the index to be lazy, the expression set to the config is the expression that returns + a value used for computing the vector. + + To update the lazy index, use a CBLIndexUpdater object, which can be obtained + from a CBLQueryIndex object. To get a CBLQueryIndex object, call CBLCollection_GetIndex. */ + bool isLazy; + + /** Vector encoding type. The default value is 8-bits Scalar Quantizer. */ + CBLVectorEncoding* encoding; + + /** Distance Metric type. The default value is euclidean distance. */ + CBLDistanceMetric metric; + + /** The minimum number of vectors for training the index. + The default value is zero, meaning that minTrainingSize will be determined based on + the number of centroids, encoding types, and the encoding parameters. + + @note The training will occur at or before the APPROX_VECTOR_DISANCE query is + executed, provided there is enough data at that time, and consequently, if + training is triggered during a query, the query may take longer to return + results. + + @note If a query is executed against the index before it is trained, a full + scan of the vectors will be performed. If there are insufficient vectors + in the database for training, a warning message will be logged, + indicating the required number of vectors. */ + unsigned minTrainingSize; + + /** The maximum number of vectors used for training the index. + The default value is zero, meaning that the maxTrainingSize will be determined based on + the number of centroids, encoding types, and encoding parameters. */ + unsigned maxTrainingSize; + + /** The number of centroids that will be scanned during a query. + The default value is zero, meaning that the numProbes will be determined based on + the number of centroids. */ + unsigned numProbes; +} CBLVectorIndexConfiguration; + +#endif + +/** @} */ + +/** @} */ + +CBL_CAPI_END diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLQueryTypes.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLQueryTypes.h new file mode 100644 index 0000000..25ad9aa --- /dev/null +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLQueryTypes.h @@ -0,0 +1,35 @@ +// +// CBLQueryTypes.h +// +// Copyright (c) 2024 Couchbase, Inc All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#pragma once +#include + +CBL_CAPI_BEGIN + +/** \defgroup queries Queries + @{ */ + +/** Supported Query languages */ +typedef CBL_ENUM(uint32_t, CBLQueryLanguage) { + kCBLJSONLanguage, ///< [JSON query schema](https://github.com/couchbase/couchbase-lite-core/wiki/JSON-Query-Schema) + kCBLN1QLLanguage ///< [N1QL syntax](https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/index.html) +}; + +/** @} */ + +CBL_CAPI_END diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLReplicator.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLReplicator.h index 9d2a627..1c61c87 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLReplicator.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLReplicator.h @@ -343,7 +343,7 @@ typedef struct { unsigned maxAttempts; /** Max wait time between retry attempts in seconds. - The default value \ref kCBLDefaultReplicatorMaxAttemptWaitTime. */ + The default value \ref kCBLDefaultReplicatorMaxAttemptsWaitTime. */ unsigned maxAttemptWaitTime; //-- WebSocket: @@ -418,8 +418,11 @@ typedef struct { @warning Deprecated : Use documentPropertyDecryptor instead. */ CBLPropertyDecryptor _cbl_nullable propertyDecryptor; - CBLDocumentPropertyEncryptor _cbl_nullable documentPropertyEncryptor; ///< Optional callback to encrypt \ref CBLEncryptable values. - CBLDocumentPropertyDecryptor _cbl_nullable documentPropertyDecryptor; ///< Optional callback to decrypt encrypted \ref CBLEncryptable values. + /** Optional callback to encrypt \ref CBLEncryptable values. */ + CBLDocumentPropertyEncryptor _cbl_nullable documentPropertyEncryptor; + + /** Optional callback to decrypt encrypted \ref CBLEncryptable values. */ + CBLDocumentPropertyDecryptor _cbl_nullable documentPropertyDecryptor; #endif /** The collections to replicate with the target's endpoint (Required if the database is not set). */ @@ -459,6 +462,7 @@ CBLReplicator* _cbl_nullable CBLReplicator_Create(const CBLReplicatorConfigurati const CBLReplicatorConfiguration* CBLReplicator_Config(CBLReplicator*) CBLAPI; /** Starts a replicator, asynchronously. Does nothing if it's already started. + @note Replicators cannot be started from within a database's transaction. @param replicator The replicator instance. @param resetCheckpoint If true, the persistent saved state ("checkpoint") for this replication will be discarded, causing it to re-scan all documents. This significantly diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLScope.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLScope.h index 591ce66..ab93483 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLScope.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBLScope.h @@ -58,6 +58,12 @@ CBL_PUBLIC extern const FLString kCBLDefaultScopeName; @return The name of the scope. */ FLString CBLScope_Name(const CBLScope* scope) CBLAPI; +/** Returns the scope's database. + @note The database object is owned by the scope object; you do not need to release it. + @param scope The scope. + @return The database of the scope. */ +CBLDatabase* CBLScope_Database(const CBLScope* scope) CBLAPI; + /** @} */ /** \name Collections diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBL_Edition.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBL_Edition.h index d0fe467..cbb4deb 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBL_Edition.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CBL_Edition.h @@ -20,8 +20,8 @@ #define COUCHBASE_ENTERPRISE #endif -#define CBLITE_VERSION "3.1.10" -#define CBLITE_VERSION_NUMBER 3001010 -#define CBLITE_BUILD_NUMBER 52760 -#define CBLITE_SOURCE_ID "036da58+f7cfc38" -#define CBLITE_BUILD_TIMESTAMP "2024-09-30T21:12:30Z" +#define CBLITE_VERSION "3.2.1" +#define CBLITE_VERSION_NUMBER 3002001 +#define CBLITE_BUILD_NUMBER 9 +#define CBLITE_SOURCE_ID "6728898+e322f9b" +#define CBLITE_BUILD_TIMESTAMP "2024-10-30T14:20:53Z" diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CompilerSupport.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CompilerSupport.h index 8098543..382b19b 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CompilerSupport.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CompilerSupport.h @@ -14,7 +14,7 @@ #ifndef _FLEECE_COMPILER_SUPPORT_H #define _FLEECE_COMPILER_SUPPORT_H -// The __has_xxx() macros are only(?) implemented by Clang. (Except GCC has __has_attribute...) +// The __has_xxx() macros are supported by [at least] Clang and GCC. // Define them to return 0 on other compilers. // https://clang.llvm.org/docs/AttributeReference.html // https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html @@ -36,24 +36,37 @@ #endif -#if defined(__clang__) || defined(__GNUC__) - // Tells the optimizer that a function's return value is never NULL. - #define RETURNS_NONNULL __attribute__((returns_nonnull)) +// Tells the optimizer that a function's return value is never NULL. +#if __has_attribute(returns_nonnull) +# define RETURNS_NONNULL __attribute__((returns_nonnull)) +#else +# define RETURNS_NONNULL +#endif - // Triggers a compile error if a call to the function ignores the returned value. - // Typically this is because the return value is something that must be released/freed. - #define MUST_USE_RESULT __attribute__((warn_unused_result)) +// deprecated; use NODISCARD instead +#if __has_attribute(returns_nonnull) +# define MUST_USE_RESULT __attribute__((warn_unused_result)) +#else +# define MUST_USE_RESULT +#endif - // These have no effect on behavior, but they hint to the optimizer which branch of an 'if' - // statement to make faster. - #define _usuallyTrue(VAL) __builtin_expect(VAL, true) - #define _usuallyFalse(VAL) __builtin_expect(VAL, false) +// NODISCARD expands to the C++17/C23 `[[nodiscard]]` attribute, or else MUST_USE_RESULT. +// (We can't just redefine MUST_USE_RESULT as `[[nodiscard]]` unfortunately, because the former is +// already in use in positions where `[[nodiscard]]` isn't valid, like at the end of a declaration.) +#if (__cplusplus >= 201700L) || (__STDC_VERSION__ >= 202000) +# define NODISCARD [[nodiscard]] #else - #define RETURNS_NONNULL - #define MUST_USE_RESULT +# define NODISCARD MUST_USE_RESULT +#endif - #define _usuallyTrue(VAL) (VAL) - #define _usuallyFalse(VAL) (VAL) +// These have no effect on behavior, but they hint to the optimizer which branch of an 'if' +// statement to make faster. +#if __has_builtin(__builtin_expect) +#define _usuallyTrue(VAL) __builtin_expect(VAL, true) +#define _usuallyFalse(VAL) __builtin_expect(VAL, false) +#else +#define _usuallyTrue(VAL) (VAL) +#define _usuallyFalse(VAL) (VAL) #endif @@ -83,10 +96,10 @@ // GCC also has an attribute with this name, but it's incompatible: it can't be applied to a // parameter, it has to come after the function and list parameters by number. Oh well. // TODO: Replace this with the better nullability annotations above. -#ifdef __clang__ - #define NONNULL __attribute__((nonnull)) +#if __has_attribute(nonnull) +# define NONNULL __attribute__((nonnull)) #else - #define NONNULL +# define NONNULL #endif @@ -104,10 +117,10 @@ // declared with the pure attribute can safely read any non-volatile objects, and modify the value // of objects in a way that does not affect their return value or the observable state of the // program." -- GCC manual -#if defined(__GNUC__) || __has_attribute(__pure__) - #define FLPURE __attribute__((__pure__)) +#if __has_attribute(__pure__) +# define FLPURE __attribute__((__pure__)) #else - #define FLPURE +# define FLPURE #endif // FLCONST is even stricter than FLPURE. The function cannot access memory at all (except for @@ -126,10 +139,10 @@ // "In general, since a function cannot distinguish data that might change from data that cannot, // const functions should never take pointer or, in C++, reference arguments. Likewise, a function // that calls a non-const function usually must not be const itself." -- GCC manual -#if defined(__GNUC__) || __has_attribute(__const__) - #define FLCONST __attribute__((__const__)) +#if __has_attribute(__const__) +# define FLCONST __attribute__((__const__)) #else - #define FLCONST +# define FLCONST #endif diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CouchbaseLite.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CouchbaseLite.h index 6802407..bce263b 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CouchbaseLite.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/CouchbaseLite.h @@ -26,6 +26,10 @@ #include #include #include +#include #include +#include +#include +#include #include #include diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLCollections.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLCollections.h index f621c6b..5e2489e 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLCollections.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLCollections.h @@ -48,7 +48,7 @@ extern "C" { FLEECE_PUBLIC bool FLArray_IsEmpty(FLArray FL_NULLABLE) FLAPI FLPURE; /** If the array is mutable, returns it cast to FLMutableArray, else NULL. */ - FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLArray_AsMutable(FLArray FL_NULLABLE) FLAPI FLPURE; + NODISCARD FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLArray_AsMutable(FLArray FL_NULLABLE) FLAPI FLPURE; /** Returns an value at an array index, or NULL if the index is out of range. */ FLEECE_PUBLIC FLValue FL_NULLABLE FLArray_Get(FLArray FL_NULLABLE, uint32_t index) FLAPI FLPURE; @@ -80,10 +80,11 @@ while (NULL != (value = FLArrayIterator_GetValue(&iter))) { } FLArrayIterator; /** Initializes a FLArrayIterator struct to iterate over an array. - Call FLArrayIteratorGetValue to get the first item, then FLArrayIteratorNext. */ + Call FLArrayIteratorGetValue to get the first item, then as long as the item is not NULL, + call FLArrayIterator_Next to advance. */ FLEECE_PUBLIC void FLArrayIterator_Begin(FLArray FL_NULLABLE, FLArrayIterator*) FLAPI; - /** Returns the current value being iterated over. */ + /** Returns the current value being iterated over, or NULL at the end. */ FLEECE_PUBLIC FLValue FL_NULLABLE FLArrayIterator_GetValue(const FLArrayIterator*) FLAPI FLPURE; /** Returns a value in the array at the given offset from the current value. */ @@ -92,7 +93,9 @@ while (NULL != (value = FLArrayIterator_GetValue(&iter))) { /** Returns the number of items remaining to be iterated, including the current one. */ FLEECE_PUBLIC uint32_t FLArrayIterator_GetCount(const FLArrayIterator*) FLAPI FLPURE; - /** Advances the iterator to the next value, or returns false if at the end. */ + /** Advances the iterator to the next value. + @warning It is illegal to call this when the iterator is already at the end. + In particular, calling this when the array is empty is always illegal. */ FLEECE_PUBLIC bool FLArrayIterator_Next(FLArrayIterator*) FLAPI; /** @} */ @@ -153,22 +156,26 @@ while (NULL != (value = FLDictIterator_GetValue(&iter))) { /** Initializes a FLDictIterator struct to iterate over a dictionary. Call FLDictIterator_GetKey and FLDictIterator_GetValue to get the first item, - then FLDictIterator_Next. */ + then as long as the item is not NULL, call FLDictIterator_Next to advance. */ FLEECE_PUBLIC void FLDictIterator_Begin(FLDict FL_NULLABLE, FLDictIterator*) FLAPI; - /** Returns the current key being iterated over. This Value will be a string or an integer. */ + /** Returns the current key being iterated over. + This Value will be a string or an integer, or NULL when there are no more keys. */ FLEECE_PUBLIC FLValue FL_NULLABLE FLDictIterator_GetKey(const FLDictIterator*) FLAPI FLPURE; - /** Returns the current key's string value. */ + /** Returns the current key's string value, or NULL when there are no more keys. */ FLEECE_PUBLIC FLString FLDictIterator_GetKeyString(const FLDictIterator*) FLAPI; - /** Returns the current value being iterated over. */ + /** Returns the current value being iterated over. + Returns NULL when there are no more values. */ FLEECE_PUBLIC FLValue FL_NULLABLE FLDictIterator_GetValue(const FLDictIterator*) FLAPI FLPURE; /** Returns the number of items remaining to be iterated, including the current one. */ FLEECE_PUBLIC uint32_t FLDictIterator_GetCount(const FLDictIterator*) FLAPI FLPURE; - /** Advances the iterator to the next value, or returns false if at the end. */ + /** Advances the iterator to the next value. + @warning It is illegal to call this when the iterator is already at the end. + In particular, calling this when the dict is empty is always illegal. */ FLEECE_PUBLIC bool FLDictIterator_Next(FLDictIterator*) FLAPI; /** Cleans up after an iterator. Only needed if (a) the dictionary is a delta, and diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLDoc.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLDoc.h index c2f631b..49f4747 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLDoc.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLDoc.h @@ -37,7 +37,7 @@ extern "C" { /** Creates an FLDoc from Fleece-encoded data that's been returned as a result from FLSlice_Copy or other API. The resulting document retains the data, so you don't need to worry about it remaining valid. */ - FLEECE_PUBLIC FLDoc FLDoc_FromResultData(FLSliceResult data, FLTrust, + NODISCARD FLEECE_PUBLIC FLDoc FLDoc_FromResultData(FLSliceResult data, FLTrust, FLSharedKeys FL_NULLABLE, FLSlice externData) FLAPI; /** Releases a reference to an FLDoc. This must be called once to free an FLDoc you created. */ @@ -61,7 +61,7 @@ extern "C" { /** Looks up the Doc containing the Value, or NULL if there is none. @note Caller must release the FLDoc reference!! */ - FLEECE_PUBLIC FLDoc FL_NULLABLE FLValue_FindDoc(FLValue FL_NULLABLE) FLAPI FLPURE; + NODISCARD FLEECE_PUBLIC FLDoc FL_NULLABLE FLValue_FindDoc(FLValue FL_NULLABLE) FLAPI FLPURE; /** Associates an arbitrary pointer value with a document, and thus its contained values. Allows client code to associate its own pointer with this FLDoc and its Values, diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLEncoder.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLEncoder.h index 7aa1368..7ce213e 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLEncoder.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLEncoder.h @@ -48,7 +48,7 @@ extern "C" { /** Creates a new encoder, for generating Fleece data. Call FLEncoder_Free when done. */ - FLEECE_PUBLIC FLEncoder FLEncoder_New(void) FLAPI; + NODISCARD FLEECE_PUBLIC FLEncoder FLEncoder_New(void) FLAPI; /** Creates a new encoder, allowing some options to be customized. @param format The output format to generate (Fleece, JSON, or JSON5.) @@ -57,12 +57,12 @@ extern "C" { as a single shared value. This saves space but makes encoding slightly slower. You should only turn this off if you know you're going to be writing large numbers of non-repeated strings. (Default is true) */ - FLEECE_PUBLIC FLEncoder FLEncoder_NewWithOptions(FLEncoderFormat format, + NODISCARD FLEECE_PUBLIC FLEncoder FLEncoder_NewWithOptions(FLEncoderFormat format, size_t reserveSize, bool uniqueStrings) FLAPI; /** Creates a new Fleece encoder that writes to a file, not to memory. */ - FLEECE_PUBLIC FLEncoder FLEncoder_NewWritingToFile(FILE*, bool uniqueStrings) FLAPI; + NODISCARD FLEECE_PUBLIC FLEncoder FLEncoder_NewWritingToFile(FILE*, bool uniqueStrings) FLAPI; /** Frees the space used by an encoder. */ FLEECE_PUBLIC void FLEncoder_Free(FLEncoder FL_NULLABLE) FLAPI; @@ -201,12 +201,12 @@ extern "C" { /** Ends encoding; if there has been no error, it returns the encoded Fleece data packaged in an FLDoc. (This function does not support JSON encoding.) This does not free the FLEncoder; call FLEncoder_Free (or FLEncoder_Reset) next. */ - MUST_USE_RESULT + NODISCARD FLEECE_PUBLIC FLDoc FL_NULLABLE FLEncoder_FinishDoc(FLEncoder, FLError* FL_NULLABLE outError) FLAPI; /** Ends encoding; if there has been no error, it returns the encoded data, else null. This does not free the FLEncoder; call FLEncoder_Free (or FLEncoder_Reset) next. */ - MUST_USE_RESULT + NODISCARD FLEECE_PUBLIC FLSliceResult FLEncoder_Finish(FLEncoder, FLError* FL_NULLABLE outError) FLAPI; /** @} */ diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLExpert.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLExpert.h index b52b77c..9dd697f 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLExpert.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLExpert.h @@ -31,6 +31,12 @@ extern "C" { /** \defgroup Obscure Rarely-needed or advanced functions @{ */ + /** For use with \ref FLDoc_FromResultData. This option prevents the function from parsing the + data at all; you are responsible for locating the FLValues in it. + This is for the case where you have trusted data in a custom format that contains Fleece- + encoded data within it. You still need an FLDoc to access the data safely (especially to + retain FLValues), but it can't be parsed as-is. */ + #define kFLTrustedDontParse FLTrust(-1) /** \name Delta Compression @{ @@ -48,7 +54,7 @@ extern "C" { @param nuu A value that's typically the new/changed state of the `old` data. @return JSON data representing the changes from `old` to `nuu`, or NULL on (extremely unlikely) failure. */ - FLEECE_PUBLIC FLSliceResult FLCreateJSONDelta(FLValue FL_NULLABLE old, + NODISCARD FLEECE_PUBLIC FLSliceResult FLCreateJSONDelta(FLValue FL_NULLABLE old, FLValue FL_NULLABLE nuu) FLAPI; /** Writes JSON that describes the changes to turn the value `old` into `nuu`. @@ -58,7 +64,7 @@ extern "C" { @param jsonEncoder An encoder to write the JSON to. Must have been created using `FLEncoder_NewWithOptions`, with JSON or JSON5 format. @return True on success, false on (extremely unlikely) failure. */ - FLEECE_PUBLIC bool FLEncodeJSONDelta(FLValue FL_NULLABLE old, + NODISCARD FLEECE_PUBLIC bool FLEncodeJSONDelta(FLValue FL_NULLABLE old, FLValue FL_NULLABLE nuu, FLEncoder jsonEncoder) FLAPI; @@ -71,7 +77,7 @@ extern "C" { @param jsonDelta A JSON-encoded delta created by `FLCreateJSONDelta` or `FLEncodeJSONDelta`. @param outError On failure, error information will be stored where this points, if non-null. @return The corresponding `nuu` value, encoded as Fleece, or null if an error occurred. */ - FLEECE_PUBLIC FLSliceResult FLApplyJSONDelta(FLValue FL_NULLABLE old, + NODISCARD FLEECE_PUBLIC FLSliceResult FLApplyJSONDelta(FLValue FL_NULLABLE old, FLSlice jsonDelta, FLError* FL_NULLABLE outError) FLAPI; @@ -110,17 +116,18 @@ extern "C" { */ /** Creates a new empty FLSharedKeys object, which must eventually be released. */ - FLEECE_PUBLIC FLSharedKeys FLSharedKeys_New(void) FLAPI; + NODISCARD FLEECE_PUBLIC FLSharedKeys FLSharedKeys_New(void) FLAPI; typedef bool (*FLSharedKeysReadCallback)(void* FL_NULLABLE context, FLSharedKeys); - FLEECE_PUBLIC FLSharedKeys FLSharedKeys_NewWithRead(FLSharedKeysReadCallback, + NODISCARD FLEECE_PUBLIC FLSharedKeys FLSharedKeys_NewWithRead(FLSharedKeysReadCallback, void* FL_NULLABLE context) FLAPI; /** Returns a data blob containing the current state (all the keys and their integers.) */ - FLEECE_PUBLIC FLSliceResult FLSharedKeys_GetStateData(FLSharedKeys) FLAPI; + NODISCARD FLEECE_PUBLIC FLSliceResult FLSharedKeys_GetStateData(FLSharedKeys) FLAPI; - /** Updates an FLSharedKeys with saved state data created by \ref FLSharedKeys_GetStateData. */ + /** Updates an FLSharedKeys with saved state data created by \ref FLSharedKeys_GetStateData. + Returns true if new keys were added, false if not. */ FLEECE_PUBLIC bool FLSharedKeys_LoadStateData(FLSharedKeys, FLSlice) FLAPI; /** Writes the current state to a Fleece encoder as a single value, @@ -129,7 +136,7 @@ extern "C" { /** Updates an FLSharedKeys object with saved state, a Fleece value previously written by \ref FLSharedKeys_WriteState. */ - FLEECE_PUBLIC bool FLSharedKeys_LoadState(FLSharedKeys, FLValue) FLAPI; + NODISCARD FLEECE_PUBLIC bool FLSharedKeys_LoadState(FLSharedKeys, FLValue) FLAPI; /** Maps a key string to a number in the range [0...2047], or returns -1 if it isn't mapped. If the key doesn't already have a mapping, and the `add` flag is true, @@ -148,8 +155,11 @@ extern "C" { /** Reverts an FLSharedKeys by "forgetting" any keys added since it had the count `oldCount`. */ FLEECE_PUBLIC void FLSharedKeys_RevertToCount(FLSharedKeys, unsigned oldCount) FLAPI; + /** Disable caching of the SharedKeys.. */ + FLEECE_PUBLIC void FLSharedKeys_DisableCaching(FLSharedKeys) FLAPI; + /** Increments the reference count of an FLSharedKeys. */ - FLEECE_PUBLIC FLSharedKeys FL_NULLABLE FLSharedKeys_Retain(FLSharedKeys FL_NULLABLE) FLAPI; + NODISCARD FLEECE_PUBLIC FLSharedKeys FL_NULLABLE FLSharedKeys_Retain(FLSharedKeys FL_NULLABLE) FLAPI; /** Decrements the reference count of an FLSharedKeys, freeing it when it reaches zero. */ FLEECE_PUBLIC void FLSharedKeys_Release(FLSharedKeys FL_NULLABLE) FLAPI; @@ -159,7 +169,7 @@ extern "C" { /** Registers a range of memory containing Fleece data that uses the given shared keys. This allows Dict accessors to look up the values of shared keys. */ - FLEECE_PUBLIC FLSharedKeyScope FLSharedKeyScope_WithRange(FLSlice range, FLSharedKeys) FLAPI; + NODISCARD FLEECE_PUBLIC FLSharedKeyScope FLSharedKeyScope_WithRange(FLSlice range, FLSharedKeys) FLAPI; /** Unregisters a scope created by \ref FLSharedKeyScope_WithRange. */ FLEECE_PUBLIC void FLSharedKeyScope_Free(FLSharedKeyScope FL_NULLABLE) FLAPI; @@ -203,14 +213,14 @@ extern "C" { will be stored here (if it's not NULL.) @param outError On failure, the error code will be stored here (if it's not NULL.) @return The converted JSON. */ - FLEECE_PUBLIC FLStringResult FLJSON5_ToJSON(FLString json5, + NODISCARD FLEECE_PUBLIC FLStringResult FLJSON5_ToJSON(FLString json5, FLStringResult* FL_NULLABLE outErrorMessage, size_t* FL_NULLABLE outErrorPos, FLError* FL_NULLABLE outError) FLAPI; /** Directly converts JSON data to Fleece-encoded data. Not commonly needed. Prefer \ref FLDoc_FromJSON instead. */ - FLEECE_PUBLIC FLSliceResult FLData_ConvertJSON(FLSlice json, FLError* FL_NULLABLE outError) FLAPI; + NODISCARD FLEECE_PUBLIC FLSliceResult FLData_ConvertJSON(FLSlice json, FLError* FL_NULLABLE outError) FLAPI; /** @} */ @@ -246,24 +256,28 @@ extern "C" { (Due to internal buffering, this is not the same as FLEncoder_BytesWritten.) */ FLEECE_PUBLIC size_t FLEncoder_GetNextWritePos(FLEncoder) FLAPI; + #define kFLNoWrittenValue INTPTR_MIN + /** Returns an opaque reference to the last complete value written to the encoder, if possible. - Fails (returning 0) if nothing has been written, or if the value is inline and can't be - referenced this way -- that only happens with small scalars or empty collections. */ + Fails (returning kFLNoWrittenValue) if nothing has been written, or if the value is inline + and can't be referenced this way -- that only happens with small scalars or empty + collections. */ FLEECE_PUBLIC intptr_t FLEncoder_LastValueWritten(FLEncoder) FLAPI; /** Writes another reference (a "pointer") to an already-written value, given a reference previously returned from \ref FLEncoder_LastValueWritten. The effect is exactly the same as if you wrote the - entire value again, except that the size of the encoded data only grows by 4 bytes. */ - FLEECE_PUBLIC void FLEncoder_WriteValueAgain(FLEncoder, intptr_t preWrittenValue) FLAPI; + entire value again, except that the size of the encoded data only grows by 4 bytes. + Returns false if the reference couldn't be written. */ + FLEECE_PUBLIC bool FLEncoder_WriteValueAgain(FLEncoder, intptr_t preWrittenValue) FLAPI; /** Returns the data written so far as a standalone Fleece document, whose root is the last value written. You can continue writing, and the final output returned by \ref FLEncoder_Finish will consist of everything after this point. That second part can be used in the future by loading it as an `FLDoc` with the first part as its `extern` reference. */ - FLEECE_PUBLIC FLSliceResult FLEncoder_Snip(FLEncoder) FLAPI; + NODISCARD FLEECE_PUBLIC FLSliceResult FLEncoder_Snip(FLEncoder) FLAPI; /** Finishes encoding the current item, and returns its offset in the output data. */ - FLEECE_PUBLIC size_t FLEncoder_FinishItem(FLEncoder) FLAPI; + NODISCARD FLEECE_PUBLIC size_t FLEncoder_FinishItem(FLEncoder) FLAPI; /** In a JSON encoder, adds a newline ('\n') and prepares to start encoding another top-level object. The encoder MUST be not be within an array or dict. diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLJSON.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLJSON.h index 5dbc78c..677d3e4 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLJSON.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLJSON.h @@ -59,15 +59,15 @@ extern "C" { /** Creates an FLDoc from JSON-encoded data. The data is first encoded into Fleece, and the Fleece data is kept by the doc; the input JSON data is no longer needed after this function returns. */ - FLEECE_PUBLIC FLDoc FLDoc_FromJSON(FLSlice json, FLError* FL_NULLABLE outError) FLAPI; + NODISCARD FLEECE_PUBLIC FLDoc FLDoc_FromJSON(FLSlice json, FLError* FL_NULLABLE outError) FLAPI; /** Creates a new mutable Array from JSON. It is an error if the JSON is not an array. Its initial ref-count is 1, so a call to FLMutableArray_Release will free it. */ - FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLMutableArray_NewFromJSON(FLString json, FLError* FL_NULLABLE outError) FLAPI; + NODISCARD FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLMutableArray_NewFromJSON(FLString json, FLError* FL_NULLABLE outError) FLAPI; /** Creates a new mutable Dict from json. It is an error if the JSON is not a dictionary/object. Its initial ref-count is 1, so a call to FLMutableDict_Release will free it. */ - FLEECE_PUBLIC FLMutableDict FL_NULLABLE FLMutableDict_NewFromJSON(FLString json, FLError* FL_NULLABLE outError) FLAPI; + NODISCARD FLEECE_PUBLIC FLMutableDict FL_NULLABLE FLMutableDict_NewFromJSON(FLString json, FLError* FL_NULLABLE outError) FLAPI; /** Parses JSON data and writes the value(s) to the encoder as their Fleece equivalents. (This acts as a single write, like WriteInt; it's just that the value written is likely to diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLKeyPath.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLKeyPath.h index b448d77..9ed12e3 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLKeyPath.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLKeyPath.h @@ -37,8 +37,7 @@ extern "C" { A leading JSONPath-like `$.` is allowed but ignored. - A '\' can be used to escape a special character ('.', '[' or '$') at the start of a - property name (but not yet in the middle of a name.) + A '\' can be used to escape a special character ('.', '[' or '$'). */ #ifndef FL_IMPL @@ -46,24 +45,24 @@ extern "C" { #endif /** Creates a new FLKeyPath object by compiling a path specifier string. */ - FLEECE_PUBLIC FLKeyPath FL_NULLABLE FLKeyPath_New(FLSlice specifier, + NODISCARD FLEECE_PUBLIC FLKeyPath FL_NULLABLE FLKeyPath_New(FLSlice specifier, FLError* FL_NULLABLE outError) FLAPI; /** Frees a compiled FLKeyPath object. (It's ok to pass NULL.) */ FLEECE_PUBLIC void FLKeyPath_Free(FLKeyPath FL_NULLABLE) FLAPI; /** Evaluates a compiled key-path for a given Fleece root object. */ - FLEECE_PUBLIC FLValue FL_NULLABLE FLKeyPath_Eval(FLKeyPath, + NODISCARD FLEECE_PUBLIC FLValue FL_NULLABLE FLKeyPath_Eval(FLKeyPath, FLValue root) FLAPI; /** Evaluates a key-path from a specifier string, for a given Fleece root object. If you only need to evaluate the path once, this is a bit faster than creating an FLKeyPath object, evaluating, then freeing it. */ - FLEECE_PUBLIC FLValue FL_NULLABLE FLKeyPath_EvalOnce(FLSlice specifier, FLValue root, + NODISCARD FLEECE_PUBLIC FLValue FL_NULLABLE FLKeyPath_EvalOnce(FLSlice specifier, FLValue root, FLError* FL_NULLABLE outError) FLAPI; /** Returns a path in string form. */ - FLEECE_PUBLIC FLStringResult FLKeyPath_ToString(FLKeyPath path) FLAPI; + NODISCARD FLEECE_PUBLIC FLStringResult FLKeyPath_ToString(FLKeyPath path) FLAPI; /** Equality test. */ FLEECE_PUBLIC bool FLKeyPath_Equals(FLKeyPath path1, FLKeyPath path2) FLAPI; diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLMutable.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLMutable.h index 7aea9f5..1072e64 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLMutable.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLMutable.h @@ -55,12 +55,12 @@ extern "C" { also set, immutable values are also copied, recursively. If the source Array is NULL, then NULL is returned. */ - FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLArray_MutableCopy(FLArray FL_NULLABLE, + NODISCARD FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLArray_MutableCopy(FLArray FL_NULLABLE, FLCopyFlags) FLAPI; /** Creates a new empty mutable Array. Its initial ref-count is 1, so a call to FLMutableArray_Release will free it. */ - FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLMutableArray_New(void) FLAPI; + NODISCARD FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLMutableArray_New(void) FLAPI; /** Increments the ref-count of a mutable Array. */ static inline FLMutableArray FL_NULLABLE FLMutableArray_Retain(FLMutableArray FL_NULLABLE d) { @@ -108,7 +108,7 @@ extern "C" { - If the value is a mutable array, returns it. - If the value is an immutable array, this function makes a mutable copy, assigns the copy as the property value, and returns the copy. */ - FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLMutableArray_GetMutableArray(FLMutableArray FL_NULLABLE, + NODISCARD FLEECE_PUBLIC FLMutableArray FL_NULLABLE FLMutableArray_GetMutableArray(FLMutableArray FL_NULLABLE, uint32_t index) FLAPI; /** Convenience function for getting an array-valued property in mutable form. @@ -116,7 +116,7 @@ extern "C" { - If the value is a mutable array, returns it. - If the value is an immutable array, this function makes a mutable copy, assigns the copy as the property value, and returns the copy. */ - FLEECE_PUBLIC FLMutableDict FL_NULLABLE FLMutableArray_GetMutableDict(FLMutableArray FL_NULLABLE, + NODISCARD FLEECE_PUBLIC FLMutableDict FL_NULLABLE FLMutableArray_GetMutableDict(FLMutableArray FL_NULLABLE, uint32_t index) FLAPI; @@ -303,21 +303,21 @@ extern "C" { You store a value to it by calling one of the nine `FLSlot_Set...` functions. \warning You should immediately store a value into the `FLSlot`. Do not keep it around; any changes to the array invalidate it.*/ - MUST_USE_RESULT + NODISCARD FLEECE_PUBLIC FLSlot FLMutableArray_Set(FLMutableArray, uint32_t index) FLAPI; /** Appends a null value to the array and returns an \ref FLSlot that refers to that position. You store a value to it by calling one of the nine `FLSlot_Set...` functions. \warning You should immediately store a value into the `FLSlot`. Do not keep it around; any changes to the array invalidate it.*/ - MUST_USE_RESULT + NODISCARD FLEECE_PUBLIC FLSlot FLMutableArray_Append(FLMutableArray) FLAPI; /** Returns an \ref FLSlot that refers to the given key/value pair of the given dictionary. You store a value to it by calling one of the nine `FLSlot_Set...` functions. \warning You should immediately store a value into the `FLSlot`. Do not keep it around; any changes to the dictionary invalidate it.*/ - MUST_USE_RESULT + NODISCARD FLEECE_PUBLIC FLSlot FLMutableDict_Set(FLMutableDict, FLString key) FLAPI; diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLSlice.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLSlice.h index 2850115..9713584 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLSlice.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/FLSlice.h @@ -60,7 +60,7 @@ typedef struct FLSlice { a `FLSliceResult` return value is to construct an `alloc_slice` from it, which will adopt the reference, and release it in its destructor. For example: `alloc_slice foo( CopyFoo() );` */ -typedef struct FLSliceResult { +struct NODISCARD FLSliceResult { const void* FL_NULLABLE buf; size_t size; @@ -69,7 +69,8 @@ typedef struct FLSliceResult { explicit operator FLSlice () const {return {buf, size};} inline explicit operator std::string() const; #endif -} FLSliceResult; +}; +typedef struct FLSliceResult FLSliceResult; /** A heap-allocated, reference-counted slice. This type is really just a hint in an API diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/Fleece+CoreFoundation.h b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/Fleece+CoreFoundation.h index 585c528..ce14e29 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/Fleece+CoreFoundation.h +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Headers/Fleece+CoreFoundation.h @@ -29,16 +29,16 @@ extern "C" { /** Writes a Core Foundation (or Objective-C) object to an Encoder. Supports all the JSON types, as well as CFData. */ - FLEECE_PUBLIC bool FLEncoder_WriteCFObject(FLEncoder, CFTypeRef) FLAPI; + NODISCARD FLEECE_PUBLIC bool FLEncoder_WriteCFObject(FLEncoder, CFTypeRef) FLAPI; /** Returns a Value as a corresponding CoreFoundation object. Caller must CFRelease the result. */ - FLEECE_PUBLIC CFTypeRef FLValue_CopyCFObject(FLValue FL_NULLABLE) FLAPI; + NODISCARD FLEECE_PUBLIC CFTypeRef FLValue_CopyCFObject(FLValue FL_NULLABLE) FLAPI; /** Same as FLDictGet, but takes the key as a CFStringRef. */ - FLEECE_PUBLIC FLValue FLDict_GetWithCFString(FLDict FL_NULLABLE, CFStringRef) FLAPI; + NODISCARD FLEECE_PUBLIC FLValue FLDict_GetWithCFString(FLDict FL_NULLABLE, CFStringRef) FLAPI; #ifdef __OBJC__ diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Info.plist b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Info.plist index 70f9984..27fb217 100644 Binary files a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Info.plist and b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Info.plist differ diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Modules/module.modulemap b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Modules/module.modulemap index 157018d..42fd88e 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Modules/module.modulemap +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/Modules/module.modulemap @@ -11,7 +11,11 @@ framework module CouchbaseLite { header "CBLEncryptable.h" header "CBLLog.h" header "CBLPlatform.h" + header "CBLPrediction.h" header "CBLQuery.h" + header "CBLQueryIndex.h" + header "CBLQueryIndexTypes.h" + header "CBLQueryTypes.h" header "CBLReplicator.h" header "CBLScope.h" diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/PrivacyInfo.xcprivacy b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/PrivacyInfo.xcprivacy index fe840a0..6cb5e91 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/PrivacyInfo.xcprivacy +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/CouchbaseLite.framework/PrivacyInfo.xcprivacy @@ -1,17 +1,23 @@ - - NSPrivacyAccessedAPITypes - - - NSPrivacyAccessedAPIType - NSPrivacyAccessedAPICategoryFileTimestamp - NSPrivacyAccessedAPITypeReasons - - C617.1 - - - - + + NSPrivacyTracking + + NSPrivacyTrackingDomains + + NSPrivacyCollectedDataTypes + + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryFileTimestamp + NSPrivacyAccessedAPITypeReasons + + C617.1 + + + + diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/dSYMs/CouchbaseLite.framework.dSYM/Contents/Info.plist b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/dSYMs/CouchbaseLite.framework.dSYM/Contents/Info.plist index f5bf4bc..dedf43b 100644 --- a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/dSYMs/CouchbaseLite.framework.dSYM/Contents/Info.plist +++ b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/dSYMs/CouchbaseLite.framework.dSYM/Contents/Info.plist @@ -13,8 +13,8 @@ CFBundleSignature ???? CFBundleShortVersionString - 3.1.10 + 3.2.1 CFBundleVersion - 52760 + 9 diff --git a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/dSYMs/CouchbaseLite.framework.dSYM/Contents/Resources/DWARF/CouchbaseLite b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/dSYMs/CouchbaseLite.framework.dSYM/Contents/Resources/DWARF/CouchbaseLite index dda3389..c99acfd 100644 Binary files a/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/dSYMs/CouchbaseLite.framework.dSYM/Contents/Resources/DWARF/CouchbaseLite and b/libcblite-3.0.3/lib/ios/CouchbaseLite.xcframework/ios-arm64_x86_64-simulator/dSYMs/CouchbaseLite.framework.dSYM/Contents/Resources/DWARF/CouchbaseLite differ diff --git a/libcblite-3.0.3/lib/macos/libcblite.3.dylib b/libcblite-3.0.3/lib/macos/libcblite.3.dylib index 3d80d37..e7fc53a 100755 Binary files a/libcblite-3.0.3/lib/macos/libcblite.3.dylib and b/libcblite-3.0.3/lib/macos/libcblite.3.dylib differ diff --git a/libcblite-3.0.3/lib/x86_64-linux-android/libcblite.so b/libcblite-3.0.3/lib/x86_64-linux-android/libcblite.so index f79f254..ba51bad 100644 Binary files a/libcblite-3.0.3/lib/x86_64-linux-android/libcblite.so and b/libcblite-3.0.3/lib/x86_64-linux-android/libcblite.so differ diff --git a/libcblite-3.0.3/lib/x86_64-linux-android/libcblite.stripped.so b/libcblite-3.0.3/lib/x86_64-linux-android/libcblite.stripped.so index 74e005a..e867847 100755 Binary files a/libcblite-3.0.3/lib/x86_64-linux-android/libcblite.stripped.so and b/libcblite-3.0.3/lib/x86_64-linux-android/libcblite.stripped.so differ diff --git a/libcblite-3.0.3/lib/x86_64-pc-windows-gnu/cblite.dll b/libcblite-3.0.3/lib/x86_64-pc-windows-gnu/cblite.dll index cbd2a4b..52a69b9 100644 Binary files a/libcblite-3.0.3/lib/x86_64-pc-windows-gnu/cblite.dll and b/libcblite-3.0.3/lib/x86_64-pc-windows-gnu/cblite.dll differ diff --git a/libcblite-3.0.3/lib/x86_64-pc-windows-gnu/cblite.lib b/libcblite-3.0.3/lib/x86_64-pc-windows-gnu/cblite.lib index f882660..37a9ced 100644 Binary files a/libcblite-3.0.3/lib/x86_64-pc-windows-gnu/cblite.lib and b/libcblite-3.0.3/lib/x86_64-pc-windows-gnu/cblite.lib differ diff --git a/libcblite-3.0.3/lib/x86_64-pc-windows-gnu/cblite.stripped.dll b/libcblite-3.0.3/lib/x86_64-pc-windows-gnu/cblite.stripped.dll index 8216b7a..de01657 100755 Binary files a/libcblite-3.0.3/lib/x86_64-pc-windows-gnu/cblite.stripped.dll and b/libcblite-3.0.3/lib/x86_64-pc-windows-gnu/cblite.stripped.dll differ diff --git a/libcblite-3.0.3/lib/x86_64-unknown-linux-gnu/libcblite.so.3 b/libcblite-3.0.3/lib/x86_64-unknown-linux-gnu/libcblite.so.3 index c56a5cf..4f44463 100644 Binary files a/libcblite-3.0.3/lib/x86_64-unknown-linux-gnu/libcblite.so.3 and b/libcblite-3.0.3/lib/x86_64-unknown-linux-gnu/libcblite.so.3 differ diff --git a/src/blob.rs b/src/blob.rs index b108de3..7736065 100644 --- a/src/blob.rs +++ b/src/blob.rs @@ -31,7 +31,7 @@ use crate::{ use std::ffi::c_void; use std::marker::PhantomData; -/** A binary attachment to a Document. */ +/// A binary attachment to a Document pub struct Blob { pub(crate) cbl_ref: *const CBLBlob, } @@ -46,7 +46,7 @@ impl CblRef for Blob { impl Blob { //////// CREATION - /** Creates a new blob, given its contents as a byte array. */ + /// Creates a new blob, given its contents as a byte array. pub fn new_from_data(data: &[u8], content_type: &str) -> Self { unsafe { let blob = CBLBlob_CreateWithData( @@ -57,8 +57,8 @@ impl Blob { } } - /** Creates a new blob from data that has has been written to a [`Writer`]. - You should then add the blob to a document as a property, using [`Slot::put_blob`]. */ + /// Creates a new blob from data that has has been written to a [`Writer`]. + /// You should then add the blob to a document as a property, using [`Slot::put_blob`]. pub fn new_from_stream(mut stream: BlobWriter, content_type: &str) -> Self { unsafe { let blob = CBLBlob_CreateWithStream(from_str(content_type).get_ref(), stream.get_ref()); @@ -67,7 +67,7 @@ impl Blob { } } - // called by FleeceReference::as_blob() + /// called by FleeceReference::as_blob() pub(crate) fn from_value(value: &V) -> Option { unsafe { let blob = FLDict_GetBlob(FLValue_AsDict(value._fleece_ref())); @@ -81,30 +81,30 @@ impl Blob { //////// ACCESSORS - /** The length of the content data in bytes. */ + /// The length of the content data in bytes pub fn length(&self) -> u64 { unsafe { CBLBlob_Length(self.get_ref()) } } - /** The unique digest of the blob: A base64-encoded SHA-1 digest of its data. */ + /// The unique digest of the blob: A base64-encoded SHA-1 digest of its data pub fn digest(&self) -> &str { unsafe { CBLBlob_Digest(self.get_ref()).as_str().unwrap() } } - /** The MIME type assigned to the blob, if any. */ + /// The MIME type assigned to the blob, if any pub fn content_type(&self) -> Option<&str> { unsafe { CBLBlob_ContentType(self.get_ref()).as_str() } } - /** The blob's metadata properties as a dictionary. */ + /// The blob's metadata properties as a dictionary pub fn properties(&self) -> Dict { unsafe { Dict::new(CBLBlob_Properties(self.get_ref())) } } //////// READING: - /** Reads the blob's contents into memory and returns them as a byte array. - This can potentially allocate a lot of memory! */ + /// Reads the blob's contents into memory and returns them as a byte array. + /// This can potentially allocate a lot of memory! pub fn load_content(&self) -> Result> { unsafe { let mut err = CBLError::default(); @@ -113,7 +113,7 @@ impl Blob { } } - /** Opens a stream for reading a blob's content from disk. */ + /// Opens a stream for reading a blob's content from disk. pub fn open_content(&self) -> Result { check_ptr( |err| unsafe { CBLBlob_OpenContentStream(self.get_ref(), err) }, @@ -146,7 +146,7 @@ impl Clone for Blob { //////// BLOB ADDITIONS FOR ARRAY / DICT: impl Slot<'_> { - /** Stores a Blob reference in an Array or Dict. This is how you add a Blob to a Document. */ + /// Stores a Blob reference in an Array or Dict. This is how you add a Blob to a Document. pub fn put_blob(self, blob: &mut Blob) { unsafe { FLSlot_SetBlob(self.get_ref(), blob.get_ref() as *mut CBLBlob) } } @@ -154,20 +154,20 @@ impl Slot<'_> { //////// BLOB READER -/** A stream for reading Blob conents. */ +/// A stream for reading Blob conents pub struct BlobReader<'r> { pub blob: &'r Blob, stream_ref: *mut CBLBlobReadStream, } -impl<'r> CblRef for BlobReader<'r> { +impl CblRef for BlobReader<'_> { type Output = *mut CBLBlobReadStream; fn get_ref(&self) -> Self::Output { self.stream_ref } } -impl<'r> std::io::Read for BlobReader<'r> { +impl std::io::Read for BlobReader<'_> { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { unsafe { check_io(|err| { @@ -182,7 +182,7 @@ impl<'r> std::io::Read for BlobReader<'r> { } } -impl<'r> Drop for BlobReader<'r> { +impl Drop for BlobReader<'_> { fn drop(&mut self) { unsafe { CBLBlobReader_Close(self.get_ref()); @@ -192,15 +192,14 @@ impl<'r> Drop for BlobReader<'r> { //////// BLOB WRITER -/** A stream for writing data that will become a Blob's contents. -After you're done writing the data, call [`Blob::new_from_stream`], -then add the Blob to a document property via [`Slot::put_blob`]. */ +/// A stream for writing data that will become a Blob's contents. +/// After you're done writing the data, call [`Blob::new_from_stream`], then add the Blob to a document property via [`Slot::put_blob`]. pub struct BlobWriter<'d> { stream_ref: *mut CBLBlobWriteStream, db: PhantomData<&'d mut Database>, } -impl<'d> CblRef for BlobWriter<'d> { +impl CblRef for BlobWriter<'_> { type Output = *mut CBLBlobWriteStream; fn get_ref(&self) -> Self::Output { self.stream_ref @@ -222,7 +221,7 @@ impl<'d> BlobWriter<'d> { } } -impl<'r> std::io::Write for BlobWriter<'r> { +impl std::io::Write for BlobWriter<'_> { fn write(&mut self, data: &[u8]) -> std::result::Result { unsafe { check_io(|err| { @@ -246,7 +245,7 @@ impl<'r> std::io::Write for BlobWriter<'r> { } } -impl<'r> Drop for BlobWriter<'r> { +impl Drop for BlobWriter<'_> { fn drop(&mut self) { unsafe { CBLBlobWriter_Close(self.get_ref()) } } diff --git a/src/collection.rs b/src/collection.rs index c399c18..0a79daa 100644 --- a/src/collection.rs +++ b/src/collection.rs @@ -2,31 +2,75 @@ use crate::{ CblRef, Listener, ListenerToken, release, retain, c_api::{ CBLCollection, CBLCollectionChange, CBLCollection_AddChangeListener, CBLCollection_Scope, - CBLCollection_Name, CBLCollection_Count, + CBLCollection_Name, CBLCollection_Count, CBLCollection_FullName, CBLCollection_Database, }, scope::Scope, + Database, }; pub static DEFAULT_NAME: &str = "_default"; +/// A Collection represents a collection which is a container for documents. +/// +/// A collection can be thought as a table in a relational database. Each collection belongs to +/// a scope which is simply a namespce, and has a name which is unique within its scope. +/// +/// When a new database is created, a default collection named "_default" will be automatically +/// created. The default collection is created under the default scope named "_default". +/// The name of the default collection and scope can be referenced by using +/// kCBLDefaultCollectionName and \ref kCBLDefaultScopeName constant. +/// +/// @note The default collection cannot be deleted. +/// +/// When creating a new collection, the collection name, and the scope name are required. +/// The naming rules of the collections and scopes are as follows: +/// - Must be between 1 and 251 characters in length. +/// - Can only contain the characters A-Z, a-z, 0-9, and the symbols _, -, and %. +/// - Cannot start with _ or %. +/// - Both scope and collection names are case sensitive. +/// +/// ## `CBLCollection` Lifespan +/// `CBLCollection` is ref-counted. Same as the CBLDocument, the CBLCollection objects +/// created or retrieved from the database must be released after you are done using them. +/// When the database is closed or released, the collection objects will become invalid, +/// most operations on the invalid \ref CBLCollection object will fail with either the +/// \ref kCBLErrorNotOpen error or null/zero/empty result. +/// +/// ##Legacy Database and API +/// When using the legacy database, the existing documents and indexes in the database will be +/// automatically migrated to the default collection. +/// +/// Any pre-existing database functions that refer to documents, listeners, and indexes without +/// specifying a collection such as \ref CBLDatabase_GetDocument will implicitly operate on +/// the default collection. In other words, they behave exactly the way they used to, but +/// collection-aware code should avoid them and use the new Collection API instead. +/// These legacy functions are deprecated and will be removed eventually. #[derive(Debug, PartialEq, Eq)] pub struct Collection { cbl_ref: *mut CBLCollection, } impl Collection { + pub const DEFAULT_NAME: &str = "_default"; + pub const DEFAULT_FULLE_NAME: &str = "_default._default"; + + //////// CONSTRUCTORS: + + /// Takes ownership of the object and increase it's reference counter. pub(crate) fn retain(cbl_ref: *mut CBLCollection) -> Self { Self { cbl_ref: unsafe { retain(cbl_ref) }, } } - /** Returns the scope of the collection. */ + //////// + + /// Returns the scope of the collection. pub fn scope(&self) -> Scope { unsafe { Scope::retain(CBLCollection_Scope(self.get_ref())) } } - /** Returns the collection name. */ + /// Returns the collection name. pub fn name(&self) -> String { unsafe { CBLCollection_Name(self.get_ref()) @@ -35,12 +79,26 @@ impl Collection { } } - /** Returns the number of documents in the collection. */ + /// Returns the collection full name. + pub fn full_name(&self) -> String { + unsafe { + CBLCollection_FullName(self.get_ref()) + .to_string() + .unwrap_or_default() + } + } + + /// Returns the collection's database. + pub fn database(&self) -> Database { + unsafe { Database::wrap(CBLCollection_Database(self.get_ref())) } + } + + /// Returns the number of documents in the collection. pub fn count(&self) -> u64 { unsafe { CBLCollection_Count(self.get_ref()) } } - /** Registers a collection change listener callback. It will be called after one or more documents are changed on disk. */ + /// Registers a collection change listener callback. It will be called after one or more documents are changed on disk. pub fn add_listener( &mut self, listener: CollectionChangeListener, @@ -82,8 +140,8 @@ impl Clone for Collection { } } -/** A collection change listener callback, invoked after one or more documents are changed on disk. */ -type CollectionChangeListener = Box)>; +/// A collection change listener callback, invoked after one or more documents are changed on disk. +pub type CollectionChangeListener = Box)>; #[no_mangle] unsafe extern "C" fn c_collection_change_listener( diff --git a/src/database.rs b/src/database.rs index 634f04f..a2d19e3 100644 --- a/src/database.rs +++ b/src/database.rs @@ -27,9 +27,9 @@ use crate::{ CBLDatabase_Open, CBLDatabase_Path, CBLDatabase_PerformMaintenance, CBLDatabase_SendNotifications, CBLEncryptionKey, CBLError, CBL_DatabaseExists, CBL_DeleteDatabase, CBLEncryptionKey_FromPassword, FLString, kCBLMaintenanceTypeCompact, - kCBLEncryptionNone, kCBLMaintenanceTypeFullOptimize, kCBLMaintenanceTypeIntegrityCheck, - kCBLMaintenanceTypeOptimize, kCBLMaintenanceTypeReindex, CBL_CopyDatabase, - CBLDatabase_ScopeNames, CBLDatabase_CollectionNames, CBLDatabase_Scope, + kCBLEncryptionAES256, kCBLEncryptionNone, kCBLMaintenanceTypeFullOptimize, + kCBLMaintenanceTypeIntegrityCheck, kCBLMaintenanceTypeOptimize, kCBLMaintenanceTypeReindex, + CBL_CopyDatabase, CBLDatabase_ScopeNames, CBLDatabase_CollectionNames, CBLDatabase_Scope, CBLDatabase_Collection, CBLDatabase_CreateCollection, CBLDatabase_DeleteCollection, CBLDatabase_DefaultScope, CBLDatabase_DefaultCollection, }, @@ -41,16 +41,32 @@ use crate::{ use std::path::{Path, PathBuf}; use std::ptr; +enum_from_primitive! { + /// Database encryption algorithms + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + pub enum EncryptionAlgorithm { + None = kCBLEncryptionNone as isize, + AES256 = kCBLEncryptionAES256 as isize, + } +} + +/// Database encryption key size +pub const ENCRYPTION_KEY_SIZE_AES256: i64 = 32; + +/// Encryption key specified in a DatabaseConfiguration #[derive(Debug, Clone)] pub struct EncryptionKey { cbl_ref: Box, } impl EncryptionKey { - pub fn new_from_password(password: &str) -> Option { + /// Derives an encryption key from a password. If your UI uses passwords, call this function to + /// create the key used to encrypt the database. It is designed for security, and deliberately + /// runs slowly to make brute-force attacks impractical. + pub fn new_from_password(algorithm: EncryptionAlgorithm, password: &str) -> Option { unsafe { let key = CBLEncryptionKey { - algorithm: kCBLEncryptionNone, + algorithm: algorithm as u32, bytes: [0; 32], }; let encryption_key = Self { @@ -76,7 +92,7 @@ impl CblRef for EncryptionKey { } } -/** Database configuration options. */ +/// Database configuration options #[derive(Debug, Clone)] pub struct DatabaseConfiguration<'a> { pub directory: &'a std::path::Path, @@ -84,17 +100,26 @@ pub struct DatabaseConfiguration<'a> { } enum_from_primitive! { + /// Maintenance Type used when performing database maintenance #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum MaintenanceType { + /// Compact the database file and delete unused attachments. Compact = kCBLMaintenanceTypeCompact as isize, + /// Rebuild the entire database's indexes. Reindex = kCBLMaintenanceTypeReindex as isize, + /// Check for the database’s corruption. If found, an error will be returned IntegrityCheck = kCBLMaintenanceTypeIntegrityCheck as isize, + /// Partially scan indexes to gather database statistics that help optimize queries. + /// This operation is also performed automatically when closing the database. Optimize = kCBLMaintenanceTypeOptimize as isize, + /// Fully scan all indexes to gather database statistics that help optimize queries. + /// This may take some time, depending on the size of the indexes, but it doesn't have to + /// be redone unless the database changes drastically, or new indexes are created. FullOptimize = kCBLMaintenanceTypeFullOptimize as isize, } } -/** A database change listener callback, invoked after one or more documents are changed on disk. */ +/// A database change listener callback, invoked after one or more documents are changed on disk #[deprecated(note = "please use `CollectionChangeListener` on default collection instead")] type DatabaseChangeListener = Box)>; @@ -116,7 +141,7 @@ unsafe extern "C" fn c_database_change_listener( (*callback)(&database, doc_ids); } -/** Callback indicating that the database (or an object belonging to it) is ready to call one or more listeners. */ +/// Callback indicating that the database (or an object belonging to it) is ready to call one or more listeners. type BufferNotifications = fn(db: &Database); #[no_mangle] unsafe extern "C" fn c_database_buffer_notifications( @@ -130,7 +155,7 @@ unsafe extern "C" fn c_database_buffer_notifications( callback(&database); } -/** A connection to an open database. */ +/// A connection to an open database #[derive(Debug, PartialEq, Eq)] pub struct Database { cbl_ref: *mut CBLDatabase, @@ -145,21 +170,23 @@ impl CblRef for Database { impl Database { //////// CONSTRUCTORS: + + /// Takes ownership of the object and increase it's reference counter. pub(crate) fn retain(cbl_ref: *mut CBLDatabase) -> Self { Self { cbl_ref: unsafe { retain(cbl_ref) }, } } + /// References the object without taking ownership and increasing it's reference counter pub(crate) const fn wrap(cbl_ref: *mut CBLDatabase) -> Self { Self { cbl_ref } } - /** Opens a database, or creates it if it doesn't exist yet, returning a new `Database` - instance. - - It's OK to open the same database file multiple times. Each `Database` instance is - independent of the others (and must be separately closed and released.) */ + /// Opens a database, or creates it if it doesn't exist yet, returning a new `Database` + /// instance. + /// It's OK to open the same database file multiple times. Each `Database` instance is + /// independent of the others (and must be separately closed and released.) pub fn open(name: &str, config: Option) -> Result { unsafe { if let Some(cfg) = config { @@ -185,7 +212,7 @@ impl Database { //////// OTHER STATIC METHODS: - /** Returns true if a database with the given name exists in the given directory. */ + /// Returns true if a database with the given name exists in the given directory. pub fn exists>(name: &str, in_directory: P) -> bool { unsafe { CBL_DatabaseExists( @@ -195,8 +222,8 @@ impl Database { } } - /** Copies a database file to a new location, and assigns it a new internal UUID to distinguish - it from the original database when replicating. */ + /// Copies a database file to a new location, and assigns it a new internal UUID to distinguish + /// it from the original database when replicating. pub fn copy_file>( current_db_full_path: P, new_db_name: &str, @@ -245,7 +272,7 @@ impl Database { check_error(&error) } - /** Deletes a database file. If the database file is open, an error is returned. */ + /// Deletes a database file. If the database file is open, an error is returned. pub fn delete_file>(name: &str, in_directory: P) -> Result { unsafe { let mut error = CBLError::default(); @@ -265,18 +292,18 @@ impl Database { //////// OPERATIONS: - /** Closes an open database. */ + /// Closes an open database. pub fn close(self) -> Result<()> { unsafe { check_bool(|error| CBLDatabase_Close(self.get_ref(), error)) } } - /** Closes and deletes a database. If there are any other connections to the database, - an error is returned. */ + /// Closes and deletes a database. If there are any other connections to the database, + /// error is returned. pub fn delete(self) -> Result<()> { unsafe { check_bool(|error| CBLDatabase_Delete(self.get_ref(), error)) } } - /** Compacts a database file, freeing up unused disk space. */ + /// Runs a maintenance operation on the database. pub fn perform_maintenance(&mut self, of_type: MaintenanceType) -> Result<()> { unsafe { check_bool(|error| { @@ -285,11 +312,11 @@ impl Database { } } - /** Invokes the callback within a database transaction - - Multiple writes are _much_ faster when grouped in a transaction. - - Changes will not be visible to other Database instances on the same database until - the transaction ends. - - Transactions can nest. Changes are not committed until the outer one ends. */ + /// Invokes the callback within a database transaction + /// - Multiple writes are _much_ faster when grouped in a transaction. + /// - Changes will not be visible to other Database instances on the same database until + /// the transaction ends. + /// - Transactions can nest. Changes are not committed until the outer one ends. pub fn in_transaction(&mut self, mut callback: F) -> Result where F: FnMut(&mut Self) -> Result, @@ -309,7 +336,7 @@ impl Database { result } - /** Encrypts or decrypts a database, or changes its encryption key. */ + /// Encrypts or decrypts a database, or changes its encryption key. pub fn change_encryption_key(&mut self, encryption_key: &EncryptionKey) -> Result<()> { unsafe { check_bool(|error| { @@ -320,25 +347,25 @@ impl Database { //////// ACCESSORS: - /** Returns the database's name. */ + /// Returns the database's name. pub fn name(&self) -> &str { unsafe { CBLDatabase_Name(self.get_ref()).as_str().unwrap() } } - /** Returns the database's full filesystem path. */ + /// Returns the database's full filesystem path. pub fn path(&self) -> PathBuf { unsafe { PathBuf::from(CBLDatabase_Path(self.get_ref()).to_string().unwrap()) } } - /** Returns the number of documents in the database. */ + /// Returns the number of documents in the database. #[deprecated(note = "please use `count` on the default collection instead")] pub fn count(&self) -> u64 { unsafe { CBLDatabase_Count(self.get_ref()) } } - /** Returns the names of all existing scopes in the database. - The scope exists when there is at least one collection created under the scope. - The default scope is exceptional in that it will always exists even there are no collections under it. */ + /// Returns the names of all existing scopes in the database. + /// - the default scope (_default) always exists. + /// - other scopes exist when it contains at least one collection pub fn scope_names(&self) -> Result> { let mut error = CBLError::default(); let array = unsafe { CBLDatabase_ScopeNames(self.get_ref(), &mut error) }; @@ -351,7 +378,7 @@ impl Database { }) } - /** Returns the names of all collections in the scope. */ + /// Returns the names of all collections in the scope. pub fn collection_names(&self, scope_name: String) -> Result> { let scope_name = from_str(&scope_name); let mut error = CBLError::default(); @@ -367,9 +394,9 @@ impl Database { }) } - /** Returns an existing scope with the given name. - The scope exists when there is at least one collection created under the scope. - The default scope is exception in that it will always exists even there are no collections under it. */ + /// Returns an existing scope with the given name. + /// - the default scope (_default) always exists. + /// - other scopes exist when it contains at least one collection pub fn scope(&self, scope_name: String) -> Result> { let scope_name = from_str(&scope_name); let mut error = CBLError::default(); @@ -384,7 +411,7 @@ impl Database { }) } - /** Returns the existing collection with the given name and scope. */ + /// Returns the existing collection with the given name and scope. pub fn collection( &self, collection_name: String, @@ -411,13 +438,13 @@ impl Database { }) } - /** Create a new collection. - The naming rules of the collections and scopes are as follows: - - Must be between 1 and 251 characters in length. - - Can only contain the characters A-Z, a-z, 0-9, and the symbols _, -, and %. - - Cannot start with _ or %. - - Both scope and collection names are case sensitive. - If the collection already exists, the existing collection will be returned. */ + /// Create a new collection. + /// The naming rules of the collections and scopes are as follows: + /// - Must be between 1 and 251 characters in length. + /// - Can only contain the characters A-Z, a-z, 0-9, and the symbols _, -, and %. + /// - Cannot start with _ or %. + /// - Both scope and collection names are case sensitive. + /// If the collection already exists, the existing collection will be returned. pub fn create_collection( &self, collection_name: String, @@ -438,13 +465,8 @@ impl Database { check_error(&error).map(|()| Collection::retain(collection)) } - /** Delete an existing collection. - @note The default collection cannot be deleted. - @param db The database. - @param collectionName The name of the collection. - @param scopeName The name of the scope. - @param outError On failure, the error will be written here. - @return True if success, or False if an error occurred. */ + /// Delete an existing collection. + /// The default collection cannot be deleted. pub fn delete_collection(&self, collection_name: String, scope_name: String) -> Result<()> { let collection_name = from_str(&collection_name); let scope_name = from_str(&scope_name); @@ -460,7 +482,7 @@ impl Database { } } - /** Returns the default scope. */ + /// Returns the default scope. pub fn default_scope(&self) -> Result { let mut error = CBLError::default(); let scope = unsafe { CBLDatabase_DefaultScope(self.get_ref(), &mut error) }; @@ -468,7 +490,7 @@ impl Database { check_error(&error).map(|()| Scope::retain(scope)) } - /** Returns the default collection. */ + /// Returns the default collection. pub fn default_collection(&self) -> Result> { let mut error = CBLError::default(); let collection = unsafe { CBLDatabase_DefaultCollection(self.get_ref(), &mut error) }; @@ -482,6 +504,7 @@ impl Database { }) } + /// Returns the default collection. pub fn default_collection_or_error(&self) -> Result { let mut error = CBLError::default(); let collection = unsafe { CBLDatabase_DefaultCollection(self.get_ref(), &mut error) }; @@ -497,15 +520,14 @@ impl Database { //////// NOTIFICATIONS: - /** Registers a database change listener function. It will be called after one or more - documents are changed on disk. Remember to keep the reference to the ChangeListener - if you want the callback to keep working. - - # Lifetime - - The listener is deleted at the end of life of the `Listener` object. - You must keep the `Listener` object as long as you need it. - */ + /// Registers a database change listener function. It will be called after one or more + /// documents are changed on disk. Remember to keep the reference to the ChangeListener + /// if you want the callback to keep working. + /// + /// # Lifetime + /// + /// The listener is deleted at the end of life of the `Listener` object. + /// You must keep the `Listener` object alive as long as you need it. #[must_use] #[deprecated(note = "please use `add_listener` on default collection instead")] pub fn add_listener( @@ -529,10 +551,10 @@ impl Database { } } - /** Switches the database to buffered-notification mode. Notifications for objects belonging - to this database (documents, queries, replicators, and of course the database) will not be - called immediately; your callback function will be called instead. You can then call - `send_notifications` when you're ready. */ + /// Switches the database to buffered-notification mode. Notifications for objects belonging + /// to this database (documents, queries, replicators, and of course the database) will not be + /// called immediately; your callback function will be called instead. You can then call + /// `send_notifications` when you're ready. pub fn buffer_notifications(&self, callback: BufferNotifications) { unsafe { let callback = callback as *mut std::ffi::c_void; @@ -545,8 +567,8 @@ impl Database { } } - /** Immediately issues all pending notifications for this database, by calling their listener - callbacks. (Only useful after `buffer_notifications` has been called.) */ + /// Immediately issues all pending notifications for this database, by calling their listener + /// callbacks. (Only useful after `buffer_notifications` has been called.) */ pub fn send_notifications(&self) { unsafe { CBLDatabase_SendNotifications(self.get_ref()); diff --git a/src/document.rs b/src/document.rs index dbe12e2..8a1695c 100644 --- a/src/document.rs +++ b/src/document.rs @@ -40,7 +40,7 @@ use crate::{ collection::Collection, }; -/** An in-memory copy of a document. */ +/// An in-memory copy of a document. #[derive(Debug)] pub struct Document { cbl_ref: *mut CBLDocument, @@ -53,16 +53,18 @@ impl CblRef for Document { } } -/** Conflict-handling options when saving or deleting a document. */ +/// Conflict-handling options when saving or deleting a document. pub enum ConcurrencyControl { + /// The current save/delete will overwrite a conflicting revision if there is a conflict. LastWriteWins = kCBLConcurrencyControlLastWriteWins as isize, + /// The current save/delete will fail if there is a conflict. FailOnConflict = kCBLConcurrencyControlFailOnConflict as isize, } -/** Custom conflict handler for use when saving or deleting a document. This handler is called -if the save would cause a conflict, i.e. if the document in the database has been updated -(probably by a pull replicator, or by application code on another thread) -since it was loaded into the CBLDocument being saved. */ +/// Custom conflict handler for use when saving or deleting a document. This handler is called +/// if the save would cause a conflict, i.e. if the document in the database has been updated +/// (probably by a pull replicator, or by application code on another thread) +/// since it was loaded into the CBLDocument being saved. type ConflictHandler = fn(&mut Document, &Document) -> bool; #[no_mangle] unsafe extern "C" fn c_conflict_handler( @@ -78,8 +80,8 @@ unsafe extern "C" fn c_conflict_handler( ) } -/** A document change listener lets you detect changes made to a specific document after they -are persisted to the database. */ +/// A document change listener lets you detect changes made to a specific document after they +/// are persisted to the database. #[deprecated(note = "please use `CollectionDocumentChangeListener` instead")] type DatabaseDocumentChangeListener = Box)>; @@ -97,8 +99,8 @@ unsafe extern "C" fn c_database_document_change_listener( //////// DATABASE'S DOCUMENT API: impl Database { - /** Reads a document from the database. Each call to this function returns a new object - containing the document's current state. */ + /// Reads a document from the database. Each call to this function returns a new object + /// containing the document's current state. #[deprecated(note = "please use `get_document` on default collection instead")] pub fn get_document(&self, id: &str) -> Result { unsafe { @@ -118,23 +120,22 @@ impl Database { } } - /** Saves a new or modified document to the database. - If a newer revision has been saved since \p doc was loaded, it will be overwritten by - this one. This can lead to data loss! To avoid this, call - `save_document_with_concurency_control` or - `save_document_resolving` instead. */ - #[deprecated(note = "please use `get_document` on default collection instead")] + /// Saves a new or modified document to the database. + /// If a newer revision has been saved since \p doc was loaded, it will be overwritten by + /// this one. This can lead to data loss! To avoid this, call + /// `save_document_with_concurency_control` or `save_document_resolving` instead. + #[deprecated(note = "please use `save_document` on default collection instead")] pub fn save_document(&mut self, doc: &mut Document) -> Result<()> { unsafe { check_bool(|error| CBLDatabase_SaveDocument(self.get_ref(), doc.get_ref(), error)) } } - /** Saves a new or modified document to the database. - If a conflicting revision has been saved since `doc` was loaded, the `concurrency` - parameter specifies whether the save should fail, or the conflicting revision should - be overwritten with the revision being saved. - If you need finer-grained control, call `save_document_resolving` instead. */ + /// Saves a new or modified document to the database. + /// If a conflicting revision has been saved since `doc` was loaded, the `concurrency` + /// parameter specifies whether the save should fail, or the conflicting revision should + /// be overwritten with the revision being saved. + /// If you need finer-grained control, call `save_document_resolving` instead. #[deprecated( note = "please use `save_document_with_concurrency_control` on default collection instead" )] @@ -156,9 +157,9 @@ impl Database { } } - /** Saves a new or modified document to the database. This function is the same as - `save_document`, except that it allows for custom conflict handling in the event - that the document has been updated since `doc` was loaded. */ + /// Saves a new or modified document to the database. This function is the same as + /// `save_document`, except that it allows for custom conflict handling in the event + /// that the document has been updated since `doc` was loaded. #[deprecated(note = "please use `save_document_resolving` on default collection instead")] pub fn save_document_resolving( &mut self, @@ -182,7 +183,7 @@ impl Database { } } - /** Deletes a document from the database. Deletions are replicated. */ + /// Deletes a document from the database. Deletions are replicated. #[deprecated(note = "please use `delete_document` on default collection instead")] pub fn delete_document(&mut self, doc: &Document) -> Result<()> { unsafe { @@ -190,7 +191,7 @@ impl Database { } } - /** Deletes a document from the database. Deletions are replicated. */ + /// Deletes a document from the database. Deletions are replicated. #[deprecated( note = "please use `delete_document_with_concurrency_control` on default collection instead" )] @@ -212,8 +213,8 @@ impl Database { } } - /** Purges a document. This removes all traces of the document from the database. - Purges are _not_ replicated. If the document is changed on a server, it will be re-created */ + /// Purges a document. This removes all traces of the document from the database. + /// Purges are _not_ replicated. If the document is changed on a server, it will be re-created. #[deprecated(note = "please use `purge_document` on default collection instead")] pub fn purge_document(&mut self, doc: &Document) -> Result<()> { unsafe { @@ -221,7 +222,7 @@ impl Database { } } - /** Purges a document, given only its ID. */ + /// Purges a document, given only its ID. #[deprecated(note = "please use `purge_document_by_id` on default collection instead")] pub fn purge_document_by_id(&mut self, id: &str) -> Result<()> { unsafe { @@ -231,9 +232,9 @@ impl Database { } } - /** Returns the time, if any, at which a given document will expire and be purged. - Documents don't normally expire; you have to call `set_document_expiration` - to set a document's expiration time. */ + /// Returns the time, if any, at which a given document will expire and be purged. + /// Documents don't normally expire; you have to call `set_document_expiration` + /// to set a document's expiration time. #[deprecated(note = "please use `document_expiration` on default collection instead")] pub fn document_expiration(&self, doc_id: &str) -> Result> { unsafe { @@ -251,8 +252,8 @@ impl Database { } } - /** Sets or clears the expiration time of a document. */ - #[deprecated(note = "please use `set_document_espiration` on default collection instead")] + /// Sets or clears the expiration time of a document. + #[deprecated(note = "please use `set_document_expiration` on default collection instead")] pub fn set_document_expiration(&mut self, doc_id: &str, when: Option) -> Result<()> { let exp: i64 = match when { Some(Timestamp(n)) => n, @@ -270,15 +271,14 @@ impl Database { } } - /** Registers a document change listener callback. It will be called after a specific document - is changed on disk. - - - # Lifetime - - The listener is deleted at the end of life of the Listener object. - You must keep the Listener object as long as you need it - */ + /// Registers a document change listener callback. It will be called after a specific document + /// is changed on disk. + /// + /// + /// # Lifetime + /// + /// The listener is deleted at the end of life of the Listener object. + /// You must keep the Listener object alive as long as you need it #[must_use] #[deprecated(note = "please use `add_document_change_listener` on default collection instead")] pub fn add_document_change_listener( @@ -304,8 +304,8 @@ impl Database { //////// COLLECTION'S DOCUMENT API: -/** A document change listener lets you detect changes made to a specific document after they -are persisted to the collection. */ +/// A document change listener lets you detect changes made to a specific document after they +/// are persisted to the collection. type CollectionDocumentChangeListener = Box)>; #[no_mangle] @@ -321,8 +321,8 @@ unsafe extern "C" fn c_collection_document_change_listener( } impl Collection { - /** Reads a document from the collection, creating a new (immutable) \ref CBLDocument object. - Each call to this function creates a new object (which must later be released.) */ + /// Reads a document from the collection, returning a new Document object. + /// Each call to this function creates a new object (which must later be released.). pub fn get_document(&self, id: &str) -> Result { unsafe { // we always get a mutable CBLDocument, @@ -344,23 +344,18 @@ impl Collection { } } - /** Saves a (mutable) document to the collection. */ + /// Saves a document to the collection. pub fn save_document(&mut self, doc: &mut Document) -> Result<()> { unsafe { check_bool(|error| CBLCollection_SaveDocument(self.get_ref(), doc.get_ref(), error)) } } - /** Saves a (mutable) document to the collection. - If a conflicting revision has been saved since \p doc was loaded, the \p concurrency - parameter specifies whether the save should fail, or the conflicting revision should - be overwritten with the revision being saved. - If you need finer-grained control, call \ref CBLCollection_SaveDocumentWithConflictHandler instead. - @param collection The collection to save to. - @param doc The mutable document to save. - @param concurrency Conflict-handling strategy (fail or overwrite). - @param outError On failure, the error will be written here. - @return True on success, false on failure. */ + /// Saves a document to the collection. + /// If a conflicting revision has been saved since the document was loaded, the concurrency + /// parameter specifies whether the save should fail, or the conflicting revision should + /// be overwritten with the revision being saved. + /// If you need finer-grained control, call save_document_resolving instead. pub fn save_document_with_concurency_control( &mut self, doc: &mut Document, @@ -379,8 +374,8 @@ impl Collection { } } - /** Saves a (mutable) document to the collection, allowing for custom conflict handling in the event - that the document has been updated since \p doc was loaded. */ + /// Saves a document to the collection, allowing for custom conflict handling in the event + /// that the document has been updated since \p doc was loaded. pub fn save_document_resolving( &mut self, doc: &mut Document, @@ -403,14 +398,14 @@ impl Collection { } } - /** Deletes a document from the collection. Deletions are replicated. */ + /// Deletes a document from the collection. Deletions are replicated. pub fn delete_document(&mut self, doc: &Document) -> Result<()> { unsafe { check_bool(|error| CBLCollection_DeleteDocument(self.get_ref(), doc.get_ref(), error)) } } - /** Deletes a document from the collection. Deletions are replicated. */ + /// Deletes a document from the collection. Deletions are replicated. pub fn delete_document_with_concurency_control( &mut self, doc: &Document, @@ -429,16 +424,16 @@ impl Collection { } } - /** Purges a document. This removes all traces of the document from the collection. - Purges are _not_ replicated. If the document is changed on a server, it will be re-created - when pulled. */ + /// Purges a document. This removes all traces of the document from the collection. + /// Purges are _not_ replicated. If the document is changed on a server, it will be re-created + /// when pulled. pub fn purge_document(&mut self, doc: &Document) -> Result<()> { unsafe { check_bool(|error| CBLCollection_PurgeDocument(self.get_ref(), doc.get_ref(), error)) } } - /** Purges a document, given only its ID. */ + /// Purges a document, given only its ID. pub fn purge_document_by_id(&mut self, id: &str) -> Result<()> { unsafe { check_bool(|error| { @@ -447,9 +442,9 @@ impl Collection { } } - /** Returns the time, if any, at which a given document will expire and be purged. - Documents don't normally expire; you have to call \ref CBLCollection_SetDocumentExpiration - to set a document's expiration time. */ + /// Returns the time, if any, at which a given document will expire and be purged. + /// Documents don't normally expire; you have to call set_document_expiration + /// to set a document's expiration time. pub fn document_expiration(&self, doc_id: &str) -> Result> { unsafe { let mut error = CBLError::default(); @@ -466,7 +461,7 @@ impl Collection { } } - /** Sets or clears the expiration time of a document. */ + /// Sets or clears the expiration time of a document. pub fn set_document_expiration(&mut self, doc_id: &str, when: Option) -> Result<()> { let exp: i64 = match when { Some(Timestamp(n)) => n, @@ -484,7 +479,7 @@ impl Collection { } } - /** Registers a document change listener callback. It will be called after a specific document is changed on disk. */ + /// Registers a document change listener callback. It will be called after a specific document is changed on disk. pub fn add_document_change_listener( &self, document: &Document, @@ -515,20 +510,21 @@ impl Default for Document { } impl Document { - /** Creates a new, empty document in memory, with an automatically generated unique ID. - It will not be added to a database until saved. */ + //////// CONSTRUCTORS: + + /// Creates a new, empty document in memory, with an automatically generated unique ID. + /// It will not be added to a database until saved. pub fn new() -> Self { unsafe { Self::wrap(CBLDocument_Create()) } } - /** Creates a new, empty document in memory, with the given ID. - It will not be added to a database until saved. */ + /// Creates a new, empty document in memory, with the given ID. + /// It will not be added to a database until saved. pub fn new_with_id(id: &str) -> Self { unsafe { Self::wrap(CBLDocument_CreateWithID(from_str(id).get_ref())) } } - /** Wrap a CBLDocument as a Document. - Increment the reference-count for the CBLDocument. */ + /// Takes ownership of the object and increase it's reference counter. pub(crate) fn retain(cbl_ref: *mut CBLDocument) -> Self { unsafe { Self { @@ -537,64 +533,63 @@ impl Document { } } - /** Wrap a CBLDocument as a Document. - The CBLDocument reference-count should already have been incremented from a type-safe source. */ + /// References the object without taking ownership and increasing it's reference counter pub(crate) const fn wrap(cbl_ref: *mut CBLDocument) -> Self { Self { cbl_ref } } - /** Returns the document's ID. */ + //////// + + /// Returns the document's ID. pub fn id(&self) -> &str { unsafe { CBLDocument_ID(self.get_ref()).as_str().unwrap() } } - /** Returns a document's revision ID, which is a short opaque string that's guaranteed to be - unique to every change made to the document. - If the document doesn't exist yet, this method returns None. */ + /// Returns a document's revision ID, which is a short opaque string that's guaranteed to be + /// unique to every change made to the document. + /// If the document has not been saved yet, this method returns None. pub fn revision_id(&self) -> Option<&str> { unsafe { CBLDocument_RevisionID(self.get_ref()).as_str() } } - /** Returns a document's current sequence in the local database. - This number increases every time the document is saved, and a more recently saved document - will have a greater sequence number than one saved earlier, so sequences may be used as an - abstract 'clock' to tell relative modification times. */ + /// Returns a document's current sequence in the local database. + /// This number increases every time the document is saved, and a more recently saved document + /// will have a greater sequence number than one saved earlier, so sequences may be used as an + /// abstract 'clock' to tell relative modification times. */ pub fn sequence(&self) -> u64 { unsafe { CBLDocument_Sequence(self.get_ref()) } } - /** Returns true if a document is deleted. - The way it is checked is by verifying if the document's properties are empty, so avoid using - this function if it makes sense functionally to have no properties on a document.*/ + /// Returns true if a document is deleted. pub fn is_deleted(&self) -> bool { self.properties().empty() } - /** Returns a document's properties as a dictionary. - This dictionary cannot be mutated; call `mutable_properties` if you want to make - changes to the document's properties. */ + /// Returns a document's properties as a dictionary. + /// They cannot be mutated; call `mutable_properties` if you want to make + /// changes to the document. pub fn properties(&self) -> Dict { unsafe { Dict::wrap(CBLDocument_Properties(self.get_ref()), self) } } - /** Returns a document's properties as an mutable dictionary. Any changes made to this - dictionary will be saved to the database when this Document instance is saved. */ + /// Returns a document's properties as an mutable dictionary. Any changes made to this + /// dictionary will be saved to the database when this Document instance is saved. pub fn mutable_properties(&mut self) -> MutableDict { unsafe { MutableDict::adopt(CBLDocument_MutableProperties(self.get_ref())) } } - /** Replaces a document's properties with the contents of the dictionary. - The dictionary is retained, not copied, so further changes _will_ affect the document. */ + /// Replaces a document's properties with the contents of the dictionary. + /// The dictionary is retained, not copied, so further changes _will_ affect the document. pub fn set_properties(&mut self, properties: &MutableDict) { unsafe { CBLDocument_SetProperties(self.get_ref(), properties.get_ref()) } } - /** Returns a document's properties as a JSON string. */ + /// Returns a document's properties as a JSON string. pub fn properties_as_json(&self) -> String { unsafe { CBLDocument_CreateJSON(self.get_ref()).to_string().unwrap() } } - /** Sets a mutable document's properties from a JSON string. */ + /// Sets a mutable document's properties from a JSON string. pub fn set_properties_as_json(&mut self, json: &str) -> Result<()> { unsafe { let mut err = CBLError::default(); diff --git a/src/encryptable.rs b/src/encryptable.rs index 836fd0a..40e4c5c 100644 --- a/src/encryptable.rs +++ b/src/encryptable.rs @@ -11,6 +11,48 @@ use crate::{ Array, CblRef, Dict, Value, release, retain, }; +/// An Encryptable is a value to be encrypted by the replicator when a document is +/// pushed to the remote server. When a document is pulled from the remote server, the +/// encrypted value will be decrypted by the replicator. +/// +/// Similar to Blob, an Encryptable acts as a proxy for a dictionary structure +/// with the special marker property `"@type":"encryptable"`, and another property `value` +/// whose value is the actual value to be encrypted by the push replicator. +/// +/// The push replicator will automatically detect Encryptable dictionaries inside +/// the document and calls the specified PropertyEncryptor callback to encrypt the +/// actual value. When the value is successfully encrypted, the replicator will transform +/// the property key and the encrypted dictionary value into +/// Couchbase Server SDK's encrypted field format : +/// +/// * The original key will be prefixed with 'encrypted$'. +/// +/// * The transformed Encryptable dictionary will contain `alg` property indicating +/// the encryption algorithm, `ciphertext` property whose value is a base-64 string of the +/// encrypted value, and optionally `kid` property indicating the encryption key identifier +/// if specified when returning the result of PropertyEncryptor callback call. +/// +/// For security reason, a document that contains Encryptable dictionaries will fail +/// to push if their value cannot be encrypted including +/// when a PropertyEncryptor callback is not specified or when there is an error +/// or a null result returned from the callback call. +/// +/// The pull replicator will automatically detect the encrypted properties that are in the +/// Couchbase Server SDK's encrypted field format and call the specified PropertyDecryptor +/// callback to decrypt the encrypted value. When the value is successfully decrypted, +/// the replicator will transform the property format back to the Encryptable format +/// including removing the 'encrypted$' prefix. +/// +/// The PropertyDecryptor callback can intentionally skip the decryption by returnning a +/// null result. When a decryption is skipped, the encrypted property in the form of +/// Couchbase Server SDK's encrypted field format will be kept as it was received from the remote +/// server. If an error is returned from the callback call, the document will be failed to pull with +/// the ErrorCrypto error. +/// +/// If a PropertyDecryptor callback is not specified, the replicator will not attempt to +/// detect any encrypted properties. As a result, all encrypted properties in the form of +/// Couchbase Server SDK's encrypted field format will be kept as they was received from the remote +/// server. pub struct Encryptable { cbl_ref: *mut CBLEncryptable, } @@ -29,36 +71,48 @@ impl From<*mut CBLEncryptable> for Encryptable { } impl Encryptable { + //////// CONSTRUCTORS: + + /// Takes ownership of the object and increase it's reference counter. pub(crate) fn retain(cbl_ref: *mut CBLEncryptable) -> Self { Self { cbl_ref: unsafe { retain(cbl_ref) }, } } + //////// + + /// Creates Encryptable object with null value. pub fn create_with_null() -> Self { unsafe { CBLEncryptable_CreateWithNull().into() } } + /// Creates Encryptable object with a boolean value. pub fn create_with_bool(value: bool) -> Self { unsafe { CBLEncryptable_CreateWithBool(value).into() } } + /// Creates Encryptable object with i64 value. pub fn create_with_int(value: i64) -> Self { unsafe { CBLEncryptable_CreateWithInt(value).into() } } + /// Creates Encryptable object with an u64 value. pub fn create_with_uint(value: u64) -> Self { unsafe { CBLEncryptable_CreateWithUInt(value).into() } } + /// Creates Encryptable object with a f32 value. pub fn create_with_float(value: f32) -> Self { unsafe { CBLEncryptable_CreateWithFloat(value).into() } } + /// Creates Encryptable object with a f64 value. pub fn create_with_double(value: f64) -> Self { unsafe { CBLEncryptable_CreateWithDouble(value).into() } } + /// Creates Encryptable object with a string value. pub fn create_with_string(value: &str) -> Self { unsafe { let slice = from_str(value); @@ -68,22 +122,27 @@ impl Encryptable { } } + /// Creates Encryptable object with an Value value. pub fn create_with_value(value: Value) -> Self { unsafe { CBLEncryptable_CreateWithValue(value.get_ref()).into() } } + /// Creates Encryptable object with an Array value. pub fn create_with_array(value: Array) -> Self { unsafe { CBLEncryptable_CreateWithArray(value.get_ref()).into() } } + /// Creates Encryptable object with a Dict value. pub fn create_with_dict(value: Dict) -> Self { unsafe { CBLEncryptable_CreateWithDict(value.get_ref()).into() } } + /// Returns the value to be encrypted by the push replicator. pub fn get_value(&self) -> Value { unsafe { Value::wrap(CBLEncryptable_Value(self.get_ref()), self) } } + /// Returns the dictionary format of the Encryptable object. pub fn get_properties(&self) -> Dict { unsafe { Dict::wrap(CBLEncryptable_Properties(self.get_ref()), self) } } diff --git a/src/error.rs b/src/error.rs index cdba254..7519ba6 100644 --- a/src/error.rs +++ b/src/error.rs @@ -27,14 +27,14 @@ use std::fmt; //////// ERROR STRUCT: -/** Error type. Wraps multiple types of errors in an enum. */ +/// Error type. Wraps multiple types of errors in an enum. #[derive(Clone, Copy, PartialEq, Eq)] pub struct Error { pub code: ErrorCode, pub(crate) internal_info: Option, } -/** The enum that stores the error domain and code for an Error. */ +/// The enum that stores the error domain and code for an Error. #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum ErrorCode { CouchbaseLite(CouchbaseLiteError), @@ -45,85 +45,142 @@ pub enum ErrorCode { WebSocket(i32), } -// Redefine `Result` to assume our `Error` type +/// Redefine `Result` to assume our `Error` type pub type Result = std::result::Result; enum_from_primitive! { - /** Couchbase Lite error codes. */ + /// Couchbase Lite error codes. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum CouchbaseLiteError { - AssertionFailed = 1, // Internal assertion failure - Unimplemented, // Oops, an unimplemented API call - UnsupportedEncryption, // Unsupported encryption algorithm - BadRevisionID, // Invalid revision ID syntax - CorruptRevisionData, // Revision contains corrupted/unreadable data - NotOpen, // Database/KeyStore/index is not open - NotFound, // Document not found - Conflict, // Document update conflict - InvalidParameter, // Invalid function parameter or struct value - UnexpectedError, /*10*/ // Internal unexpected C++ exception - CantOpenFile, // Database file can't be opened; may not exist - IOError, // File I/O error - MemoryError, // Memory allocation failed (out of memory?) - NotWriteable, // File is not writeable - CorruptData, // Data is corrupted - Busy, // Database is busy/locked - NotInTransaction, // Function must be called while in a transaction - TransactionNotClosed, // Database can't be closed while a transaction is open - Unsupported, // Operation not supported in this database - NotADatabaseFile,/*20*/ // File is not a database, or encryption key is wrong - WrongFormat, // Database exists but not in the format/storage requested - Crypto, // Encryption/decryption error - InvalidQuery, // Invalid query - MissingIndex, // No such index, or query requires a nonexistent index - InvalidQueryParam, // Unknown query param name, or param number out of range - RemoteError, // Unknown error from remote server - DatabaseTooOld, // Database file format is older than what I can open - DatabaseTooNew, // Database file format is newer than what I can open - BadDocID, // Invalid document ID - CantUpgradeDatabase,/*30*/ // DB can't be upgraded (might be unsupported dev version) + /// Internal assertion failure + AssertionFailed = 1, + /// Oops, an unimplemented API call + Unimplemented, + /// Unsupported encryption algorithm + UnsupportedEncryption, + /// Invalid revision ID syntax + BadRevisionID, + /// Revision contains corrupted/unreadable data + CorruptRevisionData, + /// Database/KeyStore/index is not open + NotOpen, + /// Document not found + NotFound, + /// Document update conflict + Conflict, + /// Invalid function parameter or struct value + InvalidParameter, + /// Internal unexpected C++ exception + UnexpectedError, /*10*/ + /// Database file can't be opened; may not exist + CantOpenFile, + /// File I/O error + IOError, + /// Memory allocation failed (out of memory?) + MemoryError, + /// File is not writeable + NotWriteable, + /// Data is corrupted + CorruptData, + /// Database is busy/locked + Busy, + /// Function must be called while in a transaction + NotInTransaction, + /// Database can't be closed while a transaction is open + TransactionNotClosed, + /// Operation not supported in this database + Unsupported, + /// File is not a database, or encryption key is wrong + NotADatabaseFile,/*20*/ + /// Database exists but not in the format/storage requested + WrongFormat, + /// Encryption/decryption error + Crypto, + /// Invalid query + InvalidQuery, + /// No such index, or query requires a nonexistent index + MissingIndex, + /// Unknown query param name, or param number out of range + InvalidQueryParam, + /// Unknown error from remote server + RemoteError, + /// Database file format is older than what I can open + DatabaseTooOld, + /// Database file format is newer than what I can open + DatabaseTooNew, + /// Invalid document ID + BadDocID, + /// DB can't be upgraded (might be unsupported dev version) + CantUpgradeDatabase,/*30*/ - UntranslatableError = 1000, // Can't translate native error (unknown domain or code) + /// Can't translate native error (unknown domain or code) + UntranslatableError = 1000, } } enum_from_primitive! { - /** Fleece error codes. */ + /// Fleece error codes #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum FleeceError { - MemoryError = 1, // Out of memory, or allocation failed - OutOfRange, // Array index or iterator out of range - InvalidData, // Bad input data (NaN, non-string key, etc.) - EncodeError, // Structural error encoding (missing value, too many ends, etc.) - JSONError, // Error parsing JSON - UnknownValue, // Unparseable data in a Value (corrupt? Or from some distant future?) - InternalError, // Something that shouldn't happen - NotFound, // Key not found - SharedKeysStateError, // Misuse of shared keys (not in transaction, etc.) - POSIXError, // Something went wrong at the OS level (file I/O, etc.) - Unsupported, // Operation is unsupported + /// Out of memory, or allocation failed + MemoryError = 1, + /// Array index or iterator out of range + OutOfRange, + /// Bad input data (NaN, non-string key, etc.) + InvalidData, + /// Structural error encoding (missing value, too many ends, etc.) + EncodeError, + /// Error parsing JSON + JSONError, + /// Unparseable data in a Value (corrupt? Or from some distant future?) + UnknownValue, + /// Something that shouldn't happen + InternalError, + /// Key not found + NotFound, + /// Misuse of shared keys (not in transaction, etc.) + SharedKeysStateError, + /// Something went wrong at the OS level (file I/O, etc.) + POSIXError, + /// Operation is unsupported + Unsupported, } } enum_from_primitive! { - /** Network error codes defined by Couchbase Lite. */ + /// Network error codes defined by Couchbase Lite. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum NetworkError { - DNSFailure = 1, // DNS lookup failed - UnknownHost, // DNS server doesn't know the hostname - Timeout, // No response received before timeout - InvalidURL, // Invalid URL - TooManyRedirects, // HTTP redirect loop - TLSHandshakeFailed, // Low-level error establishing TLS - TLSCertExpired, // Server's TLS certificate has expired - TLSCertUntrusted, // Cert isn't trusted for other reason - TLSClientCertRequired, // Server requires client to have a TLS certificate - TLSClientCertRejected, // Server rejected my TLS client certificate - TLSCertUnknownRoot, // Self-signed cert, or unknown anchor cert - InvalidRedirect, // Attempted redirect to invalid URL - Unknown, // Unknown networking error - TLSCertRevoked, // Server's cert has been revoked - TLSCertNameMismatch, // Server cert's name does not match DNS name + /// DNS lookup failed + DNSFailure = 1, + /// DNS server doesn't know the hostname + UnknownHost, + /// No response received before timeout + Timeout, + /// Invalid URL + InvalidURL, + /// HTTP redirect loop + TooManyRedirects, + /// Low-level error establishing TLS + TLSHandshakeFailed, + /// Server's TLS certificate has expired + TLSCertExpired, + /// Cert isn't trusted for other reason + TLSCertUntrusted, + /// Server requires client to have a TLS certificate + TLSClientCertRequired, + /// Server rejected my TLS client certificate + TLSClientCertRejected, + /// Self-signed cert, or unknown anchor cert + TLSCertUnknownRoot, + /// Attempted redirect to invalid URL + InvalidRedirect, + /// Unknown networking error + Unknown, + /// Server's cert has been revoked + TLSCertRevoked, + /// Server cert's name does not match DNS name + TLSCertNameMismatch, } } @@ -191,6 +248,7 @@ impl Error { } } + /// Returns a message describing an error. pub fn message(&self) -> String { if let ErrorCode::CouchbaseLite(e) = self.code { if e == CouchbaseLiteError::UntranslatableError { @@ -304,8 +362,8 @@ where check_failure(ok, &error) } -// The first parameter is a function that returns a non-null pointer or sets the error. -// The second parameter is a function that takes the returned pointer and returns the final result. +/// The first parameter is a function that returns a non-null pointer or sets the error. +/// The second parameter is a function that takes the returned pointer and returns the final result. pub(crate) fn check_ptr(func: F, map: MAPF) -> Result where F: Fn(*mut CBLError) -> *mut PTR, @@ -320,8 +378,8 @@ where } } -// The first parameter is a function that returns a non-null pointer or sets the error. -// The second parameter is a function that takes the returned pointer and returns the final result. +/// The first parameter is a function that returns a non-null pointer or sets the error. +/// The second parameter is a function that takes the returned pointer and returns the final result. pub(crate) fn check_io(mut func: F) -> std::io::Result where F: FnMut(*mut CBLError) -> i32, diff --git a/src/fleece.rs b/src/fleece.rs index 2fff72b..91144b9 100644 --- a/src/fleece.rs +++ b/src/fleece.rs @@ -42,7 +42,7 @@ use std::fmt; use std::mem::MaybeUninit; use std::ptr; use std::str; -use retain; +use crate::retain; //////// CONTAINER diff --git a/src/fleece_mutable.rs b/src/fleece_mutable.rs index 7a52740..5952789 100644 --- a/src/fleece_mutable.rs +++ b/src/fleece_mutable.rs @@ -36,12 +36,17 @@ use std::fmt; use std::marker::PhantomData; use std::ptr; +/// Option flags for making mutable copies of values. #[derive(Debug, Clone, Copy)] pub enum CopyFlags { - Default = 0, // Shallow copy of mutable values - Deep = 1, // Deep copy of mutable values - CopyImmutables = 2, // Make copies of immutable values too - DeepCopyImmutables = 3, // The works + /// Shallow copy of mutable values + Default = 0, + /// Deep copy of mutable values + Deep = 1, + /// Make copies of immutable values too + CopyImmutables = 2, + /// The works + DeepCopyImmutables = 3, } //////// MUTABLE ARRAY: @@ -58,6 +63,8 @@ impl CblRef for MutableArray { } impl MutableArray { + //////// CONSTRUCTORS: + pub fn new() -> Self { unsafe { Self { @@ -442,14 +449,14 @@ pub struct Slot<'s> { owner: PhantomData<&'s mut MutableDict>, } -impl<'s> CblRef for Slot<'s> { +impl CblRef for Slot<'_> { type Output = FLSlot; fn get_ref(&self) -> Self::Output { self.cbl_ref } } -impl<'s> Slot<'s> { +impl Slot<'_> { pub fn put_null(self) { unsafe { FLSlot_SetNull(self.get_ref()) } } diff --git a/src/index.rs b/src/index.rs index 349f90f..89fad98 100644 --- a/src/index.rs +++ b/src/index.rs @@ -3,14 +3,16 @@ use crate::{ c_api::{ CBLValueIndexConfiguration, CBLDatabase_GetIndexNames, CBLDatabase_DeleteIndex, CBLError, CBLDatabase_CreateValueIndex, CBLCollection_CreateValueIndex, CBLCollection_DeleteIndex, - CBLCollection_GetIndexNames, + CBLCollection_GetIndexNames, CBLCollection_CreateArrayIndex, CBLArrayIndexConfiguration, + CBLQueryIndex, CBLQueryIndex_Name, CBLQueryIndex_Collection, CBLCollection_GetIndex, }, - error::{Result, failure}, - slice::from_str, + error::{Error, Result, failure}, + slice::{from_str, from_c_str, Slice}, QueryLanguage, Array, collection::Collection, - check_error, + check_error, retain, CouchbaseLiteError, }; +use std::ffi::CString; pub struct ValueIndexConfiguration { cbl_ref: CBLValueIndexConfiguration, @@ -24,6 +26,10 @@ impl CblRef for ValueIndexConfiguration { } impl ValueIndexConfiguration { + /// Create a Value Index Configuration. + /// You must indicate the query language used in the expressions. + /// The expressions describe each coloumn of the index. The expressions could be specified + /// in a JSON Array or in N1QL syntax using comma delimiter. pub fn new(query_language: QueryLanguage, expressions: &str) -> Self { let slice = from_str(expressions); Self { @@ -35,7 +41,142 @@ impl ValueIndexConfiguration { } } +/// Array Index Configuration for indexing property values within arrays +/// in documents, intended for use with the UNNEST query. +#[derive(Debug)] +pub struct ArrayIndexConfiguration { + cbl_ref: CBLArrayIndexConfiguration, + _path: Slice, + _expressions: Slice, +} + +impl CblRef for ArrayIndexConfiguration { + type Output = CBLArrayIndexConfiguration; + fn get_ref(&self) -> Self::Output { + self.cbl_ref + } +} + +impl ArrayIndexConfiguration { + /// Create an Array Index Configuration for indexing property values within arrays + /// in documents, intended for use with the UNNEST query. + /// - query_langage: The language used in the expressions (Required). + /// - path: Path to the array, which can be nested to be indexed (Required). + /// Use "[]" to represent a property that is an array of each nested array level. + /// For a single array or the last level array, the "[]" is optional. For instance, + /// use "contacts[].phones" to specify an array of phones within each contact. + /// - expressions: Optional expressions representing the values within the array to be + /// indexed. The expressions could be specified in a JSON Array or in N1QL syntax + /// using comma delimiter. If the array specified by the path contains scalar values, + /// the expressions should be left unset or set to null. + /// + /// # Example 1 + /// + /// To index the values of array at path `likes` in documents: + /// + /// ``` + /// ArrayIndexConfiguration::new( + /// QueryLanguage::N1QL, + /// "likes", + /// "" + /// ) + /// ``` + /// + /// It would allow you to index the values "travel" and "skiing" in the following document: + /// { + /// likes: ["travel", "skiing"] + /// } + /// + /// # Example 2 + /// + /// ``` + /// ArrayIndexConfiguration::new( + /// QueryLanguage::N1QL, + /// "contacts[].phones", + /// "type" + /// ) + /// ``` + /// + /// It would allow you to index the values "mobile" and "home" in the following document: + /// { + /// contacts: { + /// phones: [ + /// { + /// type: "mobile" + /// }, + /// { + /// type: "home" + /// } + /// ] + /// } + /// } + pub fn new(query_language: QueryLanguage, path: &str, expressions: &str) -> Result { + let path_c = CString::new(path) + .map_err(|_| Error::cbl_error(CouchbaseLiteError::InvalidParameter))?; + let expressions_c = CString::new(expressions) + .map_err(|_| Error::cbl_error(CouchbaseLiteError::InvalidParameter))?; + + let path_s = from_c_str(path_c, path.len()); + let expressions_s = from_c_str(expressions_c, expressions.len()); + + Ok(Self { + cbl_ref: CBLArrayIndexConfiguration { + expressionLanguage: query_language as u32, + path: path_s.get_ref(), + expressions: expressions_s.get_ref(), + }, + _path: path_s, + _expressions: expressions_s, + }) + } +} + +/// QueryIndex represents an existing index in a collection. +/// The QueryIndex can be used to obtain +/// a IndexUpdater object for updating the vector index in lazy mode. +pub struct QueryIndex { + cbl_ref: *mut CBLQueryIndex, +} + +impl CblRef for QueryIndex { + type Output = *mut CBLQueryIndex; + fn get_ref(&self) -> Self::Output { + self.cbl_ref + } +} + +impl QueryIndex { + //////// CONSTRUCTORS: + + /// Takes ownership of the object and increase it's reference counter. + pub(crate) fn retain(cbl_ref: *mut CBLQueryIndex) -> Self { + Self { + cbl_ref: unsafe { retain(cbl_ref) }, + } + } + + //////// + + /// Returns the index's name. + pub fn name(&self) -> String { + unsafe { + CBLQueryIndex_Name(self.get_ref()) + .to_string() + .unwrap_or_default() + } + } + + /// Returns the collection that the index belongs to. + pub fn collection(&self) -> Collection { + unsafe { Collection::retain(CBLQueryIndex_Collection(self.get_ref())) } + } +} + impl Database { + /// Creates a value index. + /// Indexes are persistent. + /// If an identical index with that name already exists, nothing happens (and no error is returned.) + /// If a non-identical index with that name already exists, it is deleted and re-created. #[deprecated(note = "please use `create_index` on default collection instead")] pub fn create_index(&self, name: &str, config: &ValueIndexConfiguration) -> Result { let mut err = CBLError::default(); @@ -54,6 +195,7 @@ impl Database { failure(err) } + /// Deletes an index given its name. #[deprecated(note = "please use `delete_index` on default collection instead")] pub fn delete_index(&self, name: &str) -> Result { let mut err = CBLError::default(); @@ -65,6 +207,7 @@ impl Database { failure(err) } + /// Returns the names of the indexes on this database, as an Array of strings. #[deprecated(note = "please use `get_index_names` on default collection instead")] pub fn get_index_names(&self) -> Array { let arr = unsafe { CBLDatabase_GetIndexNames(self.get_ref()) }; @@ -73,6 +216,9 @@ impl Database { } impl Collection { + /// Creates a value index in the collection. + /// If an identical index with that name already exists, nothing happens (and no error is returned.) + /// If a non-identical index with that name already exists, it is deleted and re-created. pub fn create_index(&self, name: &str, config: &ValueIndexConfiguration) -> Result { let mut err = CBLError::default(); let slice = from_str(name); @@ -90,6 +236,27 @@ impl Collection { failure(err) } + /// Creates an array index for use with UNNEST queries in the collection. + /// If an identical index with that name already exists, nothing happens (and no error is returned.) + /// If a non-identical index with that name already exists, it is deleted and re-created. + pub fn create_array_index(&self, name: &str, config: &ArrayIndexConfiguration) -> Result { + let mut err = CBLError::default(); + let slice = from_str(name); + let r = unsafe { + CBLCollection_CreateArrayIndex( + self.get_ref(), + slice.get_ref(), + config.get_ref(), + &mut err, + ) + }; + if !err { + return Ok(r); + } + failure(err) + } + + /// Deletes an index in the collection by name. pub fn delete_index(&self, name: &str) -> Result { let mut err = CBLError::default(); let slice = from_str(name); @@ -100,9 +267,21 @@ impl Collection { failure(err) } + /// Returns the names of the indexes in the collection, as a Fleece array of strings. pub fn get_index_names(&self) -> Result { let mut err = CBLError::default(); let arr = unsafe { CBLCollection_GetIndexNames(self.get_ref(), &mut err) }; check_error(&err).map(|()| Array::wrap(arr)) } + + /// Returns the names of the indexes in the collection, as a Fleece array of strings. + pub fn get_index(&self, name: &str) -> Result { + let mut err = CBLError::default(); + let slice = from_str(name); + let index = unsafe { CBLCollection_GetIndex(self.get_ref(), slice.get_ref(), &mut err) }; + if !err { + return Ok(QueryIndex::retain(index)); + } + failure(err) + } } diff --git a/src/query.rs b/src/query.rs index 2c20e5b..8bdaa96 100644 --- a/src/query.rs +++ b/src/query.rs @@ -30,8 +30,8 @@ use crate::{ Listener, }; -use std::{os::raw::c_uint}; -use ListenerToken; +use std::os::raw::c_uint; +use crate::ListenerToken; /** Query languages. */ pub enum QueryLanguage { diff --git a/src/scope.rs b/src/scope.rs index df6a3ca..7db8be4 100644 --- a/src/scope.rs +++ b/src/scope.rs @@ -1,10 +1,14 @@ use crate::{ CblRef, check_error, release, retain, - c_api::{CBLScope, CBLScope_Name, CBLScope_CollectionNames, CBLScope_Collection, CBLError}, + c_api::{ + CBLScope, CBLScope_Name, CBLScope_CollectionNames, CBLScope_Collection, CBLError, + CBLScope_Database, + }, collection::Collection, error::Result, MutableArray, slice::from_str, + Database, }; #[derive(Debug, PartialEq, Eq)] @@ -13,6 +17,8 @@ pub struct Scope { } impl Scope { + pub const DEFAULT_NAME: &str = "_default"; + pub(crate) fn retain(cbl_ref: *mut CBLScope) -> Self { Self { cbl_ref: unsafe { retain(cbl_ref) }, @@ -28,6 +34,11 @@ impl Scope { } } + /** Returns the scope's database */ + pub fn database(&self) -> Database { + unsafe { Database::wrap(CBLScope_Database(self.get_ref())) } + } + /** Returns the names of all collections in the scope. */ pub fn collection_names(&self) -> Result> { let mut error = CBLError::default(); diff --git a/src/slice.rs b/src/slice.rs index 585f1c6..99cfe5a 100644 --- a/src/slice.rs +++ b/src/slice.rs @@ -21,7 +21,7 @@ use crate::{ }; use std::borrow::Cow; -use std::ffi::{CStr, c_void}; +use std::ffi::{CStr, CString, c_void}; use std::fmt::{Debug, Formatter}; use std::ptr::{self, drop_in_place}; use std::str; @@ -98,6 +98,16 @@ pub fn from_str(s: &str) -> Slice<&str> { ) } +pub fn from_c_str(s: CString, len: usize) -> Slice { + Slice::wrap( + FLSlice { + buf: s.as_ptr().cast::(), + size: len, + }, + s, + ) +} + pub fn from_bytes(s: &[u8]) -> Slice<&[u8]> { Slice::wrap( FLSlice { @@ -114,7 +124,7 @@ impl FLSlice { if !self { return None; } - return Some(std::slice::from_raw_parts(self.buf.cast::(), self.size)); + Some(std::slice::from_raw_parts(self.buf.cast::(), self.size)) } pub(crate) unsafe fn as_str<'a>(&self) -> Option<&'a str> { diff --git a/tests/collection_tests.rs b/tests/collection_tests.rs index a319c9a..6df883f 100644 --- a/tests/collection_tests.rs +++ b/tests/collection_tests.rs @@ -29,8 +29,8 @@ fn create_delete_scopes_collections() { assert!(db.scope(DEFAULT_NAME.to_string()).unwrap().is_some()); assert!(db.scope(unknown.clone()).unwrap().is_none()); assert_eq!( - db.default_scope().unwrap(), - db.scope(DEFAULT_NAME.to_string()).unwrap().unwrap() + db.default_scope().unwrap().name(), + db.scope(DEFAULT_NAME.to_string()).unwrap().unwrap().name() ); // Get collection @@ -46,10 +46,11 @@ fn create_delete_scopes_collections() { .collection(DEFAULT_NAME.to_string(), unknown.clone()) .is_err()); // Invalid scope => Err assert_eq!( - db.default_collection().unwrap().unwrap(), + db.default_collection().unwrap().unwrap().full_name(), db.collection(DEFAULT_NAME.to_string(), DEFAULT_NAME.to_string()) .unwrap() .unwrap() + .full_name() ); // Add collection in default scope @@ -61,13 +62,15 @@ fn create_delete_scopes_collections() { assert_eq!( db.collection(new_collection_1.clone(), DEFAULT_NAME.to_string()) .unwrap() - .unwrap(), - c1_default_scope + .unwrap() + .full_name(), + c1_default_scope.full_name() ); assert_eq!( db.create_collection(new_collection_1.clone(), DEFAULT_NAME.to_string()) - .unwrap(), - c1_default_scope + .unwrap() + .full_name(), + c1_default_scope.full_name() ); assert_eq!( @@ -85,13 +88,15 @@ fn create_delete_scopes_collections() { assert_eq!( db.collection(new_collection_2.clone(), new_scope.clone()) .unwrap() - .unwrap(), - c2_new_scope + .unwrap() + .full_name(), + c2_new_scope.full_name() ); assert_eq!( db.create_collection(new_collection_2.clone(), new_scope.clone()) - .unwrap(), - c2_new_scope + .unwrap() + .full_name(), + c2_new_scope.full_name() ); assert_eq!( @@ -158,8 +163,9 @@ fn collections_accessors() { assert_eq!( db.collection(new_collection_1.clone(), DEFAULT_NAME.to_string()) .unwrap() - .unwrap(), - c1_default_scope + .unwrap() + .full_name(), + c1_default_scope.full_name() ); let c2_new_scope = db @@ -168,8 +174,9 @@ fn collections_accessors() { assert_eq!( db.collection(new_collection_2.clone(), new_scope.clone()) .unwrap() - .unwrap(), - c2_new_scope + .unwrap() + .full_name(), + c2_new_scope.full_name() ); let c1_new_scope = db @@ -178,23 +185,43 @@ fn collections_accessors() { assert_eq!( db.collection(new_collection_1.clone(), new_scope.clone()) .unwrap() - .unwrap(), - c1_new_scope + .unwrap() + .full_name(), + c1_new_scope.full_name() ); let default_scope = db.scope(DEFAULT_NAME.to_string()).unwrap().unwrap(); let new_actual_scope = db.scope(new_scope.clone()).unwrap().unwrap(); // Scope - assert_eq!(c1_default_scope.scope(), default_scope); - assert_eq!(c2_new_scope.scope(), new_actual_scope); - assert_eq!(c1_new_scope.scope(), new_actual_scope); + assert_eq!(c1_default_scope.scope().name(), default_scope.name()); + assert_eq!(c2_new_scope.scope().name(), new_actual_scope.name()); + assert_eq!(c1_new_scope.scope().name(), new_actual_scope.name()); // Name assert_eq!(c1_default_scope.name(), new_collection_1.clone()); assert_eq!(c2_new_scope.name(), new_collection_2.clone()); assert_eq!(c1_new_scope.name(), new_collection_1.clone()); + // Full name + assert_eq!( + c1_default_scope.full_name(), + format!("{}.{}", DEFAULT_NAME, new_collection_1) + ); + assert_eq!( + c2_new_scope.full_name(), + format!("{}.{}", new_scope, new_collection_2) + ); + assert_eq!( + c1_new_scope.full_name(), + format!("{}.{}", new_scope, new_collection_1) + ); + + // Database + assert_eq!(c1_default_scope.database().get_ref(), db.get_ref()); + assert_eq!(c2_new_scope.database().get_ref(), db.get_ref()); + assert_eq!(c1_new_scope.database().get_ref(), db.get_ref()); + // Count assert_eq!(c1_default_scope.count(), 0); assert_eq!(c2_new_scope.count(), 0); @@ -216,8 +243,9 @@ fn scope_accessors() { assert_eq!( db.collection(new_collection_1.clone(), DEFAULT_NAME.to_string()) .unwrap() - .unwrap(), - c1_default_scope + .unwrap() + .full_name(), + c1_default_scope.full_name() ); let c2_new_scope = db @@ -226,8 +254,9 @@ fn scope_accessors() { assert_eq!( db.collection(new_collection_2.clone(), new_scope.clone()) .unwrap() - .unwrap(), - c2_new_scope + .unwrap() + .full_name(), + c2_new_scope.full_name() ); let c1_new_scope = db @@ -236,8 +265,9 @@ fn scope_accessors() { assert_eq!( db.collection(new_collection_1.clone(), new_scope.clone()) .unwrap() - .unwrap(), - c1_new_scope + .unwrap() + .full_name(), + c1_new_scope.full_name() ); let default_scope = db.scope(DEFAULT_NAME.to_string()).unwrap().unwrap(); @@ -247,6 +277,20 @@ fn scope_accessors() { assert_eq!(default_scope.name(), DEFAULT_NAME.to_string()); assert_eq!(new_actual_scope.name(), new_scope.clone()); + // Database + assert_eq!( + db.get_ref(), + db.default_scope().unwrap().database().get_ref() + ); + assert_eq!( + db.get_ref(), + db.scope(new_scope.clone()) + .unwrap() + .unwrap() + .database() + .get_ref() + ); + // Collections assert_eq!( default_scope.collection_names().unwrap(), @@ -266,22 +310,25 @@ fn scope_accessors() { default_scope .collection(new_collection_1.clone()) .unwrap() - .unwrap(), - c1_default_scope + .unwrap() + .full_name(), + c1_default_scope.full_name() ); assert_eq!( new_actual_scope .collection(new_collection_2.clone()) .unwrap() - .unwrap(), - c2_new_scope + .unwrap() + .full_name(), + c2_new_scope.full_name() ); assert_eq!( new_actual_scope .collection(new_collection_1.clone()) .unwrap() - .unwrap(), - c1_new_scope + .unwrap() + .full_name(), + c1_new_scope.full_name() ); }); } diff --git a/tests/database_tests.rs b/tests/database_tests.rs index f7e4f8e..c62cf2f 100644 --- a/tests/database_tests.rs +++ b/tests/database_tests.rs @@ -149,7 +149,8 @@ fn db_encryption_key() { directory: tmp_dir.path(), encryption_key: None, }; - let encryption_key = EncryptionKey::new_from_password("password1").unwrap(); + let encryption_key = + EncryptionKey::new_from_password(EncryptionAlgorithm::None, "password1").unwrap(); let cfg_encryption1 = DatabaseConfiguration { directory: tmp_dir.path(), encryption_key: Some(encryption_key.clone()), diff --git a/tests/lib_test.rs b/tests/lib_test.rs index e74a2ae..65da4a3 100644 --- a/tests/lib_test.rs +++ b/tests/lib_test.rs @@ -6,5 +6,5 @@ use couchbase_lite::*; #[test] fn couchbase_lite_c_version_test() { - assert_eq!(couchbase_lite_c_version(), "3.1.10".to_string()); + assert_eq!(couchbase_lite_c_version(), "3.2.1".to_string()); } diff --git a/tests/query_tests.rs b/tests/query_tests.rs index f500472..f94a0e7 100644 --- a/tests/query_tests.rs +++ b/tests/query_tests.rs @@ -1,7 +1,7 @@ extern crate couchbase_lite; extern crate regex; -use couchbase_lite::index::ValueIndexConfiguration; +use couchbase_lite::index::{ValueIndexConfiguration, ArrayIndexConfiguration}; use regex::Regex; use self::couchbase_lite::*; @@ -65,6 +65,90 @@ fn query() { }); } +#[test] +fn parameters() { + utils::with_db(|db| { + let mut doc = Document::new_with_id("id1"); + let mut props = doc.mutable_properties(); + props.at("bool").put_bool(true); + props.at("f64").put_f64(3.1); + props.at("i64").put_i64(3); + props.at("string").put_string("allo"); + db.save_document_with_concurency_control(&mut doc, ConcurrencyControl::FailOnConflict) + .expect("save"); + + let query = Query::new( + db, + QueryLanguage::N1QL, + "SELECT _.* FROM _ \ + WHERE _.bool=$bool \ + AND _.f64=$f64 \ + AND _.i64=$i64 \ + AND _.string=$string", + ) + .expect("create query"); + + let mut params = MutableDict::new(); + params.at("bool").put_bool(true); + params.at("f64").put_f64(3.1); + params.at("i64").put_i64(3); + params.at("string").put_string("allo"); + query.set_parameters(¶ms); + + let params = query.parameters(); + assert_eq!(params.get("bool").as_bool(), Some(true)); + assert_eq!(params.get("f64").as_f64(), Some(3.1)); + assert_eq!(params.get("i64").as_i64(), Some(3)); + assert_eq!(params.get("string").as_string(), Some("allo")); + + assert_eq!(query.execute().unwrap().count(), 1); + }); +} + +#[test] +fn get_index() { + utils::with_db(|db| { + // Default collection + let default_collection = db.default_collection().unwrap().unwrap(); + assert!(default_collection + .create_index( + "new_index1", + &ValueIndexConfiguration::new(QueryLanguage::JSON, r#"[[".someField"]]"#), + ) + .unwrap()); + + let index1 = default_collection.get_index("new_index1").unwrap(); + assert_eq!(index1.name(), "new_index1"); + assert_eq!( + index1.collection().full_name(), + default_collection.full_name() + ); + + // New collection + let new_coll = db + .create_collection(String::from("coll"), String::from("scop")) + .unwrap(); + + assert!(new_coll + .create_index( + "new_index2", + &ValueIndexConfiguration::new(QueryLanguage::JSON, r#"[[".someField2"]]"#), + ) + .unwrap()); + + let index2 = new_coll.get_index("new_index2").unwrap(); + assert_eq!(index2.name(), "new_index2"); + assert_eq!(index2.collection().full_name(), new_coll.full_name()); + }) +} + +fn get_index_name_from_explain(explain: &str) -> Option { + Regex::new(r"USING INDEX (\w+) ") + .unwrap() + .captures(explain) + .map(|c| c.get(1).unwrap().as_str().to_string()) +} + #[test] fn full_index() { utils::with_db(|db| { @@ -88,12 +172,7 @@ fn full_index() { ) .expect("create query"); - let index = Regex::new(r"USING INDEX (\w+) ") - .unwrap() - .captures(&query.explain().unwrap()) - .map(|c| c.get(1).unwrap().as_str().to_string()) - .unwrap(); - + let index = get_index_name_from_explain(&query.explain().unwrap()).unwrap(); assert_eq!(index, "new_index"); // Check index not used @@ -148,12 +227,7 @@ fn partial_index() { ) .expect("create query"); - let index = Regex::new(r"USING INDEX (\w+) ") - .unwrap() - .captures(&query.explain().unwrap()) - .map(|c| c.get(1).unwrap().as_str().to_string()) - .unwrap(); - + let index = get_index_name_from_explain(&query.explain().unwrap()).unwrap(); assert_eq!(index, "new_index"); // Check index not used @@ -174,41 +248,100 @@ fn partial_index() { } #[test] -fn parameters() { +fn array_index() { utils::with_db(|db| { - let mut doc = Document::new_with_id("id1"); - let mut props = doc.mutable_properties(); - props.at("bool").put_bool(true); - props.at("f64").put_f64(3.1); - props.at("i64").put_i64(3); - props.at("string").put_string("allo"); - db.save_document_with_concurency_control(&mut doc, ConcurrencyControl::FailOnConflict) - .expect("save"); + let mut default_collection = db.default_collection().unwrap().unwrap(); + + // Add one document + let mut doc = Document::new(); + doc.set_properties_as_json( + r#"{ + "name":"Sam", + "contacts":[ + { + "type":"primary", + "address":{"street":"1 St","city":"San Pedro","state":"CA"}, + "phones":[ + {"type":"home","number":"310-123-4567"}, + {"type":"mobile","number":"310-123-6789"} + ] + }, + { + "type":"secondary", + "address":{"street":"5 St","city":"Seattle","state":"WA"}, + "phones":[ + {"type":"home","number":"206-123-4567"}, + {"type":"mobile","number":"206-123-6789"} + ] + } + ], + "likes":["soccer","travel"] + }"#, + ) + .unwrap(); + default_collection.save_document(&mut doc).unwrap(); + + // Index with one level of unnest + let index_configuration = + ArrayIndexConfiguration::new(QueryLanguage::N1QL, "likes", "").unwrap(); + + let result = default_collection + .create_array_index("one_level", &index_configuration) + .unwrap(); + assert!(result); let query = Query::new( db, QueryLanguage::N1QL, - "SELECT _.* FROM _ \ - WHERE _.bool=$bool \ - AND _.f64=$f64 \ - AND _.i64=$i64 \ - AND _.string=$string", + "SELECT _.name, _like FROM _ UNNEST _.likes as _like WHERE _like = 'travel'", ) - .expect("create query"); + .unwrap(); - let mut params = MutableDict::new(); - params.at("bool").put_bool(true); - params.at("f64").put_f64(3.1); - params.at("i64").put_i64(3); - params.at("string").put_string("allo"); - query.set_parameters(¶ms); + let index = get_index_name_from_explain(&query.explain().unwrap()).unwrap(); + assert_eq!(index, "one_level"); - let params = query.parameters(); - assert_eq!(params.get("bool").as_bool(), Some(true)); - assert_eq!(params.get("f64").as_f64(), Some(3.1)); - assert_eq!(params.get("i64").as_i64(), Some(3)); - assert_eq!(params.get("string").as_string(), Some("allo")); + let mut result = query.execute().unwrap(); + let row = result.next().unwrap(); + assert_eq!(row.as_array().to_json(), r#"["Sam","travel"]"#); - assert_eq!(query.execute().unwrap().count(), 1); - }); + assert!(result.next().is_none()); + + // Index with two levels of unnest + let index_configuration = + ArrayIndexConfiguration::new(QueryLanguage::N1QL, "contacts[].phones", "type").unwrap(); + + assert!(default_collection + .create_array_index("two_levels", &index_configuration,) + .unwrap()); + + let query = Query::new( + db, + QueryLanguage::N1QL, + r#"SELECT _.name, contact.type, phone.number + FROM _ + UNNEST _.contacts as contact + UNNEST contact.phones as phone + WHERE phone.type = 'mobile'"#, + ) + .unwrap(); + + let index = get_index_name_from_explain(&query.explain().unwrap()).unwrap(); + assert_eq!(index, "two_levels"); + + let mut result = query.execute().unwrap(); + + let row = result.next().unwrap(); + assert_eq!( + row.as_array().to_json(), + r#"["Sam","primary","310-123-6789"]"# + ); + + let row = result.next().unwrap(); + assert_eq!( + row.as_array().to_json(), + r#"["Sam","secondary","206-123-6789"]"# + ); + + assert!(result.next().is_none()); + }) }