WCTDatabase Class Reference

Inherits from WCTInterface : WCTCore : NSObject
Declared in WCTDatabase.h

Overview

Thread-safe

RepairKit Methods

– backupWithCipher:

Backup metadata to recover. Since metadata will be changed while a table or an index is created or dropped, you should call this periodically.

- (BOOL)backupWithCipher:(NSData *)key

Parameters

key

The cipher key for backup

Return Value

YES only if it’s successfully backed up

Declared In

WCTDatabase+RepairKit.h

– recoverFromPath:withPageSize:backupCipher:databaseCipher:

Recover data from a corruped db. You’d better to recover a closed database. A new repair kit is developing at https://github.com/Tencent/wcdb/tree/new-repair

 WCTDatabase* database = [[WCTDatabase alloc] initWithPath:path];
 WCTDatabase* corruped = [[WCTDatabase alloc] initWithPath:corrupedDBPath];
 [corruped close:^(){
     BOOL result = [database recoverFromPath:corrupedDBPath withPageSize:4096 backupCipher:backupCipher databaseCipher:databaseCipher];
     NSLog(@"result %d", result);
 }];
- (BOOL)recoverFromPath:(NSString *)corruptedDBPath withPageSize:(const int)pageSize backupCipher:(NSData *)backupCipher databaseCipher:(NSData *)databaseCipher

Parameters

corruptedDBPath

The path to the corrupted database

pageSize

Page size of the corrupted database. It’s default to 4096 on iOS. Page size never change unless you can call “PRAGMA page_size=NewPageSize” to set it. Also, you can call “PRAGMA page_size” to check the current value while database is not corrupted.

backupCipher

The cipher key for backup

databaseCipher

The cipher key for corrupeted database

Return Value

YES only if it’s successfully recovered.

Declared In

WCTDatabase+RepairKit.h

File Methods

– removeFilesWithError:

Remove all database-related files.

- (BOOL)removeFilesWithError:(WCTError **)error

Parameters

error

error

Return Value

YES if all files are removed.

Discussion

Warning: You should call it on a closed database. Otherwise you will get a warning.

Declared In

WCTDatabase+File.h

– moveFilesToDirectory:withExtraFiles:andError:

Move all database-related files and some extra files to directory safely. You should call it on a closed database. Otherwise you will get a warning and you may get a corrupted database.

- (BOOL)moveFilesToDirectory:(NSString *)directory withExtraFiles:(NSArray<NSString*> *)extraFiles andError:(WCTError **)error

Parameters

directory

destination

extraFiles

extraFiles

error

error

Return Value

YES if all files are moved.

Discussion

Warning: Since file operation is not atomic, There may be some accidents during this period. For example, app may crash while db file is moved to destination and wal file is not. Then none of destination and source contains the whole data. This interface can make sure all of your data is in source or destination.

Declared In

WCTDatabase+File.h

– moveFilesToDirectory:withError:

This interface is equivalent to [database moveFilesToDirectory:directory withExtraFiles:nil andError:error].

- (BOOL)moveFilesToDirectory:(NSString *)directory withError:(WCTError **)error

Parameters

directory

destination

error

error

Return Value

YES if all files are moved.

Declared In

WCTDatabase+File.h

– getPaths

Paths to all database-related files.

- (NSArray<NSString*> *)getPaths

Return Value

paths

Declared In

WCTDatabase+File.h

– getFilesSizeWithError:

Get the space used by the database files.

- (NSUInteger)getFilesSizeWithError:(WCTError **)error

Parameters

error

error

Return Value

The sum of files size in bytes.

Discussion

Warning: You should call it on a closed database. Otherwise you will get a warning.

Declared In

WCTDatabase+File.h

FTS Methods

– setTokenizer:

Setup tokenizer with name for current database

- (void)setTokenizer:(NSString *)tokenizeName

Parameters

tokenizeName

registed tokenizeName. You can use builtin tokenizer named WCTTokenizerNameWCDB or WCTTokenizerNameApple while WCTTokenizerNameWCDB is recommended.

Declared In

WCTDatabase+FTS.h

– setTokenizers:

Setup multiple tokenizers with names for current database

- (void)setTokenizers:(NSArray<NSString*> *)tokenizeNames

Parameters

tokenizeNames

registed tokenizeNames. You can use builtin tokenizer named WCTTokenizerNameWCDB or WCTTokenizerNameApple while WCTTokenizerNameWCDB is recommended.

See Also

Declared In

WCTDatabase+FTS.h

Core Methods

+ DefaultBasicConfigName

Default config name. The default config for WCDB is : 1. PRAGMA locking_mode=NORMAL 2. PRAGMA synchronous=NORMAL 3. PRAGMA journal_mode=WAL 4. PRAGMA fullfsync=ON Setting config for this name will overwrite the default config.

+ (NSString *)DefaultBasicConfigName

Return Value

default config name

Declared In

WCTDatabase+Core.h

+ DefaultCipherConfigName

Default cipher config name The default cipher config for WCDB is : 1. PRAGMA key=yourCipherKey 2. PRAGMA cipher_page_size=yourCipherPageSize. Default to 4096

+ (NSString *)DefaultCipherConfigName

Return Value

default cipher config name

Declared In

WCTDatabase+Core.h

+ DefaultTraceConfigName

Default trace config name. It’s off by default. Call [WCTStatistics SetGlobalPerformanceTrace:] to open it. The config for performance and sql tracing.

+ (NSString *)DefaultTraceConfigName

Return Value

default trace config name

Declared In

WCTDatabase+Core.h

+ DefaultCheckpointConfigName

Default checkpoint config name The config for subthread checkpoint optimization

+ (NSString *)DefaultCheckpointConfigName

Return Value

default checkpoint config name

Declared In

WCTDatabase+Core.h

+ DefaultSynchronousConfigName

Default synchronous config name. It’s off by default. Call [WCTDatabase setSynchronousFull:] to open it. The default synchronous config for WCDB is : 1. PRAGMA synchronous=FULL

+ (NSString *)DefaultSynchronousConfigName

Return Value

default synchronous config name

Declared In

WCTDatabase+Core.h

+ DefaultTokenizeConfigName

Default tokenize config name

+ (NSString *)DefaultTokenizeConfigName

Return Value

default tokenize config name

Declared In

WCTDatabase+Core.h

– setConfig:forName:withOrder:

Set config for this database.

- (void)setConfig:(WCDB : : Config)config forName:(NSString *)name withOrder:(WCDB : : Configs : : Order)order

Parameters

config

config

name

The Identifier for this config

order

The smaller number is called first

Discussion

Warning: Since WCDB is a multi-handle database, an executing handle will not apply this config immediately. Instead, all handles will run this config before its next operation.

 [database setConfig:^BOOL(std::shared_ptr<WCDB::Handle> handle, WCDB::Error& error) {
    return handle->exec(WCDB::StatementPragma().pragma(WCDB::Pragma::SecureDelete, YES));
 } forName:@"demo" withOrder:1];

Declared In

WCTDatabase+Core.h

– setConfig:forName:

This interface is equivalent to [database setConfig:config forName:name withOrder:INT_MAX];

- (void)setConfig:(WCDB : : Config)config forName:(NSString *)name

Parameters

config

config

name

The Identifier for this config

Declared In

WCTDatabase+Core.h

– setSynchronousFull:

Set Synchronous for this database. It will disable checkpoint opti to avoid performance degradation. Synchronous can improve the stability of the database and reduce database damage, but there will be performance degradation.

- (void)setSynchronousFull:(BOOL)full

Parameters

full

enable or disable full synchronous

Declared In

WCTDatabase+Core.h

Table Methods

– createTableAndIndexesOfName:withClass:

