Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cpp/DBHostObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ void DBHostObject::create_jsi_functions() {

return create_js_rows(rt, status);
});

function_map["executeRawSync"] = HOSTFN("executeRawSync") {
const std::string query = args[0].asString(rt).utf8(rt);
std::vector<JSVariant> params = count == 2 && args[1].isObject()
Expand Down
13 changes: 5 additions & 8 deletions cpp/bridge.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -855,15 +855,12 @@ opsqlite_execute_batch(sqlite3 *db,
const auto &command = commands->at(i);
// We do not provide a datastructure to receive query data because we
// don't need/want to handle this results in a batch execution
try {
auto result = opsqlite_execute(db, command.sql, &command.params);
affectedRows += result.affectedRows;
} catch (std::exception &exc) {
opsqlite_execute(db, "ROLLBACK", nullptr);
throw exc;
}
// There is also no need to commit/catch this transaction, this is done
// in the JS code
auto result = opsqlite_execute(db, command.sql, &command.params);
affectedRows += result.affectedRows;
}
// opsqlite_execute(db, "COMMIT", nullptr);

return BatchResult{
.affectedRows = affectedRows,
.commands = static_cast<int>(commandCount),
Expand Down
2 changes: 1 addition & 1 deletion example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"build:ios": "cd ios && xcodebuild -workspace OPSQLiteExample.xcworkspace -scheme debug -configuration Debug -sdk iphonesimulator CC=clang CPLUSPLUS=clang++ LD=clang LDPLUSPLUS=clang++ GCC_OPTIMIZATION_LEVEL=0 GCC_PRECOMPILE_PREFIX_HEADER=YES ASSETCATALOG_COMPILER_OPTIMIZATION=time DEBUG_INFORMATION_FORMAT=dwarf COMPILER_INDEX_STORE_ENABLE=NO"
},
"dependencies": {
"@op-engineering/op-test": "^0.2.3",
"@op-engineering/op-test": "^0.2.4",
"chance": "^1.1.9",
"clsx": "^2.0.0",
"events": "^3.3.0",
Expand Down
35 changes: 35 additions & 0 deletions example/src/tests/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,41 @@ describe('Hooks', () => {
db.updateHook(null);
});

it('Execute batch should trigger update hook', async () => {
const id = chance.integer();
const name = chance.name();
const age = chance.integer();
const networth = chance.floating();

db.executeSync(
'INSERT INTO "User" (id, name, age, networth) VALUES(?, ?, ?, ?)',
[id, name, age, networth],
);

let promiseResolve: any;
let promise = new Promise<{
rowId: number;
row?: any;
operation: string;
table: string;
}>(resolve => {
promiseResolve = resolve;
});

db.updateHook(data => {
promiseResolve(data);
});

await db.executeBatch([
['UPDATE "User" SET name = ? WHERE id = ?', ['foo', id]],
]);

const data = await promise;

expect(data.operation).toEqual('UPDATE');
expect(data.rowId).toEqual(1);
});

it('remove update hook', async () => {
const hookRes: string[] = [];

Expand Down
2 changes: 1 addition & 1 deletion example/src/tests/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -579,7 +579,7 @@ describe('Queries tests', () => {
expect(ranCallback).toEqual(true);
});

it('Batch execute', async () => {
it('executeBatch', async () => {
const id1 = chance.integer();
const name1 = chance.name();
const age1 = chance.integer();
Expand Down
71 changes: 71 additions & 0 deletions example/src/tests/reactive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,77 @@ describe('Reactive queries', () => {
unsubscribe3();
});

it('Row reactive query with executeBatch', async () => {
let firstReactiveRan = false;
let secondReactiveRan = false;
let emittedUser = null;

const unsubscribe = db.reactiveExecute({
query: 'SELECT * FROM User;',
arguments: [],
fireOn: [
{
table: 'User',
ids: [2],
},
],
callback: () => {
firstReactiveRan = true;
},
});

const unsubscribe2 = db.reactiveExecute({
query: 'SELECT * FROM User;',
arguments: [],
fireOn: [
{
table: 'Foo',
},
],
callback: () => {
secondReactiveRan = true;
},
});

const unsubscribe3 = db.reactiveExecute({
query: 'SELECT name FROM User;',
arguments: [],
fireOn: [
{
table: 'User',
ids: [1],
},
],
callback: data => {
emittedUser = data.rows[0];
},
});

await db.executeBatch([
[
'INSERT INTO User (id, name, age, networth, nickname) VALUES (?, ?, ?, ?, ?);',
[1, 'John', 30, 1000, 'Johnny'],
],
]);

await sleep(0);

await db.transaction(async tx => {
await tx.execute('UPDATE User SET name = ? WHERE id = ?;', ['Foo', 1]);
});

await sleep(0);

expect(!!firstReactiveRan).toBe(false);
expect(!!secondReactiveRan).toBe(false);
expect(emittedUser).toDeepEqual({
name: 'Foo',
});
unsubscribe();
unsubscribe2();
unsubscribe3();
});

it('Update hook and reactive queries work at the same time', async () => {
let promiseResolve: any;
let promise = new Promise(resolve => {
Expand Down
16 changes: 9 additions & 7 deletions src/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,22 +97,24 @@ function enhanceDB(db: _InternalDB, options: DBParams): DB {
executeBatch: async (
commands: SQLBatchTuple[]
): Promise<BatchQueryResult> => {
const sanitizedCommands = commands.map(([query, params]) => {
if (params) {
return [query, sanitizeArrayBuffersInArray(params)];
// Do normal for loop and replace in place for performance
for (let i = 0; i < commands.length; i++) {
// [1] is the params arg
if (commands[i]![1]) {
commands[i]![1] = sanitizeArrayBuffersInArray(commands[i]![1]) as any;
}

return [query];
});
}

async function run() {
try {
enhancedDb.executeSync('BEGIN TRANSACTION;');

let res = await db.executeBatch(sanitizedCommands as any[]);
let res = await db.executeBatch(commands as any[]);

enhancedDb.executeSync('COMMIT;');

await db.flushPendingReactiveQueries();

return res;
} catch (executionError) {
try {
Expand Down
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ export type ColumnMetadata = {
*/
export type SQLBatchTuple =
| [string]
| [string, Array<Scalar> | Array<Array<Scalar>>];
| [string, Scalar[]]
| [string, Scalar[][]];

export type UpdateHookOperation = 'INSERT' | 'DELETE' | 'UPDATE';

Expand Down
10 changes: 5 additions & 5 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3262,15 +3262,15 @@ __metadata:
languageName: unknown
linkType: soft

"@op-engineering/op-test@npm:^0.2.3":
version: 0.2.3
resolution: "@op-engineering/op-test@npm:0.2.3"
"@op-engineering/op-test@npm:^0.2.4":
version: 0.2.4
resolution: "@op-engineering/op-test@npm:0.2.4"
dependencies:
react-native-safe-area-context: "npm:^5.6.1"
peerDependencies:
react: "*"
react-native: "*"
checksum: 10c0/a256568acef2d72b739cbb33ac4e7d7541b028ad49ad5512a6e806eec3dc3bff485b9251a22f6148a0fa46f7a2d2e25c981b476bc65b5b48a21a7fb1aea14136
checksum: 10c0/6dacc5124b0d2e23e9c95a33d120bc5edde4fd2f6bb05e3e2b77487549856b2577a5285320472982df7b1907e9e1b43e5062484914c1f37b34b1795d8439e0c2
languageName: node
linkType: hard

Expand Down Expand Up @@ -7365,7 +7365,7 @@ __metadata:
"@babel/core": "npm:^7.25.2"
"@babel/preset-env": "npm:^7.25.3"
"@babel/runtime": "npm:^7.25.0"
"@op-engineering/op-test": "npm:^0.2.3"
"@op-engineering/op-test": "npm:^0.2.4"
"@react-native-community/cli": "npm:^18.0.0"
"@react-native-community/cli-platform-android": "npm:18.0.0"
"@react-native-community/cli-platform-ios": "npm:18.0.0"
Expand Down
Loading