Class ThreadSafeDatabase
Confines a database and its cursors to a single thread.
A Database is not thread safe, and neither are the cursors it hands out. Wrapping one in this
class routes every call through one worker thread, so several application threads can share a
connection without coordinating.
Database db = new ThreadSafeDatabase(Database.openOrCreate("shared.db"));
The cost is that every call is a thread handoff, so a tight loop over a large result set is meaningfully slower than using a connection per thread. Prefer one database per thread when the threads do not actually need to share state.
This class used to be deprecated, on the grounds that platform specific behaviour had defeated it. That behaviour has since been fixed: the iOS port no longer closes SQLite handles from the garbage collector thread, and it opens each connection in serialised mode rather than trying to configure the whole process.
-
Field Summary
Fields inherited from class Database
COLUMN_BLOB, COLUMN_FLOAT, COLUMN_INTEGER, COLUMN_NULL, COLUMN_TEXT, COLUMN_UNKNOWN, inTransaction -
Constructor Summary
ConstructorsConstructorDescriptionWraps the given database with a threadsafe version -
Method Summary
Modifier and TypeMethodDescriptionvoidStarts a transaction.voidchangeKey(DatabaseConfig config) Changes the key of this open database, or removes it entirely.longchanges()The number of rows the most recent INSERT, UPDATE or DELETE on this connection changed, as SQLite'schanges()reports it.voidclose()Closes the database on the worker, and shuts the worker down.voidCommits current transactionvoidcreateFunction(String name, int argCount, Function<Object[], Object> function) Makes a Java function callable from SQL on this connection, undernamewithargCountarguments (-1 for any number), replacing a function of the same name and arity.voidExecute an update query.voidExecute an update query with params.voidExecute an update query with params.executeQuery(String sql) This method should be called with SELECT type statements that return row set.executeQuery(String sql, Object... params) This method should be called with SELECT type statements that return row set it accepts object with params.executeQuery(String sql, String[] params) This method should be called with SELECT type statements that return row set.Returns the underlying easy thread we can use to pipe tasks to the db threadbooleanReports whether a transaction is currently open on this database.longThe rowid of the most recent successful INSERT on this connection, as SQLite'slast_insert_rowid()reports it, or 0 when there was none.voidRolls back current transactionbooleanTrue whenDatabase.createFunction(String, int, Function)works on this database.Methods inherited from class Database
abandonFailedCommit, beforeFirst, beginTransactionMode, checkBeginTransaction, checkEndTransaction, checkNoTransactionForKeyChange, coerceToText, count, decrypt, delete, encrypt, executeStatus, exists, failStatus, forgetManagedKey, getDatabasePath, getStatusMessage, getValue, getValues, hasAttachments, isBlobQueryParameterSupported, isCustomPathSupported, isDatabaseBeingDeleted, isEncrypted, isEncryptionSupported, isInMemorySupported, isLegacyBehavior, isPlainStatement, markTransactionEnded, normalizeDatabaseKey, normalizeDatabasePathKey, noteConnectionClosed, noteEngineTransactionState, noteFirstStatementTransactionControl, noteScriptTransactionControl, openDatabaseCount, openInMemory, openOrCreate, openOrCreate, registerOpenDatabase, releaseKeyChangeClaim, releaseOpenDatabase, requireAttachmentsHeld, requireQueryStatement, requireSoleConnectionForKeyChange, reserveAttachments, reserveAttachments, setLegacyBehavior, supportsNestedTransactions, supportsWasNull, toPragmaLiteral, transactionControlKeyword, wasNull
-
Constructor Details
-
ThreadSafeDatabase
Wraps the given database with a threadsafe version
Parameters
db: the database
-
-
Method Details
-
getThread
Returns the underlying easy thread we can use to pipe tasks to the db thread
Returns
the easy thread object
-
beginTransaction
Description copied from class:DatabaseStarts a transaction.
Transactions are flat. Calling this while a transaction is already open throws, and committing or rolling back returns the connection to autocommit. Closing a database with an open transaction rolls it back.
Throws
IOException: if the database is not open, or a transaction is already in progress
- Specified by:
beginTransactionin classDatabase- Throws:
IOException
-
commitTransaction
Description copied from class:DatabaseCommits current transaction
NOTE: Not supported in Javascript port. This method will do nothing when running in Javascript.
Throws
IOException: if database is not opened or transaction was not started
- Specified by:
commitTransactionin classDatabase- Throws:
IOException
-
rollbackTransaction
Description copied from class:DatabaseRolls back current transaction
NOTE: Not supported in Javascript port. This method will do nothing when running in Javascript.
Throws
IOException: if database is not opened or transaction was not started
- Specified by:
rollbackTransactionin classDatabase- Throws:
IOException
-
isInTransaction
public boolean isInTransaction()Description copied from class:DatabaseReports whether a transaction is currently open on this database.
Returns
true between a successful
#beginTransaction()and its commit or rollback- Overrides:
isInTransactionin classDatabase
-
changeKey
Description copied from class:DatabaseChanges the key of this open database, or removes it entirely.
Passing a plaintext config decrypts the database. The engine performs the conversion as a single transaction and preserves schema metadata such as
PRAGMA user_version.Ports that support encryption override this. The default implementation reports that the platform cannot do it; it is deliberately concrete rather than abstract, because
Databaseis public and is subclassed outside this repository.Parameters
config: the new key, orDatabaseConfig#plain()to decrypt
Throws
IOException: if the key cannot be changed
- Overrides:
changeKeyin classDatabase- Throws:
IOException
-
changes
Description copied from class:DatabaseThe number of rows the most recent INSERT, UPDATE or DELETE on this connection changed, as SQLite's
changes()reports it.The default implementation asks the engine with a query; ports whose engine they call directly answer without one.
Throws
IOException: if the engine cannot be asked
- Overrides:
changesin classDatabase- Throws:
IOException
-
lastInsertRowId
Description copied from class:DatabaseThe rowid of the most recent successful INSERT on this connection, as SQLite's
last_insert_rowid()reports it, or 0 when there was none.The default implementation asks the engine with a query; ports whose engine they call directly answer without one.
Throws
IOException: if the engine cannot be asked
- Overrides:
lastInsertRowIdin classDatabase- Throws:
IOException
-
supportsFunctions
public boolean supportsFunctions()Description copied from class:DatabaseTrue whenDatabase.createFunction(String, int, Function)works on this database. Android's framework SQLite has no API for it, and the browser's database is not SQLite.- Overrides:
supportsFunctionsin classDatabase
-
createFunction
public void createFunction(String name, int argCount, Function<Object[], Object> function) throws IOExceptionDescription copied from class:DatabaseMakes a Java function callable from SQL on this connection, under
namewithargCountarguments (-1 for any number), replacing a function of the same name and arity. Anullfunction removes it.The function receives the arguments, each
null(SQL NULL), aLong, aDouble, aStringor abyte[], and answers one of those same types; aBooleanis stored as 1 or 0, and any otherNumberas aLongor aDouble. ARuntimeExceptionit throws fails the statement with its message. It runs on the thread stepping the statement, once for every row the statement evaluates it on.Check
Database.supportsFunctions()first: where the platform's engine can't call back into the application (Android's framework SQLite has no API for it), this throws and the caller has to compute the value itself.The default implementation reports that the platform cannot do it; it is concrete rather than abstract because
Databaseis subclassed outside this repository.Throws
IOException: if the platform has no SQL functions, or the engine refuses the definition
- Overrides:
createFunctionin classDatabase- Throws:
IOException
-
close
Closes the database on the worker, and shuts the worker down.
Idempotent, and synchronous: it returns with the database closed, so a
delete()on the next line does not race it. If the worker was stopped from outside --getThread()is public, and bothkill()andkillWhenIdle()on it are calls anybody can make -- this waits for the work that worker had already accepted before closing the database itself, rather than closing it underneath an operation that is still running.- Specified by:
closein classDatabase- Throws:
IOException
-
execute
Description copied from class:DatabaseExecute an update query. Used for INSERT, UPDATE, DELETE and similar sql statements.
Parameters
sql: the sql to execute
Throws
IOException
- Specified by:
executein classDatabase- Throws:
IOException
-
execute
Description copied from class:DatabaseExecute an update query with params. Used for INSERT, UPDATE, DELETE and similar sql statements. The sql can be constructed with '?' and the params will be binded to the query
Parameters
-
sql: the sql to execute -
params: to bind to the query where the '?' exists
Throws
IOException
- Specified by:
executein classDatabase- Throws:
IOException
-
-
executeQuery
Description copied from class:DatabaseThis method should be called with SELECT type statements that return row set.
Parameters
-
sql: the sql to execute -
params: to bind to the query where the '?' exists
Returns
a cursor to iterate over the results
Throws
IOException
- Specified by:
executeQueryin classDatabase- Throws:
IOException
-
-
executeQuery
Description copied from class:DatabaseThis method should be called with SELECT type statements that return row set.
Parameters
sql: the sql to execute
Returns
a cursor to iterate over the results
Throws
IOException
- Specified by:
executeQueryin classDatabase- Throws:
IOException
-
executeQuery
Description copied from class:DatabaseThis method should be called with SELECT type statements that return row set it accepts object with params.
Parameters
-
sql: the sql to execute -
params: @param params to bind to the query where the '?' exists, supported object types are String, byte[], Double, Long and null
Returns
a cursor to iterate over the results
Throws
IOException
- Overrides:
executeQueryin classDatabase- Throws:
IOException
-
-
execute
Description copied from class:DatabaseExecute an update query with params. Used for INSERT, UPDATE, DELETE and similar sql statements. The sql can be constructed with '?' and the params will be binded to the query
Parameters
-
sql: the sql to execute -
params: @param params to bind to the query where the '?' exists, supported object types are String, byte[], Double, Long and null
Throws
IOException
- Overrides:
executein classDatabase- Throws:
IOException
-
-