Create table and indexes from ORM if not exists. Note that it will add newly defined columns automatically. Note that it will run embedded transaction. The embedded transaction means that it will run a transaction if it’s not in other transaction, otherwise it will be executed within the existing transaction.

- (BOOL)createTableAndIndexesOfName:(NSString *)tableName withClass:(Class<WCTTableCoding>)cls

Parameters

tableName

This would be the name of the table and the prefix of the index names.

cls

class

Return Value

YES while creating table or adding newly defined columns succeeds. It will not fail if error occurs during creating indexes.

Declared In

WCTDatabase+Table.h

– getTableOfName:withClass:

Get a wrapper from an existing table.

- (WCTTable *)getTableOfName:(NSString *)tableName withClass:(Class<WCTTableCoding>)cls

Parameters

tableName

The name of the table.

cls

a class implement WCTTableCoding.

Return Value

WCTTable nil for a non-existent table.

Declared In

WCTDatabase+Table.h

– createVirtualTableOfName:withClass:

Create virtual table from ORM if not exists.

- (BOOL)createVirtualTableOfName:(NSString *)tableName withClass:(Class<WCTTableCoding>)cls

Parameters

tableName

The name of the virtual table to be created.

cls

a class implement WCTTableCoding.

Return Value

YES only if no error occurs.

Declared In

WCTDatabase+Table.h

– createTableOfName:withColumnDefList:andConstraintList:

Create table from user-defined column if not exists.

- (BOOL)createTableOfName:(NSString *)tableName withColumnDefList:(const WCTColumnDefList &)columnDefList andConstraintList:(const WCTTableConstraintList &)constraintList

Parameters

tableName

The name of the table to be created.

columnDefList

The list of column definition.

constraintList

The list of constraint.

Return Value

YES only if no error occurs.

Declared In

WCTDatabase+Table.h

– createTableOfName:withColumnDefList:

This interface is equivalent to [database createTableOfName:tableName withColumnDefList:columnDefList andConstraintList:{}].

- (BOOL)createTableOfName:(NSString *)tableName withColumnDefList:(const WCTColumnDefList &)columnDefList

Parameters

tableName

The name of the table to be created.

columnDefList

The list of column definition.

Return Value

YES only if no error occurs.

Declared In

WCTDatabase+Table.h

– isTableExists:

Check whether table exists

- (BOOL)isTableExists:(NSString *)tableName

Parameters

tableName

The name of the table to be checked.

Return Value

YES if table exists. NO if table does not exist or an error occurs.

Declared In

WCTDatabase+Table.h

– dropTableOfName:

Drop table if exists.

- (BOOL)dropTableOfName:(NSString *)tableName

Parameters

tableName

The name of the table to be dropped.

Return Value

YES only if no error occurs.

Declared In

WCTDatabase+Table.h

– createIndexOfName:withIndexList:forTable:

Create table from user-defined index if not exists.

- (BOOL)createIndexOfName:(NSString *)indexName withIndexList:(const WCTIndexList &)indexList forTable:(NSString *)tableName

Parameters

indexName

The name of the index to be created.

indexList

The list of index definition.

tableName

The name of index-associated table.

Return Value

YES only if no error occurs.

Declared In

WCTDatabase+Table.h

– dropIndexOfName:

Drop index if not exists.

- (BOOL)dropIndexOfName:(NSString *)indexName

Parameters

indexName

The name of the index to be dropped.

Return Value

YES only if no error occurs.

Declared In

WCTDatabase+Table.h

– addColumn:forTable:

Add column.

- (BOOL)addColumn:(const WCTColumnDef &)columnDef forTable:(NSString *)tableName

Parameters

columnDef

The definition of column to be added.

tableName

The name of table to do a column addition.

Return Value

YES only if no error occurs.

Declared In

WCTDatabase+Table.h

Transaction Methods

– getTransaction

