Skip to content

Commit ef05c17

Browse files
author
Oscar Franco
authored
Merge pull request #62 from ospfranco/proxy-object
2 parents d3160c1 + 5be1158 commit ef05c17

10 files changed

Lines changed: 137 additions & 121 deletions

File tree

README.md

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -135,14 +135,13 @@ openDatabase(
135135

136136
# Usage
137137

138-
Import as early as possible, auto-installs bindings in a thread-safe manner.
138+
Just import the package and fire away
139139

140140
```typescript
141141
// Thanks to @mrousavy for this installation method, see one example: https://github.com/mrousavy/react-native-mmkv/blob/75b425db530e26cf10c7054308583d03ff01851f/src/createMMKV.ts#L56
142-
import 'react-native-quick-sqlite';
142+
import { QuickSQLite } from 'react-native-quick-sqlite';
143143

144-
// Afterwards `sqlite` is a globally registered object, so you can directly call it from anywhere in your javascript
145-
const dbOpenResult = sqlite.open('myDatabase', 'databases');
144+
const dbOpenResult = QuickSQLite.open('myDatabase', 'databases');
146145

147146
// status === 1, operation failed
148147
if (dbOpenResult.status) {
@@ -155,7 +154,7 @@ if (dbOpenResult.status) {
155154
The basic query is **synchronous**, it will block rendering on large operations, below there are async versions.
156155

157156
```typescript
158-
let { status, rows } = sqlite.executeSql(
157+
let { status, rows } = QuickSQLite.executeSql(
159158
'myDatabase',
160159
'SELECT somevalue FROM sometable'
161160
);
@@ -165,7 +164,7 @@ if (!status) {
165164
});
166165
}
167166

