[关闭]
@Fancy-Bai 2017-08-03T02:43:26.000000Z 字数 64562 阅读 2387

Cordova/PhoneGap SQLCipher adapter plugin

Cordova-plugin


Cordova/PhoneGap SQLCipher adapter plugin

Native interface to sqlcipher in a Cordova/PhoneGap plugin for Android, iOS, macOS, and Windows 10 (UWP), with API similar to HTML5/Web SQL API.

License for Android and Windows versions: MIT or Apache 2.0

License for iOS/macOS version: MIT only

Android Circle-CI (full suite) iOS Travis-CI (partial suite)
Cordova-sqlcipher-adapter.svg?style=svg未知大小 Build Status

WARNING: In case you lose the database password you have no way to recover the data.

IMPORTANT: EXPORT REQUIREMENTS

IMPORTANT EXPORT REQUIREMENTS described at: https://discuss.zetetic.net/t/export-requirements-for-applications-using-sqlcipher/47

About this version

Version with SQLCipher

Services available

The primary author and maintainer @brodybits (Christopher J. Brody aka Chris Brody) is available for part-time contract assignments. Services available for this project include:

Other services available include:

For more information:
- http://litehelpers.net/
-

A quick tour

To open a database:

  1. var db = null;
  2. document.addEventListener('deviceready', function() {
  3. db = window.sqlitePlugin.openDatabase({name: 'demo.db', key: 'your-password-here', location: 'default'});
  4. });

IMPORTANT: Like with the other Cordova plugins your application must wait for the deviceready event. This is especially tricky in Angular/ngCordova/Ionic controller/factory/service callbacks which may be triggered before the deviceready event is fired.

To populate a database using the standard transaction API:

  1. db.transaction(function(tx) {
  2. tx.executeSql('CREATE TABLE IF NOT EXISTS DemoTable (name, score)');
  3. tx.executeSql('INSERT INTO DemoTable VALUES (?,?)', ['Alice', 101]);
  4. tx.executeSql('INSERT INTO DemoTable VALUES (?,?)', ['Betty', 202]);
  5. }, function(error) {
  6. console.log('Transaction ERROR: ' + error.message);
  7. }, function() {
  8. console.log('Populated database OK');
  9. });

To check the data using the standard transaction API:

  1. db.transaction(function(tx) {
  2. tx.executeSql('SELECT count(*) AS mycount FROM DemoTable', [], function(tx, rs) {
  3. console.log('Record count (expected to be 2): ' + rs.rows.item(0).mycount);
  4. }, function(tx, error) {
  5. console.log('SELECT error: ' + error.message);
  6. });
  7. });

To populate a database using the SQL batch API:

  1. db.sqlBatch([
  2. 'CREATE TABLE IF NOT EXISTS DemoTable (name, score)',
  3. [ 'INSERT INTO DemoTable VALUES (?,?)', ['Alice', 101] ],
  4. [ 'INSERT INTO DemoTable VALUES (?,?)', ['Betty', 202] ],
  5. ], function() {
  6. console.log('Populated database OK');
  7. }, function(error) {
  8. console.log('SQL batch ERROR: ' + error.message);
  9. });

To check the data using the single SQL statement API:

  1. db.executeSql('SELECT count(*) AS mycount FROM DemoTable', [], function(rs) {
  2. console.log('Record count (expected to be 2): ' + rs.rows.item(0).mycount);
  3. }, function(error) {
  4. console.log('SELECT SQL statement ERROR: ' + error.message);
  5. });

See the Sample section for a sample with a more detailed explanation.

Status

Announcements

Highlights

TIP: It is possible to migrate from Cordova to a pure native solution and continue using the data stored by this plugin.

Some apps using Cordova SQLCipher adapter

TBD YOUR APP HERE

Getting started

These prereqisites are very well documented in a number of excellent resources including:
- http://cordova.apache.org/ (redirected from http://cordova.io)
- http://www.tutorialspoint.com/cordova/
- https://ccoenraets.github.io/cordova-tutorial/
- https://www.toptal.com/mobile/developing-mobile-applications-with-apache-cordova
- http://www.tutorialspoint.com/cordova/index.htm

More resources can be found by https://www.google.com/search?q=cordova+tutorial. There are even some tutorials available on YouTube as well.

In addition, this guide assumes a basic knowledge of some key JavaScript concepts such as variables, function calls, and callback functions. There is an excellent explanation of JavaScript callbacks at http://cwbuecheler.com/web/tutorials/2013/javascript-callbacks/.

MAJOR TIPS: As described in the Installing section:
- It is recommended to use the --save flag when installing plugins to track them in config.xml. If all plugins are tracked in config.xml then there is no need to commit the plugins subdirectory tree into the source repository.
- In general it is not recommended to commit the platforms subdirectory tree into the source repository.

NOTICE: This plugin is only supported with the Cordova CLI. This plugin is not supported with other Cordova/PhoneGap systems such as PhoneGap CLI, PhoneGap Build, Plugman, Intel XDK, Webstorm, etc.

Windows platform notes

The Windows platform can present a number of challenges which increase when using this plugin. The following tips are recommended for getting started with Windows:

Quick installation