Generation a WCTTransaction object to do a transaction.

- (WCTTransaction *)getTransaction

Return Value

WCTTransaction

Declared In

WCTDatabase+Transaction.h

– runTransaction:event:

Run a transaction in block.

 BOOL committed = [database runTransaction:^BOOL(){
    BOOL result = [database insertObject:object into:tableName];
    return result;//return YES to commit transaction and return NO to rollback transaction.
 } event:^(WCTTransactionEvent event) {
    switch (event) {
        case WCTTransactionEventBeginFailed:
            break;
        case WCTTransactionEventCommitFailed:
            break;
        case WCTTransactionEventRollback:
            break;
        case WCTTransactionEventRollbackFailed:
            break;
    };
 }];
- (BOOL)runTransaction:(WCTTransactionBlock)inTransaction event:(WCTTransactionEventBlock)onTransactionStateChanged

Parameters

inTransaction

Operation inside transaction.

onTransactionStateChanged

State changed event.

Return Value

YES only if transaction is committed.

Declared In

WCTDatabase+Transaction.h

– runTransaction:

This interface is equivalent to [database runTransaction:transaction event:nil];

- (BOOL)runTransaction:(WCTTransactionBlock)inTransaction

Parameters

inTransaction

Operation inside transaction.

Return Value

YES only if transaction is committed.

Declared In

WCTDatabase+Transaction.h

– beginTransaction

Separate interface of runTransaction:

- (BOOL)beginTransaction

Return Value

YES only if no error occurs.

Discussion

Warning: You should call beginTransaction, commitTransaction, rollbackTransaction and all other operations in same thread. To do a cross-thread transaction, use WCTTransaction.

See Also

Declared In

WCTDatabase+Transaction.h

– commitTransaction

Separate interface of runTransaction:

- (BOOL)commitTransaction

Return Value

YES only if no error occurs.

Discussion

Warning: You should call beginTransaction , commitTransaction , rollbackTransaction and all other operations in same thread. To do a cross-thread transaction, use WCTTransaction.

See Also

Declared In

WCTDatabase+Transaction.h

– rollbackTransaction

Separate interface of runTransaction:

- (BOOL)rollbackTransaction

Return Value

YES only if no error occurs.

Discussion

Warning: You should call beginTransaction , commitTransaction , rollbackTransaction and all other operations in same thread. To do a cross-thread transaction, use WCTTransaction.

See Also

Declared In

WCTDatabase+Transaction.h

Statistics Methods

– setPerformanceTrace:

You can register a tracer to monitor the performance of all SQLs in this database. The database tracer will recover the global tracer for specifiy database.

- (void)setPerformanceTrace:(WCTPerformanceTrace)trace

Parameters

trace

trace

Declared In

WCTDatabase+Statistics.h

Database Methods

– initWithPath:

Init a database from path. Note that all database objects with same path share the same core. So you can create multiple database objects. WCDB will manage them automatically. Note that WCDB will not generate a sqlite handle until the first operation, which is also called as lazy initialization.

- (instancetype)initWithPath:(NSString *)path

Parameters

path

Path to your database

Return Value

WCTDatabase

Declared In

WCTDatabase+Database.h

– initWithExistingTag:

Init a database from existing tag. Note that all database objects with same path share the same core. So you can create multiple database objects. WCDB will manage them automatically. Note that WCDB will not generate a sqlite handle until the first operation, which is also called as lazy initialization.

- (instancetype)initWithExistingTag:(WCTTag)tag

Parameters

tag

a tag already exists. Note that 0 is not a valid tag.

Return Value

nil if the tag do not exists

Declared In

WCTDatabase+Database.h

– setCipherKey:

This interface is equivalent to [database setCipherKey:cipherKey andCipherPageSize:4096];

- (void)setCipherKey:(NSData *)cipherKey

Parameters

cipherKey

Cipher key.

Declared In

WCTDatabase+Database.h