168-
let { status, rowsAffected } = sqlite.executeSql(
167+
let { status, rowsAffected } = QuickSQLite.executeSql(
169168
'myDatabase',
170169
'UPDATE sometable SET somecolumn = ? where somekey = ?',
171170
[0, 1]
@@ -182,7 +181,7 @@ Transactions are supported. However, due to the library being opinionated and mo
182181
JSI bindings are fast but there is still some overhead calling `executeSql` for single queries, if you want to execute a large set of commands as fast as possible you should use the `executeSqlBatch` method below, it still uses transactions, but only transmits data between JS and native once.
183182

184183
```typescript
185-
sqlite.transaction('myDatabase', (tx) => {
184+
QuickSQLite.transaction('myDatabase', (tx) => {
186185
const {
187186
status,
188187
} = tx.executeSql('UPDATE sometable SET somecolumn = ? where somekey = ?', [
@@ -209,7 +208,7 @@ const commands = [
209208
('INSERT INTO TABLE TEST (id) VALUES (?)', [2])
210209
][('INSERT INTO TABLE TEST (id) VALUES (?)', [[3], [4], [5], [6]])],
211210
];
212-
const result = sqlite.executeSqlBatch('myDatabase', commands);
211+
const result = QuickSQLite.executeSqlBatch('myDatabase', commands);
213212
if (!result.status) {
214213
// result.status undefined or 0 === success
215214
console.log(`Batch affected ${result.rowsAffected} rows`);
@@ -225,7 +224,7 @@ sqlite datatypes. When fetching data directly from tables or views linked to tab
225224
to identify the table declared types:
226225

227226
```typescript
228-
let { status, metadata } = sqlite.executeSql(
227+
let { status, metadata } = QuickSQLite.executeSql(
229228
'myDatabase',
230229
'SELECT int_column_1, bol_column_2 FROM sometable'
231230
);
@@ -244,7 +243,7 @@ if (!status) {
244243
You might have too much SQL to process and it will cause your application to freeze. There are async versions for some of the operations. This will offload the SQLite processing to a different thread.
245244

246245
```ts
247-
sqlite.asyncExecuteSql(
246+
QuickSQLite.asyncExecuteSql(
248247
'myDatabase',
249248
'SELECT * FROM "User";',
250249
[],
@@ -270,21 +269,29 @@ SQLite have a limit for attached databases: A default of 10, and a global max of
270269
References: [Attach](https://www.sqlite.org/lang_attach.html) - [Detach](https://www.sqlite.org/lang_detach.html)
271270

272271
```ts
273-
const result = sqlite.attach('mainDatabase', 'statistics', 'stats', '../databases',);
272+
const result = QuickSQLite.attach(
273+
'mainDatabase',
274+
'statistics',
275+
'stats',
276+
'../databases'
277+
);
274278

275279
// Database is attached sucefully
276-
if(!result.status) {
277-
const data = sqlite.executeSql('mainDatabase', 'SELECT * FROM some_table_from_mainschema a INNER JOIN stats.some_table b on a.id_column = b.id_column');
280+
if (!result.status) {
281+
const data = QuickSQLite.executeSql(
282+
'mainDatabase',
283+
'SELECT * FROM some_table_from_mainschema a INNER JOIN stats.some_table b on a.id_column = b.id_column'
284+
);
278285
// Consume the results
279-
if(!data.status) {}
286+
if (!data.status) {
287+
}
280288
}
281289

282290
// You can detach databases at any moment
283-
const detachResult = sqlite.detach('mainDatabase', 'stats');
284-
if(!detachResult.status) {
291+
const detachResult = QuickSQLite.detach('mainDatabase', 'stats');
292+
if (!detachResult.status) {
285293
// Database dettached
286294
}
287-
288295
```
289296

290297
## Use built-in SQLite

cpp/installer.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -498,5 +498,5 @@ void install(jsi::Runtime &rt, std::shared_ptr<react::CallInvoker> jsCallInvoker
498498
module.setProperty(rt, "loadSqlFile", move(loadSQLFile));
499499
module.setProperty(rt, "asyncLoadSqlFile", move(loadSQLFileAsync));
500500

501-
rt.global().setProperty(rt, "sqlite", move(module));
501+
rt.global().setProperty(rt, "__QuickSQLiteProxy", move(module));
502502
}

example/ios/Podfile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ target 'SequelExample' do
1111
:hermes_enabled => true
1212
)
1313

14-
# pod 'react-native-quick-sqlite', :path => '../..'
14+
pod 'react-native-quick-sqlite', :path => '../..'
1515

1616
post_install do |installer|
1717
react_native_post_install(installer)

example/ios/Podfile.lock

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ PODS:
228228
- React-jsinspector (0.67.3)
229229
- React-logger (0.67.3):
230230
- glog
231-
- react-native-quick-sqlite (3.1.6):
231+
- react-native-quick-sqlite (3.1.9):
232232
- React
233233
- React-callinvoker
234234
- React-Core
@@ -322,7 +322,7 @@ DEPENDENCIES:
322322
- React-jsiexecutor (from `../node_modules/react-native/ReactCommon/jsiexecutor`)
323323
- React-jsinspector (from `../node_modules/react-native/ReactCommon/jsinspector`)
324324
- React-logger (from `../node_modules/react-native/ReactCommon/logger`)
325-
- react-native-quick-sqlite (from `../node_modules/react-native-quick-sqlite`)
325+
- react-native-quick-sqlite (from `../..`)
326326
- React-perflogger (from `../node_modules/react-native/ReactCommon/reactperflogger`)
327327
- React-RCTActionSheet (from `../node_modules/react-native/Libraries/ActionSheetIOS`)
328328
- React-RCTAnimation (from `../node_modules/react-native/Libraries/NativeAnimation`)
@@ -381,7 +381,7 @@ EXTERNAL SOURCES:
381381
React-logger:
382382
:path: "../node_modules/react-native/ReactCommon/logger"
383383
react-native-quick-sqlite:
384-
:path: "../node_modules/react-native-quick-sqlite"
384+
:path: "../.."
385385
React-perflogger:
386386
:path: "../node_modules/react-native/ReactCommon/reactperflogger"
387387
React-RCTActionSheet:
@@ -431,7 +431,7 @@ SPEC CHECKSUMS:
431431
React-jsiexecutor: 15ea57ead631a11fad57634ff69f78e797113a39
432432
React-jsinspector: 1e1e03345cf6d47779e2061d679d0a87d9ae73d8
433433
React-logger: 1e10789cb84f99288479ba5f20822ce43ced6ffe
434-
react-native-quick-sqlite: 0ef475fce0dc4bf4fdc2a9844d79a698414ea0b9
434+
react-native-quick-sqlite: 839371a5e9ee06ce460a3e4f27f93fd51c2d31b4
435435
React-perflogger: 93d3f142d6d9a46e635f09ba0518027215a41098
436436
React-RCTActionSheet: 87327c3722203cc79cf79d02fb83e7332aeedd18
437437
React-RCTAnimation: 009c87c018d50e0b38692699405ebe631ff4872d
@@ -446,6 +446,6 @@ SPEC CHECKSUMS:
446446
ReactCommon: 650e33cde4fb7d36781cd3143f5276da0abb2f96
447447
Yoga: 90dcd029e45d8a7c1ff059e8b3c6612ff409061a
448448

449-
PODFILE CHECKSUM: d17e982a36a0c00f901deed42f61b5a036acbc9f
449+
PODFILE CHECKSUM: 23fbb34cc9cd3db2810e5bb10e37bce3ce025dee
450450

451451
COCOAPODS: 1.11.3

example/package.json

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
"buffer": "^6.0.3",
1616
"react": "17.0.2",
1717
"react-native": "0.67.3",
18-
"react-native-quick-sqlite": "./..",
1918
"reflect-metadata": "^0.1.13",
2019
"typeorm": "^0.3.6"
2120
},

example/src/App.tsx

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@ import {
1515
queryUsers,
1616
testInsert,
1717
testTransaction,
18-
typeORMGetBooks,
19-
typeORMInit,
18+
// typeORMGetBooks,
19+
// typeORMInit,
2020
executeFailingTypeORMQuery,
2121
} from './Database';
2222
import type { User } from './model/User';
@@ -26,14 +26,15 @@ export default function App() {
2626
let [users, setUsers] = React.useState<User[]>([]);
2727

2828
React.useEffect(() => {
29-
// lowLevelInit();
30-
// const users = queryUsers();
31-
// setUsers(users);
32-
typeORMInit().then(() => {
33-
typeORMGetBooks().then((books) => {
34-
// console.warn('typeORM books', books);
35-
});
36-
});
29+
lowLevelInit();
30+
const users = queryUsers();
31+
console.warn('db users', users);
32+
setUsers(users);
33+
// typeORMInit().then(() => {
34+
// typeORMGetBooks().then((books) => {
35+
// // console.warn('typeORM books', books);
36+
// });
37+
// });
3738
}, []);
3839

3940
return (
@@ -58,6 +59,10 @@ export default function App() {
5859
title="Create user (with transaction)"
5960
onPress={() => {
6061
testTransaction();
62+
setTimeout(() => {
63+
const users = queryUsers();
64+
setUsers(users);
65+
}, 1000);
6166
}}
6267
/>
6368
<Button

example/src/Database.ts

Lines changed: 12 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/* eslint-disable no-undef */
2-
import '../..';
2+
import { QuickSQLite as sqlite } from 'react-native-quick-sqlite';
33
import { DataSource } from 'typeorm';
44
import { Book } from './model/Book';
55
import { User } from './model/User';
@@ -30,47 +30,35 @@ export const lowLevelInit = () => {
3030
export const testTransaction = () => {
3131
sqlite.transaction('test', (tx) => {
3232
tx.executeSql(
33-
'INSERT INTO "User" (id, name, age, networth) VALUES(?, ?, ?, ?)',
33+
'INSERT INTO "User" (id, name, age, networth) VALUES(?, ?, ?, ?);',
3434
[new Date().getMilliseconds(), `Jerry`, 45, 20.23]
3535
);
36-
37-
tx.executeSql(
38-
'INSERT INTO "User" (id, name, age, networth) VALUES(?, ?, ?, ?)',
39-
[new Date().getMilliseconds(), `Tom`, 23, 100]
40-
);
41-
36+
console.warn('committing transaction');
4237
// return true to commit transaction, false to revert
4338
return true;
4439
});
4540
};
4641

4742
export const testInsert = () => {
4843
// Basic request
49-
const { status: createUserStatus } = sqlite.executeSql(
44+
const { status: createUserStatus, message } = sqlite.executeSql(
5045
'test',
51-
'INSERT INTO "User" (id, name, age, networth) VALUES(?, ?, ?, ?)',
52-
[
53-
new Date().getMilliseconds(),
54-
`{"nickname":"mike", "name":"michael"}`,
55-
32,
56-
3000.23,
57-
]
46+
'INSERT INTO "User" (id, name, age, networth) VALUES(?, ?, ?, ?);',
47+
[new Date().getMilliseconds(), `TOM`, 32, 3000.23]
5848
);
5949

6050
// handle error
6151
if (createUserStatus) {
62-
console.error('Failed to insert user');
52+
console.error('Failed to insert user:', message);
6353
}
6454

55+
console.warn('user inserted', createUserStatus);
56+
6557
return queryUsers();
6658
};
6759

6860
export const queryUsers = () => {
69-
const queryResult = sqlite.executeSql(
70-
'test',
71-
`SELECT *, json_extract("User".name, '$.nickname') as name FROM "User"`,
72-
[]
73-
);
61+
const queryResult = sqlite.executeSql('test', `SELECT * FROM "User"`, []);
7462

7563
return queryResult.rows?._array;
7664

@@ -83,9 +71,9 @@ export const queryUsers = () => {
8371
export async function typeORMInit() {
8472
datasource = new DataSource({
8573
type: 'react-native',
86-
database: 'test2',
74+
database: 'test',
8775
location: '.',
88-
entities: [Book],
76+
entities: [Book, User],
8977
synchronize: true,
9078
});
9179

ios/QuickSQLite.mm

Lines changed: 19 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,42 @@
1-
/*
2-
* Sequel.mm
3-
*
4-
* Created by Oscar Franco on 2021/03/07
5-
* Copyright (c) 2021 Oscar Franco
6-
*
7-
* This code is licensed under the MIT license
8-
*/
9-
101
#import "QuickSQLite.h"
11-
#import "installer.h"
122

133
#import <React/RCTBridge+Private.h>
14-
#import <jsi/jsi.h>
15-
#import <ReactCommon/RCTTurboModuleManager.h>
164

175
#import <React/RCTUtils.h>
18-
#import <ReactCommon/CallInvoker.h>
6+
#import <ReactCommon/RCTTurboModule.h>
7+
#import <jsi/jsi.h>
198

20-
#import <memory>
9+
#import "../cpp/installer.h"
2110

2211
@implementation QuickSQLite
2312

24-
@synthesize bridge = _bridge;
25-
@synthesize methodQueue = _methodQueue;
13+
RCT_EXPORT_MODULE(QuickSQLite)
2614

27-
RCT_EXPORT_MODULE()
2815

29-
+ (BOOL)requiresMainQueueSetup {
30-
return YES;
31-
}
16+
RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(install) {
17+
NSLog(@"Installing QuickSQLite module...");
18+
19+
RCTBridge *bridge = [RCTBridge currentBridge];
20+
RCTCxxBridge *cxxBridge = (RCTCxxBridge *)bridge;
21+
if (cxxBridge == nil) {
22+
return @false;
23+
}
3224

33-
- (void)setBridge:(RCTBridge *)bridge {
34-
_bridge = bridge;
35-
_setBridgeOnMainQueue = RCTIsMainQueue();
25+
using namespace facebook;
3626

37-
RCTCxxBridge *cxxBridge = (RCTCxxBridge *)self.bridge;
38-
if (!cxxBridge.runtime) {
39-
return;
27+
auto jsiRuntime = (jsi::Runtime *)cxxBridge.runtime;
28+
if (jsiRuntime == nil) {
29+
return @false;
4030
}
41-
31+
auto &runtime = *jsiRuntime;
4232
auto callInvoker = bridge.jsCallInvoker;
4333

4434
// Get iOS app's document directory (to safely store database .sqlite3 file)
4535
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true);
4636
NSString *documentPath = [paths objectAtIndex:0];
4737

48-
install(*(facebook::jsi::Runtime *)cxxBridge.runtime, callInvoker,[documentPath UTF8String]);
38+
install(runtime, callInvoker,[documentPath UTF8String]);
39+
return @true;
4940
}
5041

5142
@end

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "react-native-quick-sqlite",
3-
"version": "3.1.9",
3+
"version": "4.0.0",
44
"description": "Fast SQLite for react-native",
55
"main": "lib/commonjs/index",
66
"module": "lib/module/index",

0 commit comments

Comments
 (0)