Use the following command to install this plugin from the Cordova CLI:

  1. cordova plugin add cordova-sqlcipher-adapter --save

Add any desired platform(s) if not already present, for example:

  1. cordova platform add android

OPTIONAL: prepare before building (MANDATORY for cordova-ios older than 4.3.0 (Cordova CLI 6.4.0))

  1. cordova prepare

or to prepare for a single platform, Android for example:

  1. cordova prepare android

Please see the Installing section for more details.

NOTE: The new brodybits / cordova-sqlite-test-app project includes the echo test, self test, and string test described below along with some more sample functions.

Self test

Try the following programs to verify successful installation and operation:

Echo test - verify successful installation and build:

  1. document.addEventListener('deviceready', function() {
  2. window.sqlitePlugin.echoTest(function() {
  3. console.log('ECHO test OK');
  4. });
  5. });

Self test - automatically verify basic database access operations including opening a database; basic CRUD operations (create data in a table, read the data from the table, update the data, and delete the data); close and delete the database:

  1. document.addEventListener('deviceready', function() {
  2. window.sqlitePlugin.selfTest(function() {
  3. console.log('SELF test OK');
  4. });
  5. });

NOTE: It may be easier to use a JavaScript or native alert function call along with (or instead of) console.log to verify that the installation passes both tests. Same for the SQL string test variations below. (Note that the Windows platform does not support the standard alert function, please use cordova-plugin-dialogs instead.)

SQL string test

This test verifies that you can open a database, execute a basic SQL statement, and get the results (should be TEST STRING):

  1. document.addEventListener('deviceready', function() {
  2. var db = window.sqlitePlugin.openDatabase({name: 'test.db', location: 'default'});
  3. db.transaction(function(tr) {
  4. tr.executeSql("SELECT upper('Test string') AS upperString", [], function(tr, rs) {
  5. console.log('Got upperString result: ' + rs.rows.item(0).upperString);
  6. });
  7. });
  8. });

Here is a variation that uses a SQL parameter instead of a string literal:

  1. document.addEventListener('deviceready', function() {
  2. var db = window.sqlitePlugin.openDatabase({name: 'test.db', location: 'default'});
  3. db.transaction(function(tr) {
  4. tr.executeSql('SELECT upper(?) AS upperString', ['Test string'], function(tr, rs) {
  5. console.log('Got upperString result: ' + rs.rows.item(0).upperString);
  6. });
  7. });
  8. });

Moving forward

It is recommended to read through the usage and sample sections before building more complex applications. In general it is recommended to start by doing things one step at a time, especially when an application does not work as expected.

The new brodybits / cordova-sqlite-test-app sample is intended to be a boilerplate to reproduce and demonstrate any issues you may have with this plugin. You may also use it as a starting point to build a new app.

In case you get stuck with something please read through the support section and follow the instructions before raising an issue. Professional support is also available by contacting:

Plugin usage examples

Plugin tutorials

NOTICE: The above tutorial shows cordova plugin add cordova-sqlite-storage with the --save flag missing. Please be sure to use the --save flag to keep the plugins in config.xml.

Other plugin tutorials wanted ref: litehelpers/Cordova-sqlite-storage#609

SQLite resources

Some other Cordova resources

Some apps using this plugin

Security

Security of sensitive data

According to Web SQL Database API 7.2 Sensitivity of data:

User agents should treat persistently stored data as potentially sensitive; it's quite possible for e-mails, calendar appointments, health records, or other confidential documents to be stored in this mechanism.

To this end, user agents should ensure that when deleting data, it is promptly deleted from the underlying storage.

Unfortunately this plugin will not actually overwrite the deleted content unless the secure_delete PRAGMA is used.

SQL injection

As "strongly recommended" by Web SQL Database API 8.5 SQL injection:

Authors are strongly recommended to make use of the ? placeholder feature of the executeSql() method, and to never construct SQL statements on the fly.

Avoiding data loss

Deviations

Some known deviations from the Web SQL database standard

Security of deleted data

See Security of sensitive data in the Security section above.

Other differences with WebKit Web SQL implementations

Known issues

Some more known issues are tracked in the open Cordova-sqlite-storage bugs.

Other limitations

Some more limitations are tracked in the open Cordova-sqlite-storage documentation issues.

Further testing needed

Some tips and tricks

Pitfalls

Some common pitfall(s)

Some weird pitfall(s)

Windows platform pitfalls

General Cordova pitfalls

Documented in: brodybits / Avoiding-some-Cordova-pitfalls

General SQLite pitfalls

From https://www.sqlite.org/datatype3.html#section_1:

SQLite uses a more general dynamic type system.

This is generally nice to have, especially in conjunction with a dynamically typed language such as JavaScript. Here are some major SQLite data typing principles:
- From https://www.sqlite.org/datatype3.html#section_3: the CREATE TABLE SQL statement declares each column with one of the following type affinities: TEXT, NUMERIC, INTEGER, REAL, or BLOB.
- From https://www.sqlite.org/datatype3.html#section_3_1 with column type affinity determination rules: it should be possible to do CREATE TABLE with columns of almost any type name (for example: CREATE TABLE MyTable (data ABC);) and each column type affinity is determined according to pattern matching. If a declared column type name does not match any of the patterns the column has NUMERIC affinity.
- From https://www.sqlite.org/datatype3.html#section_3_2: a column with no data type name specified actually gets the BLOB affinity.

