-
Notifications
You must be signed in to change notification settings - Fork 0
DBCDatabase
#DBCDatabase Class Reference
[SQLitews]:http://www.sqlite.org
[MAS]:http://www.apple.com/mac/app-store/
[DBCDatabase+Advanced]:https://github.com/parfeon/DBConnect/wiki/DBCDatabase+Advanced
[DBCDatabase+AdvancedOpen]:https://github.com/parfeon/DBConnect/wiki/DBCDatabase+Advanced#m1
[DBCDatabase+AiasesAttach]:https://github.com/parfeon/DBConnect/wiki/DBCDatabase+Aiases#m1
[DBCDatabase+AiasesAttachExample]:https://github.com/parfeon/DBConnect/wiki/DBCDatabase+Aiases#m1e
[DBCDatabase+AiasesCR]:https://github.com/parfeon/DBConnect/wiki/DBCDatabase+Aiases
[DBCDatabaseResultCR]:https://github.com/parfeon/DBConnect/wiki/DBCDatabaseResult
[DBCDatabaseRowCR]:https://github.com/parfeon/DBConnect/wiki/DBCDatabaseRow
[DBCDatabaseEncodingUTF8c]:https://github.com/parfeon/DBConnect/wiki/Constants#DBCDatabaseEncodingUTF8
[DBCDatabaseTransactionLockC]:https://github.com/parfeon/DBConnect/wiki/DBCDatabaseTransactionLock
[DBCDatabaseAutocommitModeDeferredc]:https://github.com/parfeon/DBConnect/wiki/DBCDatabaseTransactionLock#DBCDatabaseAutocommitModeDeferred
[DBCErrorwiki]:https://github.com/parfeon/DBConnect/wiki/DBCError
Overview
The DBCDatabase defines methods to communicate with [SQLite][SQLitews] database.
DBCDatabase designed to:
- control multi-threaded access to database handler (if it was passed to another thread) or sqlite database file
- execute queries and update to database
- cache prepared sqlite statements (this allows speeding up requests execution)
- control SQL transactions
- create new database with 'read-only' or 'read-write' access
- create new database from SQL dump file (file like MySQL database dump file)
- create mutable copy of database
In some methods I'll reference on this small example:
DBCError *error = nil; DBCDatabase *db = [DBCDatabase databaseWithPath:@":memory:"]; if([db openError:&error]){ [db executeUpdate:@"DROP TABLE IF EXISTS test; CREATE TABLE IF NOT EXISTS test (pid INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, \ pType TEXT NOT NULL, pTitle TEXT, \ loc_lat FLOAT NOT NULL, loc_lon FLOAT NOT NULL); \ CREATE UNIQUE INDEX locationIndex ON test (loc_lat, loc_lon); \ INSERT INTO test (pType, pTitle, loc_lat, loc_lon) VALUES ( ?1, ?2, ?3, ?4 ); \ INSERT INTO test (pType, pTitle, loc_lat, loc_lon) VALUES ( ?1, ?5, ?6, ?7 ); \ INSERT INTO test (pType, pTitle, loc_lat, loc_lon) VALUES ( ?1, ?8, ?9, ?10 ); \ INSERT INTO test (pType, pTitle, loc_lat, loc_lon) VALUES ( ?1, ?11, ?12, ?13 );" error:&error, @"City", @"Cupertino", [NSNumber numberWithFloat:37.3261f], [NSNumber numberWithFloat:-122.0320f], @"New York", [NSNumber numberWithFloat:40.724f], [NSNumber numberWithFloat:-74.06f], @"Dnepropetrovsk", [NSNumber numberWithFloat:48.47f], [NSNumber numberWithFloat:35.050f], @"Kiev", [NSNumber numberWithFloat:50.457f], [NSNumber numberWithFloat:30.525f], nil]; if(error != nil){ // Hmm, something has gone wrong, try to log out an error to find out something useful. Or you can set a flag for DBCUseDebugLogger in DBCConfiguration.h, than DBConnect will log out all debug information. NSLog(@"Occurred an error: %@", error); } } else { // In some rare cases an error may occur, just log it out to find out what has gone wrong. Or you can set a flag for DBCUseDebugLogger in DBCConfiguration.h, than DBConnect will log out all debug information. NSLog(@"Occurred an error: %@", error); }
##Tasks
###DBCDatabase instance initialization
+ databaseWithPath:
+ databaseWithPath:defaultEncoding:
+ databaseFromFile:atPath:continueOnExecutionErrors:error:
+ databaseFromFile:atPath:defaultEncoding:continueOnExecutionErrors:error:
- initWithPath:defaultEncoding:
- createDatabaseFromFile:atPath:defaultEncoding:continueOnExecutionErrors:error:
###DBCDatabase sqlite database connection open/close
- openError:
- openReadonlyError:
- makeMutableAt:rewriteExisting:error:
- closeError:
###DBCDatabase DDL and DML
- executeUpdate:error:
- executeQuery:error:
- executeStatementsFromFile:continueOnExecutionErrors:error:
###DBCDatabase TCL
- beginTransactionError:
- beginDeferredTransactionError:
- beginImmediateTransactionError:
- beginExclusiveTransactionError:
- commitTransactionError:
- rollbackTransactionError:
###DBCDatabase misc
- databaseVersionError:
- databaseVersionFor:error:
- changeDatabaseVersion:error:
- changeDatabaseVersion:forDatabase:error:
###DBCDatabase properties
busyRetryCount
defaultSQLSequencesTransactionLock
statementsCachingEnabled
rollbackSQLSequenceTransactionOnError
createTransactionOnSQLSequences
database
##Properties
This property stores statements execution retry count.
@property (nonatomic)int busyRetryCount
Discussion
If you pass reference on DBCDatabase to another thread or maybe few instances of DBCDatabase access to the same [sqlite][SQLitews] database file at the same time, requests execution may not pass because database is busy or locked. This parameter tells DBCDatabase instance to retry for specified number of times to execute statement.
Default value is set to 5
.
defaultSQLSequencesTransactionLock
This property stores default SQL statements transaction lock.
@property (nonatomic)DBCDatabaseTransactionLock defaultSQLSequencesTransactionLock
Discussion
Available list of [DBCDatabaseTransactionLock][DBCDatabaseTransactionLockC] locks.
By default value set to [DBCDatabaseAutocommitModeDeferred][DBCDatabaseAutocommitModeDeferredc].
This property specify whether compiled statements caching enabled or not.
@property (nonatomic, getter = isStatementsCachingEnabled)BOOL statementsCachingEnabled
Discussion
This flag tells DBCDatabase to cache compiled statements to make their future execution faster, because there is no time loss on statement compilation.
Default value is set to YES
.
rollbackSQLSequenceTransactionOnError
This property specify whether DBCDatabase should rollback statements which were executed inside of transaction or not.
@property (nonatomic)BOOL rollbackSQLSequenceTransactionOnError
Discussion
If YES
DBCDatabase will automatically rollback transaction (if started).
Default value is set to YES
.
createTransactionOnSQLSequences
This property stores specify whether DBCDatabase should wrap SQL statements sequence with TCL or not.
@property (nonatomic)BOOL createTransactionOnSQLSequences
Discussion
If YES
, than DBCDatabase will automatically wrap SQL statements sequence with transaction BEGIN and COMMIT (if transaction control was not detected in provided SQL statements list).
Default value is set to YES
.
This property stores reference on opened [SQLite][SQLitews] database connection.
@property (nonatomic, readonly, getter = database)sqlite3 *dbConnection
Return value
Reference on opened [sqlite][SQLitews] database connection or nil
.
Discussion
If database connection is opened, than this property will return reference on it, otherwise nil
.
##Class methods
Create and initialize DBCDatabase instance, which can be used to communicate with [sqlite][SQLitews].
+ (id)databaseWithPath:(NSString*)dbFilePath
Parameters
dbFilePath
[SQLite][SQLitews] database source can be specified as: path
, file
, ":memory:"
, ""
or nil
.
Return value
Autoreleased DBCDatabase instance.
Discussion
This is the fastest method to create DBCDatabase and to start working with the database. This method will prepare DBCDatabase for working with database in UTF-8 encoding.
If you are planning to use database with read-write access, you should place [sqlite][SQLitews] database file somewhere, where system can change file. Don't forget, what in iOS and Mac OS X (apps from [Mac App Store][MAS]) applications you can't modify database file inside application bundle.
dbFilePath tells to DBCDatabase where it should open/create database:
1. if dbFilePath is absolute path to database file, then DBCDatabase will use that persistent [sqlite][SQLitews] database file. If file does not exist, it will be created.
2. if dbFilePath is ":memory:"
, then DBCDatabase will create temporary in-memory
database. Database can be reached only from instance, which created it. When database connection will be closed, database will be removed from memory.
3. if dbFilePath is ""
or nil
, then DBCDatabase will create temporary database on device like file. As in-memory
database, it can be reached only from instance, which created it and will be removed from filesystem as soon as connection will be closed.
How to use
Create DBCDatabase instance for [sqlite][SQLitews] database file, stored in Documents directory for example:
DBCDatabase *db = [DBCDatabase databaseWithPath:@"test.sqlite"];
Create DBCDatabase instance for database, which will be temporary stored in memory:
DBCDatabase *db = [DBCDatabase databaseWithPath:@":memory:"];
Create DBCDatabase instance for database, which will temporarily be stored on filesystem:
DBCDatabase *db = [DBCDatabase databaseWithPath:@""];
DBCDatabase *db = [DBCDatabase databaseWithPath:nil];
See Also
+ databaseWithPath:defaultEncoding:
+ databaseFromFile:atPath:continueOnExecutionErrors:error:
+ databaseFromFile:atPath:defaultEncoding:continueOnExecutionErrors:error:
- initWithPath:defaultEncoding:
- createDatabaseFromFile:atPath:defaultEncoding:continueOnExecutionErrors:error:
databaseWithPath:defaultEncoding:
Create and initialize DBCDatabase instance, which can be used to communicate with [sqlite][SQLitews]
+ (id)databaseWithPath:(NSString*)dbFilePath defaultEncoding:(DBCDatabaseEncoding)encoding
Parameters
dbFilePath
[SQLite][SQLitews] database source can be specified as: path
, file
, ":memory:"
, ""
or nil
.
encoding
The database encoding, which will be used to define which method from SQLite C API to use. The default value is [DBCDatabaseEncodingUTF8][DBCDatabaseEncodingUTF8c].
Return value
Autoreleased DBCDatabase instance.
Discussion
This method creates DBCDatabase and prepares it to work with provided encoding. There are few methods in SQLite C API which can be used specially for UTF-8/UTF-16 encodings. But I hope you will keep close to the light side of the force and use UTF-8 encoding.
If you are planing to use database with read-write access, you should place [sqlite][SQLitews] database file somewhere, where system can change file. Don't forget, what in iOS and Mac OS X (apps from [Mac App Store][MAS]) applications you can't modify database file inside application bundle.
dbFilePath tells DBCDatabase where it should open/create database:
1. if dbFilePath is an absolute path to database file, then DBCDatabase will use that persistent [sqlite][SQLitews] database file. If file does not exist, it will be created.
2. if dbFilePath is ":memory:"
, then DBCDatabase will create temporary in-memory
database. Database can be reached only from instance, which created it. When database connection will be closed, database will be removed from memory.
3. if dbFilePath is ""
or nil
, then DBCDatabase will create temporary database on device like file. As in-memory
database, it can be reached only from instance, which created it and will be removed from filesystem on connection close.
How to use
Usage is almost same as in case of databaseWithPath:, but with this method you can additionally specify encoding, which will be used instead of default UTF-8.
For example, to create DBCDatabase instance using UTF-16 encoding for database, which will be temporary stored in memory do something like this:
DBCDatabase *db = [DBCDatabase databaseWithPath:@":memory:" defaultEncoding:DBCDatabaseEncodingUTF16];
See Also
+ databaseWithPath:
+ databaseFromFile:atPath:continueOnExecutionErrors:error:
+ databaseFromFile:atPath:defaultEncoding:continueOnExecutionErrors:error:
- initWithPath:defaultEncoding:
- createDatabaseFromFile:atPath:defaultEncoding:continueOnExecutionErrors:error:
databaseFromFile:atPath:continueOnExecutionErrors:error:
Create and initialize DBCDatabase instance, which will create/restore/update for you a database from external dump file.
+ (id)databaseFromFile:(NSString*)sqlStatementsListFilepath atPath:(NSString*)dbFilePath continueOnExecutionErrors:(BOOL)continueOnExecutionErrors error:(DBCError**)error
Parameters
sqlStatementsListFilepath
The path or file for database dump with SQL statements list.
dbFilePath
Dump processing result destination can be specified as: path
, file
, ":memory:"
, ""
or nil
.
continueOnExecutionErrors
Specify YES
to proceed dump file processing even in case of SQL execution error or NO
- to terminate processing immediately.
error
If an error occurs, upon return contains an [DBCError][DBCErrorwiki] object that describes the problem. Pass NULL
if you don't want error information.
Return value
Autoreleased DBCDatabase instance or nil
if occurred an error.
Discussion
This method allows you to create/restore/update [sqlite][SQLitews] database from SQL dump file and prepare DBCDatabase to work with it in default UTF-8 encoding.
You can use file
, :memory:
or ""
as a target for database dump processing result. This means what you can create some persistent/temporary [sqlite][SQLitews] database. Also this method can be used to perform database upgrades from file with SQL statements.
After successful execution, you'll get DBCDatabase instance with ready to use, there is no need to call openError: (but this is OK to do that).
How to use
Create DBCDatabase instance and execute SQL statements from dump file on [sqlite][SQLitews] database file, which is stored in Documents directory for example. Processing will proceed even in case of errors in SQL statement execution:
NSString *dumpFilePath = ...; DBCError *error = nil; DBCDatabase *db = [DBCDatabase databaseFromFile:dumpFilePath atPath:@"rstored.sqlite" continueOnExecutionErrors:YES error:&error]; if(error != nil){ // In some rare cases an error may occur, just log it out to find out what has gone wrong. Or you can set a flag for DBCUseDebugLogger in DBCConfiguration.h, than DBConnect will log out all debug information. NSLog(@"Occurred an error: %@", error); }
Create DBCDatabase instance and execute SQL statements from dump file on [sqlite][SQLitews] in-memory
temporary database. Processing won't proceed in case of errors in SQL statement execution:
NSString *dumpFilePath = ...; DBCError *error = nil; DBCDatabase *db = [DBCDatabase databaseFromFile:dumpFilePath atPath:@":memory:" continueOnExecutionErrors:NO error:&error]; if(error != nil){ // In some rare cases an error may occur, just log it out to find out what has gone wrong. Or you can set a flag for DBCUseDebugLogger in DBCConfiguration.h, than DBConnect will log out all debug information. NSLog(@"Occurred an error: %@", error); }
Create DBCDatabase instance and execute SQL statements from dump file on [sqlite][SQLitews] database temporary stored on filesystem. Processing won't proceed in case of errors in SQL statement execution:
NSString *dumpFilePath = ...; DBCError *error = nil; DBCDatabase *db = [DBCDatabase databaseFromFile:dumpFilePath atPath:@"" continueOnExecutionErrors:NO error:&error]; if(error != nil){ // In some rare cases an error may occur, just log it out to find out what has gone wrong. Or you can set a flag for DBCUseDebugLogger in DBCConfiguration.h, than DBConnect will log out all debug information. NSLog(@"Occurred an error: %@", error); }
See Also
+ databaseWithPath:
+ databaseWithPath:defaultEncoding:
+ databaseFromFile:atPath:defaultEncoding:continueOnExecutionErrors:error:
- initWithPath:defaultEncoding:
- createDatabaseFromFile:atPath:defaultEncoding:continueOnExecutionErrors:error:
databaseFromFile:atPath:defaultEncoding:continueOnExecutionErrors:error:
Create and initialize DBCDatabase instance, which will create/restore/update for you a database from external dump file.
+ (id)databaseFromFile:(NSString*)sqlStatementsListFilepath atPath:(NSString*)dbFilePath defaultEncoding:(DBCDatabaseEncoding)encoding continueOnExecutionErrors:(BOOL)continueOnExecutionErrors error:(DBCError**)error
Parameters
sqlStatementsListFilepath
The path or file for database dump with SQL statements list.
dbFilePath
Dump processing result destination can be specified as: path
, file
, ":memory:"
, ""
or nil
.
encoding
Database encoding, which will be used to define which method from SQLite C API to use. Default value is [DBCDatabaseEncodingUTF8][DBCDatabaseEncodingUTF8c].
continueOnExecutionErrors
Specify YES
to proceed dump file processing even in case of SQL execution error or NO
- to terminate processing immediately.
error
If an error occurs, upon return contains an [DBCError][DBCErrorwiki] object that describes the problem. Pass NULL
if you don't want error information.
Return value
Autoreleased DBCDatabase instance or nil
if occurred an error.
Discussion
As databaseFromFile:atPath:continueOnExecutionErrors:error: this method allows you to create/restore/update [sqlite][SQLitews] database from SQL dump file and prepare DBCDatabase to work with it in specified encoding.
How to use
For example, to create and initialize DBCDatabase instance with UTF-8 encoding for database, which will be temporary stored on filesystem, we need to do something like this:
NSString *dumpFilePath = ...; DBCError *error = nil; DBCDatabase *db = [DBCDatabase databaseFromFile:dumpFilePath atPath:@"" defaultEncoding:DBCDatabaseEncodingUTF8 continueOnExecutionErrors:NO error:&error]; if(error != nil){ // In some rare cases an error may occur, just log it out to find out what has gone wrong. Or you can set a flag for DBCUseDebugLogger in DBCConfiguration.h, than DBConnect will log out all debug information. NSLog(@"Occurred an error: %@", error); }
See Also
+ databaseWithPath:
+ databaseWithPath:defaultEncoding:
+ databaseFromFile:atPath:continueOnExecutionErrors:error:
- initWithPath:defaultEncoding:
- createDatabaseFromFile:atPath:defaultEncoding:continueOnExecutionErrors:error:
##Instance methods
Initialize DBCDatabase instance, which can be used to communicate with [sqlite][SQLitews]
- (id)initWithPath:(NSString*)dbFilePath defaultEncoding:(DBCDatabaseEncoding)encoding
Parameters
dbFilePath
[SQLite][SQLitews] database source can be specified as: path
, file
, ":memory:"
, ""
or nil
.
encoding
The database encoding, which will be used to define which method from SQLite C API to use. The default value is [DBCDatabaseEncodingUTF8][DBCDatabaseEncodingUTF8c].
Return value
Initialized DBCDatabase instance
Discussion
This method initializes DBCDatabase instance and prepares it to work with provided encoding. There are few methods in SQLite C API which can be used specially for UTF-8/UTF-16 encodings. But I hope you will keep close to the light side of the force and use UTF-8 encoding.
If you are planning to use database in 'read-write' mode, you should place [sqlite][SQLitews] database file somewhere, where system can change file. Don't forget, what in iOS and Mac OS X (apps from [Mac App Store][MAS]) applications you can't modify database file inside application bundle.
dbFilePath tells to DBCDatabase where it should open/create the database:
1. if dbFilePath is an absolute path to database file, then DBCDatabase will use that persistent [sqlite][SQLitews] database file. If file does not exist, it will be created.
2. if dbFilePath is ":memory:"
, then DBCDatabase will create temporary database in memory. Database can be reached only from instance, which created it. When database connection will be closed, database will be removed from memory.
3. if dbFilePath is ""
or nil
, then DBCDatabase will create temporary database on device like file. As in-memory database, it can be reached only from instance, which created it and will be removed from filesystem on connection close.
How to use
All you have to do is to allocate DBCDatabase and than do the same as shown in databaseWithPath:defaultEncoding: class method.
For example, to create and initialize DBCDatabase instance using UTF-8 encoding for database, which will be temporary stored in memory. Do something like this:
DBCDatabase *db = [[DBCDatabase alloc] initWithPath:@":memory:" defaultEncoding:DBCDatabaseEncodingUTF8];
See Also
+ databaseWithPath:
+ databaseWithPath:defaultEncoding:
+ databaseFromFile:atPath:continueOnExecutionErrors:error:
+ databaseFromFile:atPath:defaultEncoding:continueOnExecutionErrors:error:
- createDatabaseFromFile:atPath:defaultEncoding:continueOnExecutionErrors:error:
databaseFromFile:atPath:defaultEncoding:continueOnExecutionErrors:error:
Initialize DBCDatabase instance, which will create/restore/update for you a database from external dump file.
- (id)createDatabaseFromFile:(NSString*)sqlQeryListPath atPath:(NSString*)databasePath defaultEncoding:(DBCDatabaseEncoding)encoding continueOnExecutionErrors:(BOOL)continueOnExecutionErrors error:(DBCError**)error
Parameters
sqlStatementsListFilepath
The path or file for a database dump with SQL statements list.
dbFilePath
Dump processing result destination can be specified as: path
, file
, ":memory:"
, ""
or nil
.
encoding
The database encoding, which will be used to define which method from SQLite C API to use. Default value is [DBCDatabaseEncodingUTF8][DBCDatabaseEncodingUTF8c].
continueOnExecutionErrors
Specify YES
to proceed dump file processing even in case of SQL execution error or NO
- to terminate processing immediately.
error
If an error occurs, upon return contains an [DBCError][DBCErrorwiki] object that describes the problem. Pass NULL
if you do not want error information.
Return value
Initialized DBCDatabase instance or nil
if occurred an error.
Discussion
This method allows you to create/restore/update [sqlite][SQLitews] database from SQL dump file and prepare DBCDatabase to work with it in specified encoding.
You can use file
, :memory:
or ""
as a target for database dump processing result. This means that you can create some persistent/temporary [sqlite][SQLitews] database. Also this method can be used to perform database upgrades from file with SQL statements.
After successful processing, you'll get DBCDatabase instance ready to use, there is no need to call openError: (but this is OK to do that).
How to use
All you have to do is to allocate DBCDatabase and than do the same as shown in databaseFromFile:atPath:defaultEncoding:continueOnExecutionErrors:error: class method.
For example, to create and initialize DBCDatabase instance with UTF-16 encoding for database, which will be temporary stored on filesystem, we need to do something like this:
NSString *dumpFilePath = ...; DBCError *error = nil; DBCDatabase *db = [[DBCDatabase alloc] createDatabaseFromFile:dumpFilePath atPath:@"" defaultEncoding:DBCDatabaseEncodingUTF16 continueOnExecutionErrors:NO error:&error]; if(error != nil){ // In some rare cases an error may occur, just log it out to find out what has gone wrong. Or you can set a flag for DBCUseDebugLogger in DBCConfiguration.h, than DBConnect will log out all debug information. NSLog(@"Occurred an error: %@", error); }
See Also
+ databaseWithPath:
+ databaseWithPath:defaultEncoding:
+ databaseFromFile:atPath:continueOnExecutionErrors:error:
+ databaseFromFile:atPath:defaultEncoding:continueOnExecutionErrors:error:
- initWithPath:defaultEncoding:
Open [sqlite][SQLitews] database connection with read-write access.
- (BOOL)openError:(DBCError**)error
Parameters
error
If an error occurs, upon return contains an [DBCError][DBCErrorwiki] object that describes the problem. Pass NULL
if you do not want error information.
Return value
YES
if connection successfully opened, otherwise - NO
.
Discussion
This method opens [sqlite][SQLitews] connection with specified database source and encoding. This is one of few methods, which tries to decide which one of SQLite C API to use, based on provided encoding. If file does not exist, it will be automatically created (if it is not located in application bundle).
This method uses [openWithFlags:][DBCDatabase+AdvancedOpen] from [Advanced][DBCDatabase+Advanced] category inside. DBCDatabase instance opened by this method will use read-write access on [attached][DBCDatabase+AiasesAttach] databases too.
It is possible, what connection can't be opened because of few reasons, so you need to handle an error and ensure what connection successfully opened.
How to use
To create and open database connection you don't even need [sqlite][SQLitews] database source, because you can create temporary in-memory
database. Next example will show how to open connection for in-memory
database:
DBCError *error = nil; DBCDatabase *db = [DBCDatabase databaseWithPath:@":memory:"]; if([db openError:&error] && error == nil){ NSLog(@"Connection opened"); } else { // In some rare cases an error may occur, just log it out to find out what has gone wrong. Or you can set a flag for DBCUseDebugLogger in DBCConfiguration.h, than DBConnect will log out all debug information. NSLog(@"Occurred an error: %@", error); }
See Also
- openReadonlyError:
- makeMutableAt:rewriteExisting:error:
- closeError:
Open [sqlite][SQLitews] database connection with read-only access.
- (BOOL)openReadonlyError:(DBCError**)error
Parameters
error
If an error occurs, upon return contains an [DBCError][DBCErrorwiki] object that describes the problem. Pass NULL
if you do not want error information.
Return value
YES
if connection successfully opened, otherwise -NO
.
Discussion
This method opens [sqlite][SQLitews] connection with specified database source and encoding. This is one of few methods, which try to decide which one of SQLite C API to use, basing on provided encoding. If file does not exist, it will be automatically created (if it not located in application bundle).
This method uses [openWithFlags:][DBCDatabase+AdvancedOpen] from [Advanced][DBCDatabase+Advanced] category inside. DBCDatabase instance opened with this method will use read-only access on [attached][DBCDatabase+AiasesAttach] databases too.
It is possible, what connection can't be opened because of few reasons, so you need to handle an error and ensure what connection successfully opened.
How to use
To create and open database connection you don't even need [sqlite][SQLitews] database source, because you can create temporary in-memory
database. Next example will show how to open connection for in-memory
database
DBCError *error = nil; DBCDatabase *db = [DBCDatabase databaseWithPath:@":memory:"]; if(![db openReadonlyError:&error]){ // In some rare cases an error may occur, just log it out to find out what has gone wrong. Or you can set a flag for DBCUseDebugLogger in DBCConfiguration.h, than DBConnect will log out all debug information. NSLog(@"Occurred an error: %@", error); }
See Also
- openError:
- makeMutableAt:rewriteExisting:error:
- closeError:
makeMutableAt:rewriteExisting:error:
This method was created as some kind of helper to copy database file to a new location.
- (BOOL)makeMutableAt:(NSString*)mutableDatabaseStoreDestination rewriteExisting:(BOOL)shouldRewriteExistingFile error:(DBCError**)error
Parameters
mutableDatabaseStoreDestination
The path or file for current [sqlite][SQLitews] database file copy destination.
shouldRewriteExistingFile
YES
if should rewrite existing, otherwise - NO
.
error
If an error occurs, upon return contains an [DBCError][DBCErrorwiki] object that describes the problem. Pass NULL
, if you do not want error information.
Return value
YES
if copy was successfully created, otherwise - NO
.
Discussion
Sometimes there is a need to make a mutable copy of database file (move it out from application bundle). Currently initiated/opened database file will be moved to a new location (if file does not exist) and automatically reopen database connection with new file. To ensure, what database file won't be changed by current connection, it will be closed.
To make a mutable copy, you don't even need to open connection. If connection was opened, it will be reopened for new database file.
This methods can't be called on temporary databases.
How to use
NSString *targetDatabaseLocation = ...; DBCError *error = nil; DBCDatabase *db = [DBCDatabase databaseWithPath:@"test.sqlite"]; if(![db makeMutableAt:targetDatabaseLocation rewriteExisting:YES error:&error]){ // In some rare cases an error may occur, just log it out to find out what has gone wrong. Or you can set a flag for DBCUseDebugLogger in DBCConfiguration.h, than DBConnect will log out all debug information. NSLog(@"Occurred an error: %@", error); }
See Also
- openError:
- openReadonlyError:
- closeError:
Close current [sqlite][SQLitews] database connection.
- (BOOL)closeError:(DBCError**)error
Parameters
error
If an error occurs, upon return contains an [DBCError][DBCErrorwiki] object that describes the problem. Pass NULL
if you do not want error information.
Return value
YES
if connection was successfully closed, otherwise - NO
.
Discussion
Simply close connection and cleanup some caches (if enabled).
How to use
There is nothing special in this method, it just closes current connection:
DBCError *error = nil; DBCDatabase *db = ...; if(![db closeError:&error]){ // In some rare cases an error may occur, just log it out to find out what has gone wrong. Or you can set a flag for DBCUseDebugLogger in DBCConfiguration.h, than DBConnect will log out all debug information. NSLog(@"Occurred an error: %@", error); }
See Also
- openError:
- openReadonlyError:
- makeMutableAt:error:
Execute DDL or DML request to [sqlite][SQLitews] database.
- (BOOL)executeUpdate:(NSString*)sqlUpdate error:(DBCError**)error, ...
Parameters
sqlUpdate
SQL query command.
error
If an error occurs, upon return contains an [DBCError][DBCErrorwiki] object that describes the problem. Pass NULL
if you do not want error information.
...
List of binding parameters.
Return value
YES
if update statements were successfully executed, otherwise - NO
.
Discussion
I've tried to design both basic methods for DDL and DML to be as simple as possible to use them in your purposes.
This method can't be called on database with read-only access.
Of course it has some rules, to work as it should.
Lets start from SQL statement format
You can't use anything else except SQL query format. Parameter tokens can be: NSLog format specifiers, anonymous (?
), indexed (?<index>
), named (:<name>
, @<name>
, $<name>
).
Only with NSLog format specifiers parameter tokens you can use non-Objective-C data types, in other cases Objective-C objects only.
Main NSLog format specifiers benefits are what you can specify any datatype from format specifier:
- Opjective-C object
- signed int
- unsigned int
- short int
- unsigned short int
- long int
- long long int
- unsigned long long
- double
- c string
Let's study something about what we can pass as list of bindings in this method
As written above, with NSLog format specifiers you can pass both Objective-C objects and C data types. To pass them, you just write them into a list of bindings parameters in their origin form (I will show it in How to use section).
With other type of parameter tokens you can pass them one by one like Objective-C objects, or you can pass NSDictionary for named or NSArray for indexed tokens.
How to use
In this series of examples, we will use results from one of the examples, shown earlier.
To use NSLog format specifiers, we have to do something like this:
error = nil; [db executeUpdate:@"INSERT INTO test (pType, pTitle, loc_lat, loc_lon) VALUES ( %s, %@, %f, %d );" error:&error, "City", @"Denver", 40.2338f, (int)-76.1372f, nil];
I hope you noticed, what I have to do some type cast to pass correct value. So for %d
I have to pass integer, if you pass some float value it won't be automatically rounded and execution will fail. So try to use corresponding format specifiers for correct data passed as parameters.
To use anonymous tokens for the same task we will do next:
error = nil; [db executeUpdate:@"INSERT INTO test (pType, pTitle, loc_lat, loc_lon) VALUES ( ?, ?, ?, ? );" error:&error, @"City", @"Denver", [NSNumber numberWithFloat:40.2338f], [NSNumber numberWithFloat:-76.1372f], nil];
As we can see, we have to pass same count of parameters as declared in statement by anonymous tokens.
Also you can pass here an array of values. This is also possible with indexed tokens, but ensure what you did not mess with indices values. In case of anonymous tokens you have to provide array and place values inside of it in the order, to correspond to target column. Here is an example of how to do this:
[db executeUpdate:@"INSERT INTO test (pType, pTitle, loc_lat, loc_lon) VALUES ( ?, ?, ?, ? );" error:&error, [NSArray arrayWithObjects:@"City", @"Denver", [NSNumber numberWithFloat:40.2338f], [NSNumber numberWithFloat:-76.1372f], nil], nil];
To use indexed tokens for the same task we will do next:
error = nil; [db executeUpdate:@"INSERT INTO test (pType, pTitle, loc_lat, loc_lon) VALUES ( ?1, ?2, ?3, ?3 );" error:&error, @"City", @"Denver", [NSNumber numberWithFloat:40.2338f], nil];
Also you can pass here an array of values. This is also possible with anonymous tokens, but ensure what you did not mess with indices values. In case of indexed tokens you can use indices inside array and place them as indexed tokens but incremented by 1. Here is an example of how to do this:
[db executeUpdate:@"INSERT INTO test (pType, pTitle, loc_lat, loc_lon) VALUES ( ?1, ?2, ?3, ?3 );" error:&error, [NSArray arrayWithObjects:@"City", @"Denver", [NSNumber numberWithFloat:40.2338f], nil], nil];
Just to show you benefits of using indexed tokens I've placed the same latitude value as longitude.
To use named tokens for the same task we will do next:
error = nil; [db executeUpdate:@"INSERT INTO test (pType, pTitle, loc_lat, loc_lon) \ VALUES ( :placeType, @placeTitle, $placeLatitude, :placeLatitude );" error:&error, [NSDictionary dictionaryWithObjectsAndKeys:@"City", @"placeType", @"Denver", @"placeTitle", [NSNumber numberWithFloat:40.2338f], @"placeLatitude", nil];
Just to show you benefits of using named tokens I've placed same latitude value as longitude. Also example above shows how you can use named tokens in statement.
See Also
- executeQuery:error:
- executeStatementsFromFile:continueOnExecutionErrors:error:
Execute DDL or DML request to [sqlite][SQLitews] database.
- (DBCDatabaseResult*)executeQuery:(NSString*)sqlQuery error:(DBCError**)error, ...
Parameters
sqlQuery
SQL query command.
error
If an error occurs, upon return contains an [DBCError][DBCErrorwiki] object that describes the problem. Pass NULL
if you do not want error information.
...
List of binding parameters.
Return value
[DBCDatabaseResult][DBCDatabaseResultCR] instance with array of [DBCDatabaseRow][DBCDatabaseRowCR].
Discussion
This method designed in same way as executeUpdate:error: to make it easy to use. Check executeUpdate:error: rules and acceptable datatypes.
This method can't be called on database with read-only access.
How to use
In this example, we will use results from one of the examples, shown earlier.
error = nil; DBCDatabaseResult *result = [db executeQuery:@"SELECT * FROM test WHERE loc_lat > %d AND loc_lat < %d" error:&error, 37, 41, nil]; if(error == nil){ NSLog(@"%@", [[result columnNames] componentsJoinedByString:@" | "]); for(DBCDatabaseRow *row in result) NSLog(@"%@", row); } /* Output: pid | ptype | ptitle | loc_lat | loc_lon 1 | City | Cupertino | 37.3261 | -122.032 2 | City | New York | 40.724 | -74.006 */ if(error == nil){ NSLog(@"%@", result); } /* Output: Result for: SELECT * FROM test WHERE loc_lat > ?1 AND loc_lat < ?2; Query execution done in 0.000000s Found: 2 records Column names: pid | ptype | ptitle | loc_lat | loc_lon Result rows: ( "1 | City | Cupertino | 37.3261 | -122.032", "2 | City | New York | 40.724 | -74.006" ) */
See Also
- executeUpdate:error:
- executeStatementsFromFile:continueOnExecutionErrors:error:
executeStatementsFromFile:continueOnExecutionErrors:error:
Execute DDL or DML request from file to [sqlite][SQLitews] database.
- (BOOL)executeStatementsFromFile:(NSString*)statementsFilePath continueOnExecutionErrors:(BOOL)continueOnExecutionErrors error:(DBCError**)error
Parameters
statementsFilePath
The path to SQL statements list.
continueOnExecutionErrors
Specify YES
to proceed file processing even in case of SQL execution error or NO
- to terminate processing immediately.
error
If an error occurs, upon return contains an [DBCError][DBCErrorwiki] object that describes the problem. Pass NULL
if you do not want error information.
Return value
YES
if statements list from file was successfully executed, otherwise - NO
.
Discussion
This method allows you to execute list of statements directly from the file stored somewhere in application bundle or elsewhere.
This method can't be called on database with read-only access.
How to use
In this example we will reproduce the same result as shown in this example by executing SQL statements from external file.
DBCError *error = nil; DBCDatabase *db = [DBCDatabase databaseWithPath:@":memory:"]; if([db openError:&error]){ [db executeStatementsFromFile:[[NSBundle mainBundle] pathForResource:@"test.sql" ofType:@"dump"] continueOnExecutionErrors:NO error:&error]; if(error != nil){ // Hmm, something has gone wrong, try to log out an error to find out something useful. Or you can set a flag for DBCUseDebugLogger in DBCConfiguration.h, than DBConnect will log out all debug information. NSLog(@"Occurred an error: %@", error); } else { DBCDatabaseResult *result = [db executeQuery:@"SELECT * FROM test" error:&error, nil]; if(error == nil){ NSLog(@"%@", result); } /* Output: Result for: SELECT * FROM test; Query execution done in 0.000000s Found: 4 records Column names: pid | ptype | ptitle | loc_lat | loc_lon Result rows: ( "1 | City | Cupertino | 37.3261 | -122.032", "2 | City | New York | 40.724 | -74.06", "3 | City | Dnepropetrovsk | 48.47 | 35.05", "4 | City | Kiev | 50.457 | 30.525" ) */ } } else { // In some rare cases an error may occur, just log it out to find out what has gone wrong. Or you can set a flag for DBCUseDebugLogger in DBCConfiguration.h, than DBConnect will log out all debug information. NSLog(@"Occurred an error: %@", error); }
See Also
- executeUpdate:error:
- executeQuery:error:
Begin transaction with default lock mode.
- (BOOL)beginTransactionError:(DBCError**)error
Return value
YES
if transaction started with default lock mode, otherwise - NO
.
Discussion
This method allows you to begin transaction in default lock mode. If database is accessed from few threads for example, than the locking mode defines how to balance peer access with ensured success of the transaction.
This method can't be called on database with read-only access.
Transactions are usually used when you need to execute large number of inserts or other data manipulation at once.
Be careful, because when you manually begin transaction, database leaves auto-commit mode and won't write anything will you commit transaction by yourself.
How to use
In this example, we will use results from one of the examples, shown earlier.
error = nil; [db beginTransactionError:&error]; if(error != nil){ // Hmm, something has gone wrong, try to log out an error to find out something useful. Or you can set a flag for DBCUseDebugLogger in DBCConfiguration.h, than DBConnect will log out all debug information. NSLog(@"Occurred an error: %@", error); } else { [db executeUpdate:@"INSERT INTO test (pType, pTitle, loc_lat, loc_lon) VALUES ( %s, %@, %f, %d );" error:&error, "City", @"Denver", 40.2338f, (int)-76.1372f, nil]; [db executeUpdate:@"INSERT INTO test (pType, pTitle, loc_lat, loc_lon) VALUES ( %s, %@, %f, %d );" error:&error, "City", @"San Jose", 37.3397f, (int)-121.8949f, nil]; } error = nil; [db commitTransactionError:&error]; if(error != nil){ // Hmm, something has gone wrong, try to log out an error to find out something useful. Or you can set a flag for DBCUseDebugLogger in DBCConfiguration.h, than DBConnect will log out all debug information. NSLog(@"Occurred an error: %@", error); }
See Also
- beginDeferredTransactionError:
- beginImmediateTransactionError:
- beginExclusiveTransactionError:
- commitTransactionError:
- rollbackTransactionError:
beginDeferredTransactionError:
Begin transaction in deferred lock mode.
- (BOOL)beginDeferredTransactionError:(DBCError**)error
Return value
YES
if transaction started in deferred lock mode, otherwise - NO
.
Discussion
This method allows you to begin transaction in deferred lock mode. If database accessed from few threads for example, than the locking mode defines how to balance peer access with ensured success of the transaction.
This method can't be called on database with read-only access.
Transactions are usually used when you need to execute large number of inserts or other data manipulation at once.
Be careful because when you manually begin transaction, database leaves auto-commit mode and won't write anything will you commit transaction by yourself.
How to use
This method can be used in the same way as beginTransactionError: . The difference will be only in transaction lock mode.
See Also
- beginTransactionError:
- beginImmediateTransactionError:
- beginExclusiveTransactionError:
- commitTransactionError:
- rollbackTransactionError:
beginImmediateTransactionError:
Begin transaction with immediate lock mode.
- (BOOL)beginImmediateTransactionError:(DBCError**)error
Return value
YES
if transaction started with immediate lock mode, otherwise - NO
.
Discussion
This method allows you to begin transaction in immediate lock mode. If database is accessed from few threads for example, than the locking mode defines how to balance peer access with ensured success of the transaction.
This method can't be called on database with read-only access.
Transactions are usually used when you need to execute large number of inserts or other data manipulation at once.
Be careful because when you manually begin transaction, database leaves auto-commit mode and won't write anything will you commit transaction by yourself.
How to use
This method can be used in the same way as beginTransactionError:. The difference will be only in transaction lock mode.
See Also
- beginTransactionError:
- beginDeferredTransactionError:
- beginExclusiveTransactionError:
- commitTransactionError:
- rollbackTransactionError:
beginExclusiveTransactionError:
Begin transaction in exclusive lock mode.
- (BOOL)beginExclusiveTransactionError:(DBCError**)error
Return value
YES
if transaction started with exclusive lock mode, otherwise - NO
.
Discussion
This method allows you to begin transaction with exclusive lock mode. If database is accessed from few threads for example, than the locking mode defines how to balance peer access with ensured success of the transaction.
This method can't be called on database with read-only access.
Transactions are usually used when you need to execute large number of inserts or other data manipulation at once.
Be careful because when you manually begin transaction, database leaves auto-commit mode and won't write anything will you commit transaction by yourself.
How to use
This method can be used in the same way as beginTransactionError: . The difference will be only in transaction lock mode.
See Also
- beginTransactionError:
- beginDeferredTransactionError:
- beginImmediateTransactionError:
- commitTransactionError:
- rollbackTransactionError:
Commit recently started transaction.
- (BOOL)commitTransactionError:(DBCError**)error
Return value
YES
if transaction commit was successful, otherwise - NO
.
Discussion
This method allows you to commit recently performed data manipulation SQL statements and write them down into [sqlite][SQLitews] database file.
This method can't be called on database with read-only access.
How to use
Usage of this method was shown in 'How to use' for beginTransactionError:.
See Also
- beginTransactionError:
- beginDeferredTransactionError:
- beginImmediateTransactionError:
- beginExclusiveTransactionError:
- rollbackTransactionError:
Rollback recent data manipulation SQL statements to the state, before transaction was started.
- (BOOL)rollbackTransactionError:(DBCError**)error
Return value
YES
if transaction rollback was successful, otherwise - NO
.
Discussion
This method allows you to restore database state to the state before all data manipulation was made in transaction.
This method can't be called on database with read-only access.
How to use
Usage of this method was shown in 'How to use' for beginTransactionError:.
error = nil; [db beginTransactionError:&error]; if(error != nil){ // Hmm, something has gone wrong, try to log out an error to find out something useful. Or you can set a flag for DBCUseDebugLogger in DBCConfiguration.h, than DBConnect will log out all debug information. NSLog(@"Occurred an error: %@", error); } else { error = nil; [db executeUpdate:@"INSERT INTO test (pType, pTitle, loc_lat, loc_lon) VALUES ( %s, %@, %f, %d );" error:&error, "City", @"Denver", 40.2338f, (int)-76.1372f, nil]; [db executeUpdate:@"INSERT INTO test (pType, pTitle, loc_lat, loc_lon) VALUES ( %s, %@, %f, %d );" error:&error, "City", @"San Jose", 37.3397f, (int)-121.8949f, nil]; if(error != nil) { // Hmm, something has gone wrong, try to log out an error to find out something useful. Or you can set a flag for DBCUseDebugLogger in DBCConfiguration.h, than DBConnect will log out all debug information. NSLog(@"Occurred an error: %@", error); error = nil; [db rollbackTransactionError:&error]; if(error != nil) { // Hmm, something has gone wrong, try to log out an error to find out something useful. Or you can set a flag for DBCUseDebugLogger in DBCConfiguration.h, than DBConnect will log out all debug information. NSLog(@"Occurred an error: %@", error); } } } error = nil; [db commitTransactionError:&error]; if(error != nil){ // Hmm, something has gone wrong, try to log out an error to find out something useful. Or you can set a flag for DBCUseDebugLogger in DBCConfiguration.h, than DBConnect will log out all debug information. NSLog(@"Occurred an error: %@", error); }
See Also
- beginTransactionError:
- beginDeferredTransactionError:
- beginImmediateTransactionError:
- beginExclusiveTransactionError:
- commitTransactionError:
This method helps to retrieve main database version.
- (int)databaseVersionError:(DBCError**)error
Parameters
error
If an error occurs, upon return contains an [DBCError][DBCErrorwiki] object that describes the problem. Pass NULL
if you do not want error information.
Return value
Big-endian 32-bit signed integer which represents main database version.
Discussion
This method retrieves from database header version number for database. Initially database version is assigned to 0
.
How to use
In this example, we will use results from [example][DBCDatabase+AiasesAttachExample], shown earlier in [DBCDatabase+Aiases Category Reference][DBCDatabase+AiasesCR] and retrieve main database version.
error = nil; int version = [db databaseVersionError:&error]; if(error != nil){ // Hmm, something has gone wrong, try to log out an error to find out something useful. Or you can set a flag for DBCUseDebugLogger in DBCConfiguration.h, than DBConnect will log out all debug information. NSLog(@"Occurred an error: %@", error); }
See Also
- databaseVersionFor:error:
- changeDatabaseVersion:error:
- changeDatabaseVersion:forDatabase:error:
This method helps to retrieve specified database version.
- (int)databaseVersionFor:(NSString*)databaseName error:(DBCError**)error
Parameters
databaseName
The name of the database for which you would like to retrieve database version. If nil than main database will be used.
error
If an error occurs, upon return contains an [DBCError][DBCErrorwiki] object that describes the problem. Pass NULL
if you do not want error information.
Return value
Big-endian 32-bit signed integer which represents specified database version.
Discussion
This method retrieves from database header version number for database. Initially database version assigned to 0
.
How to use
In this example, we will use results from [example][DBCDatabase+AiasesAttachExample], shown earlier in [DBCDatabase+Aiases Category Reference][DBCDatabase+AiasesCR] and retrieve aTest database version.
error = nil; int version = [db databaseVersionFor:@"aTest" error:&error]; if(error != nil){ // Hmm, something has gone wrong, try to log out an error to find out something useful. Or you can set a flag for DBCUseDebugLogger in DBCConfiguration.h, than DBConnect will log out all debug information. NSLog(@"Occurred an error: %@", error); }
See Also
- databaseVersionError:
- changeDatabaseVersion:error:
- changeDatabaseVersion:forDatabase:error:
This method allows you to change main database version.
- (BOOL)changeDatabaseVersion:(int)version error:(DBCError**)error
Parameters
version
New database version.
error
If an error occurs, upon return contains an [DBCError][DBCErrorwiki] object that describes the problem. Pass NULL
if you do not want error information.
Return value
YES
if database version was successfully changed, otherwise - NO
.
Discussion
This method allows you to change main database version to desired. This versions for example can be used when performing incremental database migration.
How to use
In this example, we will use results from [example][DBCDatabase+AiasesAttachExample], shown earlier in [DBCDatabase+Aiases Category Reference][DBCDatabase+AiasesCR] and change main database version to 2
.
error = nil; [db changeDatabaseVersion:2 error:&error]; if(error != nil){ // Hmm, something has gone wrong, try to log out an error to find out something useful. Or you can set a flag for DBCUseDebugLogger in DBCConfiguration.h, than DBConnect will log out all debug information. NSLog(@"Occurred an error: %@", error); }
See Also
- databaseVersionError:
- databaseVersionFor:error:
- changeDatabaseVersion:forDatabase:error:
changeDatabaseVersion:forDatabase:error:
This method allows you to change main database version.
- (int)changeDatabaseVersion:(int)version forDatabase:(NSString*)databaseName error:(DBCError**)error
Parameters
version
New database version.
databaseName
The name of the database for which you would like to change database version. If nil than main database will be used.
error
If an error occurs, upon return contains an [DBCError][DBCErrorwiki] object that describes the problem. Pass NULL
if you do not want error information.
Return value
YES
if database version was successfully changed, otherwise - NO
.
Discussion
This method allows you to change main database version to desired. This versions for example can be used when performing incremental database migration.
How to use
In this example, we will use results from [example][DBCDatabase+AiasesAttachExample], shown earlier in [DBCDatabase+Aiases Category Reference][DBCDatabase+AiasesCR] and change aTest database version to 53
.
error = nil; [db changeDatabaseVersion:53 forDatabase:@"aTest" error:&error]; if(error != nil){ // Hmm, something has gone wrong, try to log out an error to find out something useful. Or you can set a flag for DBCUseDebugLogger in DBCConfiguration.h, than DBConnect will log out all debug information. NSLog(@"Occurred an error: %@", error); }
See Also
- databaseVersionError:
- databaseVersionFor:error:
- changeDatabaseVersion:error: