Bug 1561435 - Format storage/, a=automatic-formatting

# ignore-this-changeset

Differential Revision: https://phabricator.services.mozilla.com/D35935

--HG--
extra : source : 77bfd37cea066708241ba39795e94f5ee4a06ff6
This commit is contained in:
Victor Porof 2019-07-05 10:59:24 +02:00
parent 942931c838
commit 9eeaa5c80c
34 changed files with 761 additions and 536 deletions

View file

@ -45,7 +45,6 @@ module.exports = {
"overrides": [{ "overrides": [{
"files": [ "files": [
"devtools/**", "devtools/**",
"storage/**",
"taskcluster/**", "taskcluster/**",
"testing/**", "testing/**",
"toolkit/**", "toolkit/**",

View file

@ -40,7 +40,6 @@ toolkit/components/telemetry/datareporting-prefs.js
toolkit/components/telemetry/healthreport-prefs.js toolkit/components/telemetry/healthreport-prefs.js
# Ignore all top-level directories for now. # Ignore all top-level directories for now.
storage/**
taskcluster/** taskcluster/**
testing/** testing/**
toolkit/** toolkit/**

View file

@ -2,10 +2,13 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); var { XPCOMUtils } = ChromeUtils.import(
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); "resource://gre/modules/XPCOMUtils.jsm"
var {AppConstants} = ChromeUtils.import("resource://gre/modules/AppConstants.jsm"); );
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { AppConstants } = ChromeUtils.import(
"resource://gre/modules/AppConstants.jsm"
);
do_get_profile(); do_get_profile();
var gDBConn = null; var gDBConn = null;
@ -36,8 +39,13 @@ function getFakeDB() {
function deleteTestDB() { function deleteTestDB() {
print("*** Storage Tests: Trying to remove file!"); print("*** Storage Tests: Trying to remove file!");
var dbFile = getTestDB(); var dbFile = getTestDB();
if (dbFile.exists()) if (dbFile.exists()) {
try { dbFile.remove(false); } catch (e) { /* stupid windows box */ } try {
dbFile.remove(false);
} catch (e) {
/* stupid windows box */
}
}
} }
function cleanup() { function cleanup() {
@ -62,7 +70,9 @@ function asyncCleanup() {
// close the connection // close the connection
print("*** Storage Tests: Trying to asyncClose!"); print("*** Storage Tests: Trying to asyncClose!");
getOpenedDatabase().asyncClose(function() { closed = true; }); getOpenedDatabase().asyncClose(function() {
closed = true;
});
let tm = Cc["@mozilla.org/thread-manager;1"].getService(); let tm = Cc["@mozilla.org/thread-manager;1"].getService();
tm.spinEventLoopUntil(() => closed); tm.spinEventLoopUntil(() => closed);
@ -148,13 +158,19 @@ function expectError(aErrorCode, aFunction) {
aFunction(); aFunction();
} catch (e) { } catch (e) {
if (e.result != aErrorCode) { if (e.result != aErrorCode) {
do_throw("Got an exception, but the result code was not the expected " + do_throw(
"one. Expected " + aErrorCode + ", got " + e.result); "Got an exception, but the result code was not the expected " +
"one. Expected " +
aErrorCode +
", got " +
e.result
);
} }
exceptionCaught = true; exceptionCaught = true;
} }
if (!exceptionCaught) if (!exceptionCaught) {
do_throw(aFunction + " should have thrown an exception but did not!"); do_throw(aFunction + " should have thrown an exception but did not!");
}
} }
/** /**
@ -174,9 +190,16 @@ function verifyQuery(aSQLString, aBind, aResults) {
try { try {
Assert.ok(stmt.executeStep()); Assert.ok(stmt.executeStep());
let nCols = stmt.numEntries; let nCols = stmt.numEntries;
if (aResults.length != nCols) if (aResults.length != nCols) {
do_throw("Expected " + aResults.length + " columns in result but " + do_throw(
"there are only " + aResults.length + "!"); "Expected " +
aResults.length +
" columns in result but " +
"there are only " +
aResults.length +
"!"
);
}
for (let iCol = 0; iCol < nCols; iCol++) { for (let iCol = 0; iCol < nCols; iCol++) {
let expectedVal = aResults[iCol]; let expectedVal = aResults[iCol];
let valType = stmt.getTypeOfIndex(iCol); let valType = stmt.getTypeOfIndex(iCol);
@ -194,9 +217,11 @@ function verifyQuery(aSQLString, aBind, aResults) {
} else if (typeof expectedVal == "string") { } else if (typeof expectedVal == "string") {
Assert.equal(stmt.VALUE_TYPE_TEXT, valType); Assert.equal(stmt.VALUE_TYPE_TEXT, valType);
Assert.equal(expectedVal, stmt.getUTF8String(iCol)); Assert.equal(expectedVal, stmt.getUTF8String(iCol));
} else { // blob } else {
// blob
Assert.equal(stmt.VALUE_TYPE_BLOB, valType); Assert.equal(stmt.VALUE_TYPE_BLOB, valType);
let count = { value: 0 }, blob = { value: null }; let count = { value: 0 },
blob = { value: null };
stmt.getBlob(iCol, count, blob); stmt.getBlob(iCol, count, blob);
Assert.equal(count.value, expectedVal.length); Assert.equal(count.value, expectedVal.length);
for (let i = 0; i < count.value; i++) { for (let i = 0; i < count.value; i++) {
@ -261,8 +286,9 @@ function openAsyncDatabase(file, options) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let properties; let properties;
if (options) { if (options) {
properties = Cc["@mozilla.org/hash-property-bag;1"]. properties = Cc["@mozilla.org/hash-property-bag;1"].createInstance(
createInstance(Ci.nsIWritablePropertyBag); Ci.nsIWritablePropertyBag
);
for (let k in options) { for (let k in options) {
properties.setProperty(k, options[k]); properties.setProperty(k, options[k]);
} }

View file

@ -27,9 +27,9 @@ var tests = [test_vacuum];
function run_test() { function run_test() {
setup(); setup();
for (var i = 0; i < tests.length; i++) for (var i = 0; i < tests.length; i++) {
tests[i](); tests[i]();
}
cleanup(); cleanup();
} }

View file

@ -5,7 +5,9 @@
function setup() { function setup() {
getOpenedDatabase().createTable("t1", "x TEXT"); getOpenedDatabase().createTable("t1", "x TEXT");
var stmt = createStatement("INSERT INTO t1 (x) VALUES ('/mozilla.org/20070129_1/Europe/Berlin')"); var stmt = createStatement(
"INSERT INTO t1 (x) VALUES ('/mozilla.org/20070129_1/Europe/Berlin')"
);
stmt.execute(); stmt.execute();
stmt.finalize(); stmt.finalize();
} }
@ -14,7 +16,8 @@ function test_bug429521() {
var stmt = createStatement( var stmt = createStatement(
"SELECT DISTINCT(zone) FROM (" + "SELECT DISTINCT(zone) FROM (" +
"SELECT x AS zone FROM t1 WHERE x LIKE '/mozilla.org%'" + "SELECT x AS zone FROM t1 WHERE x LIKE '/mozilla.org%'" +
");"); ");"
);
print("*** test_bug429521: started"); print("*** test_bug429521: started");

View file

@ -4,11 +4,15 @@
function setup() { function setup() {
// Create the table // Create the table
getOpenedDatabase().createTable("test_bug444233", getOpenedDatabase().createTable(
"id INTEGER PRIMARY KEY, value TEXT"); "test_bug444233",
"id INTEGER PRIMARY KEY, value TEXT"
);
// Insert dummy data, using wrapper methods // Insert dummy data, using wrapper methods
var stmt = createStatement("INSERT INTO test_bug444233 (value) VALUES (:value)"); var stmt = createStatement(
"INSERT INTO test_bug444233 (value) VALUES (:value)"
);
stmt.params.value = "value1"; stmt.params.value = "value1";
stmt.execute(); stmt.execute();
stmt.finalize(); stmt.finalize();
@ -48,4 +52,3 @@ function run_test() {
test_bug444233(); test_bug444233();
cleanup(); cleanup();
} }

View file

@ -53,17 +53,21 @@ function new_file(name) {
function run_test() { function run_test() {
const kExpectedCacheSize = -2048; // 2MiB const kExpectedCacheSize = -2048; // 2MiB
let pageSizes = [ let pageSizes = [1024, 4096, 32768];
1024,
4096,
32768,
];
for (let i = 0; i < pageSizes.length; i++) { for (let i = 0; i < pageSizes.length; i++) {
let pageSize = pageSizes[i]; let pageSize = pageSizes[i];
check_size(getDatabase, check_size(
new_file("shared" + pageSize), pageSize, kExpectedCacheSize); getDatabase,
check_size(Services.storage.openUnsharedDatabase, new_file("shared" + pageSize),
new_file("unshared" + pageSize), pageSize, kExpectedCacheSize); pageSize,
kExpectedCacheSize
);
check_size(
Services.storage.openUnsharedDatabase,
new_file("unshared" + pageSize),
pageSize,
kExpectedCacheSize
);
} }
} }

View file

@ -23,7 +23,6 @@
* - test_double_asyncClose_throws * - test_double_asyncClose_throws
*/ */
/** /**
* Sanity check that our close indeed happens after asynchronously executed * Sanity check that our close indeed happens after asynchronously executed
* statements scheduled during the same turn of the event loop. Note that we * statements scheduled during the same turn of the event loop. Note that we
@ -41,8 +40,10 @@ add_task(async function test_asyncClose_does_not_complete_before_statements() {
// Issue the close. (And now the order of yielding doesn't matter.) // Issue the close. (And now the order of yielding doesn't matter.)
// Branch coverage: (asyncThread && mDBConn) // Branch coverage: (asyncThread && mDBConn)
await asyncClose(db); await asyncClose(db);
equal((await asyncStatementPromise), equal(
Ci.mozIStorageStatementCallback.REASON_FINISHED); await asyncStatementPromise,
Ci.mozIStorageStatementCallback.REASON_FINISHED
);
}); });
/** /**

View file

@ -49,14 +49,16 @@ add_task(async function test_first_create_and_add() {
stmts[1].bindBlobByIndex(3, BLOB, BLOB.length); stmts[1].bindBlobByIndex(3, BLOB, BLOB.length);
// asynchronously execute the statements // asynchronously execute the statements
let execResult = await executeMultipleStatementsAsync( let execResult = await executeMultipleStatementsAsync(db, stmts, function(
db, aResultSet
stmts, ) {
function(aResultSet) {
ok(false, "we only did inserts so we should not have gotten results!"); ok(false, "we only did inserts so we should not have gotten results!");
}); });
equal(Ci.mozIStorageStatementCallback.REASON_FINISHED, execResult, equal(
"execution should have finished successfully."); Ci.mozIStorageStatementCallback.REASON_FINISHED,
execResult,
"execution should have finished successfully."
);
// Check that the result is in the table // Check that the result is in the table
let stmt = db.createStatement( let stmt = db.createStatement(
@ -72,16 +74,15 @@ add_task(async function test_first_create_and_add() {
let blob = { value: null }; let blob = { value: null };
stmt.getBlob(3, count, blob); stmt.getBlob(3, count, blob);
Assert.equal(BLOB.length, count.value); Assert.equal(BLOB.length, count.value);
for (let i = 0; i < BLOB.length; i++) for (let i = 0; i < BLOB.length; i++) {
Assert.equal(BLOB[i], blob.value[i]); Assert.equal(BLOB[i], blob.value[i]);
}
} finally { } finally {
stmt.finalize(); stmt.finalize();
} }
// Make sure we have two rows in the table // Make sure we have two rows in the table
stmt = db.createStatement( stmt = db.createStatement("SELECT COUNT(1) FROM test");
"SELECT COUNT(1) FROM test"
);
try { try {
Assert.ok(stmt.executeStep()); Assert.ok(stmt.executeStep());
Assert.equal(2, stmt.getInt32(0)); Assert.equal(2, stmt.getInt32(0));
@ -101,15 +102,17 @@ add_task(async function test_last_multiple_bindings_on_statements() {
let stmts = []; let stmts = [];
let db = getOpenedDatabase(); let db = getOpenedDatabase();
let sqlString = "INSERT INTO test (id, string, number, nuller, blober) " + let sqlString =
"INSERT INTO test (id, string, number, nuller, blober) " +
"VALUES (:int, :text, :real, :null, :blob)"; "VALUES (:int, :text, :real, :null, :blob)";
// We run the same statement twice, and should insert 2 * AMOUNT_TO_ADD. // We run the same statement twice, and should insert 2 * AMOUNT_TO_ADD.
for (let i = 0; i < ITERATIONS; i++) { for (let i = 0; i < ITERATIONS; i++) {
// alternate the type of statement we create // alternate the type of statement we create
if (i % 2) if (i % 2) {
stmts[i] = db.createStatement(sqlString); stmts[i] = db.createStatement(sqlString);
else } else {
stmts[i] = db.createAsyncStatement(sqlString); stmts[i] = db.createAsyncStatement(sqlString);
}
let params = stmts[i].newBindingParamsArray(); let params = stmts[i].newBindingParamsArray();
for (let j = 0; j < AMOUNT_TO_ADD; j++) { for (let j = 0; j < AMOUNT_TO_ADD; j++) {
@ -137,20 +140,21 @@ add_task(async function test_last_multiple_bindings_on_statements() {
} }
// Execute asynchronously. // Execute asynchronously.
let execResult = await executeMultipleStatementsAsync( let execResult = await executeMultipleStatementsAsync(db, stmts, function(
db, aResultSet
stmts, ) {
function(aResultSet) {
ok(false, "we only did inserts so we should not have gotten results!"); ok(false, "we only did inserts so we should not have gotten results!");
}); });
equal(Ci.mozIStorageStatementCallback.REASON_FINISHED, execResult, equal(
"execution should have finished successfully."); Ci.mozIStorageStatementCallback.REASON_FINISHED,
execResult,
"execution should have finished successfully."
);
// Check to make sure we added all of our rows. // Check to make sure we added all of our rows.
try { try {
Assert.ok(countStmt.executeStep()); Assert.ok(countStmt.executeStep());
Assert.equal(currentRows + (ITERATIONS * AMOUNT_TO_ADD), Assert.equal(currentRows + ITERATIONS * AMOUNT_TO_ADD, countStmt.row.count);
countStmt.row.count);
} finally { } finally {
countStmt.finalize(); countStmt.finalize();
} }

View file

@ -14,20 +14,31 @@ const REAL = 3.23;
add_task(async function test_create_and_add() { add_task(async function test_create_and_add() {
let adb = await openAsyncDatabase(getTestDB()); let adb = await openAsyncDatabase(getTestDB());
let completion = await executeSimpleSQLAsync(adb, let completion = await executeSimpleSQLAsync(
"CREATE TABLE test (id INTEGER, string TEXT, number REAL)"); adb,
"CREATE TABLE test (id INTEGER, string TEXT, number REAL)"
);
Assert.equal(Ci.mozIStorageStatementCallback.REASON_FINISHED, completion); Assert.equal(Ci.mozIStorageStatementCallback.REASON_FINISHED, completion);
completion = await executeSimpleSQLAsync(adb, completion = await executeSimpleSQLAsync(
adb,
"INSERT INTO test (id, string, number) " + "INSERT INTO test (id, string, number) " +
"VALUES (" + INTEGER + ", \"" + TEXT + "\", " + REAL + ")"); "VALUES (" +
INTEGER +
', "' +
TEXT +
'", ' +
REAL +
")"
);
Assert.equal(Ci.mozIStorageStatementCallback.REASON_FINISHED, completion); Assert.equal(Ci.mozIStorageStatementCallback.REASON_FINISHED, completion);
let result = null; let result = null;
completion = await executeSimpleSQLAsync(adb, completion = await executeSimpleSQLAsync(
adb,
"SELECT string, number FROM test WHERE id = 1", "SELECT string, number FROM test WHERE id = 1",
function(aResultSet) { function(aResultSet) {
result = aResultSet.getNextRow(); result = aResultSet.getNextRow();
@ -41,8 +52,9 @@ add_task(async function test_create_and_add() {
Assert.notEqual(result, null); Assert.notEqual(result, null);
result = null; result = null;
await executeSimpleSQLAsync(adb, "SELECT COUNT(0) FROM test", await executeSimpleSQLAsync(adb, "SELECT COUNT(0) FROM test", function(
function(aResultSet) { aResultSet
) {
result = aResultSet.getNextRow(); result = aResultSet.getNextRow();
Assert.equal(1, result.getInt32(0)); Assert.equal(1, result.getInt32(0));
}); });
@ -52,13 +64,13 @@ add_task(async function test_create_and_add() {
await asyncClose(adb); await asyncClose(adb);
}); });
add_task(async function test_asyncClose_does_not_complete_before_statement() { add_task(async function test_asyncClose_does_not_complete_before_statement() {
let adb = await openAsyncDatabase(getTestDB()); let adb = await openAsyncDatabase(getTestDB());
let executed = false; let executed = false;
let reason = await executeSimpleSQLAsync(adb, "SELECT * FROM test", let reason = await executeSimpleSQLAsync(adb, "SELECT * FROM test", function(
function(aResultSet) { aResultSet
) {
let result = aResultSet.getNextRow(); let result = aResultSet.getNextRow();
Assert.notEqual(result, null); Assert.notEqual(result, null);
@ -67,8 +79,7 @@ add_task(async function test_asyncClose_does_not_complete_before_statement() {
Assert.equal(TEXT, result.getString(1)); Assert.equal(TEXT, result.getString(1));
Assert.equal(REAL, result.getDouble(2)); Assert.equal(REAL, result.getDouble(2));
executed = true; executed = true;
} });
);
Assert.equal(Ci.mozIStorageStatementCallback.REASON_FINISHED, reason); Assert.equal(Ci.mozIStorageStatementCallback.REASON_FINISHED, reason);

View file

@ -16,9 +16,10 @@ add_task(async function test_failsafe_close_of_async_connection() {
let db = getOpenedDatabase(); let db = getOpenedDatabase();
// do something async // do something async
let callbackInvoked = new Promise((resolve) => { let callbackInvoked = new Promise(resolve => {
db.executeSimpleSQLAsync("CREATE TABLE test (id INTEGER)", db.executeSimpleSQLAsync("CREATE TABLE test (id INTEGER)", {
{ handleCompletion: resolve }); handleCompletion: resolve,
});
}); });
// drop our reference and force a GC so the only live reference is owned by // drop our reference and force a GC so the only live reference is owned by

View file

@ -6,35 +6,43 @@
add_task(async function test_sync_conn() { add_task(async function test_sync_conn() {
// Interrupt can only be used on async connections. // Interrupt can only be used on async connections.
let db = getOpenedDatabase(); let db = getOpenedDatabase();
Assert.throws(() => db.interrupt(), Assert.throws(
() => db.interrupt(),
/NS_ERROR_ILLEGAL_VALUE/, /NS_ERROR_ILLEGAL_VALUE/,
"interrupt() should throw if invoked on a synchronous connection"); "interrupt() should throw if invoked on a synchronous connection"
);
db.close(); db.close();
}); });
add_task(async function test_wr_async_conn() { add_task(async function test_wr_async_conn() {
// Interrupt cannot be used on R/W async connections. // Interrupt cannot be used on R/W async connections.
let db = await openAsyncDatabase(getTestDB()); let db = await openAsyncDatabase(getTestDB());
Assert.throws(() => db.interrupt(), Assert.throws(
() => db.interrupt(),
/NS_ERROR_ILLEGAL_VALUE/, /NS_ERROR_ILLEGAL_VALUE/,
"interrupt() should throw if invoked on a R/W connection"); "interrupt() should throw if invoked on a R/W connection"
);
await asyncClose(db); await asyncClose(db);
}); });
add_task(async function test_closed_conn() { add_task(async function test_closed_conn() {
let db = await openAsyncDatabase(getTestDB(), {readOnly: true}); let db = await openAsyncDatabase(getTestDB(), { readOnly: true });
await asyncClose(db); await asyncClose(db);
Assert.throws(() => db.interrupt(), Assert.throws(
() => db.interrupt(),
/NS_ERROR_NOT_INITIALIZED/, /NS_ERROR_NOT_INITIALIZED/,
"interrupt() should throw if invoked on a closed connection"); "interrupt() should throw if invoked on a closed connection"
);
}); });
add_task({ add_task(
{
// We use a timeout in the test that may be insufficient on Android emulators. // We use a timeout in the test that may be insufficient on Android emulators.
// We don't really need the Android coverage, so skip on Android. // We don't really need the Android coverage, so skip on Android.
skip_if: () => AppConstants.platform == "android", skip_if: () => AppConstants.platform == "android",
}, async function test_async_conn() { },
let db = await openAsyncDatabase(getTestDB(), {readOnly: true}); async function test_async_conn() {
let db = await openAsyncDatabase(getTestDB(), { readOnly: true });
// This query is built to hang forever. // This query is built to hang forever.
let stmt = db.createAsyncStatement(` let stmt = db.createAsyncStatement(`
WITH RECURSIVE test(n) AS ( WITH RECURSIVE test(n) AS (
@ -68,9 +76,12 @@ add_task({
db.interrupt(); db.interrupt();
Assert.equal(await completePromise, Assert.equal(
await completePromise,
Ci.mozIStorageStatementCallback.REASON_CANCELED, Ci.mozIStorageStatementCallback.REASON_CANCELED,
"Should have been canceled"); "Should have been canceled"
);
await asyncClose(db); await asyncClose(db);
}); }
);

View file

@ -12,25 +12,22 @@
// Test Functions // Test Functions
function test_params_enumerate() { function test_params_enumerate() {
let stmt = createStatement( let stmt = createStatement("SELECT * FROM test WHERE id IN (:a, :b, :c)");
"SELECT * FROM test WHERE id IN (:a, :b, :c)"
);
// Make sure they are right. // Make sure they are right.
let expected = [0, 1, 2, "a", "b", "c", "length"]; let expected = [0, 1, 2, "a", "b", "c", "length"];
let index = 0; let index = 0;
for (let name in stmt.params) { for (let name in stmt.params) {
if (name == "QueryInterface") if (name == "QueryInterface") {
continue; continue;
}
Assert.equal(name, expected[index++]); Assert.equal(name, expected[index++]);
} }
Assert.equal(index, 7); Assert.equal(index, 7);
} }
function test_params_prototype() { function test_params_prototype() {
let stmt = createStatement( let stmt = createStatement("SELECT * FROM sqlite_master");
"SELECT * FROM sqlite_master"
);
// Set a property on the prototype and make sure it exist (will not be a // Set a property on the prototype and make sure it exist (will not be a
// bindable parameter, however). // bindable parameter, however).
@ -42,9 +39,7 @@ function test_params_prototype() {
} }
function test_row_prototype() { function test_row_prototype() {
let stmt = createStatement( let stmt = createStatement("SELECT * FROM sqlite_master");
"SELECT * FROM sqlite_master"
);
Assert.ok(stmt.executeStep()); Assert.ok(stmt.executeStep());
@ -59,9 +54,7 @@ function test_row_prototype() {
} }
function test_row_enumerate() { function test_row_enumerate() {
let stmt = createStatement( let stmt = createStatement("SELECT * FROM test");
"SELECT * FROM test"
);
Assert.ok(stmt.executeStep()); Assert.ok(stmt.executeStep());
@ -82,9 +75,13 @@ function test_row_enumerate() {
let savedOffRow = stmt.row; let savedOffRow = stmt.row;
stmt = null; stmt = null;
Cu.forceGC(); Cu.forceGC();
Assert.throws(() => { return savedOffRow.string; }, Assert.throws(
() => {
return savedOffRow.string;
},
/NS_ERROR_NOT_INITIALIZED/, /NS_ERROR_NOT_INITIALIZED/,
"GC'ed statement should throw"); "GC'ed statement should throw"
);
} }
function test_params_gets_sync() { function test_params_gets_sync() {
@ -142,9 +139,7 @@ function run_test() {
// Create our database. // Create our database.
getOpenedDatabase().executeSimpleSQL( getOpenedDatabase().executeSimpleSQL(
"CREATE TABLE test (" + "CREATE TABLE test (" + "id INTEGER PRIMARY KEY, string TEXT" + ")"
"id INTEGER PRIMARY KEY, string TEXT" +
")"
); );
getOpenedDatabase().executeSimpleSQL( getOpenedDatabase().executeSimpleSQL(
"INSERT INTO test (id, string) VALUES (123, 'foo')" "INSERT INTO test (id, string) VALUES (123, 'foo')"

View file

@ -176,8 +176,17 @@ function test_like_8() {
stmt.finalize(); stmt.finalize();
} }
var tests = [test_count, test_like_1, test_like_2, test_like_3, test_like_4, var tests = [
test_like_5, test_like_6, test_like_7, test_like_8]; test_count,
test_like_1,
test_like_2,
test_like_3,
test_like_4,
test_like_5,
test_like_6,
test_like_7,
test_like_8,
];
function run_test() { function run_test() {
setup(); setup();
@ -188,4 +197,3 @@ function run_test() {
cleanup(); cleanup();
} }

View file

@ -8,7 +8,9 @@ const LATIN1_ae = "\xe6";
function setup() { function setup() {
getOpenedDatabase().createTable("t1", "x TEXT"); getOpenedDatabase().createTable("t1", "x TEXT");
var stmt = createStatement("INSERT INTO t1 (x) VALUES ('foo/bar_baz%20cheese')"); var stmt = createStatement(
"INSERT INTO t1 (x) VALUES ('foo/bar_baz%20cheese')"
);
stmt.execute(); stmt.execute();
stmt.finalize(); stmt.finalize();
@ -33,7 +35,10 @@ function test_escape_for_like_ascii() {
function test_escape_for_like_non_ascii() { function test_escape_for_like_non_ascii() {
var stmt = createStatement("SELECT x FROM t1 WHERE x LIKE ?1 ESCAPE '/'"); var stmt = createStatement("SELECT x FROM t1 WHERE x LIKE ?1 ESCAPE '/'");
var paramForLike = stmt.escapeStringForLIKE("oo%20" + LATIN1_AE + "/_ba", "/"); var paramForLike = stmt.escapeStringForLIKE(
"oo%20" + LATIN1_AE + "/_ba",
"/"
);
// verify that we escaped / _ and % // verify that we escaped / _ and %
Assert.equal(paramForLike, "oo/%20" + LATIN1_AE + "///_ba"); Assert.equal(paramForLike, "oo/%20" + LATIN1_AE + "///_ba");
// prepend and append with % for "contains" // prepend and append with % for "contains"

View file

@ -73,8 +73,9 @@ function ensureResultsAreCorrect(aActual, aExpected) {
print("Expected results: " + aExpected); print("Expected results: " + aExpected);
Assert.equal(aActual.length, aExpected.length); Assert.equal(aActual.length, aExpected.length);
for (let i = 0; i < aActual.length; i++) for (let i = 0; i < aActual.length; i++) {
Assert.equal(aActual[i], aExpected[i]); Assert.equal(aActual[i], aExpected[i]);
}
} }
/** /**
@ -90,10 +91,12 @@ function ensureResultsAreCorrect(aActual, aExpected) {
*/ */
function getResults(aCollation, aConn) { function getResults(aCollation, aConn) {
let results = []; let results = [];
let stmt = aConn.createStatement("SELECT t FROM test " + let stmt = aConn.createStatement(
"ORDER BY t COLLATE " + aCollation + " ASC"); "SELECT t FROM test " + "ORDER BY t COLLATE " + aCollation + " ASC"
while (stmt.executeStep()) );
while (stmt.executeStep()) {
results.push(stmt.row.t); results.push(stmt.row.t);
}
stmt.finalize(); stmt.finalize();
return results; return results;
} }
@ -165,8 +168,9 @@ function readTestData() {
let file = do_get_file(DATA_BASENAME); let file = do_get_file(DATA_BASENAME);
let istream = Cc["@mozilla.org/network/file-input-stream;1"]. let istream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(
createInstance(Ci.nsIFileInputStream); Ci.nsIFileInputStream
);
istream.init(file, -1, -1, 0); istream.init(file, -1, -1, 0);
istream.QueryInterface(Ci.nsILineInputStream); istream.QueryInterface(Ci.nsILineInputStream);
@ -191,8 +195,10 @@ function readTestData() {
* A connection to either the UTF-8 database or the UTF-16 database. * A connection to either the UTF-8 database or the UTF-16 database.
*/ */
function runTest(aCollation, aConn) { function runTest(aCollation, aConn) {
ensureResultsAreCorrect(getResults(aCollation, aConn), ensureResultsAreCorrect(
gStrings.slice(0).sort(localeCompare(aCollation))); getResults(aCollation, aConn),
gStrings.slice(0).sort(localeCompare(aCollation))
);
} }
/** /**
@ -232,8 +238,9 @@ function setup() {
gUtf16Conn = createUtf16Database(); gUtf16Conn = createUtf16Database();
initTableWithStrings(gStrings, gUtf16Conn); initTableWithStrings(gStrings, gUtf16Conn);
let collFact = Cc["@mozilla.org/intl/collation-factory;1"]. let collFact = Cc["@mozilla.org/intl/collation-factory;1"].createInstance(
createInstance(Ci.nsICollationFactory); Ci.nsICollationFactory
);
gLocaleCollation = collFact.CreateCollation(); gLocaleCollation = collFact.CreateCollation();
} }

View file

@ -5,7 +5,8 @@
// and async connections. // and async connections.
function minimizeMemory() { function minimizeMemory() {
Services.storage.QueryInterface(Ci.nsIObserver) Services.storage
.QueryInterface(Ci.nsIObserver)
.observe(null, "memory-pressure", null); .observe(null, "memory-pressure", null);
} }

View file

@ -3,7 +3,7 @@
/* eslint-disable mozilla/no-arbitrary-setTimeout */ /* eslint-disable mozilla/no-arbitrary-setTimeout */
const {setTimeout} = ChromeUtils.import("resource://gre/modules/Timer.jsm"); const { setTimeout } = ChromeUtils.import("resource://gre/modules/Timer.jsm");
function getProfileFile(name) { function getProfileFile(name) {
let file = do_get_profile(); let file = do_get_profile();
@ -105,8 +105,10 @@ add_task(async function test_retry_on_busy() {
info("Attach second writer to new database"); info("Attach second writer to new database");
let attachStmt = db2.createAsyncStatement(`ATTACH :path AS newDB`); let attachStmt = db2.createAsyncStatement(`ATTACH :path AS newDB`);
attachStmt.bindByName("path", attachStmt.bindByName(
getProfileFile("retry-on-busy-attach.sqlite").path); "path",
getProfileFile("retry-on-busy-attach.sqlite").path
);
await promiseExecuteStatement(attachStmt); await promiseExecuteStatement(attachStmt);
info("Create triggers on second writer"); info("Create triggers on second writer");
@ -126,7 +128,9 @@ add_task(async function test_retry_on_busy() {
let begin2Stmt = db2.createAsyncStatement("BEGIN IMMEDIATE"); let begin2Stmt = db2.createAsyncStatement("BEGIN IMMEDIATE");
await promiseExecuteStatement(begin2Stmt); await promiseExecuteStatement(begin2Stmt);
info("Begin transaction on first writer; should busy-wait until second writer is done"); info(
"Begin transaction on first writer; should busy-wait until second writer is done"
);
let begin1Stmt = db1.createAsyncStatement("BEGIN IMMEDIATE"); let begin1Stmt = db1.createAsyncStatement("BEGIN IMMEDIATE");
let promise1Began = promiseExecuteStatement(begin1Stmt); let promise1Began = promiseExecuteStatement(begin1Stmt);
let update1Stmt = db1.createAsyncStatement(`UPDATE a SET b = 3 WHERE b = 1`); let update1Stmt = db1.createAsyncStatement(`UPDATE a SET b = 3 WHERE b = 1`);
@ -158,13 +162,25 @@ add_task(async function test_retry_on_busy() {
deepEqual(rows.map(row => row.getResultByName("b")), [2, 3]); deepEqual(rows.map(row => row.getResultByName("b")), [2, 3]);
info("Clean up"); info("Clean up");
for (let stmt of [walStmt, createAStmt, createPrevAStmt, createATriggerStmt, for (let stmt of [
attachStmt, createCStmt, createCTriggerStmt, walStmt,
begin2Stmt, begin1Stmt, insertIntoA2Stmt, createAStmt,
insertIntoC2Stmt, deleteFromC2Stmt, createPrevAStmt,
createATriggerStmt,
attachStmt,
createCStmt,
createCTriggerStmt,
begin2Stmt,
begin1Stmt,
insertIntoA2Stmt,
insertIntoC2Stmt,
deleteFromC2Stmt,
commit2Stmt, commit2Stmt,
update1Stmt, commit1Stmt, select1Stmt]) { update1Stmt,
commit1Stmt,
select1Stmt,
]) {
stmt.finalize(); stmt.finalize();
} }
await promiseClose(db1); await promiseClose(db1);

View file

@ -19,12 +19,14 @@
* @return the contents of the file in the form of a string. * @return the contents of the file in the form of a string.
*/ */
function getFileContents(aFile) { function getFileContents(aFile) {
let fstream = Cc["@mozilla.org/network/file-input-stream;1"]. let fstream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(
createInstance(Ci.nsIFileInputStream); Ci.nsIFileInputStream
);
fstream.init(aFile, -1, 0, 0); fstream.init(aFile, -1, 0, 0);
let bstream = Cc["@mozilla.org/binaryinputstream;1"]. let bstream = Cc["@mozilla.org/binaryinputstream;1"].createInstance(
createInstance(Ci.nsIBinaryInputStream); Ci.nsIBinaryInputStream
);
bstream.setInputStream(fstream); bstream.setInputStream(fstream);
return bstream.readBytes(bstream.available()); return bstream.readBytes(bstream.available());
} }

View file

@ -47,8 +47,9 @@ const BLOB = [1, 2];
*/ */
function execAsync(aStmt, aOptions, aResults) { function execAsync(aStmt, aOptions, aResults) {
let caller = Components.stack.caller; let caller = Components.stack.caller;
if (aOptions == null) if (aOptions == null) {
aOptions = {}; aOptions = {};
}
let resultsExpected; let resultsExpected;
let resultsChecker; let resultsChecker;
@ -58,7 +59,8 @@ function execAsync(aStmt, aOptions, aResults) {
resultsExpected = aResults; resultsExpected = aResults;
} else if (typeof aResults == "function") { } else if (typeof aResults == "function") {
resultsChecker = aResults; resultsChecker = aResults;
} else { // array } else {
// array
resultsExpected = aResults.length; resultsExpected = aResults.length;
resultsChecker = function(aResultNum, aTup, aCaller) { resultsChecker = function(aResultNum, aTup, aCaller) {
aResults[aResultNum](aTup, aCaller); aResults[aResultNum](aTup, aCaller);
@ -71,52 +73,80 @@ function execAsync(aStmt, aOptions, aResults) {
let altReasonExpected = null; let altReasonExpected = null;
if ("error" in aOptions) { if ("error" in aOptions) {
errorCodeExpected = aOptions.error; errorCodeExpected = aOptions.error;
if (errorCodeExpected) if (errorCodeExpected) {
reasonExpected = Ci.mozIStorageStatementCallback.REASON_ERROR; reasonExpected = Ci.mozIStorageStatementCallback.REASON_ERROR;
} }
}
let errorCodeSeen = false; let errorCodeSeen = false;
if ("cancel" in aOptions && aOptions.cancel) if ("cancel" in aOptions && aOptions.cancel) {
altReasonExpected = Ci.mozIStorageStatementCallback.REASON_CANCELED; altReasonExpected = Ci.mozIStorageStatementCallback.REASON_CANCELED;
}
let completed = false; let completed = false;
let listener = { let listener = {
handleResult(aResultSet) { handleResult(aResultSet) {
let row, resultsSeenThisCall = 0; let row,
resultsSeenThisCall = 0;
while ((row = aResultSet.getNextRow()) != null) { while ((row = aResultSet.getNextRow()) != null) {
if (resultsChecker) if (resultsChecker) {
resultsChecker(resultsSeen, row, caller); resultsChecker(resultsSeen, row, caller);
}
resultsSeen++; resultsSeen++;
resultsSeenThisCall++; resultsSeenThisCall++;
} }
if (!resultsSeenThisCall) if (!resultsSeenThisCall) {
do_throw("handleResult invoked with 0 result rows!"); do_throw("handleResult invoked with 0 result rows!");
}
}, },
handleError(aError) { handleError(aError) {
if (errorCodeSeen) if (errorCodeSeen) {
do_throw("handleError called when we already had an error!"); do_throw("handleError called when we already had an error!");
}
errorCodeSeen = aError.result; errorCodeSeen = aError.result;
}, },
handleCompletion(aReason) { handleCompletion(aReason) {
if (completed) // paranoia check if (completed) {
// paranoia check
do_throw("Received a second handleCompletion notification!", caller); do_throw("Received a second handleCompletion notification!", caller);
}
if (resultsSeen != resultsExpected) if (resultsSeen != resultsExpected) {
do_throw("Expected " + resultsExpected + " rows of results but " + do_throw(
"got " + resultsSeen + " rows!", caller); "Expected " +
resultsExpected +
" rows of results but " +
"got " +
resultsSeen +
" rows!",
caller
);
}
if (errorCodeExpected && !errorCodeSeen) if (errorCodeExpected && !errorCodeSeen) {
do_throw("Expected an error, but did not see one.", caller); do_throw("Expected an error, but did not see one.", caller);
else if (errorCodeExpected != errorCodeSeen) } else if (errorCodeExpected != errorCodeSeen) {
do_throw("Expected error code " + errorCodeExpected + " but got " + do_throw(
errorCodeSeen, caller); "Expected error code " +
errorCodeExpected +
" but got " +
errorCodeSeen,
caller
);
}
if (aReason != reasonExpected && aReason != altReasonExpected) if (aReason != reasonExpected && aReason != altReasonExpected) {
do_throw("Expected reason " + reasonExpected + do_throw(
(altReasonExpected ? (" or " + altReasonExpected) : "") + "Expected reason " +
" but got " + aReason, caller); reasonExpected +
(altReasonExpected ? " or " + altReasonExpected : "") +
" but got " +
aReason,
caller
);
}
completed = true; completed = true;
}, },
@ -125,15 +155,18 @@ function execAsync(aStmt, aOptions, aResults) {
let pending; let pending;
// Only get a pending reference if we're supposed to do. // Only get a pending reference if we're supposed to do.
// (note: This does not stop XPConnect from holding onto one currently.) // (note: This does not stop XPConnect from holding onto one currently.)
if (("cancel" in aOptions && aOptions.cancel) || if (
("returnPending" in aOptions && aOptions.returnPending)) { ("cancel" in aOptions && aOptions.cancel) ||
("returnPending" in aOptions && aOptions.returnPending)
) {
pending = aStmt.executeAsync(listener); pending = aStmt.executeAsync(listener);
} else { } else {
aStmt.executeAsync(listener); aStmt.executeAsync(listener);
} }
if ("cancel" in aOptions && aOptions.cancel) if ("cancel" in aOptions && aOptions.cancel) {
pending.cancel(); pending.cancel();
}
Services.tm.spinEventLoopUntil(() => completed || _quit); Services.tm.spinEventLoopUntil(() => completed || _quit);
@ -148,12 +181,12 @@ function execAsync(aStmt, aOptions, aResults) {
function test_illegal_sql_async_deferred() { function test_illegal_sql_async_deferred() {
// gibberish // gibberish
let stmt = makeTestStatement("I AM A ROBOT. DO AS I SAY."); let stmt = makeTestStatement("I AM A ROBOT. DO AS I SAY.");
execAsync(stmt, {error: Ci.mozIStorageError.ERROR}); execAsync(stmt, { error: Ci.mozIStorageError.ERROR });
stmt.finalize(); stmt.finalize();
// legal SQL syntax, but with semantics issues. // legal SQL syntax, but with semantics issues.
stmt = makeTestStatement("SELECT destination FROM funkytown"); stmt = makeTestStatement("SELECT destination FROM funkytown");
execAsync(stmt, {error: Ci.mozIStorageError.ERROR}); execAsync(stmt, { error: Ci.mozIStorageError.ERROR });
stmt.finalize(); stmt.finalize();
run_next_test(); run_next_test();
@ -202,9 +235,11 @@ function test_add_data() {
stmt.finalize(); stmt.finalize();
// Check that the result is in the table // Check that the result is in the table
verifyQuery("SELECT string, number, nuller, blober FROM test WHERE id = ?", verifyQuery(
"SELECT string, number, nuller, blober FROM test WHERE id = ?",
INTEGER, INTEGER,
[TEXT, REAL, null, BLOB]); [TEXT, REAL, null, BLOB]
);
run_next_test(); run_next_test();
} }
@ -221,20 +256,26 @@ function test_get_data() {
Assert.ok(!tuple.getIsNull(0)); Assert.ok(!tuple.getIsNull(0));
Assert.equal(tuple.getResultByName("string"), tuple.getResultByIndex(0)); Assert.equal(tuple.getResultByName("string"), tuple.getResultByIndex(0));
Assert.equal(TEXT, tuple.getResultByName("string")); Assert.equal(TEXT, tuple.getResultByName("string"));
Assert.equal(Ci.mozIStorageValueArray.VALUE_TYPE_TEXT, Assert.equal(
tuple.getTypeOfIndex(0)); Ci.mozIStorageValueArray.VALUE_TYPE_TEXT,
tuple.getTypeOfIndex(0)
);
Assert.ok(!tuple.getIsNull(1)); Assert.ok(!tuple.getIsNull(1));
Assert.equal(tuple.getResultByName("number"), tuple.getResultByIndex(1)); Assert.equal(tuple.getResultByName("number"), tuple.getResultByIndex(1));
Assert.equal(REAL, tuple.getResultByName("number")); Assert.equal(REAL, tuple.getResultByName("number"));
Assert.equal(Ci.mozIStorageValueArray.VALUE_TYPE_FLOAT, Assert.equal(
tuple.getTypeOfIndex(1)); Ci.mozIStorageValueArray.VALUE_TYPE_FLOAT,
tuple.getTypeOfIndex(1)
);
Assert.ok(tuple.getIsNull(2)); Assert.ok(tuple.getIsNull(2));
Assert.equal(tuple.getResultByName("nuller"), tuple.getResultByIndex(2)); Assert.equal(tuple.getResultByName("nuller"), tuple.getResultByIndex(2));
Assert.equal(null, tuple.getResultByName("nuller")); Assert.equal(null, tuple.getResultByName("nuller"));
Assert.equal(Ci.mozIStorageValueArray.VALUE_TYPE_NULL, Assert.equal(
tuple.getTypeOfIndex(2)); Ci.mozIStorageValueArray.VALUE_TYPE_NULL,
tuple.getTypeOfIndex(2)
);
Assert.ok(!tuple.getIsNull(3)); Assert.ok(!tuple.getIsNull(3));
var blobByName = tuple.getResultByName("blober"); var blobByName = tuple.getResultByName("blober");
@ -249,25 +290,29 @@ function test_get_data() {
var blob = { value: null }; var blob = { value: null };
tuple.getBlob(3, count, blob); tuple.getBlob(3, count, blob);
Assert.equal(BLOB.length, count.value); Assert.equal(BLOB.length, count.value);
for (let i = 0; i < BLOB.length; i++) for (let i = 0; i < BLOB.length; i++) {
Assert.equal(BLOB[i], blob.value[i]); Assert.equal(BLOB[i], blob.value[i]);
Assert.equal(Ci.mozIStorageValueArray.VALUE_TYPE_BLOB, }
tuple.getTypeOfIndex(3)); Assert.equal(
Ci.mozIStorageValueArray.VALUE_TYPE_BLOB,
tuple.getTypeOfIndex(3)
);
Assert.ok(!tuple.getIsNull(4)); Assert.ok(!tuple.getIsNull(4));
Assert.equal(tuple.getResultByName("id"), tuple.getResultByIndex(4)); Assert.equal(tuple.getResultByName("id"), tuple.getResultByIndex(4));
Assert.equal(INTEGER, tuple.getResultByName("id")); Assert.equal(INTEGER, tuple.getResultByName("id"));
Assert.equal(Ci.mozIStorageValueArray.VALUE_TYPE_INTEGER, Assert.equal(
tuple.getTypeOfIndex(4)); Ci.mozIStorageValueArray.VALUE_TYPE_INTEGER,
}]); tuple.getTypeOfIndex(4)
);
},
]);
stmt.finalize(); stmt.finalize();
run_next_test(); run_next_test();
} }
function test_tuple_out_of_bounds() { function test_tuple_out_of_bounds() {
var stmt = makeTestStatement( var stmt = makeTestStatement("SELECT string FROM test");
"SELECT string FROM test"
);
execAsync(stmt, {}, [ execAsync(stmt, {}, [
function(tuple) { function(tuple) {
Assert.notEqual(null, tuple); Assert.notEqual(null, tuple);
@ -300,15 +345,14 @@ function test_tuple_out_of_bounds() {
} catch (e) { } catch (e) {
Assert.equal(Cr.NS_ERROR_ILLEGAL_VALUE, e.result); Assert.equal(Cr.NS_ERROR_ILLEGAL_VALUE, e.result);
} }
}]); },
]);
stmt.finalize(); stmt.finalize();
run_next_test(); run_next_test();
} }
function test_no_listener_works_on_success() { function test_no_listener_works_on_success() {
var stmt = makeTestStatement( var stmt = makeTestStatement("DELETE FROM test WHERE id = ?");
"DELETE FROM test WHERE id = ?"
);
stmt.bindByIndex(0, 0); stmt.bindByIndex(0, 0);
stmt.executeAsync(); stmt.executeAsync();
stmt.finalize(); stmt.finalize();
@ -318,9 +362,7 @@ function test_no_listener_works_on_success() {
} }
function test_no_listener_works_on_results() { function test_no_listener_works_on_results() {
var stmt = makeTestStatement( var stmt = makeTestStatement("SELECT ?");
"SELECT ?"
);
stmt.bindByIndex(0, 1); stmt.bindByIndex(0, 1);
stmt.executeAsync(); stmt.executeAsync();
stmt.finalize(); stmt.finalize();
@ -331,9 +373,7 @@ function test_no_listener_works_on_results() {
function test_no_listener_works_on_error() { function test_no_listener_works_on_error() {
// commit without a transaction will trigger an error // commit without a transaction will trigger an error
var stmt = makeTestStatement( var stmt = makeTestStatement("COMMIT");
"COMMIT"
);
stmt.executeAsync(); stmt.executeAsync();
stmt.finalize(); stmt.finalize();
@ -342,9 +382,7 @@ function test_no_listener_works_on_error() {
} }
function test_partial_listener_works() { function test_partial_listener_works() {
var stmt = makeTestStatement( var stmt = makeTestStatement("DELETE FROM test WHERE id = ?");
"DELETE FROM test WHERE id = ?"
);
stmt.bindByIndex(0, 0); stmt.bindByIndex(0, 0);
stmt.executeAsync({ stmt.executeAsync({
handleResult(aResultSet) {}, handleResult(aResultSet) {},
@ -368,11 +406,9 @@ function test_partial_listener_works() {
* actually works correctly. * actually works correctly.
*/ */
function test_immediate_cancellation() { function test_immediate_cancellation() {
var stmt = makeTestStatement( var stmt = makeTestStatement("DELETE FROM test WHERE id = ?");
"DELETE FROM test WHERE id = ?"
);
stmt.bindByIndex(0, 0); stmt.bindByIndex(0, 0);
execAsync(stmt, {cancel: true}); execAsync(stmt, { cancel: true });
stmt.finalize(); stmt.finalize();
run_next_test(); run_next_test();
} }
@ -381,14 +417,11 @@ function test_immediate_cancellation() {
* Test that calling cancel twice throws the second time. * Test that calling cancel twice throws the second time.
*/ */
function test_double_cancellation() { function test_double_cancellation() {
var stmt = makeTestStatement( var stmt = makeTestStatement("DELETE FROM test WHERE id = ?");
"DELETE FROM test WHERE id = ?"
);
stmt.bindByIndex(0, 0); stmt.bindByIndex(0, 0);
let pendingStatement = execAsync(stmt, {cancel: true}); let pendingStatement = execAsync(stmt, { cancel: true });
// And cancel again - expect an exception // And cancel again - expect an exception
expectError(Cr.NS_ERROR_UNEXPECTED, expectError(Cr.NS_ERROR_UNEXPECTED, () => pendingStatement.cancel());
() => pendingStatement.cancel());
stmt.finalize(); stmt.finalize();
run_next_test(); run_next_test();
@ -399,11 +432,9 @@ function test_double_cancellation() {
* has fully run to completion. * has fully run to completion.
*/ */
function test_cancellation_after_execution() { function test_cancellation_after_execution() {
var stmt = makeTestStatement( var stmt = makeTestStatement("DELETE FROM test WHERE id = ?");
"DELETE FROM test WHERE id = ?"
);
stmt.bindByIndex(0, 0); stmt.bindByIndex(0, 0);
let pendingStatement = execAsync(stmt, {returnPending: true}); let pendingStatement = execAsync(stmt, { returnPending: true });
// (the statement has fully executed at this point) // (the statement has fully executed at this point)
// canceling after the statement has run to completion should not throw! // canceling after the statement has run to completion should not throw!
pendingStatement.cancel(); pendingStatement.cancel();
@ -419,9 +450,7 @@ function test_cancellation_after_execution() {
* handleResult to get called multiple times) and not comprehensive. * handleResult to get called multiple times) and not comprehensive.
*/ */
function test_double_execute() { function test_double_execute() {
var stmt = makeTestStatement( var stmt = makeTestStatement("SELECT 1");
"SELECT 1"
);
execAsync(stmt, null, 1); execAsync(stmt, null, 1);
execAsync(stmt, null, 1); execAsync(stmt, null, 1);
stmt.finalize(); stmt.finalize();
@ -429,9 +458,7 @@ function test_double_execute() {
} }
function test_finalized_statement_does_not_crash() { function test_finalized_statement_does_not_crash() {
var stmt = makeTestStatement( var stmt = makeTestStatement("SELECT * FROM TEST");
"SELECT * FROM TEST"
);
stmt.finalize(); stmt.finalize();
// we are concerned about a crash here; an error is fine. // we are concerned about a crash here; an error is fine.
try { try {
@ -460,9 +487,11 @@ function test_bind_direct_binding_params_by_index() {
stmt.bindBlobByIndex(4, BLOB, BLOB.length); stmt.bindBlobByIndex(4, BLOB, BLOB.length);
execAsync(stmt); execAsync(stmt);
stmt.finalize(); stmt.finalize();
verifyQuery("SELECT string, number, nuller, blober FROM test WHERE id = ?", verifyQuery(
"SELECT string, number, nuller, blober FROM test WHERE id = ?",
insertId, insertId,
[TEXT, REAL, null, BLOB]); [TEXT, REAL, null, BLOB]
);
run_next_test(); run_next_test();
} }
@ -482,9 +511,11 @@ function test_bind_direct_binding_params_by_name() {
stmt.bindBlobByName("blob", BLOB); stmt.bindBlobByName("blob", BLOB);
execAsync(stmt); execAsync(stmt);
stmt.finalize(); stmt.finalize();
verifyQuery("SELECT string, number, nuller, blober FROM test WHERE id = ?", verifyQuery(
"SELECT string, number, nuller, blober FROM test WHERE id = ?",
insertId, insertId,
[TEXT, REAL, null, BLOB]); [TEXT, REAL, null, BLOB]
);
run_next_test(); run_next_test();
} }
@ -501,8 +532,11 @@ function test_bind_js_params_helper_by_index() {
stmt.params[0] = insertId; stmt.params[0] = insertId;
execAsync(stmt); execAsync(stmt);
stmt.finalize(); stmt.finalize();
verifyQuery("SELECT string, number, nuller FROM test WHERE id = ?", insertId, verifyQuery(
[TEXT, REAL, null]); "SELECT string, number, nuller FROM test WHERE id = ?",
insertId,
[TEXT, REAL, null]
);
run_next_test(); run_next_test();
} }
@ -519,8 +553,11 @@ function test_bind_js_params_helper_by_name() {
stmt.params.int = insertId; stmt.params.int = insertId;
execAsync(stmt); execAsync(stmt);
stmt.finalize(); stmt.finalize();
verifyQuery("SELECT string, number, nuller FROM test WHERE id = ?", insertId, verifyQuery(
[TEXT, REAL, null]); "SELECT string, number, nuller FROM test WHERE id = ?",
insertId,
[TEXT, REAL, null]
);
run_next_test(); run_next_test();
} }
@ -581,20 +618,17 @@ function test_bind_multiple_rows_by_name() {
* try and bind to an illegal index. * try and bind to an illegal index.
*/ */
function test_bind_out_of_bounds_sync_immediate() { function test_bind_out_of_bounds_sync_immediate() {
let stmt = makeTestStatement( let stmt = makeTestStatement("INSERT INTO test (id) " + "VALUES (?)");
"INSERT INTO test (id) " +
"VALUES (?)"
);
let array = stmt.newBindingParamsArray(); let array = stmt.newBindingParamsArray();
let bp = array.newBindingParams(); let bp = array.newBindingParams();
// Check variant binding. // Check variant binding.
expectError(Cr.NS_ERROR_INVALID_ARG, expectError(Cr.NS_ERROR_INVALID_ARG, () => bp.bindByIndex(1, INTEGER));
() => bp.bindByIndex(1, INTEGER));
// Check blob binding. // Check blob binding.
expectError(Cr.NS_ERROR_INVALID_ARG, expectError(Cr.NS_ERROR_INVALID_ARG, () =>
() => bp.bindBlobByIndex(1, BLOB, BLOB.length)); bp.bindBlobByIndex(1, BLOB, BLOB.length)
);
stmt.finalize(); stmt.finalize();
run_next_test(); run_next_test();
@ -606,10 +640,7 @@ test_bind_out_of_bounds_sync_immediate.syncOnly = true;
* we bind to an illegal index. * we bind to an illegal index.
*/ */
function test_bind_out_of_bounds_async_deferred() { function test_bind_out_of_bounds_async_deferred() {
let stmt = makeTestStatement( let stmt = makeTestStatement("INSERT INTO test (id) " + "VALUES (?)");
"INSERT INTO test (id) " +
"VALUES (?)"
);
let array = stmt.newBindingParamsArray(); let array = stmt.newBindingParamsArray();
let bp = array.newBindingParams(); let bp = array.newBindingParams();
@ -618,7 +649,7 @@ function test_bind_out_of_bounds_async_deferred() {
bp.bindByIndex(1, INTEGER); bp.bindByIndex(1, INTEGER);
array.addParams(bp); array.addParams(bp);
stmt.bindParameters(array); stmt.bindParameters(array);
execAsync(stmt, {error: Ci.mozIStorageError.RANGE}); execAsync(stmt, { error: Ci.mozIStorageError.RANGE });
stmt.finalize(); stmt.finalize();
run_next_test(); run_next_test();
@ -626,20 +657,19 @@ function test_bind_out_of_bounds_async_deferred() {
test_bind_out_of_bounds_async_deferred.asyncOnly = true; test_bind_out_of_bounds_async_deferred.asyncOnly = true;
function test_bind_no_such_name_sync_immediate() { function test_bind_no_such_name_sync_immediate() {
let stmt = makeTestStatement( let stmt = makeTestStatement("INSERT INTO test (id) " + "VALUES (:foo)");
"INSERT INTO test (id) " +
"VALUES (:foo)"
);
let array = stmt.newBindingParamsArray(); let array = stmt.newBindingParamsArray();
let bp = array.newBindingParams(); let bp = array.newBindingParams();
// Check variant binding. // Check variant binding.
expectError(Cr.NS_ERROR_INVALID_ARG, expectError(Cr.NS_ERROR_INVALID_ARG, () =>
() => bp.bindByName("doesnotexist", INTEGER)); bp.bindByName("doesnotexist", INTEGER)
);
// Check blob binding. // Check blob binding.
expectError(Cr.NS_ERROR_INVALID_ARG, expectError(Cr.NS_ERROR_INVALID_ARG, () =>
() => bp.bindBlobByName("doesnotexist", BLOB)); bp.bindBlobByName("doesnotexist", BLOB)
);
stmt.finalize(); stmt.finalize();
run_next_test(); run_next_test();
@ -647,10 +677,7 @@ function test_bind_no_such_name_sync_immediate() {
test_bind_no_such_name_sync_immediate.syncOnly = true; test_bind_no_such_name_sync_immediate.syncOnly = true;
function test_bind_no_such_name_async_deferred() { function test_bind_no_such_name_async_deferred() {
let stmt = makeTestStatement( let stmt = makeTestStatement("INSERT INTO test (id) " + "VALUES (:foo)");
"INSERT INTO test (id) " +
"VALUES (:foo)"
);
let array = stmt.newBindingParamsArray(); let array = stmt.newBindingParamsArray();
let bp = array.newBindingParams(); let bp = array.newBindingParams();
@ -658,7 +685,7 @@ function test_bind_no_such_name_async_deferred() {
bp.bindByName("doesnotexist", INTEGER); bp.bindByName("doesnotexist", INTEGER);
array.addParams(bp); array.addParams(bp);
stmt.bindParameters(array); stmt.bindParameters(array);
execAsync(stmt, {error: Ci.mozIStorageError.RANGE}); execAsync(stmt, { error: Ci.mozIStorageError.RANGE });
stmt.finalize(); stmt.finalize();
run_next_test(); run_next_test();
@ -667,10 +694,7 @@ test_bind_no_such_name_async_deferred.asyncOnly = true;
function test_bind_bogus_type_by_index() { function test_bind_bogus_type_by_index() {
// We try to bind a JS Object here that should fail to bind. // We try to bind a JS Object here that should fail to bind.
let stmt = makeTestStatement( let stmt = makeTestStatement("INSERT INTO test (blober) " + "VALUES (?)");
"INSERT INTO test (blober) " +
"VALUES (?)"
);
let array = stmt.newBindingParamsArray(); let array = stmt.newBindingParamsArray();
let bp = array.newBindingParams(); let bp = array.newBindingParams();
@ -682,10 +706,7 @@ function test_bind_bogus_type_by_index() {
function test_bind_bogus_type_by_name() { function test_bind_bogus_type_by_name() {
// We try to bind a JS Object here that should fail to bind. // We try to bind a JS Object here that should fail to bind.
let stmt = makeTestStatement( let stmt = makeTestStatement("INSERT INTO test (blober) " + "VALUES (:blob)");
"INSERT INTO test (blober) " +
"VALUES (:blob)"
);
let array = stmt.newBindingParamsArray(); let array = stmt.newBindingParamsArray();
let bp = array.newBindingParams(); let bp = array.newBindingParams();
@ -696,10 +717,7 @@ function test_bind_bogus_type_by_name() {
} }
function test_bind_params_already_locked() { function test_bind_params_already_locked() {
let stmt = makeTestStatement( let stmt = makeTestStatement("INSERT INTO test (id) " + "VALUES (:int)");
"INSERT INTO test (id) " +
"VALUES (:int)"
);
let array = stmt.newBindingParamsArray(); let array = stmt.newBindingParamsArray();
let bp = array.newBindingParams(); let bp = array.newBindingParams();
@ -707,18 +725,14 @@ function test_bind_params_already_locked() {
array.addParams(bp); array.addParams(bp);
// We should get an error after we call addParams and try to bind again. // We should get an error after we call addParams and try to bind again.
expectError(Cr.NS_ERROR_UNEXPECTED, expectError(Cr.NS_ERROR_UNEXPECTED, () => bp.bindByName("int", INTEGER));
() => bp.bindByName("int", INTEGER));
stmt.finalize(); stmt.finalize();
run_next_test(); run_next_test();
} }
function test_bind_params_array_already_locked() { function test_bind_params_array_already_locked() {
let stmt = makeTestStatement( let stmt = makeTestStatement("INSERT INTO test (id) " + "VALUES (:int)");
"INSERT INTO test (id) " +
"VALUES (:int)"
);
let array = stmt.newBindingParamsArray(); let array = stmt.newBindingParamsArray();
let bp1 = array.newBindingParams(); let bp1 = array.newBindingParams();
@ -729,18 +743,14 @@ function test_bind_params_array_already_locked() {
bp2.bindByName("int", INTEGER); bp2.bindByName("int", INTEGER);
// We should get an error after we have bound the array to the statement. // We should get an error after we have bound the array to the statement.
expectError(Cr.NS_ERROR_UNEXPECTED, expectError(Cr.NS_ERROR_UNEXPECTED, () => array.addParams(bp2));
() => array.addParams(bp2));
stmt.finalize(); stmt.finalize();
run_next_test(); run_next_test();
} }
function test_no_binding_params_from_locked_array() { function test_no_binding_params_from_locked_array() {
let stmt = makeTestStatement( let stmt = makeTestStatement("INSERT INTO test (id) " + "VALUES (:int)");
"INSERT INTO test (id) " +
"VALUES (:int)"
);
let array = stmt.newBindingParamsArray(); let array = stmt.newBindingParamsArray();
let bp = array.newBindingParams(); let bp = array.newBindingParams();
@ -750,18 +760,14 @@ function test_no_binding_params_from_locked_array() {
// We should not be able to get a new BindingParams object after we have bound // We should not be able to get a new BindingParams object after we have bound
// to the statement. // to the statement.
expectError(Cr.NS_ERROR_UNEXPECTED, expectError(Cr.NS_ERROR_UNEXPECTED, () => array.newBindingParams());
() => array.newBindingParams());
stmt.finalize(); stmt.finalize();
run_next_test(); run_next_test();
} }
function test_not_right_owning_array() { function test_not_right_owning_array() {
let stmt = makeTestStatement( let stmt = makeTestStatement("INSERT INTO test (id) " + "VALUES (:int)");
"INSERT INTO test (id) " +
"VALUES (:int)"
);
let array1 = stmt.newBindingParamsArray(); let array1 = stmt.newBindingParamsArray();
let array2 = stmt.newBindingParamsArray(); let array2 = stmt.newBindingParamsArray();
@ -769,22 +775,15 @@ function test_not_right_owning_array() {
bp.bindByName("int", INTEGER); bp.bindByName("int", INTEGER);
// We should not be able to add bp to array2 since it was created from array1. // We should not be able to add bp to array2 since it was created from array1.
expectError(Cr.NS_ERROR_UNEXPECTED, expectError(Cr.NS_ERROR_UNEXPECTED, () => array2.addParams(bp));
() => array2.addParams(bp));
stmt.finalize(); stmt.finalize();
run_next_test(); run_next_test();
} }
function test_not_right_owning_statement() { function test_not_right_owning_statement() {
let stmt1 = makeTestStatement( let stmt1 = makeTestStatement("INSERT INTO test (id) " + "VALUES (:int)");
"INSERT INTO test (id) " + let stmt2 = makeTestStatement("INSERT INTO test (id) " + "VALUES (:int)");
"VALUES (:int)"
);
let stmt2 = makeTestStatement(
"INSERT INTO test (id) " +
"VALUES (:int)"
);
let array1 = stmt1.newBindingParamsArray(); let array1 = stmt1.newBindingParamsArray();
stmt2.newBindingParamsArray(); stmt2.newBindingParamsArray();
@ -793,8 +792,7 @@ function test_not_right_owning_statement() {
array1.addParams(bp); array1.addParams(bp);
// We should not be able to bind array1 since it was created from stmt1. // We should not be able to bind array1 since it was created from stmt1.
expectError(Cr.NS_ERROR_UNEXPECTED, expectError(Cr.NS_ERROR_UNEXPECTED, () => stmt2.bindParameters(array1));
() => stmt2.bindParameters(array1));
stmt1.finalize(); stmt1.finalize();
stmt2.finalize(); stmt2.finalize();
@ -802,17 +800,13 @@ function test_not_right_owning_statement() {
} }
function test_bind_empty_array() { function test_bind_empty_array() {
let stmt = makeTestStatement( let stmt = makeTestStatement("INSERT INTO test (id) " + "VALUES (:int)");
"INSERT INTO test (id) " +
"VALUES (:int)"
);
let paramsArray = stmt.newBindingParamsArray(); let paramsArray = stmt.newBindingParamsArray();
// We should not be able to bind this array to the statement because it is // We should not be able to bind this array to the statement because it is
// empty. // empty.
expectError(Cr.NS_ERROR_UNEXPECTED, expectError(Cr.NS_ERROR_UNEXPECTED, () => stmt.bindParameters(paramsArray));
() => stmt.bindParameters(paramsArray));
stmt.finalize(); stmt.finalize();
run_next_test(); run_next_test();
@ -906,9 +900,12 @@ function run_next_test() {
while (index < tests.length) { while (index < tests.length) {
let test = tests[index++]; let test = tests[index++];
// skip tests not appropriate to the current test pass // skip tests not appropriate to the current test pass
if ((testPass == TEST_PASS_SYNC && ("asyncOnly" in test)) || if (
(testPass == TEST_PASS_ASYNC && ("syncOnly" in test))) (testPass == TEST_PASS_SYNC && "asyncOnly" in test) ||
(testPass == TEST_PASS_ASYNC && "syncOnly" in test)
) {
continue; continue;
}
// Asynchronous tests means that exceptions don't kill the test. // Asynchronous tests means that exceptions don't kill the test.
try { try {

View file

@ -7,8 +7,10 @@
// This file tests the functions of mozIStorageStatementWrapper // This file tests the functions of mozIStorageStatementWrapper
function setup() { function setup() {
getOpenedDatabase().createTable("test", "id INTEGER PRIMARY KEY, val NONE," + getOpenedDatabase().createTable(
"alt_val NONE"); "test",
"id INTEGER PRIMARY KEY, val NONE," + "alt_val NONE"
);
} }
/** /**
@ -32,7 +34,9 @@ function setup() {
* the value retrieved from the database * the value retrieved from the database
*/ */
function checkVal(aActualVal, aReturnedVal) { function checkVal(aActualVal, aReturnedVal) {
if (aActualVal instanceof Date) aActualVal = aActualVal.valueOf() * 1000.0; if (aActualVal instanceof Date) {
aActualVal = aActualVal.valueOf() * 1000.0;
}
Assert.equal(aActualVal, aReturnedVal); Assert.equal(aActualVal, aReturnedVal);
} }
@ -98,8 +102,9 @@ function insertAndCheckSingleParam(aVal) {
function insertAndCheckMultipleParams(aVal) { function insertAndCheckMultipleParams(aVal) {
clearTable(); clearTable();
var stmt = createStatement("INSERT INTO test (val, alt_val) " + var stmt = createStatement(
"VALUES (:val, :val)"); "INSERT INTO test (val, alt_val) " + "VALUES (:val, :val)"
);
stmt.params.val = aVal; stmt.params.val = aVal;
stmt.execute(); stmt.execute();
stmt.finalize(); stmt.finalize();
@ -127,8 +132,11 @@ function printValDesc(aVal) {
} catch (ex) { } catch (ex) {
toSource = ""; toSource = "";
} }
print("Testing value: toString=" + aVal + print(
(toSource ? " toSource=" + toSource : "")); "Testing value: toString=" +
aVal +
(toSource ? " toSource=" + toSource : "")
);
} }
function run_test() { function run_test() {

View file

@ -93,9 +93,14 @@ function test_aggregate_result() {
stmt.finalize(); stmt.finalize();
} }
var tests = [test_aggregate_registration, test_aggregate_no_double_registration, var tests = [
test_aggregate_removal, test_aggregate_no_aliases, test_aggregate_call, test_aggregate_registration,
test_aggregate_result]; test_aggregate_no_double_registration,
test_aggregate_removal,
test_aggregate_no_aliases,
test_aggregate_call,
test_aggregate_result,
];
function run_test() { function run_test() {
setup(); setup();

View file

@ -52,7 +52,9 @@ add_task(async function test_indexExists_not_created() {
add_task(async function test_temp_tableExists_and_indexExists() { add_task(async function test_temp_tableExists_and_indexExists() {
var msc = getOpenedDatabase(); var msc = getOpenedDatabase();
msc.executeSimpleSQL("CREATE TEMP TABLE test_temp(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)"); msc.executeSimpleSQL(
"CREATE TEMP TABLE test_temp(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)"
);
Assert.ok(msc.tableExists("test_temp")); Assert.ok(msc.tableExists("test_temp"));
msc.executeSimpleSQL("CREATE INDEX test_temp_ind ON test_temp (name)"); msc.executeSimpleSQL("CREATE INDEX test_temp_ind ON test_temp (name)");
@ -77,8 +79,10 @@ add_task(async function test_indexExists_created() {
add_task(async function test_createTable_already_created() { add_task(async function test_createTable_already_created() {
var msc = getOpenedDatabase(); var msc = getOpenedDatabase();
Assert.ok(msc.tableExists("test")); Assert.ok(msc.tableExists("test"));
Assert.throws(() => msc.createTable("test", "id INTEGER PRIMARY KEY, name TEXT"), Assert.throws(
/NS_ERROR_FAILURE/); () => msc.createTable("test", "id INTEGER PRIMARY KEY, name TEXT"),
/NS_ERROR_FAILURE/
);
}); });
add_task(async function test_attach_createTable_tableExists_indexExists() { add_task(async function test_attach_createTable_tableExists_indexExists() {
@ -90,8 +94,10 @@ add_task(async function test_attach_createTable_tableExists_indexExists() {
Assert.ok(!msc.tableExists("sample.test")); Assert.ok(!msc.tableExists("sample.test"));
msc.createTable("sample.test", "id INTEGER PRIMARY KEY, name TEXT"); msc.createTable("sample.test", "id INTEGER PRIMARY KEY, name TEXT");
Assert.ok(msc.tableExists("sample.test")); Assert.ok(msc.tableExists("sample.test"));
Assert.throws(() => msc.createTable("sample.test", "id INTEGER PRIMARY KEY, name TEXT"), Assert.throws(
/NS_ERROR_FAILURE/); () => msc.createTable("sample.test", "id INTEGER PRIMARY KEY, name TEXT"),
/NS_ERROR_FAILURE/
);
Assert.ok(!msc.indexExists("sample.test_ind")); Assert.ok(!msc.indexExists("sample.test_ind"));
msc.executeSimpleSQL("CREATE INDEX sample.test_ind ON test (name)"); msc.executeSimpleSQL("CREATE INDEX sample.test_ind ON test (name)");
@ -181,8 +187,9 @@ add_task(async function test_createTable() {
// Do nothing. // Do nothing.
} }
} }
Assert.ok(e.result == Cr.NS_ERROR_NOT_INITIALIZED || Assert.ok(
e.result == Cr.NS_ERROR_FAILURE); e.result == Cr.NS_ERROR_NOT_INITIALIZED || e.result == Cr.NS_ERROR_FAILURE
);
} finally { } finally {
if (con) { if (con) {
con.close(); con.close();
@ -226,7 +233,8 @@ add_task(async function test_close_does_not_spin_event_loop() {
gDBConn = null; gDBConn = null;
}); });
add_task(async function test_asyncClose_succeeds_with_finalized_async_statement() { add_task(
async function test_asyncClose_succeeds_with_finalized_async_statement() {
// XXX this test isn't perfect since we can't totally control when events will // XXX this test isn't perfect since we can't totally control when events will
// run. If this paticular function fails randomly, it means we have a // run. If this paticular function fails randomly, it means we have a
// real bug. // real bug.
@ -241,7 +249,8 @@ add_task(async function test_asyncClose_succeeds_with_finalized_async_statement(
await asyncClose(getOpenedDatabase()); await asyncClose(getOpenedDatabase());
// Reset gDBConn so that later tests will get a new connection object. // Reset gDBConn so that later tests will get a new connection object.
gDBConn = null; gDBConn = null;
}); }
);
// Would assert on debug builds. // Would assert on debug builds.
if (!AppConstants.DEBUG) { if (!AppConstants.DEBUG) {
@ -250,7 +259,9 @@ if (!AppConstants.DEBUG) {
// statements after the database has been closed (typically by // statements after the database has been closed (typically by
// letting the gc finalize the statement). // letting the gc finalize the statement).
let db = getOpenedDatabase(); let db = getOpenedDatabase();
let stmt = createStatement("SELECT * FROM test -- test_close_then_release_statement"); let stmt = createStatement(
"SELECT * FROM test -- test_close_then_release_statement"
);
db.close(); db.close();
stmt.finalize(); // Finalize too late - this should not crash stmt.finalize(); // Finalize too late - this should not crash
@ -263,7 +274,9 @@ if (!AppConstants.DEBUG) {
// statements after the database has been async closed (typically by // statements after the database has been async closed (typically by
// letting the gc finalize the statement). // letting the gc finalize the statement).
let db = getOpenedDatabase(); let db = getOpenedDatabase();
let stmt = createStatement("SELECT * FROM test -- test_asyncClose_then_release_statement"); let stmt = createStatement(
"SELECT * FROM test -- test_asyncClose_then_release_statement"
);
await asyncClose(db); await asyncClose(db);
stmt.finalize(); // Finalize too late - this should not crash stmt.finalize(); // Finalize too late - this should not crash
@ -336,7 +349,11 @@ async function standardAsyncTest(promisedDB, name, shouldInit = false) {
let found = false; let found = false;
await executeAsync(stmt, function(results) { await executeAsync(stmt, function(results) {
info("Data has been extracted"); info("Data has been extracted");
for (let row = results.getNextRow(); row != null; row = results.getNextRow()) { for (
let row = results.getNextRow();
row != null;
row = results.getNextRow()
) {
if (row.getResultByName("name") == name) { if (row.getResultByName("name") == name) {
found = true; found = true;
break; break;
@ -353,20 +370,30 @@ async function standardAsyncTest(promisedDB, name, shouldInit = false) {
add_task(async function test_open_async() { add_task(async function test_open_async() {
await standardAsyncTest(openAsyncDatabase(getTestDB(), null), "default"); await standardAsyncTest(openAsyncDatabase(getTestDB(), null), "default");
await standardAsyncTest(openAsyncDatabase(getTestDB()), "no optional arg"); await standardAsyncTest(openAsyncDatabase(getTestDB()), "no optional arg");
await standardAsyncTest(openAsyncDatabase(getTestDB(), await standardAsyncTest(
{shared: false, growthIncrement: 54}), "non-default options"); openAsyncDatabase(getTestDB(), { shared: false, growthIncrement: 54 }),
await standardAsyncTest(openAsyncDatabase("memory"), "non-default options"
"in-memory database", true); );
await standardAsyncTest(openAsyncDatabase("memory", await standardAsyncTest(
{shared: false}), openAsyncDatabase("memory"),
"in-memory database and options", true); "in-memory database",
true
);
await standardAsyncTest(
openAsyncDatabase("memory", { shared: false }),
"in-memory database and options",
true
);
info("Testing async opening with bogus options 0"); info("Testing async opening with bogus options 0");
let raised = false; let raised = false;
let adb = null; let adb = null;
try { try {
adb = await openAsyncDatabase("memory", {shared: false, growthIncrement: 54}); adb = await openAsyncDatabase("memory", {
shared: false,
growthIncrement: 54,
});
} catch (ex) { } catch (ex) {
raised = true; raised = true;
} finally { } finally {
@ -380,7 +407,7 @@ add_task(async function test_open_async() {
raised = false; raised = false;
adb = null; adb = null;
try { try {
adb = await openAsyncDatabase(getTestDB(), {shared: "forty-two"}); adb = await openAsyncDatabase(getTestDB(), { shared: "forty-two" });
} catch (ex) { } catch (ex) {
raised = true; raised = true;
} finally { } finally {
@ -394,7 +421,9 @@ add_task(async function test_open_async() {
raised = false; raised = false;
adb = null; adb = null;
try { try {
adb = await openAsyncDatabase(getTestDB(), {growthIncrement: "forty-two"}); adb = await openAsyncDatabase(getTestDB(), {
growthIncrement: "forty-two",
});
} catch (ex) { } catch (ex) {
raised = true; raised = true;
} finally { } finally {
@ -405,10 +434,9 @@ add_task(async function test_open_async() {
Assert.ok(raised); Assert.ok(raised);
}); });
add_task(async function test_async_open_with_shared_cache() { add_task(async function test_async_open_with_shared_cache() {
info("Testing that opening with a shared cache doesn't break stuff"); info("Testing that opening with a shared cache doesn't break stuff");
let adb = await openAsyncDatabase(getTestDB(), {shared: true}); let adb = await openAsyncDatabase(getTestDB(), { shared: true });
let stmt = adb.createAsyncStatement("INSERT INTO test (name) VALUES (:name)"); let stmt = adb.createAsyncStatement("INSERT INTO test (name) VALUES (:name)");
stmt.params.name = "clockworker"; stmt.params.name = "clockworker";
@ -421,7 +449,11 @@ add_task(async function test_async_open_with_shared_cache() {
let found = false; let found = false;
await executeAsync(stmt, function(results) { await executeAsync(stmt, function(results) {
info("Data has been extracted"); info("Data has been extracted");
for (let row = results.getNextRow(); row != null; row = results.getNextRow()) { for (
let row = results.getNextRow();
row != null;
row = results.getNextRow()
) {
if (row.getResultByName("name") == "clockworker") { if (row.getResultByName("name") == "clockworker") {
found = true; found = true;
break; break;
@ -457,14 +489,17 @@ add_task(async function test_clone_no_optional_param_async() {
info("Cloning database"); info("Cloning database");
let adb2 = await asyncClone(adb1); let adb2 = await asyncClone(adb1);
info("Testing that the cloned db is a mozIStorageAsyncConnection " + info(
"and not a mozIStorageConnection"); "Testing that the cloned db is a mozIStorageAsyncConnection " +
"and not a mozIStorageConnection"
);
Assert.ok(adb2 instanceof Ci.mozIStorageAsyncConnection); Assert.ok(adb2 instanceof Ci.mozIStorageAsyncConnection);
Assert.ok(adb2 instanceof Ci.mozIStorageConnection); Assert.ok(adb2 instanceof Ci.mozIStorageConnection);
info("Inserting data into source db"); info("Inserting data into source db");
let stmt = adb1. let stmt = adb1.createAsyncStatement(
createAsyncStatement("INSERT INTO test (name) VALUES (:name)"); "INSERT INTO test (name) VALUES (:name)"
);
stmt.params.name = "yoric"; stmt.params.name = "yoric";
let result = await executeAsync(stmt); let result = await executeAsync(stmt);
@ -476,7 +511,11 @@ add_task(async function test_clone_no_optional_param_async() {
let found = false; let found = false;
await executeAsync(stmt, function(results) { await executeAsync(stmt, function(results) {
info("Data has been extracted"); info("Data has been extracted");
for (let row = results.getNextRow(); row != null; row = results.getNextRow()) { for (
let row = results.getNextRow();
row != null;
row = results.getNextRow()
) {
if (row.getResultByName("name") == "yoric") { if (row.getResultByName("name") == "yoric") {
found = true; found = true;
break; break;
@ -538,10 +577,7 @@ add_task(async function test_clone_shared_readonly() {
}); });
add_task(async function test_close_clone_fails() { add_task(async function test_close_clone_fails() {
let calls = [ let calls = ["openDatabase", "openUnsharedDatabase"];
"openDatabase",
"openUnsharedDatabase",
];
calls.forEach(function(methodName) { calls.forEach(function(methodName) {
let db = Services.storage[methodName](getTestDB()); let db = Services.storage[methodName](getTestDB());
db.close(); db.close();
@ -557,14 +593,8 @@ add_task(async function test_memory_clone_fails() {
add_task(async function test_clone_copies_functions() { add_task(async function test_clone_copies_functions() {
const FUNC_NAME = "test_func"; const FUNC_NAME = "test_func";
let calls = [ let calls = ["openDatabase", "openUnsharedDatabase"];
"openDatabase", let functionMethods = ["createFunction", "createAggregateFunction"];
"openUnsharedDatabase",
];
let functionMethods = [
"createFunction",
"createAggregateFunction",
];
calls.forEach(function(methodName) { calls.forEach(function(methodName) {
[true, false].forEach(function(readOnly) { [true, false].forEach(function(readOnly) {
functionMethods.forEach(function(functionMethod) { functionMethods.forEach(function(functionMethod) {
@ -579,7 +609,9 @@ add_task(async function test_clone_copies_functions() {
// Clone it, and make sure the function exists still. // Clone it, and make sure the function exists still.
let db2 = db1.clone(readOnly); let db2 = db1.clone(readOnly);
// Note: this would fail if the function did not exist. // Note: this would fail if the function did not exist.
let stmt = db2.createStatement("SELECT " + FUNC_NAME + "(id) FROM test"); let stmt = db2.createStatement(
"SELECT " + FUNC_NAME + "(id) FROM test"
);
stmt.finalize(); stmt.finalize();
db1.close(); db1.close();
db2.close(); db2.close();
@ -603,14 +635,8 @@ add_task(async function test_clone_copies_overridden_functions() {
onFinal: () => 0, onFinal: () => 0,
}; };
let calls = [ let calls = ["openDatabase", "openUnsharedDatabase"];
"openDatabase", let functionMethods = ["createFunction", "createAggregateFunction"];
"openUnsharedDatabase",
];
let functionMethods = [
"createFunction",
"createAggregateFunction",
];
calls.forEach(function(methodName) { calls.forEach(function(methodName) {
[true, false].forEach(function(readOnly) { [true, false].forEach(function(readOnly) {
functionMethods.forEach(function(functionMethod) { functionMethods.forEach(function(functionMethod) {
@ -622,7 +648,9 @@ add_task(async function test_clone_copies_overridden_functions() {
// Clone it, and make sure the function gets called. // Clone it, and make sure the function gets called.
let db2 = db1.clone(readOnly); let db2 = db1.clone(readOnly);
let stmt = db2.createStatement("SELECT " + FUNC_NAME + "(id) FROM test"); let stmt = db2.createStatement(
"SELECT " + FUNC_NAME + "(id) FROM test"
);
stmt.executeStep(); stmt.executeStep();
Assert.ok(func.called); Assert.ok(func.called);
stmt.finalize(); stmt.finalize();
@ -723,9 +751,11 @@ add_task(async function test_clone_attach_database() {
let c = 0; let c = 0;
function attachDB(conn, name) { function attachDB(conn, name) {
let file = Services.dirsvc.get("ProfD", Ci.nsIFile); let file = Services.dirsvc.get("ProfD", Ci.nsIFile);
file.append("test_storage_" + (++c) + ".sqlite"); file.append("test_storage_" + ++c + ".sqlite");
let db = Services.storage.openUnsharedDatabase(file); let db = Services.storage.openUnsharedDatabase(file);
conn.executeSimpleSQL(`ATTACH DATABASE '${db.databaseFile.path}' AS ${name}`); conn.executeSimpleSQL(
`ATTACH DATABASE '${db.databaseFile.path}' AS ${name}`
);
db.executeSimpleSQL(`CREATE TABLE test_${name}(name TEXT);`); db.executeSimpleSQL(`CREATE TABLE test_${name}(name TEXT);`);
db.close(); db.close();
} }
@ -790,7 +820,8 @@ add_task(async function test_async_clone_with_temp_trigger_and_table() {
AFTER DELETE ON test_temp FOR EACH ROW AFTER DELETE ON test_temp FOR EACH ROW
BEGIN BEGIN
INSERT INTO test(name) VALUES(OLD.name); INSERT INTO test(name) VALUES(OLD.name);
END`]; END`,
];
for (let query of createQueries) { for (let query of createQueries) {
let stmt = db.createAsyncStatement(query); let stmt = db.createAsyncStatement(query);
await executeAsync(stmt); await executeAsync(stmt);
@ -920,29 +951,37 @@ add_task(async function test_defaultTransactionType() {
Assert.ok(db instanceof Ci.mozIStorageAsyncConnection); Assert.ok(db instanceof Ci.mozIStorageAsyncConnection);
info("Verify default transaction type"); info("Verify default transaction type");
Assert.equal(db.defaultTransactionType, Assert.equal(
Ci.mozIStorageConnection.TRANSACTION_DEFERRED); db.defaultTransactionType,
Ci.mozIStorageConnection.TRANSACTION_DEFERRED
);
info("Test other transaction types"); info("Test other transaction types");
for (let type of [Ci.mozIStorageConnection.TRANSACTION_IMMEDIATE, for (let type of [
Ci.mozIStorageConnection.TRANSACTION_EXCLUSIVE]) { Ci.mozIStorageConnection.TRANSACTION_IMMEDIATE,
Ci.mozIStorageConnection.TRANSACTION_EXCLUSIVE,
]) {
db.defaultTransactionType = type; db.defaultTransactionType = type;
Assert.equal(db.defaultTransactionType, type); Assert.equal(db.defaultTransactionType, type);
} }
info("Should reject unknown transaction types"); info("Should reject unknown transaction types");
Assert.throws(() => db.defaultTransactionType = Assert.throws(
Ci.mozIStorageConnection.TRANSACTION_DEFAULT, () =>
/NS_ERROR_ILLEGAL_VALUE/); (db.defaultTransactionType =
Ci.mozIStorageConnection.TRANSACTION_DEFAULT),
/NS_ERROR_ILLEGAL_VALUE/
);
db.defaultTransactionType = db.defaultTransactionType = Ci.mozIStorageConnection.TRANSACTION_IMMEDIATE;
Ci.mozIStorageConnection.TRANSACTION_IMMEDIATE;
info("Clone should inherit default transaction type"); info("Clone should inherit default transaction type");
let clone = await asyncClone(db, true); let clone = await asyncClone(db, true);
Assert.ok(clone instanceof Ci.mozIStorageAsyncConnection); Assert.ok(clone instanceof Ci.mozIStorageAsyncConnection);
Assert.equal(clone.defaultTransactionType, Assert.equal(
Ci.mozIStorageConnection.TRANSACTION_IMMEDIATE); clone.defaultTransactionType,
Ci.mozIStorageConnection.TRANSACTION_IMMEDIATE
);
info("Begin immediate transaction on main connection"); info("Begin immediate transaction on main connection");
db.beginTransaction(); db.beginTransaction();
@ -972,7 +1011,8 @@ add_task(async function test_defaultTransactionType() {
add_task(async function test_getInterface() { add_task(async function test_getInterface() {
let db = getOpenedDatabase(); let db = getOpenedDatabase();
let target = db.QueryInterface(Ci.nsIInterfaceRequestor) let target = db
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIEventTarget); .getInterface(Ci.nsIEventTarget);
// Just check that target is non-null. Other tests will ensure that it has // Just check that target is non-null. Other tests will ensure that it has
// the correct value. // the correct value.

View file

@ -11,7 +11,8 @@ function test_table_creation() {
var msc = getOpenedUnsharedDatabase(); var msc = getOpenedUnsharedDatabase();
msc.executeSimpleSQL( msc.executeSimpleSQL(
"CREATE VIRTUAL TABLE recipe USING fts3(name, ingredients)"); "CREATE VIRTUAL TABLE recipe USING fts3(name, ingredients)"
);
Assert.ok(msc.tableExists("recipe")); Assert.ok(msc.tableExists("recipe"));
} }
@ -19,14 +20,22 @@ function test_table_creation() {
function test_insertion() { function test_insertion() {
var msc = getOpenedUnsharedDatabase(); var msc = getOpenedUnsharedDatabase();
msc.executeSimpleSQL("INSERT INTO recipe (name, ingredients) VALUES " + msc.executeSimpleSQL(
"('broccoli stew', 'broccoli peppers cheese tomatoes')"); "INSERT INTO recipe (name, ingredients) VALUES " +
msc.executeSimpleSQL("INSERT INTO recipe (name, ingredients) VALUES " + "('broccoli stew', 'broccoli peppers cheese tomatoes')"
"('pumpkin stew', 'pumpkin onions garlic celery')"); );
msc.executeSimpleSQL("INSERT INTO recipe (name, ingredients) VALUES " + msc.executeSimpleSQL(
"('broccoli pie', 'broccoli cheese onions flour')"); "INSERT INTO recipe (name, ingredients) VALUES " +
msc.executeSimpleSQL("INSERT INTO recipe (name, ingredients) VALUES " + "('pumpkin stew', 'pumpkin onions garlic celery')"
"('pumpkin pie', 'pumpkin sugar flour butter')"); );
msc.executeSimpleSQL(
"INSERT INTO recipe (name, ingredients) VALUES " +
"('broccoli pie', 'broccoli cheese onions flour')"
);
msc.executeSimpleSQL(
"INSERT INTO recipe (name, ingredients) VALUES " +
"('pumpkin pie', 'pumpkin sugar flour butter')"
);
var stmt = msc.createStatement("SELECT COUNT(*) FROM recipe"); var stmt = msc.createStatement("SELECT COUNT(*) FROM recipe");
stmt.executeStep(); stmt.executeStep();
@ -41,7 +50,8 @@ function test_selection() {
var msc = getOpenedUnsharedDatabase(); var msc = getOpenedUnsharedDatabase();
var stmt = msc.createStatement( var stmt = msc.createStatement(
"SELECT rowid, name, ingredients FROM recipe WHERE name MATCH 'pie'"); "SELECT rowid, name, ingredients FROM recipe WHERE name MATCH 'pie'"
);
Assert.ok(stmt.executeStep()); Assert.ok(stmt.executeStep());
Assert.equal(stmt.getInt32(0), 3); Assert.equal(stmt.getInt32(0), 3);

View file

@ -72,9 +72,14 @@ function test_function_result() {
stmt.finalize(); stmt.finalize();
} }
var tests = [test_function_registration, test_function_no_double_registration, var tests = [
test_function_removal, test_function_aliases, test_function_call, test_function_registration,
test_function_result]; test_function_no_double_registration,
test_function_removal,
test_function_aliases,
test_function_call,
test_function_result,
];
function run_test() { function run_test() {
setup(); setup();

View file

@ -9,7 +9,9 @@ function setup() {
msc.createTable("handler_tests", "id INTEGER PRIMARY KEY, num INTEGER"); msc.createTable("handler_tests", "id INTEGER PRIMARY KEY, num INTEGER");
msc.beginTransaction(); msc.beginTransaction();
var stmt = createStatement("INSERT INTO handler_tests (id, num) VALUES(?1, ?2)"); var stmt = createStatement(
"INSERT INTO handler_tests (id, num) VALUES(?1, ?2)"
);
for (let i = 0; i < 100; ++i) { for (let i = 0; i < 100; ++i) {
stmt.bindByIndex(0, i); stmt.bindByIndex(0, i);
stmt.bindByIndex(1, Math.floor(Math.random() * 1000)); stmt.bindByIndex(1, Math.floor(Math.random() * 1000));
@ -53,7 +55,8 @@ function test_handler_call() {
msc.setProgressHandler(50, testProgressHandler); msc.setProgressHandler(50, testProgressHandler);
// Some long-executing request // Some long-executing request
var stmt = createStatement( var stmt = createStatement(
"SELECT SUM(t1.num * t2.num) FROM handler_tests AS t1, handler_tests AS t2"); "SELECT SUM(t1.num * t2.num) FROM handler_tests AS t1, handler_tests AS t2"
);
while (stmt.executeStep()) { while (stmt.executeStep()) {
// Do nothing. // Do nothing.
} }
@ -67,7 +70,8 @@ function test_handler_abort() {
msc.setProgressHandler(50, testProgressHandler); msc.setProgressHandler(50, testProgressHandler);
// Some long-executing request // Some long-executing request
var stmt = createStatement( var stmt = createStatement(
"SELECT SUM(t1.num * t2.num) FROM handler_tests AS t1, handler_tests AS t2"); "SELECT SUM(t1.num * t2.num) FROM handler_tests AS t1, handler_tests AS t2"
);
const SQLITE_INTERRUPT = 9; const SQLITE_INTERRUPT = 9;
try { try {
@ -89,9 +93,13 @@ function test_handler_abort() {
} }
} }
var tests = [test_handler_registration, test_handler_return, var tests = [
test_handler_removal, test_handler_call, test_handler_registration,
test_handler_abort]; test_handler_return,
test_handler_removal,
test_handler_call,
test_handler_abort,
];
function run_test() { function run_test() {
setup(); setup();

View file

@ -84,7 +84,10 @@ function test_backup_not_new_filename() {
} }
function test_backup_new_filename() { function test_backup_new_filename() {
var backup = Services.storage.backupDatabaseFile(getTestDB(), BACKUP_FILE_NAME); var backup = Services.storage.backupDatabaseFile(
getTestDB(),
BACKUP_FILE_NAME
);
Assert.equal(BACKUP_FILE_NAME, backup.leafName); Assert.equal(BACKUP_FILE_NAME, backup.leafName);
backup.remove(false); backup.remove(false);
@ -93,13 +96,17 @@ function test_backup_new_filename() {
function test_backup_new_folder() { function test_backup_new_folder() {
var parentDir = getTestDB().parent; var parentDir = getTestDB().parent;
parentDir.append("test_storage_temp"); parentDir.append("test_storage_temp");
if (parentDir.exists()) if (parentDir.exists()) {
parentDir.remove(true); parentDir.remove(true);
}
parentDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0o755); parentDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0o755);
Assert.ok(parentDir.exists()); Assert.ok(parentDir.exists());
var backup = Services.storage.backupDatabaseFile(getTestDB(), BACKUP_FILE_NAME, var backup = Services.storage.backupDatabaseFile(
parentDir); getTestDB(),
BACKUP_FILE_NAME,
parentDir
);
Assert.equal(BACKUP_FILE_NAME, backup.leafName); Assert.equal(BACKUP_FILE_NAME, backup.leafName);
Assert.ok(parentDir.equals(backup.parent)); Assert.ok(parentDir.equals(backup.parent));

View file

@ -20,12 +20,15 @@ function test_openUnsharedDatabase_file_exists() {
Assert.ok(db.exists()); Assert.ok(db.exists());
} }
var tests = [test_openUnsharedDatabase_file_DNE, var tests = [
test_openUnsharedDatabase_file_exists]; test_openUnsharedDatabase_file_DNE,
test_openUnsharedDatabase_file_exists,
];
function run_test() { function run_test() {
for (var i = 0; i < tests.length; i++) for (var i = 0; i < tests.length; i++) {
tests[i](); tests[i]();
}
cleanup(); cleanup();
} }

View file

@ -30,7 +30,9 @@ function test_getParameterName() {
} }
function test_getParameterIndex_different() { function test_getParameterIndex_different() {
var stmt = createStatement("SELECT * FROM test WHERE id = :id OR name = :name"); var stmt = createStatement(
"SELECT * FROM test WHERE id = :id OR name = :name"
);
Assert.equal(0, stmt.getParameterIndex("id")); Assert.equal(0, stmt.getParameterIndex("id"));
Assert.equal(1, stmt.getParameterIndex("name")); Assert.equal(1, stmt.getParameterIndex("name"));
stmt.reset(); stmt.reset();
@ -38,7 +40,9 @@ function test_getParameterIndex_different() {
} }
function test_getParameterIndex_same() { function test_getParameterIndex_same() {
var stmt = createStatement("SELECT * FROM test WHERE id = :test OR name = :test"); var stmt = createStatement(
"SELECT * FROM test WHERE id = :test OR name = :test"
);
Assert.equal(0, stmt.getParameterIndex("test")); Assert.equal(0, stmt.getParameterIndex("test"));
stmt.reset(); stmt.reset();
stmt.finalize(); stmt.finalize();
@ -100,11 +104,15 @@ function test_state_executing() {
stmt = createStatement("SELECT name, id FROM test"); stmt = createStatement("SELECT name, id FROM test");
stmt.executeStep(); stmt.executeStep();
Assert.equal(Ci.mozIStorageStatement.MOZ_STORAGE_STATEMENT_EXECUTING, Assert.equal(
stmt.state); Ci.mozIStorageStatement.MOZ_STORAGE_STATEMENT_EXECUTING,
stmt.state
);
stmt.executeStep(); stmt.executeStep();
Assert.equal(Ci.mozIStorageStatement.MOZ_STORAGE_STATEMENT_EXECUTING, Assert.equal(
stmt.state); Ci.mozIStorageStatement.MOZ_STORAGE_STATEMENT_EXECUTING,
stmt.state
);
stmt.reset(); stmt.reset();
Assert.equal(Ci.mozIStorageStatement.MOZ_STORAGE_STATEMENT_READY, stmt.state); Assert.equal(Ci.mozIStorageStatement.MOZ_STORAGE_STATEMENT_READY, stmt.state);
stmt.finalize(); stmt.finalize();
@ -114,7 +122,10 @@ function test_state_after_finalize() {
var stmt = createStatement("SELECT name, id FROM test"); var stmt = createStatement("SELECT name, id FROM test");
stmt.executeStep(); stmt.executeStep();
stmt.finalize(); stmt.finalize();
Assert.equal(Ci.mozIStorageStatement.MOZ_STORAGE_STATEMENT_INVALID, stmt.state); Assert.equal(
Ci.mozIStorageStatement.MOZ_STORAGE_STATEMENT_INVALID,
stmt.state
);
} }
function test_failed_execute() { function test_failed_execute() {
@ -139,18 +150,24 @@ function test_failed_execute() {
function test_bind_undefined() { function test_bind_undefined() {
var stmt = createStatement("INSERT INTO test (name) VALUES ('foo')"); var stmt = createStatement("INSERT INTO test (name) VALUES ('foo')");
expectError(Cr.NS_ERROR_ILLEGAL_VALUE, expectError(Cr.NS_ERROR_ILLEGAL_VALUE, () => stmt.bindParameters(undefined));
() => stmt.bindParameters(undefined));
stmt.finalize(); stmt.finalize();
} }
var tests = [test_parameterCount_none, test_parameterCount_one, var tests = [
test_getParameterName, test_getParameterIndex_different, test_parameterCount_none,
test_getParameterIndex_same, test_columnCount, test_parameterCount_one,
test_getColumnName, test_getColumnIndex_same_case, test_getParameterName,
test_getColumnIndex_different_case, test_state_ready, test_getParameterIndex_different,
test_state_executing, test_state_after_finalize, test_getParameterIndex_same,
test_columnCount,
test_getColumnName,
test_getColumnIndex_same_case,
test_getColumnIndex_different_case,
test_state_ready,
test_state_executing,
test_state_after_finalize,
test_failed_execute, test_failed_execute,
test_bind_undefined, test_bind_undefined,
]; ];
@ -164,4 +181,3 @@ function run_test() {
cleanup(); cleanup();
} }

View file

@ -5,11 +5,15 @@
// This file tests the functions of mozIStorageValueArray // This file tests the functions of mozIStorageValueArray
add_task(async function setup() { add_task(async function setup() {
getOpenedDatabase().createTable("test", "id INTEGER PRIMARY KEY, name TEXT," + getOpenedDatabase().createTable(
"number REAL, nuller NULL, blobber BLOB"); "test",
"id INTEGER PRIMARY KEY, name TEXT," +
"number REAL, nuller NULL, blobber BLOB"
);
var stmt = createStatement("INSERT INTO test (name, number, blobber) " + var stmt = createStatement(
"VALUES (?1, ?2, ?3)"); "INSERT INTO test (name, number, blobber) " + "VALUES (?1, ?2, ?3)"
);
stmt.bindByIndex(0, "foo"); stmt.bindByIndex(0, "foo");
stmt.bindByIndex(1, 2.34); stmt.bindByIndex(1, 2.34);
stmt.bindBlobByIndex(2, [], 0); stmt.bindBlobByIndex(2, [], 0);
@ -53,8 +57,10 @@ add_task(async function test_value_type_null() {
stmt.bindByIndex(0, 1); stmt.bindByIndex(0, 1);
Assert.ok(stmt.executeStep()); Assert.ok(stmt.executeStep());
Assert.equal(Ci.mozIStorageValueArray.VALUE_TYPE_NULL, Assert.equal(
stmt.getTypeOfIndex(0)); Ci.mozIStorageValueArray.VALUE_TYPE_NULL,
stmt.getTypeOfIndex(0)
);
stmt.reset(); stmt.reset();
stmt.finalize(); stmt.finalize();
}); });
@ -64,8 +70,10 @@ add_task(async function test_value_type_integer() {
stmt.bindByIndex(0, 1); stmt.bindByIndex(0, 1);
Assert.ok(stmt.executeStep()); Assert.ok(stmt.executeStep());
Assert.equal(Ci.mozIStorageValueArray.VALUE_TYPE_INTEGER, Assert.equal(
stmt.getTypeOfIndex(0)); Ci.mozIStorageValueArray.VALUE_TYPE_INTEGER,
stmt.getTypeOfIndex(0)
);
stmt.reset(); stmt.reset();
stmt.finalize(); stmt.finalize();
}); });
@ -75,8 +83,10 @@ add_task(async function test_value_type_float() {
stmt.bindByIndex(0, 1); stmt.bindByIndex(0, 1);
Assert.ok(stmt.executeStep()); Assert.ok(stmt.executeStep());
Assert.equal(Ci.mozIStorageValueArray.VALUE_TYPE_FLOAT, Assert.equal(
stmt.getTypeOfIndex(0)); Ci.mozIStorageValueArray.VALUE_TYPE_FLOAT,
stmt.getTypeOfIndex(0)
);
stmt.reset(); stmt.reset();
stmt.finalize(); stmt.finalize();
}); });
@ -86,8 +96,10 @@ add_task(async function test_value_type_text() {
stmt.bindByIndex(0, 1); stmt.bindByIndex(0, 1);
Assert.ok(stmt.executeStep()); Assert.ok(stmt.executeStep());
Assert.equal(Ci.mozIStorageValueArray.VALUE_TYPE_TEXT, Assert.equal(
stmt.getTypeOfIndex(0)); Ci.mozIStorageValueArray.VALUE_TYPE_TEXT,
stmt.getTypeOfIndex(0)
);
stmt.reset(); stmt.reset();
stmt.finalize(); stmt.finalize();
}); });
@ -97,8 +109,10 @@ add_task(async function test_value_type_blob() {
stmt.bindByIndex(0, 2); stmt.bindByIndex(0, 2);
Assert.ok(stmt.executeStep()); Assert.ok(stmt.executeStep());
Assert.equal(Ci.mozIStorageValueArray.VALUE_TYPE_BLOB, Assert.equal(
stmt.getTypeOfIndex(0)); Ci.mozIStorageValueArray.VALUE_TYPE_BLOB,
stmt.getTypeOfIndex(0)
);
stmt.reset(); stmt.reset();
stmt.finalize(); stmt.finalize();
}); });
@ -178,5 +192,3 @@ add_task(async function test_getBlob() {
stmt.reset(); stmt.reset();
stmt.finalize(); stmt.finalize();
}); });

View file

@ -16,7 +16,9 @@ function new_file(name) {
return file; return file;
} }
function run_test() { function run_test() {
let read_hgram = Services.telemetry.getHistogramById("MOZ_SQLITE_OTHER_READ_B"); let read_hgram = Services.telemetry.getHistogramById(
"MOZ_SQLITE_OTHER_READ_B"
);
let old_sum = read_hgram.snapshot().sum; let old_sum = read_hgram.snapshot().sum;
const file = new_file("telemetry.sqlite"); const file = new_file("telemetry.sqlite");
var d = getDatabase(file); var d = getDatabase(file);

View file

@ -29,7 +29,9 @@ add_task(async function setup() {
}); });
add_task(async function test_upper_ascii() { add_task(async function test_upper_ascii() {
var stmt = createStatement("SELECT name, id FROM test WHERE name = upper('a')"); var stmt = createStatement(
"SELECT name, id FROM test WHERE name = upper('a')"
);
Assert.ok(stmt.executeStep()); Assert.ok(stmt.executeStep());
Assert.equal("A", stmt.getString(0)); Assert.equal("A", stmt.getString(0));
Assert.equal(2, stmt.getInt32(1)); Assert.equal(2, stmt.getInt32(1));
@ -38,7 +40,9 @@ add_task(async function test_upper_ascii() {
}); });
add_task(async function test_upper_non_ascii() { add_task(async function test_upper_non_ascii() {
var stmt = createStatement("SELECT name, id FROM test WHERE name = upper(?1)"); var stmt = createStatement(
"SELECT name, id FROM test WHERE name = upper(?1)"
);
stmt.bindByIndex(0, LATIN1_ae); stmt.bindByIndex(0, LATIN1_ae);
Assert.ok(stmt.executeStep()); Assert.ok(stmt.executeStep());
Assert.equal(LATIN1_AE, stmt.getString(0)); Assert.equal(LATIN1_AE, stmt.getString(0));
@ -48,7 +52,9 @@ add_task(async function test_upper_non_ascii() {
}); });
add_task(async function test_lower_ascii() { add_task(async function test_lower_ascii() {
var stmt = createStatement("SELECT name, id FROM test WHERE name = lower('B')"); var stmt = createStatement(
"SELECT name, id FROM test WHERE name = lower('B')"
);
Assert.ok(stmt.executeStep()); Assert.ok(stmt.executeStep());
Assert.equal("b", stmt.getString(0)); Assert.equal("b", stmt.getString(0));
Assert.equal(3, stmt.getInt32(1)); Assert.equal(3, stmt.getInt32(1));
@ -57,7 +63,9 @@ add_task(async function test_lower_ascii() {
}); });
add_task(async function test_lower_non_ascii() { add_task(async function test_lower_non_ascii() {
var stmt = createStatement("SELECT name, id FROM test WHERE name = lower(?1)"); var stmt = createStatement(
"SELECT name, id FROM test WHERE name = lower(?1)"
);
stmt.bindByIndex(0, LATIN1_AE); stmt.bindByIndex(0, LATIN1_AE);
Assert.ok(stmt.executeStep()); Assert.ok(stmt.executeStep());
Assert.equal(LATIN1_ae, stmt.getString(0)); Assert.equal(LATIN1_ae, stmt.getString(0));

View file

@ -17,9 +17,9 @@ function load_test_vacuum_component() {
// This is a lazy check, there could be more participants than just this test // This is a lazy check, there could be more participants than just this test
// we just mind that the test exists though. // we just mind that the test exists though.
const EXPECTED_ENTRIES = ["vacuumParticipant"]; const EXPECTED_ENTRIES = ["vacuumParticipant"];
let {catMan} = Services; let { catMan } = Services;
let found = false; let found = false;
for (let {data: entry} of catMan.enumerateCategory(CATEGORY_NAME)) { for (let { data: entry } of catMan.enumerateCategory(CATEGORY_NAME)) {
print("Check if the found category entry (" + entry + ") is expected."); print("Check if the found category entry (" + entry + ") is expected.");
if (EXPECTED_ENTRIES.includes(entry)) { if (EXPECTED_ENTRIES.includes(entry)) {
print("Check that only one test entry exists."); print("Check that only one test entry exists.");
@ -76,9 +76,10 @@ function run_test() {
} }
const TESTS = [ const TESTS = [
function test_common_vacuum() { function test_common_vacuum() {
print("\n*** Test that a VACUUM correctly happens and all notifications are fired."); print(
"\n*** Test that a VACUUM correctly happens and all notifications are fired."
);
// Wait for VACUUM begin. // Wait for VACUUM begin.
let beginVacuumReceived = false; let beginVacuumReceived = false;
Services.obs.addObserver(function onVacuum(aSubject, aTopic, aData) { Services.obs.addObserver(function onVacuum(aSubject, aTopic, aData) {
@ -118,8 +119,10 @@ const TESTS = [
function test_skipped_if_recent_vacuum() { function test_skipped_if_recent_vacuum() {
print("\n*** Test that a VACUUM is skipped if it was run recently."); print("\n*** Test that a VACUUM is skipped if it was run recently.");
Services.prefs.setIntPref("storage.vacuum.last.testVacuum.sqlite", Services.prefs.setIntPref(
parseInt(Date.now() / 1000)); "storage.vacuum.last.testVacuum.sqlite",
parseInt(Date.now() / 1000)
);
// Wait for VACUUM begin. // Wait for VACUUM begin.
let vacuumObserver = { let vacuumObserver = {
@ -162,7 +165,9 @@ const TESTS = [
}, },
function test_skipped_optout_vacuum() { function test_skipped_optout_vacuum() {
print("\n*** Test that a VACUUM is skipped if the participant wants to opt-out."); print(
"\n*** Test that a VACUUM is skipped if the participant wants to opt-out."
);
Services.obs.notifyObservers(null, "test-options", "opt-out"); Services.obs.notifyObservers(null, "test-options", "opt-out");
// Wait for VACUUM begin. // Wait for VACUUM begin.
@ -307,8 +312,10 @@ function run_next_test() {
do_test_finished(); do_test_finished();
} else { } else {
// Set last VACUUM to a date in the past. // Set last VACUUM to a date in the past.
Services.prefs.setIntPref("storage.vacuum.last.testVacuum.sqlite", Services.prefs.setIntPref(
parseInt(Date.now() / 1000 - 31 * 86400)); "storage.vacuum.last.testVacuum.sqlite",
parseInt(Date.now() / 1000 - 31 * 86400)
);
executeSoon(TESTS.shift()); executeSoon(TESTS.shift());
} }
} }

View file

@ -4,8 +4,10 @@
// This testing component is used in test_vacuum* tests. // This testing component is used in test_vacuum* tests.
const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); const { XPCOMUtils } = ChromeUtils.import(
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); "resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
/** /**
* Returns a new nsIFile reference for a profile database. * Returns a new nsIFile reference for a profile database.
@ -30,8 +32,7 @@ function vacuumParticipant() {
Services.obs.addObserver(this, "test-options"); Services.obs.addObserver(this, "test-options");
} }
vacuumParticipant.prototype = vacuumParticipant.prototype = {
{
classDescription: "vacuumParticipant", classDescription: "vacuumParticipant",
classID: Components.ID("{52aa0b22-b82f-4e38-992a-c3675a3355d2}"), classID: Components.ID("{52aa0b22-b82f-4e38-992a-c3675a3355d2}"),
contractID: "@unit.test.com/test-vacuum-participant;1", contractID: "@unit.test.com/test-vacuum-participant;1",