However there are some possible gotchas:

  1. From https://www.sqlite.org/datatype3.html#section_3_2:

    Note that a declared type of "FLOATING POINT" would give INTEGER affinity, not REAL affinity, due to the "INT" at the end of "POINT". And the declared type of "STRING" has an affinity of NUMERIC, not TEXT.

  2. From ibid: a column declared as "DATETIME" has NUMERIC affinity, which gives no hint whether an INTEGER Unix time value, a REAL Julian time value, or possibly even a TEXT ISO8601 date/time string may be stored (further refs: https://www.sqlite.org/datatype3.html#section_2_2, https://www.sqlite.org/datatype3.html#section_3)

From https://groups.google.com/forum/#!topic/phonegap/za7z51_fKRw, as discussed in litehelpers/Cordova-sqlite-storage#546: it was discovered that are some more points of possible confusion with date/time. For example, there is also a datetime function that returns date/time in TEXT string format. This should be considered a case of "DATETIME" overloading since SQLite is not case sensitive. This could really become confusing if different programmers or functions consider date/time to be stored in different ways.

FUTURE TBD: Proper date/time handling will be further tested and documented at some point.

Major TODOs

For future considertion

Alternatives

NOTE: None of these alternatives currently support SQLCipher.

Other versions

Other SQLite adapter projects

Alternative solutions

Usage

Self-test functions

To verify that both the Javascript and native part of this plugin are installed in your application:

  1. window.sqlitePlugin.echoTest(successCallback, errorCallback);

To verify that this plugin is able to open a database (named ___$$$___litehelpers___$$$___test___$$$___.db), execute the CRUD (create, read, update, and delete) operations, and clean it up properly:

  1. window.sqlitePlugin.selfTest(successCallback, errorCallback);

IMPORTANT: Please wait for the 'deviceready' event (see below for an example).

General

NOTE: If a sqlite statement in a transaction fails with an error, the error handler must return false in order to recover the transaction. This is correct according to the HTML5/Web SQL API standard. This is different from the WebKit implementation of Web SQL in Android and iOS which recovers the transaction if a sql error hander returns a non-true value.

See the Sample section for a sample with detailed explanations.

Opening a database

To open a database access handle object (in the new default location):

  1. var db = window.sqlitePlugin.openDatabase({name: 'my.db', key: 'your-password-here', location: 'default'}, successcb, errorcb);

WARNING: The new "default" location value is NOT the same as the old default location and would break an upgrade for an app that was using the old default value (0) on iOS.

To specify a different location (affects iOS/macOS only):

  1. var db = window.sqlitePlugin.openDatabase({name: 'my.db', key: 'your-password-here', iosDatabaseLocation: 'Library'}, successcb, errorcb);

where the iosDatabaseLocation option may be set to one of the following choices:
- default: Library/LocalDatabase subdirectory - NOT visible to iTunes and NOT backed up by iCloud
- Library: Library subdirectory - backed up by iCloud, NOT visible to iTunes
- Documents: Documents subdirectory - visible to iTunes and backed up by iCloud

WARNING: Again, the new "default" iosDatabaseLocation value is NOT the same as the old default location and would break an upgrade for an app using the old default value (0) on iOS.

ALTERNATIVE (deprecated):
- var db = window.sqlitePlugin.openDatabase({name: 'my.db', key: 'your-password-here', location: 1}, successcb, errorcb);

with the location option set to one the following choices (affects iOS only):
- 0 (default): Documents - visible to iTunes and backed up by iCloud
- 1: Library - backed up by iCloud, NOT visible to iTunes
- 2: Library/LocalDatabase - NOT visible to iTunes and NOT backed up by iCloud (same as using "default")

No longer supported (see tip below to overwrite window.openDatabase): var db = window.sqlitePlugin.openDatabase("myDatabase.db", "1.0", "Demo", -1);

IMPORTANT: Please wait for the 'deviceready' event, as in the following example:

  1. // Wait for Cordova to load
  2. document.addEventListener('deviceready', onDeviceReady, false);
  3. // Cordova is ready
  4. function onDeviceReady() {
  5. var db = window.sqlitePlugin.openDatabase({name: 'my.db', key: 'your-password-here', location: 'default'});
  6. // ...
  7. }

The successcb and errorcb callback parameters are optional but can be extremely helpful in case anything goes wrong. For example:

  1. window.sqlitePlugin.openDatabase({name: 'my.db', key: 'your-password-here', location: 'default'}, function(db) {
  2. db.transaction(function(tx) {
  3. // ...
  4. }, function(err) {
  5. console.log('Open database ERROR: ' + JSON.stringify(err));
  6. });
  7. });

If any sql statements or transactions are attempted on a database object before the openDatabase result is known, they will be queued and will be aborted in case the database cannot be opened.

DATABASE NAME NOTES:

OTHER NOTES:
- The database file name should include the extension, if desired.
- It is possible to open multiple database access handle objects for the same database.
- The database handle access object can be closed as described below.

Web SQL replacement tip:

To overwrite window.openDatabase:

  1. window.openDatabase = function(dbname, ignored1, ignored2, ignored3) {
  2. return window.sqlitePlugin.openDatabase({name: dbname, location: 'default'});
  3. };

iCloud backup notes

As documented in the "A User’s iCloud Storage Is Limited" section of iCloudFundamentals in Mac Developer Library iCloud Design Guide (near the beginning):

  • DO store the following in iCloud:
    • [other items omitted]
    • Change log files for a SQLite database (a SQLite database’s store file must never be stored in iCloud)
  • DO NOT store the following in iCloud:
    • [items omitted]
- iCloudFundamentals in Mac Developer Library iCloud Design Guide

How to disable iCloud backup

Use the location or iosDatabaseLocation option in sqlitePlugin.openDatabase() to store the database in a subdirectory that is NOT backed up to iCloud, as described in the section below.

NOTE: Changing BackupWebStorage in config.xml has no effect on a database created by this plugin. BackupWebStorage applies only to local storage and/or Web SQL storage created in the WebView (not using this plugin). For reference: phonegap/build#338 (comment)

SQL transactions

The following types of SQL transactions are supported by this version:
- Single-statement transactions
- SQL batch transactions
- Standard asynchronous transactions

NOTE: Transaction requests are kept in one queue per database and executed in sequential order, according to the HTML5/Web SQL API.

WARNING: It is possible to request a SQL statement list such as "SELECT 1; SELECT 2" within a single SQL statement string, however the plugin will only execute the first statement and silently ignore the others. This could result in data loss if such a SQL statement list with any INSERT or UPDATE statement(s) are included. For reference: litehelpers/Cordova-sqlite-storage#551

Single-statement transactions

Sample with INSERT:

  1. db.executeSql('INSERT INTO MyTable VALUES (?)', ['test-value'], function (resultSet) {
  2. console.log('resultSet.insertId: ' + resultSet.insertId);
  3. console.log('resultSet.rowsAffected: ' + resultSet.rowsAffected);
  4. }, function(error) {
  5. console.log('SELECT error: ' + error.message);
  6. });

Sample with SELECT:

  1. db.executeSql("SELECT LENGTH('tenletters') AS stringlength", [], function (resultSet) {
  2. console.log('got stringlength: ' + resultSet.rows.item(0).stringlength);
  3. }, function(error) {
  4. console.log('SELECT error: ' + error.message);
  5. });

NOTE/minor bug: The object returned by resultSet.rows.item(rowNumber) is not immutable. In addition, multiple calls to resultSet.rows.item(rowNumber) with the same rowNumber on the same resultSet object return the same object. For example, the following code will show Second uppertext result: ANOTHER:

  1. db.executeSql("SELECT UPPER('First') AS uppertext", [], function (resultSet) {
  2. var obj1 = resultSet.rows.item(0);
  3. obj1.uppertext = 'ANOTHER';
  4. console.log('Second uppertext result: ' + resultSet.rows.item(0).uppertext);
  5. console.log('SELECT error: ' + error.message);
  6. });

SQL batch transactions

Sample:

  1. db.sqlBatch([
  2. 'DROP TABLE IF EXISTS MyTable',
  3. 'CREATE TABLE MyTable (SampleColumn)',
  4. [ 'INSERT INTO MyTable VALUES (?)', ['test-value'] ],
  5. ], function() {
  6. db.executeSql('SELECT * FROM MyTable', [], function (resultSet) {
  7. console.log('Sample column value: ' + resultSet.rows.item(0).SampleColumn);
  8. });
  9. }, function(error) {
  10. console.log('Populate table error: ' + error.message);
  11. });

In case of an error, all changes in a sql batch are automatically discarded using ROLLBACK.

Standard asynchronous transactions

Standard asynchronous transactions follow the HTML5/Web SQL API which is very well documented and uses BEGIN and COMMIT or ROLLBACK to keep the transactions failure-safe. Here is a simple example:

  1. db.transaction(function(tx) {
  2. tx.executeSql('DROP TABLE IF EXISTS MyTable');
  3. tx.executeSql('CREATE TABLE MyTable (SampleColumn)');
  4. tx.executeSql('INSERT INTO MyTable VALUES (?)', ['test-value'], function(tx, resultSet) {
  5. console.log('resultSet.insertId: ' + resultSet.insertId);
  6. console.log('resultSet.rowsAffected: ' + resultSet.rowsAffected);
  7. }, function(tx, error) {
  8. console.log('INSERT error: ' + error.message);
  9. });
  10. }, function(error) {
  11. console.log('transaction error: ' + error.message);
  12. }, function() {
  13. console.log('transaction ok');
  14. });

In case of a read-only transaction, it is possible to use readTransaction which will not use BEGIN, COMMIT, or ROLLBACK:

  1. db.readTransaction(function(tx) {
  2. tx.executeSql("SELECT UPPER('Some US-ASCII text') AS uppertext", [], function(tx, resultSet) {
  3. console.log("resultSet.rows.item(0).uppertext: " + resultSet.rows.item(0).uppertext);
  4. }, function(tx, error) {
  5. console.log('SELECT error: ' + error.message);
  6. });
  7. }, function(error) {
  8. console.log('transaction error: ' + error.message);
  9. }, function() {
  10. console.log('transaction ok');
  11. });

WARNING: It is NOT allowed to execute sql statements on a transaction after it has finished. Here is an example from the Populating Cordova SQLite storage with the JQuery API post at http://www.brodybits.com/cordova/sqlite/api/jquery/2015/10/26/populating-cordova-sqlite-storage-with-the-jquery-api.html:

  1. // BROKEN SAMPLE:
  2. db.executeSql("DROP TABLE IF EXISTS tt");
  3. db.executeSql("CREATE TABLE tt (data)");
  4. db.transaction(function(tx) {
  5. $.ajax({
  6. url: 'https://api.github.com/users/litehelpers/repos',
  7. dataType: 'json',
  8. success: function(res) {
  9. console.log('Got AJAX response: ' + JSON.stringify(res));
  10. $.each(res, function(i, item) {
  11. console.log('REPO NAME: ' + item.name);
  12. tx.executeSql("INSERT INTO tt values (?)", JSON.stringify(item.name));
  13. });
  14. }
  15. });
  16. }, function(e) {
  17. console.log('Transaction error: ' + e.message);
  18. }, function() {
  19. // Check results:
  20. db.executeSql('SELECT COUNT(*) FROM tt', [], function(res) {
  21. console.log('Check SELECT result: ' + JSON.stringify(res.rows.item(0)));
  22. });
  23. });

You can find more details and a step-by-step description how to do this right in the Populating Cordova SQLite storage with the JQuery API post at: http://www.brodybits.com/cordova/sqlite/api/jquery/2015/10/26/populating-cordova-sqlite-storage-with-the-jquery-api.html

NOTE/minor bug: Just like the single-statement transaction described above, the object returned by resultSet.rows.item(rowNumber) is not immutable. In addition, multiple calls to resultSet.rows.item(rowNumber) with the same rowNumber on the same resultSet object return the same object. For example, the following code will show Second uppertext result: ANOTHER:

  1. db.readTransaction(function(tx) {
  2. tx.executeSql("SELECT UPPER('First') AS uppertext", [], function(tx, resultSet) {
  3. var obj1 = resultSet.rows.item(0);
  4. obj1.uppertext = 'ANOTHER';
  5. console.log('Second uppertext result: ' + resultSet.rows.item(0).uppertext);
  6. console.log('SELECT error: ' + error.message);
  7. });
  8. });

FUTURE TBD: It should be possible to get a row result object using resultSet.rows[rowNumber], also in case of a single-statement transaction. This is non-standard but is supported by the Chrome desktop browser.

Background processing

The threading model depends on which version is used:
- For Android, one background thread per db;
- for iOS/macOS, background processing using a very limited thread pool (only one thread working at a time);
- for Windows, no background processing.

Sample with PRAGMA feature

Creates a table, adds a single entry, then queries the count to check if the item was inserted as expected. Note that a new transaction is created in the middle of the first callback.

  1. // Wait for Cordova to load
  2. document.addEventListener('deviceready', onDeviceReady, false);
  3. // Cordova is ready
  4. function onDeviceReady() {
  5. var db = window.sqlitePlugin.openDatabase({name: 'my.db', location: 'default'});
  6. db.transaction(function(tx) {
  7. tx.executeSql('DROP TABLE IF EXISTS test_table');
  8. tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)');
  9. // demonstrate PRAGMA:
  10. db.executeSql("pragma table_info (test_table);", [], function(res) {
  11. console.log("PRAGMA res: " + JSON.stringify(res));
  12. });
  13. tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function(tx, res) {
  14. console.log("insertId: " + res.insertId + " -- probably 1");
  15. console.log("rowsAffected: " + res.rowsAffected + " -- should be 1");
  16. db.transaction(function(tx) {
  17. tx.executeSql("select count(id) as cnt from test_table;", [], function(tx, res) {
  18. console.log("res.rows.length: " + res.rows.length + " -- should be 1");
  19. console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1");
  20. });
  21. });
  22. }, function(e) {
  23. console.log("ERROR: " + e.message);
  24. });
  25. });
  26. }