– setCipherKey:andCipherPageSize:

Set cipher key for a database. For an encrypted database, you must call it before all other operation. The cipher page size defaults to 4096 in WCDB, but it defaults to 1024 in other databases. So for an existing database created by other database framework, you should set it to 1024. Otherwise, you’d better to use cipher page size with 4096 or simply call setCipherKey: interface to get better performance.

- (void)setCipherKey:(NSData *)cipherKey andCipherPageSize:(int)cipherPageSize

Parameters

cipherKey

Cipher key.

cipherPageSize

Cipher Page Size

Declared In

WCTDatabase+Database.h

– setTag:

Set the tag of the database. Note that WCTCore objects with same path share this tag, even they are not the same object.

- (void)setTag:(WCTTag)tag

Parameters

tag

Default to 0.

Declared In

WCTDatabase+Database.h

– canOpen

Since WCDB is using lazy initialization, [initWithPath:] never return nil even the database can’t open. So you can call this to check whether the database can be opened.

- (BOOL)canOpen

Return Value

NO if an error occurs during sqlite handle initialization.

Declared In

WCTDatabase+Database.h

– isOpened

Check database is already opened.

- (BOOL)isOpened

Return Value

isOpened

Declared In

WCTDatabase+Database.h

– close:

close the database. Since Multi-threaded operation is supported in WCDB, other operations in different thread can open the closed database. So this method can make sure database is closed in the “onClosed” block. All other operations will be blocked until this method returns. A close operation consists of 4 steps: 1. blockade, which blocks all other operations. 2. close, which waits until all sqlite handles return and closes them. 3. onClosed, which trigger the callback. 4. unblokade, which unblocks all other opreations. You can simply call close: to do all steps above or call these separately. Since this method will wait until all sqlite handles return, it may lead to deadlock in some bad practice. The key to avoid deadlock is to make sure all WCDB objects in current thread is dealloced. In detail: 1. You should not keep WCDB objects, including WCTInsert, WCTDelete, WCTUpdate, WCTSelect, WCTRowSelect, WCTMultiSelect, WCTStatement, WCTTransaction. These objects should not be kept. You should get them, use them, then release them(set to nil) right away. 2. WCDB objects may not be out of its' scope. 3. Further more, those WCDB objects may be kept by NSAutoReleasePool, which is done by ARC automatically. So you should make sure that all WCDB objects in NSAutoReleasePool is drained. The best practice is to call close: in sub-thread and display a loading animation in main thread.

 //close directly
 [database close:^(){
    //do something on this closed database
 }];
 //close separately
 [database blockade];
 [database close];
 //do something on this closed database
 [database unblockade];
- (void)close:(WCTCloseBlock)onClosed

Parameters

onClosed

Trigger on database closed.

Declared In

WCTDatabase+Database.h

– close

This interface is equivalent to [database close:nil].

- (void)close

See Also

Declared In

WCTDatabase+Database.h

– blockade

Blockade the database.

- (void)blockade

See Also

Declared In

WCTDatabase+Database.h

– unblockade

Unblockade the database.

- (void)unblockade

See Also

Declared In

WCTDatabase+Database.h

– isBlockaded

Check whether database is blockaded.

- (BOOL)isBlockaded

Return Value

isBlockaded

See Also

Declared In

WCTDatabase+Database.h

– purgeFreeHandles

Purge all free handles of this database. WCDB will cache and reuse some sqlite handles to improve performance. The max count of free sqlite handles is same as the number of concurrent threads supported by the hardware implementation. You can call it to save some memory.

- (void)purgeFreeHandles

Declared In

WCTDatabase+Database.h

+ PurgeFreeHandlesInAllDatabases

Purge all free handles of all databases. Note that WCDB will call this interface automatically while it receives memory warning on iOS.

+ (void)PurgeFreeHandlesInAllDatabases

Declared In

WCTDatabase+Database.h