Skip to content

Commit 378d6c8

Browse files
committed
Add finalized snippets for existing tags on C
1 parent 3373865 commit 378d6c8

File tree

1 file changed

+245
-5
lines changed
  • modules/c/examples/code_snippets

1 file changed

+245
-5
lines changed

modules/c/examples/code_snippets/main.c

Lines changed: 245 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,20 @@
11
#include <cbl/CouchbaseLite.h>
22

33
#include <time.h>
4+
#include <inttypes.h>
45
#ifdef _MSC_VER
56
#include <direct.h>
7+
#include <Shlwapi.h>
8+
9+
void usleep(unsigned int us) {
10+
Sleep(us / 1000);
11+
}
612
#else
713
#include <unistd.h>
814
#endif
915

1016
static CBLDatabase* kDatabase;
1117
static CBLReplicator* kReplicator;
12-
static CBLListenerToken* kListenerToken;
13-
static bool kNeedsExtraDocs;
1418

1519
static void getting_started_change_listener(void* context, CBLReplicator* repl, const CBLReplicatorStatus* status) {
1620
if(status->error.code != 0) {
@@ -141,6 +145,7 @@ static void getting_started() {
141145
// Later, stop and release the replicator
142146
// end::getting-started[]
143147

148+
CBLListener_Remove(token);
144149
kReplicator = replicator;
145150
}
146151

@@ -182,7 +187,7 @@ static bool custom_conflict_handler(void* context, CBLDocument* documentBeingSav
182187
FLDictIterator d;
183188
FLDictIterator_Begin(currentProps, &d);
184189
FLValue currentValue;
185-
while(currentValue = FLDictIterator_GetValue(&d)) {
190+
while((currentValue = FLDictIterator_GetValue(&d))) {
186191
FLString currentKey = FLDictIterator_GetKeyString(&d);
187192
if(FLDict_Get(newProps, currentKey)) {
188193
continue;
@@ -203,7 +208,8 @@ static void test_save_with_conflict_handler() {
203208

204209
CBLError err;
205210
CBLDocument* mutableDocument = CBLDatabase_GetMutableDocument(database, FLSTR("xyz"), &err);
206-
FLDict properties = CBLDocument_MutableProperties(mutableDocument);
211+
FLMutableDict properties = CBLDocument_MutableProperties(mutableDocument);
212+
FLMutableDict_SetString(properties, FLSTR("name"), FLSTR("apples"));
207213

208214
/*
209215
static bool custom_conflict_handler(void* context, CBLDocument* documentBeingSaved,
@@ -451,6 +457,8 @@ static void database_change_listener() {
451457
CBLListenerToken* token = CBLDatabase_AddDocumentChangeListener(db, FLSTR("user.john"),
452458
document_listener, NULL);
453459
// end::document-listener[]
460+
461+
CBLListener_Remove(token);
454462
}
455463

456464
static void document_expiration() {
@@ -799,7 +807,7 @@ static void group_by() {
799807
int64_t count = FLValue_AsInt(CBLResultSet_ValueForKey(results, FLSTR("$1")));
800808
FLString tz = FLValue_AsString(CBLResultSet_ValueForKey(results, FLSTR("tz")));
801809
FLString country = FLValue_AsString(CBLResultSet_ValueForKey(results, FLSTR("country")));
802-
printf("There are %lld airports in the %.*s timezone located in %.*s and above 300 ft\n",
810+
printf("There are %" PRIi64 " airports in the %.*s timezone located in %.*s and above 300 ft\n",
803811
count, (int)tz.size, (const char *)tz.buf, (int)country.size, (const char *)country.buf);
804812
}
805813

@@ -808,6 +816,238 @@ static void group_by() {
808816
// end::query-groupby[]
809817
}
810818

819+
static void order_by() {
820+
CBLDatabase* db = kDatabase;
821+
822+
// tag::query-orderby[]
823+
// NOTE: No error handling, for brevity (see getting started)
824+
825+
CBLError err;
826+
CBLQuery* query = CBLDatabase_CreateQuery(db, kCBLN1QLLanguage,
827+
FLSTR("SELECT meta().id, title FROM _ WHERE type = \"hotel\" ORDER BY title ASC LIMIT 10"),
828+
NULL, &err);
829+
830+
CBLResultSet* results = CBLQuery_Execute(query, &err);
831+
while(CBLResultSet_Next(results)) {
832+
FLString title = FLValue_AsString(CBLResultSet_ValueForKey(results, FLSTR("title")));
833+
printf("Title :: %.*s\n", (int)title.size, (const char *)title.buf);
834+
}
835+
836+
CBLResultSet_Release(results);
837+
CBLQuery_Release(query);
838+
// end::query-orderby[]
839+
}
840+
841+
static void test_explain_statement() {
842+
CBLDatabase* db = kDatabase;
843+
844+
{
845+
// tag::query-explain-all[]
846+
// NOTE: No error handling, for brevity (see getting started)
847+
848+
CBLError err;
849+
CBLQuery* query = CBLDatabase_CreateQuery(db, kCBLN1QLLanguage,
850+
FLSTR("SELECT * FROM _ WHERE type = \"hotel\" GROUP BY country ORDER BY title ASC LIMIT 10"),
851+
NULL, &err);
852+
853+
FLSliceResult explanation = CBLQuery_Explain(query);
854+
printf("%.*s", (int)explanation.size, (const char *)explanation.buf);
855+
FLSliceResult_Release(explanation);
856+
// end::query-explain-all[]
857+
}
858+
859+
// DOCS NOTE: Others omitted for now
860+
}
861+
862+
static void create_full_text_index() {
863+
CBLDatabase* db = kDatabase;
864+
865+
const char* tasks[] = { "buy groceries", "play chess", "book travels", "buy museum tickets" };
866+
char idBuffer[7];
867+
for(int i = 0; i < 4; i++) {
868+
const char* task = tasks[i];
869+
sprintf(idBuffer, "extra%d", i);
870+
const CBLDocument* doc = CBLDatabase_GetDocument(db, FLStr(idBuffer), NULL);
871+
if(doc) {
872+
CBLDocument_Release(doc);
873+
continue;
874+
}
875+
876+
CBLDocument* mutableDoc = CBLDocument_CreateWithID(FLStr(idBuffer));
877+
FLMutableDict properties = CBLDocument_MutableProperties(mutableDoc);
878+
FLMutableDict_SetString(properties, FLSTR("type"), FLSTR("task"));
879+
FLMutableDict_SetString(properties, FLSTR("task"), FLStr(task));
880+
CBLDatabase_SaveDocument(db, mutableDoc, NULL);
881+
CBLDocument_Release(mutableDoc);
882+
}
883+
884+
// tag::fts-index[]
885+
// NOTE: No error handling, for brevity (see getting started)
886+
887+
CBLError err;
888+
CBLFullTextIndexConfiguration config = {
889+
kCBLN1QLLanguage,
890+
FLSTR("name"),
891+
false
892+
};
893+
894+
CBLDatabase_CreateFullTextIndex(db, FLSTR("nameFTSIndex"), config, &err);
895+
// end::fts-index[]
896+
}
897+
898+
static void full_text_search() {
899+
CBLDatabase* db = kDatabase;
900+
901+
// tag::fts-query[]
902+
// NOTE: No error handling, for brevity (see getting started)
903+
904+
CBLError err;
905+
CBLQuery* query = CBLDatabase_CreateQuery(db, kCBLN1QLLanguage,
906+
FLSTR("SELECT meta().id FROM _ WHERE MATCH(nameFTSIndex, \"'buy'\")"),
907+
NULL, &err);
908+
909+
CBLResultSet* results = CBLQuery_Execute(query, &err);
910+
while(CBLResultSet_Next(results)) {
911+
FLString id = FLValue_AsString(CBLResultSet_ValueAtIndex(results, 0));
912+
printf("Document id :: %.*s\n", (int)id.size, (const char *)id.buf);
913+
}
914+
915+
CBLResultSet_Release(results);
916+
CBLQuery_Release(query);
917+
// end::fts-query[]
918+
}
919+
920+
static void start_replication() {
921+
CBLDatabase* db = kDatabase;
922+
923+
/*
924+
* This requires Sync Gateway running with the following config, or equivalent:
925+
*
926+
* {
927+
* "log":["*"],
928+
* "databases": {
929+
* "db": {
930+
* "server":"walrus:",
931+
* "users": {
932+
* "GUEST": {"disabled": false, "admin_channels": ["*"] }
933+
* }
934+
* }
935+
* }
936+
* }
937+
*/
938+
939+
// tag::replication[]
940+
// NOTE: No error handling, for brevity (see getting started)
941+
// Note: Android emulator needs to use 10.0.2.2 for localhost (10.0.3.2 for GenyMotion)
942+
943+
CBLError err;
944+
FLString url = FLSTR("ws://localhost:4984/db");
945+
CBLEndpoint* target = CBLEndpoint_CreateWithURL(url, &err);
946+
CBLReplicatorConfiguration config;
947+
memset(&config, 0, sizeof(CBLReplicatorConfiguration));
948+
config.database = db;
949+
config.endpoint = target;
950+
config.replicatorType = kCBLReplicatorTypePull;
951+
952+
CBLReplicator* replicator = CBLReplicator_Create(&config, &err);
953+
CBLEndpoint_Free(target);
954+
CBLReplicator_Start(replicator, false);
955+
// end::replication[]
956+
957+
kReplicator = replicator;
958+
}
959+
960+
// Console logging domain methods not applicable to C
961+
962+
static void file_logging() {
963+
// tag::file-logging[]
964+
// NOTE: No error handling, for brevity (see getting started)
965+
// NOTE: You will need to use a platform appropriate method for finding
966+
// a temporary directory
967+
968+
FLString tempFolder = FLSTR("/tmp/cbllog");
969+
970+
CBLLogFileConfiguration config; // Don't bother zeroing, since we set all properties
971+
config.level = kCBLLogInfo;
972+
config.directory = tempFolder;
973+
config.maxRotateCount = 5;
974+
config.maxSize = 10240;
975+
config.usePlaintext = false;
976+
977+
CBLError err;
978+
CBLLog_SetFileConfig(config, &err);
979+
// end::file-logging[]
980+
}
981+
982+
// tag::custom-logging[]
983+
static void custom_log_callback(CBLLogDomain domain, CBLLogLevel level, FLString message) {
984+
// handle the message, for example piping it to
985+
// a third party framework
986+
}
987+
// end::custom-logging[]
988+
989+
static void enable_custom_logging() {
990+
// tag::set-custom-logging[]
991+
CBLLog_SetCallback(custom_log_callback);
992+
// end::set-custom-logging[]
993+
}
994+
995+
static void enable_basic_auth() {
996+
CBLDatabase* db = kDatabase;
997+
998+
// tag::basic-authentication[]
999+
// NOTE: No error handling, for brevity (see getting started)
1000+
1001+
CBLError err;
1002+
FLString url = FLSTR("ws://localhost:4984/mydatabase");
1003+
CBLEndpoint* target = CBLEndpoint_CreateWithURL(url, &err);
1004+
CBLAuthenticator* basicAuth = CBLAuth_CreatePassword(FLSTR("john"), FLSTR("pass"));
1005+
1006+
CBLReplicatorConfiguration config;
1007+
memset(&config, 0, sizeof(CBLReplicatorConfiguration));
1008+
config.database = db;
1009+
config.endpoint = target;
1010+
config.authenticator = basicAuth;
1011+
1012+
CBLReplicator* replicator = CBLReplicator_Create(&config, &err);
1013+
CBLEndpoint_Free(target);
1014+
CBLAuth_Free(basicAuth);
1015+
1016+
CBLReplicator_Start(replicator, false);
1017+
// end::basic-authentication[]
1018+
}
1019+
8111020
int main(int argc, char** argv) {
1021+
create_new_database();
1022+
create_document();
1023+
update_document();
1024+
do_batch_operation();
1025+
use_blob();
1026+
select_meta();
1027+
1028+
load_prebuilt();
1029+
create_index();
1030+
select_where();
1031+
use_collection_contains();
1032+
select_like();
1033+
select_wildcard_like();
1034+
select_wildcard_character_like();
1035+
select_regex();
1036+
select_join();
1037+
group_by();
1038+
order_by();
1039+
1040+
create_full_text_index();
1041+
full_text_search();
1042+
start_replication();
1043+
1044+
CBLReplicator_Stop(kReplicator);
1045+
while(CBLReplicator_Status(kReplicator).activity != kCBLReplicatorStopped) {
1046+
printf("Waiting for replicator to stop...");
1047+
usleep(200000);
1048+
}
1049+
1050+
CBLDatabase_Close(kDatabase, NULL);
1051+
8121052
return 0;
8131053
}

0 commit comments

Comments
 (0)