NOTE: PRAGMA statements must be executed in executeSql() on the database object (i.e. db.executeSql()) and NOT within a transaction.

Sample with transaction-level nesting

In this case, the same transaction in the first executeSql() callback is being reused to run executeSql() again.

  1. // Wait for Cordova to load
  2. document.addEventListener('deviceready', onDeviceReady, false);
  3. // Cordova is ready
  4. function onDeviceReady() {
  5. var db = window.sqlitePlugin.openDatabase({name: "my.db", key: "your-password-here", location: 'default'});
  6. db.transaction(function(tx) {
  7. tx.executeSql('DROP TABLE IF EXISTS test_table');
  8. tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)');
  9. tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function(tx, res) {
  10. console.log("insertId: " + res.insertId + " -- probably 1");
  11. console.log("rowsAffected: " + res.rowsAffected + " -- should be 1");
  12. tx.executeSql("select count(id) as cnt from test_table;", [], function(tx, res) {
  13. console.log("res.rows.length: " + res.rows.length + " -- should be 1");
  14. console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1");
  15. });
  16. }, function(tx, e) {
  17. console.log("ERROR: " + e.message);
  18. });
  19. });
  20. }

This case will also works with Safari (WebKit) (with no encryption), assuming you replace window.sqlitePlugin.openDatabase with window.openDatabase.

Close a database object

This will invalidate all handle access handle objects for the database that is closed:

  1. db.close(successcb, errorcb);

It is OK to close the database within a transaction callback but NOT within a statement callback. The following example is OK:

  1. db.transaction(function(tx) {
  2. tx.executeSql("SELECT LENGTH('tenletters') AS stringlength", [], function(tx, res) {
  3. console.log('got stringlength: ' + res.rows.item(0).stringlength);
  4. });
  5. }, function(error) {
  6. // OK to close here:
  7. console.log('transaction error: ' + error.message);
  8. db.close();
  9. }, function() {
  10. // OK to close here:
  11. console.log('transaction ok');
  12. db.close(function() {
  13. console.log('database is closed ok');
  14. });
  15. });

The following example is NOT OK:

  1. // BROKEN:
  2. db.transaction(function(tx) {
  3. tx.executeSql("SELECT LENGTH('tenletters') AS stringlength", [], function(tx, res) {
  4. console.log('got stringlength: ' + res.rows.item(0).stringlength);
  5. // BROKEN - this will trigger the error callback:
  6. db.close(function() {
  7. console.log('database is closed ok');
  8. }, function(error) {
  9. console.log('ERROR closing database');
  10. });
  11. });
  12. });

BUG: It is currently NOT possible to close a database in a db.executeSql callback. For example:

  1. // BROKEN DUE TO BUG:
  2. db.executeSql("SELECT LENGTH('tenletters') AS stringlength", [], function (res) {
  3. var stringlength = res.rows.item(0).stringlength;
  4. console.log('got stringlength: ' + res.rows.item(0).stringlength);
  5. // BROKEN - this will trigger the error callback DUE TO BUG:
  6. db.close(function() {
  7. console.log('database is closed ok');
  8. }, function(error) {
  9. console.log('ERROR closing database');
  10. });
  11. });

SECOND BUG: When a database connection is closed, any queued transactions are left hanging. All pending transactions should be errored when a database connection is closed.

NOTE: As described above, if multiple database access handle objects are opened for the same database and one database handle access object is closed, the database is no longer available for the other database handle objects. Possible workarounds:
- It is still possible to open one or more new database handle objects on a database that has been closed.
- It should be OK not to explicitly close a database handle since database transactions are ACID compliant and the app's memory resources are cleaned up by the system upon termination.

FUTURE TBD: dispose method on the database access handle object, such that a database is closed once all access handle objects are disposed.

Delete a database

  1. window.sqlitePlugin.deleteDatabase({name: 'my.db', location: 'default'}, successcb, errorcb);

with location or iosDatabaseLocation parameter required as described above for openDatabase (affects iOS/macOS only)

BUG: When a database is deleted, any queued transactions for that database are left hanging. All pending transactions should be errored when a database is deleted.

Database schema versions

The transactional nature of the API makes it relatively straightforward to manage a database schema that may be upgraded over time (adding new columns or new tables, for example). Here is the recommended procedure to follow upon app startup:
- Check your database schema version number (you can use db.executeSql since it should be a very simple query)
- If your database needs to be upgraded, do the following within a single transaction to be failure-safe:
- Create your database schema version table (single row single column) if it does not exist (you can check the sqlite_master table as described at: http://stackoverflow.com/questions/1601151/how-do-i-check-in-sqlite-whether-a-table-exists)
- Add any missing columns and tables, and apply any other changes necessary

IMPORTANT: Since we cannot be certain when the users will actually update their apps, old schema versions will have to be supported for a very long time.

Use with Ionic/ngCordova/Angular

Ionic 2

Tutorials with Ionic 2:
- https://www.thepolyglotdeveloper.com/2016/08/using-sqlstorage-instead-sqlite-ionic-2-app/ (title is somewhat misleading, "SQL storage" does use this sqlite plugin)
- https://www.thepolyglotdeveloper.com/2015/12/use-sqlite-in-ionic-2-instead-of-local-storage/ (older tutorial)

Sample for Ionic 2 wanted ref: litehelpers/Cordova-sqlite-storage#585

Ionic 1

Tutorial with Ionic 1: https://blog.nraboy.com/2014/11/use-sqlite-instead-local-storage-ionic-framework/

A sample for Ionic 1 is provided at: litehelpers / Ionic-sqlite-database-example

Documentation at: http://ngcordova.com/docs/plugins/sqlite/

Other resource (apparently for Ionic 1): https://www.packtpub.com/books/content/how-use-sqlite-ionic-store-data

NOTE: Some Ionic and other Angular pitfalls are described above.

Installing

Easy installation with Cordova CLI tool

  1. npm install -g cordova # (in case you don't have cordova)
  2. cordova create MyProjectFolder com.my.project MyProject && cd MyProjectFolder # if you are just starting
  3. cordova plugin add cordova-sqlcipher-adapter --save
  4. cordova platform add <desired platform> # repeat for all desired platform(s)
  5. cordova prepare # OPTIONAL (MANDATORY cordova-ios older than 4.3.0 (Cordova CLI 6.4.0))

Additional Cordova CLI NOTES:

  1. cordova platform rm ios
  2. cordova platform add ios

or more drastically:

  1. rm -rf platforms
  2. cordova platform add ios

Plugin installation sources

Windows platform usage

This plugin can be challenging to use on Windows since it includes a native SQLite3 library that is built as a part of the Cordova app. Here are some requirements:

Installation test

Easy installation test

Use window.sqlitePlugin.echoTest and/or window.sqlitePlugin.selfTest as described above (please wait for the deviceready event).

Quick installation test

Assuming your app has a recent template as used by the Cordova create script, add the following code to the onDeviceReady function, after app.receivedEvent('deviceready');:

  1. window.sqlitePlugin.openDatabase({ name: 'hello-world.db', location: 'default' }, function (db) {
  2. db.executeSql("select length('tenletters') as stringlength", [], function (res) {
  3. var stringlength = res.rows.item(0).stringlength;
  4. console.log('got stringlength: ' + stringlength);
  5. document.getElementById('deviceready').querySelector('.received').innerHTML = 'stringlength: ' + stringlength;
  6. });
  7. });

Support

Free support policy

Free support is provided on a best-effort basis and is only available in public forums. Please follow the steps below to be sure you have done your best before requesting help.

Professional support

Professional support is available by contacting:

For more information: http://litehelpers.net/

Before seeking help

First steps:
- Verify that you have followed the steps in brodybits / Cordova-quick-start-checklist
- Try the self-test functions as described above
- Check the pitfalls and troubleshooting steps in the pitfalls section and brodybits / Avoiding-some-Cordova-pitfalls for possible troubleshooting

and check the following:
- You are using the latest version of the Plugin (Javascript and platform-specific part) from this repository.
- The plugin is installed correctly.
- You have included the correct version of cordova.js.
- You have registered the plugin properly in config.xml.

If you still cannot get something to work:
- create a fresh, clean Cordova project, ideally based on brodybits / cordova-sqlite-test-app;
- add this plugin according to the instructions above;
- double-check that you follwed the steps in brodybits / Cordova-quick-start-checklist;
- try a simple test program;
- double-check the pitfalls in brodybits / Avoiding-some-Cordova-pitfalls

Issues with AJAX

General: As documented above with a negative example the application must wait for the AJAX query to finish before starting a transaction and adding the data elements.

In case of issues it is recommended to rework the reproduction program insert the data from a JavaScript object after a delay. There is already a test function for this in brodybits / cordova-sqlite-test-app.

FUTURE TBD examples

Test program to seek help

If you continue to see the issue: please make the simplest test program possible based on brodybits / cordova-sqlite-test-app to demonstrate the issue with the following characteristics:
- it completely self-contained, i.e. it is using no extra libraries beyond cordova & SQLitePlugin.js;
- if the issue is with adding data to a table, that the test program includes the statements you used to open the database and create the table;
- if the issue is with retrieving data from a table, that the test program includes the statements you used to open the database, create the table, and enter the data you are trying to retrieve.

What will be supported for free

It is recommended to make a small, self-contained test program based on brodybits / cordova-sqlite-test-app that can demonstrate your problem and post it. Please do not use any other plugins or frameworks than are absolutely necessary to demonstrate your problem.

In case of a problem with a pre-populated database, please post your entire project.

What is NOT supported for free

What information is needed for help

Please include the following:
- Which platform(s) Android/iOS/macOS/Windows
- Clear description of the issue
- A small, complete, self-contained program that demonstrates the problem, preferably as a Github project, based on brodybits / cordova-sqlite-test-app. ZIP/TGZ/BZ2 archive available from a public link is OK. No RAR or other such formats please.
- In case of a Windows build problem please capture the entire compiler output.

Please do NOT use any of these formats

Where to ask for help

Once you have followed the directions above, you may request free support in the following location(s):
- litehelpers / Cordova-sqlcipher-adapter / issues
- litehelpers / Cordova-sqlite-help

Please include the information described above otherwise.

Unit tests

Unit testing is done in spec.

running tests from shell

TBD test.sh not tested with sqlcipher version of this plugin: does not auto-remove correct plugin id

To run the tests from *nix shell, simply do either:

./bin/test.sh ios

or for Android:

./bin/test.sh android

To run from a windows powershell (here is a sample for android target):

.\bin\test.ps1 android

Adapters

PouchDB

The adapter is part of PouchDB as documented at:
- https://pouchdb.com/api.html#create_database (with key option)
- https://pouchdb.com/adapters.html
- http://pouchdb.com/faq.html

Lawnchair adapter

BROKEN: The Lawnchair adapter does not support the openDatabase options such as key, location or iosDatabaseLocation options and is therefore not expected to work with this plugin.

PouchDB

Adapters FUTURE TBD

Sample

Contributed by @Mikejo5000 (Mike Jones) from Microsoft.

Interact with the SQLite database

The SQLite storage plugin sample allows you to execute SQL statements to interact with the database. The code snippets in this section demonstrate simple plugin tasks including:

Open the database and create a table

Call the openDatabase() function to get started, passing in the name and location for the database.

  1. var db = window.sqlitePlugin.openDatabase({ name: 'my.db', location: 'default' }, function (db) {
  2. // Here, you might create or open the table.
  3. }, function (error) {
  4. console.log('Open database ERROR: ' + JSON.stringify(error));
  5. });

Create a table with three columns for first name, last name, and a customer account number. If the table already exists, this SQL statement opens the table.

  1. db.transaction(function (tx) {
  2. // ...
  3. tx.executeSql('CREATE TABLE customerAccounts (firstname, lastname, acctNo)');
  4. }, function (error) {
  5. console.log('transaction error: ' + error.message);
  6. }, function () {
  7. console.log('transaction ok');
  8. });

By wrapping the previous executeSql() function call in db.transaction(), we will make these tasks asynchronous. If you want to, you can use multiple executeSql() statements within a single transaction (not shown).

Add a row to the database

Add a row to the database using the INSERT INTO SQL statement.

  1. function addItem(first, last, acctNum) {
  2. db.transaction(function (tx) {
  3. var query = "INSERT INTO customerAccounts (firstname, lastname, acctNo) VALUES (?,?,?)";
  4. tx.executeSql(query, [first, last, acctNum], function(tx, res) {
  5. console.log("insertId: " + res.insertId + " -- probably 1");
  6. console.log("rowsAffected: " + res.rowsAffected + " -- should be 1");
  7. },
  8. function(tx, error) {
  9. console.log('INSERT error: ' + error.message);
  10. });
  11. }, function(error) {
  12. console.log('transaction error: ' + error.message);
  13. }, function() {
  14. console.log('transaction ok');
  15. });
  16. }

To add some actual rows in your app, call the addItem function several times.

  1. addItem("Fred", "Smith", 100);
  2. addItem("Bob", "Yerunkle", 101);
  3. addItem("Joe", "Auzomme", 102);
  4. addItem("Pete", "Smith", 103);

Read data from the database

Add code to read from the database using a SELECT statement. Include a WHERE condition to match the resultSet to the passed in last name.

  1. function getData(last) {
  2. db.transaction(function (tx) {
  3. var query = "SELECT firstname, lastname, acctNo FROM customerAccounts WHERE lastname = ?";
  4. tx.executeSql(query, [last], function (tx, resultSet) {
  5. for(var x = 0; x < resultSet.rows.length; x++) {
  6. console.log("First name: " + resultSet.rows.item(x).firstname +
  7. ", Acct: " + resultSet.rows.item(x).acctNo);
  8. }
  9. },
  10. function (tx, error) {
  11. console.log('SELECT error: ' + error.message);
  12. });
  13. }, function (error) {
  14. console.log('transaction error: ' + error.message);
  15. }, function () {
  16. console.log('transaction ok');
  17. });
  18. }

Remove a row from the database

Add a function to remove a row from the database that matches the passed in customer account number.

  1. function removeItem(acctNum) {
  2. db.transaction(function (tx) {
  3. var query = "DELETE FROM customerAccounts WHERE acctNo = ?";
  4. tx.executeSql(query, [acctNum], function (tx, res) {
  5. console.log("removeId: " + res.insertId);
  6. console.log("rowsAffected: " + res.rowsAffected);
  7. },
  8. function (tx, error) {
  9. console.log('DELETE error: ' + error.message);
  10. });
  11. }, function (error) {
  12. console.log('transaction error: ' + error.message);
  13. }, function () {
  14. console.log('transaction ok');
  15. });
  16. }

Update rows in the database

Add a function to update rows in the database for records that match the passed in customer account number. In this form, the statement will update multiple rows if the account numbers are not unique.

  1. function updateItem(first, id) {
  2. // UPDATE Cars SET Name='Skoda Octavia' WHERE Id=3;
  3. db.transaction(function (tx) {
  4. var query = "UPDATE customerAccounts SET firstname = ? WHERE acctNo = ?";
  5. tx.executeSql(query, [first, id], function(tx, res) {
  6. console.log("insertId: " + res.insertId);
  7. console.log("rowsAffected: " + res.rowsAffected);
  8. },
  9. function(tx, error) {
  10. console.log('UPDATE error: ' + error.message);
  11. });
  12. }, function(error) {
  13. console.log('transaction error: ' + error.message);
  14. }, function() {
  15. console.log('transaction ok');
  16. });
  17. }

To call the preceding function, add code like this in your app.

  1. updateItem("Yme", 102);

Close the database

When you are finished with your transactions, close the database. Call closeDB within the transaction success or failure callbacks (rather than the callbacks for executeSql()).

  1. function closeDB() {
  2. db.close(function () {
  3. console.log("DB closed!");
  4. }, function (error) {
  5. console.log("Error closing DB:" + error.message);
  6. });
  7. }

Source tree

Contributing

Community

Code

WARNING: Please do NOT propose changes from your default branch. Contributions may be rebased using git rebase or git cherry-pick and not merged.

Contact

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注