expo-sqlite 14.0.0 → 14.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/android/build.gradle +5 -5
- package/android/src/main/java/expo/modules/sqlite/SQLiteModuleNext.kt +14 -0
- package/build/ExpoSQLiteNext.d.ts +1 -0
- package/build/ExpoSQLiteNext.d.ts.map +1 -1
- package/build/ExpoSQLiteNext.js +3 -0
- package/build/ExpoSQLiteNext.js.map +1 -1
- package/build/SQLiteDatabase.js.map +1 -1
- package/build/SQLiteStatement.js.map +1 -1
- package/build/hooks.d.ts +19 -0
- package/build/hooks.d.ts.map +1 -1
- package/build/hooks.js +20 -7
- package/build/hooks.js.map +1 -1
- package/build/legacy/SQLite.d.ts.map +1 -1
- package/build/legacy/SQLite.js.map +1 -1
- package/build/legacy/SQLite.web.js.map +1 -1
- package/build/legacy/polyfillNextTick.js.map +1 -1
- package/build/paramUtils.js.map +1 -1
- package/ios/ExpoSQLite.podspec +2 -1
- package/ios/SQLiteModuleNext.swift +16 -0
- package/package.json +2 -2
- package/src/ExpoSQLiteNext.ts +8 -0
- package/src/hooks.tsx +58 -5
package/CHANGELOG.md
CHANGED
|
@@ -10,6 +10,18 @@
|
|
|
10
10
|
|
|
11
11
|
### 💡 Others
|
|
12
12
|
|
|
13
|
+
## 14.0.2 — 2024-04-22
|
|
14
|
+
|
|
15
|
+
### 🎉 New features
|
|
16
|
+
|
|
17
|
+
- Bumped SQLite version to 3.45.3 and enabled the [bytecodevtab](https://www.sqlite.org/bytecodevtab.html) feature. ([#28358](https://github.com/expo/expo/pull/28358) by [@kudo](https://github.com/kudo))
|
|
18
|
+
|
|
19
|
+
## 14.0.1 — 2024-04-19
|
|
20
|
+
|
|
21
|
+
### 🎉 New features
|
|
22
|
+
|
|
23
|
+
- Added `SQLiteProvider.assetSource` to import an existing database from assets. ([#28291](https://github.com/expo/expo/pull/28291) by [@kudo](https://github.com/kudo))
|
|
24
|
+
|
|
13
25
|
## 14.0.0 — 2024-04-18
|
|
14
26
|
|
|
15
27
|
### 🛠 Breaking changes
|
package/android/build.gradle
CHANGED
|
@@ -4,7 +4,7 @@ apply plugin: 'com.android.library'
|
|
|
4
4
|
apply plugin: 'de.undercouch.download'
|
|
5
5
|
|
|
6
6
|
group = 'host.exp.exponent'
|
|
7
|
-
version = '14.0.
|
|
7
|
+
version = '14.0.2'
|
|
8
8
|
|
|
9
9
|
def expoModulesCorePlugin = new File(project(":expo-modules-core").projectDir.absolutePath, "ExpoModulesCorePlugin.gradle")
|
|
10
10
|
apply from: expoModulesCorePlugin
|
|
@@ -21,13 +21,13 @@ String toPlatformIndependentPath(File path) {
|
|
|
21
21
|
return result
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
-
def SQLITE_VERSION = '
|
|
24
|
+
def SQLITE_VERSION = '3450300'
|
|
25
25
|
def customDownloadsDir = System.getenv("REACT_NATIVE_DOWNLOADS_DIR")
|
|
26
26
|
def downloadsDir = customDownloadsDir ? new File(customDownloadsDir) : new File("$buildDir/downloads")
|
|
27
27
|
def SQLITE3_SRC_DIR = new File("$buildDir/sqlite3_src")
|
|
28
28
|
|
|
29
29
|
def getSQLiteBuildFlags() {
|
|
30
|
-
def buildFlags = ''
|
|
30
|
+
def buildFlags = '-DSQLITE_ENABLE_BYTECODE_VTAB=1'
|
|
31
31
|
if (findProperty('expo.sqlite.enableFTS') !== 'false') {
|
|
32
32
|
buildFlags <<= '-DSQLITE_ENABLE_FTS4=1 -DSQLITE_ENABLE_FTS3_PARENTHESIS=1 -DSQLITE_ENABLE_FTS5=1'
|
|
33
33
|
}
|
|
@@ -57,7 +57,7 @@ android {
|
|
|
57
57
|
namespace "expo.modules.sqlite"
|
|
58
58
|
defaultConfig {
|
|
59
59
|
versionCode 18
|
|
60
|
-
versionName "14.0.
|
|
60
|
+
versionName "14.0.2"
|
|
61
61
|
|
|
62
62
|
externalNativeBuild {
|
|
63
63
|
cmake {
|
|
@@ -89,7 +89,7 @@ def createNativeDepsDirectories = tasks.register('createNativeDepsDirectories')
|
|
|
89
89
|
|
|
90
90
|
def downloadSQLite = tasks.register('downloadSQLite', Download) {
|
|
91
91
|
dependsOn(createNativeDepsDirectories)
|
|
92
|
-
src("https://www.sqlite.org/
|
|
92
|
+
src("https://www.sqlite.org/2024/sqlite-amalgamation-${SQLITE_VERSION}.zip")
|
|
93
93
|
onlyIfNewer(true)
|
|
94
94
|
overwrite(false)
|
|
95
95
|
dest(new File(downloadsDir, "sqlite-amalgamation-${SQLITE_VERSION}.zip"))
|
|
@@ -3,7 +3,9 @@
|
|
|
3
3
|
package expo.modules.sqlite
|
|
4
4
|
|
|
5
5
|
import android.content.Context
|
|
6
|
+
import android.net.Uri
|
|
6
7
|
import android.util.Log
|
|
8
|
+
import androidx.core.net.toFile
|
|
7
9
|
import androidx.core.os.bundleOf
|
|
8
10
|
import expo.modules.kotlin.exception.Exceptions
|
|
9
11
|
import expo.modules.kotlin.modules.Module
|
|
@@ -50,6 +52,18 @@ class SQLiteModuleNext : Module() {
|
|
|
50
52
|
deleteDatabase(databaseName)
|
|
51
53
|
}
|
|
52
54
|
|
|
55
|
+
AsyncFunction("importAssetDatabaseAsync") { databaseName: String, assetDatabasePath: String, forceOverwrite: Boolean ->
|
|
56
|
+
val dbFile = File(pathForDatabaseName(databaseName))
|
|
57
|
+
if (dbFile.exists() && !forceOverwrite) {
|
|
58
|
+
return@AsyncFunction
|
|
59
|
+
}
|
|
60
|
+
val assetFile = Uri.parse(assetDatabasePath).toFile()
|
|
61
|
+
if (!assetFile.isFile) {
|
|
62
|
+
throw OpenDatabaseException(assetDatabasePath)
|
|
63
|
+
}
|
|
64
|
+
assetFile.copyTo(dbFile, forceOverwrite)
|
|
65
|
+
}
|
|
66
|
+
|
|
53
67
|
Class(NativeDatabase::class) {
|
|
54
68
|
Constructor { databaseName: String, options: OpenDatabaseOptions, serializedData: ByteArray? ->
|
|
55
69
|
val database: NativeDatabase
|
|
@@ -4,6 +4,7 @@ declare const _default: {
|
|
|
4
4
|
NativeStatement(): void;
|
|
5
5
|
deleteDatabaseAsync(databaseName: string): Promise<void>;
|
|
6
6
|
deleteDatabaseSync(databaseName: string): void;
|
|
7
|
+
importAssetDatabaseAsync(databaseName: string, assetDatabasePath: string, forceOverwrite: boolean): Promise<void>;
|
|
7
8
|
addListener(): never;
|
|
8
9
|
removeListeners(): never;
|
|
9
10
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ExpoSQLiteNext.d.ts","sourceRoot":"","sources":["../src/ExpoSQLiteNext.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;;iCAInC,MAAM,YACV,iBAAiB,mBACV,UAAU,GAC1B,IAAI;uBAIY,IAAI;sCAIiB,MAAM,GAAG,
|
|
1
|
+
{"version":3,"file":"ExpoSQLiteNext.d.ts","sourceRoot":"","sources":["../src/ExpoSQLiteNext.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;;iCAInC,MAAM,YACV,iBAAiB,mBACV,UAAU,GAC1B,IAAI;uBAIY,IAAI;sCAIiB,MAAM,GAAG,QAAQ,IAAI,CAAC;qCAI7B,MAAM,GAAG,IAAI;2CAK9B,MAAM,qBACD,MAAM,kBACT,OAAO,GACtB,QAAQ,IAAI,CAAC;;;;AAzBlB,wBAuCE"}
|
package/build/ExpoSQLiteNext.js
CHANGED
|
@@ -11,6 +11,9 @@ export default {
|
|
|
11
11
|
deleteDatabaseSync(databaseName) {
|
|
12
12
|
throw new Error('Unimplemented');
|
|
13
13
|
},
|
|
14
|
+
importAssetDatabaseAsync(databaseName, assetDatabasePath, forceOverwrite) {
|
|
15
|
+
throw new Error('Unimplemented');
|
|
16
|
+
},
|
|
14
17
|
//#region EventEmitter implementations
|
|
15
18
|
addListener() {
|
|
16
19
|
throw new Error('Unimplemented');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ExpoSQLiteNext.js","sourceRoot":"","sources":["../src/ExpoSQLiteNext.ts"],"names":[],"mappings":"AAEA,eAAe;IACb,cAAc,CACZ,YAAoB,EACpB,OAA2B,EAC3B,cAA2B;QAE3B,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;IACnC,CAAC;IAED,eAAe;QACb,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;IACnC,CAAC;IAED,KAAK,CAAC,mBAAmB,CAAC,YAAoB;QAC5C,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;IACnC,CAAC;IAED,kBAAkB,CAAC,YAAoB;QACrC,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;IACnC,CAAC;IAED,sCAAsC;IAEtC,WAAW;QACT,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;IACnC,CAAC;IACD,eAAe;QACb,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;IACnC,CAAC;IAED,YAAY;CACb,CAAC","sourcesContent":["import { SQLiteOpenOptions } from './NativeDatabase';\n\nexport default {\n NativeDatabase(\n databaseName: string,\n options?: SQLiteOpenOptions,\n serializedData?: Uint8Array\n ): void {\n throw new Error('Unimplemented');\n },\n\n NativeStatement(): void {\n throw new Error('Unimplemented');\n },\n\n async deleteDatabaseAsync(databaseName: string): Promise<void> {\n throw new Error('Unimplemented');\n },\n\n deleteDatabaseSync(databaseName: string): void {\n throw new Error('Unimplemented');\n },\n\n //#region EventEmitter implementations\n\n addListener() {\n throw new Error('Unimplemented');\n },\n removeListeners() {\n throw new Error('Unimplemented');\n },\n\n //#endregion\n};\n"]}
|
|
1
|
+
{"version":3,"file":"ExpoSQLiteNext.js","sourceRoot":"","sources":["../src/ExpoSQLiteNext.ts"],"names":[],"mappings":"AAEA,eAAe;IACb,cAAc,CACZ,YAAoB,EACpB,OAA2B,EAC3B,cAA2B;QAE3B,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;IACnC,CAAC;IAED,eAAe;QACb,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;IACnC,CAAC;IAED,KAAK,CAAC,mBAAmB,CAAC,YAAoB;QAC5C,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;IACnC,CAAC;IAED,kBAAkB,CAAC,YAAoB;QACrC,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;IACnC,CAAC;IAED,wBAAwB,CACtB,YAAoB,EACpB,iBAAyB,EACzB,cAAuB;QAEvB,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;IACnC,CAAC;IAED,sCAAsC;IAEtC,WAAW;QACT,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;IACnC,CAAC;IACD,eAAe;QACb,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;IACnC,CAAC;IAED,YAAY;CACb,CAAC","sourcesContent":["import { SQLiteOpenOptions } from './NativeDatabase';\n\nexport default {\n NativeDatabase(\n databaseName: string,\n options?: SQLiteOpenOptions,\n serializedData?: Uint8Array\n ): void {\n throw new Error('Unimplemented');\n },\n\n NativeStatement(): void {\n throw new Error('Unimplemented');\n },\n\n async deleteDatabaseAsync(databaseName: string): Promise<void> {\n throw new Error('Unimplemented');\n },\n\n deleteDatabaseSync(databaseName: string): void {\n throw new Error('Unimplemented');\n },\n\n importAssetDatabaseAsync(\n databaseName: string,\n assetDatabasePath: string,\n forceOverwrite: boolean\n ): Promise<void> {\n throw new Error('Unimplemented');\n },\n\n //#region EventEmitter implementations\n\n addListener() {\n throw new Error('Unimplemented');\n },\n removeListeners() {\n throw new Error('Unimplemented');\n },\n\n //#endregion\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SQLiteDatabase.js","sourceRoot":"","sources":["../src/SQLiteDatabase.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAgB,MAAM,mBAAmB,CAAC;AAE/D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AAQ,EAAE,CAAC;IAC1B,OAAO,IAAI,cAAc,CAAC,UAAU,EAAE,WAAW,EAAE,cAAc,CAAC,CAAC;AACrE,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,mBAAmB,CAAC,YAAoB;IAC5D,OAAO,MAAM,UAAU,CAAC,mBAAmB,CAAC,YAAY,CAAC,CAAC;AAC5D,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,kBAAkB,CAAC,YAAoB;IACrD,OAAO,UAAU,CAAC,kBAAkB,CAAC,YAAY,CAAC,CAAC;AACrD,CAAC;AAmBD;;;;;;GAMG;AACH,MAAM,UAAU,yBAAyB,CACvC,QAA8C;IAE9C,OAAO,OAAO,CAAC,WAAW,CAAC,kBAAkB,EAAE,QAAQ,CAAC,CAAC;AAC3D,CAAC;AAED;;;GAGG;AACH,MAAM,WAAY,SAAQ,cAAc;IAC/B,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC,EAAkB;QAChD,MAAM,OAAO,GAAG,EAAE,GAAG,EAAE,CAAC,OAAO,EAAE,gBAAgB,EAAE,IAAI,EAAE,CAAC;QAC1D,MAAM,cAAc,GAAG,IAAI,UAAU,CAAC,cAAc,CAAC,EAAE,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;QAC/E,MAAM,cAAc,CAAC,SAAS,EAAE,CAAC;QACjC,OAAO,IAAI,WAAW,CAAC,EAAE,CAAC,YAAY,EAAE,OAAO,EAAE,cAAc,CAAC,CAAC;IACnE,CAAC;CACF","sourcesContent":["import { EventEmitter, Subscription } from 'expo-modules-core';\n\nimport ExpoSQLite from './ExpoSQLiteNext';\nimport { NativeDatabase, SQLiteOpenOptions } from './NativeDatabase';\nimport {\n SQLiteBindParams,\n SQLiteExecuteAsyncResult,\n SQLiteExecuteSyncResult,\n SQLiteRunResult,\n SQLiteStatement,\n SQLiteVariadicBindParams,\n} from './SQLiteStatement';\n\nexport { SQLiteOpenOptions };\n\nconst emitter = new EventEmitter(ExpoSQLite);\n\n/**\n * A SQLite database.\n */\nexport class SQLiteDatabase {\n constructor(\n public readonly databaseName: string,\n public readonly options: SQLiteOpenOptions,\n private readonly nativeDatabase: NativeDatabase\n ) {}\n\n /**\n * Asynchronous call to return whether the database is currently in a transaction.\n */\n public isInTransactionAsync(): Promise<boolean> {\n return this.nativeDatabase.isInTransactionAsync();\n }\n\n /**\n * Close the database.\n */\n public closeAsync(): Promise<void> {\n return this.nativeDatabase.closeAsync();\n }\n\n /**\n * Execute all SQL queries in the supplied string.\n * > Note: The queries are not escaped for you! Be careful when constructing your queries.\n *\n * @param source A string containing all the SQL queries.\n */\n public execAsync(source: string): Promise<void> {\n return this.nativeDatabase.execAsync(source);\n }\n\n /**\n * [Serialize the database](https://sqlite.org/c3ref/serialize.html) as `Uint8Array`.\n *\n * @param databaseName The name of the current attached databases. The default value is `main` which is the default database name.\n */\n public serializeAsync(databaseName: string = 'main'): Promise<Uint8Array> {\n return this.nativeDatabase.serializeAsync(databaseName);\n }\n\n /**\n * Create a [prepared SQLite statement](https://www.sqlite.org/c3ref/prepare.html).\n *\n * @param source A string containing the SQL query.\n */\n public async prepareAsync(source: string): Promise<SQLiteStatement> {\n const nativeStatement = new ExpoSQLite.NativeStatement();\n await this.nativeDatabase.prepareAsync(nativeStatement, source);\n return new SQLiteStatement(this.nativeDatabase, nativeStatement);\n }\n\n /**\n * Execute a transaction and automatically commit/rollback based on the `task` result.\n *\n * > **Note:** This transaction is not exclusive and can be interrupted by other async queries.\n * @example\n * ```ts\n * db.withTransactionAsync(async () => {\n * await db.execAsync('UPDATE test SET name = \"aaa\"');\n *\n * //\n * // We cannot control the order of async/await order, so order of execution is not guaranteed.\n * // The following UPDATE query out of transaction may be executed here and break the expectation.\n * //\n *\n * const result = await db.getAsync<{ name: string }>('SELECT name FROM Users');\n * expect(result?.name).toBe('aaa');\n * });\n * db.execAsync('UPDATE test SET name = \"bbb\"');\n * ```\n * If you worry about the order of execution, use `withExclusiveTransactionAsync` instead.\n *\n * @param task An async function to execute within a transaction.\n */\n public async withTransactionAsync(task: () => Promise<void>): Promise<void> {\n try {\n await this.execAsync('BEGIN');\n await task();\n await this.execAsync('COMMIT');\n } catch (e) {\n await this.execAsync('ROLLBACK');\n throw e;\n }\n }\n\n /**\n * Execute a transaction and automatically commit/rollback based on the `task` result.\n *\n * The transaction may be exclusive.\n * As long as the transaction is converted into a write transaction,\n * the other async write queries will abort with `database is locked` error.\n *\n * @param task An async function to execute within a transaction. Any queries inside the transaction must be executed on the `txn` object.\n * The `txn` object has the same interfaces as the [`SQLiteDatabase`](#sqlitedatabase) object. You can use `txn` like a [`SQLiteDatabase`](#sqlitedatabase) object.\n *\n * @example\n * ```ts\n * db.withExclusiveTransactionAsync(async (txn) => {\n * await txn.execAsync('UPDATE test SET name = \"aaa\"');\n * });\n * ```\n */\n public async withExclusiveTransactionAsync(\n task: (txn: Transaction) => Promise<void>\n ): Promise<void> {\n const transaction = await Transaction.createAsync(this);\n let error;\n try {\n await transaction.execAsync('BEGIN');\n await task(transaction);\n await transaction.execAsync('COMMIT');\n } catch (e) {\n await transaction.execAsync('ROLLBACK');\n error = e;\n } finally {\n await transaction.closeAsync();\n }\n if (error) {\n throw error;\n }\n }\n\n /**\n * Synchronous call to return whether the database is currently in a transaction.\n */\n public isInTransactionSync(): boolean {\n return this.nativeDatabase.isInTransactionSync();\n }\n\n /**\n * Close the database.\n */\n public closeSync(): void {\n return this.nativeDatabase.closeSync();\n }\n\n /**\n * Execute all SQL queries in the supplied string.\n *\n * > **Note:** The queries are not escaped for you! Be careful when constructing your queries.\n *\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n *\n * @param source A string containing all the SQL queries.\n */\n public execSync(source: string): void {\n return this.nativeDatabase.execSync(source);\n }\n\n /**\n * [Serialize the database](https://sqlite.org/c3ref/serialize.html) as `Uint8Array`.\n *\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n *\n * @param databaseName The name of the current attached databases. The default value is `main` which is the default database name.\n */\n public serializeSync(databaseName: string = 'main'): Uint8Array {\n return this.nativeDatabase.serializeSync(databaseName);\n }\n\n /**\n * Create a [prepared SQLite statement](https://www.sqlite.org/c3ref/prepare.html).\n *\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n *\n * @param source A string containing the SQL query.\n */\n public prepareSync(source: string): SQLiteStatement {\n const nativeStatement = new ExpoSQLite.NativeStatement();\n this.nativeDatabase.prepareSync(nativeStatement, source);\n return new SQLiteStatement(this.nativeDatabase, nativeStatement);\n }\n\n /**\n * Execute a transaction and automatically commit/rollback based on the `task` result.\n *\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n *\n * @param task An async function to execute within a transaction.\n */\n public withTransactionSync(task: () => void): void {\n try {\n this.execSync('BEGIN');\n task();\n this.execSync('COMMIT');\n } catch (e) {\n this.execSync('ROLLBACK');\n throw e;\n }\n }\n\n //#region Statement API shorthands\n\n /**\n * A convenience wrapper around [`SQLiteDatabase.prepareAsync()`](#prepareasyncsource), [`SQLiteStatement.executeAsync()`](#executeasyncparams), and [`SQLiteStatement.finalizeAsync()`](#finalizeasync).\n * @param source A string containing the SQL query.\n * @param params The parameters to bind to the prepared statement. You can pass values in array, object, or variadic arguments. See [`SQLiteBindValue`](#sqlitebindvalue) for more information about binding values.\n */\n public runAsync(source: string, params: SQLiteBindParams): Promise<SQLiteRunResult>;\n\n /**\n * @hidden\n */\n public runAsync(source: string, ...params: SQLiteVariadicBindParams): Promise<SQLiteRunResult>;\n public async runAsync(source: string, ...params: any[]): Promise<SQLiteRunResult> {\n const statement = await this.prepareAsync(source);\n let result: SQLiteExecuteAsyncResult<unknown>;\n try {\n result = await statement.executeAsync(...params);\n } finally {\n await statement.finalizeAsync();\n }\n return result;\n }\n\n /**\n * A convenience wrapper around [`SQLiteDatabase.prepareAsync()`](#prepareasyncsource), [`SQLiteStatement.executeAsync()`](#executeasyncparams), [`SQLiteExecuteAsyncResult.getFirstAsync()`](#getfirstasync), and [`SQLiteStatement.finalizeAsync()`](#finalizeasync).\n * @param source A string containing the SQL query.\n * @param params The parameters to bind to the prepared statement. You can pass values in array, object, or variadic arguments. See [`SQLiteBindValue`](#sqlitebindvalue) for more information about binding values.\n */\n public getFirstAsync<T>(source: string, params: SQLiteBindParams): Promise<T | null>;\n /**\n * @hidden\n */\n public getFirstAsync<T>(source: string, ...params: SQLiteVariadicBindParams): Promise<T | null>;\n public async getFirstAsync<T>(source: string, ...params: any[]): Promise<T | null> {\n const statement = await this.prepareAsync(source);\n let firstRow: T | null;\n try {\n const result = await statement.executeAsync<T>(...params);\n firstRow = await result.getFirstAsync();\n } finally {\n await statement.finalizeAsync();\n }\n return firstRow;\n }\n\n /**\n * A convenience wrapper around [`SQLiteDatabase.prepareAsync()`](#prepareasyncsource), [`SQLiteStatement.executeAsync()`](#executeasyncparams), [`SQLiteExecuteAsyncResult`](#sqliteexecuteasyncresult) `AsyncIterator`, and [`SQLiteStatement.finalizeAsync()`](#finalizeasync).\n * @param source A string containing the SQL query.\n * @param params The parameters to bind to the prepared statement. You can pass values in array, object, or variadic arguments. See [`SQLiteBindValue`](#sqlitebindvalue) for more information about binding values.\n * @returns Rather than returning Promise, this function returns an [`AsyncIterableIterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncIterator). You can use `for await...of` to iterate over the rows from the SQLite query result.\n */\n public getEachAsync<T>(source: string, params: SQLiteBindParams): AsyncIterableIterator<T>;\n /**\n * @hidden\n */\n public getEachAsync<T>(\n source: string,\n ...params: SQLiteVariadicBindParams\n ): AsyncIterableIterator<T>;\n public async *getEachAsync<T>(source: string, ...params: any[]): AsyncIterableIterator<T> {\n const statement = await this.prepareAsync(source);\n try {\n const result = await statement.executeAsync<T>(...params);\n for await (const row of result) {\n yield row;\n }\n } finally {\n await statement.finalizeAsync();\n }\n }\n\n /**\n * A convenience wrapper around [`SQLiteDatabase.prepareAsync()`](#prepareasyncsource), [`SQLiteStatement.executeAsync()`](#executeasyncparams), [`SQLiteExecuteAsyncResult.getAllAsync()`](#getallasync), and [`SQLiteStatement.finalizeAsync()`](#finalizeasync).\n * @param source A string containing the SQL query.\n * @param params The parameters to bind to the prepared statement. You can pass values in array, object, or variadic arguments. See [`SQLiteBindValue`](#sqlitebindvalue) for more information about binding values.\n * @example\n * ```ts\n * // For unnamed parameters, you pass values in an array.\n * db.getAllAsync('SELECT * FROM test WHERE intValue = ? AND name = ?', [1, 'Hello']);\n *\n * // For unnamed parameters, you pass values in variadic arguments.\n * db.getAllAsync('SELECT * FROM test WHERE intValue = ? AND name = ?', 1, 'Hello');\n *\n * // For named parameters, you should pass values in object.\n * db.getAllAsync('SELECT * FROM test WHERE intValue = $intValue AND name = $name', { $intValue: 1, $name: 'Hello' });\n * ```\n */\n public getAllAsync<T>(source: string, params: SQLiteBindParams): Promise<T[]>;\n /**\n * @hidden\n */\n public getAllAsync<T>(source: string, ...params: SQLiteVariadicBindParams): Promise<T[]>;\n public async getAllAsync<T>(source: string, ...params: any[]): Promise<T[]> {\n const statement = await this.prepareAsync(source);\n let allRows;\n try {\n const result = await statement.executeAsync<T>(...params);\n allRows = await result.getAllAsync();\n } finally {\n await statement.finalizeAsync();\n }\n return allRows;\n }\n\n /**\n * A convenience wrapper around [`SQLiteDatabase.prepareSync()`](#preparesyncsource), [`SQLiteStatement.executeSync()`](#executesyncparams), and [`SQLiteStatement.finalizeSync()`](#finalizesync).\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n * @param source A string containing the SQL query.\n * @param params The parameters to bind to the prepared statement. You can pass values in array, object, or variadic arguments. See [`SQLiteBindValue`](#sqlitebindvalue) for more information about binding values.\n */\n public runSync(source: string, params: SQLiteBindParams): SQLiteRunResult;\n /**\n * @hidden\n */\n public runSync(source: string, ...params: SQLiteVariadicBindParams): SQLiteRunResult;\n public runSync(source: string, ...params: any[]): SQLiteRunResult {\n const statement = this.prepareSync(source);\n let result: SQLiteExecuteSyncResult<unknown>;\n try {\n result = statement.executeSync(...params);\n } finally {\n statement.finalizeSync();\n }\n return result;\n }\n\n /**\n * A convenience wrapper around [`SQLiteDatabase.prepareSync()`](#preparesyncsource), [`SQLiteStatement.executeSync()`](#executesyncparams), [`SQLiteExecuteSyncResult.getFirstSync()`](#getfirstsync), and [`SQLiteStatement.finalizeSync()`](#finalizesync).\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n * @param source A string containing the SQL query.\n * @param params The parameters to bind to the prepared statement. You can pass values in array, object, or variadic arguments. See [`SQLiteBindValue`](#sqlitebindvalue) for more information about binding values.\n */\n public getFirstSync<T>(source: string, params: SQLiteBindParams): T | null;\n /**\n * @hidden\n */\n public getFirstSync<T>(source: string, ...params: SQLiteVariadicBindParams): T | null;\n public getFirstSync<T>(source: string, ...params: any[]): T | null {\n const statement = this.prepareSync(source);\n let firstRow: T | null;\n try {\n const result = statement.executeSync<T>(...params);\n firstRow = result.getFirstSync();\n } finally {\n statement.finalizeSync();\n }\n return firstRow;\n }\n\n /**\n * A convenience wrapper around [`SQLiteDatabase.prepareSync()`](#preparesyncsource), [`SQLiteStatement.executeSync()`](#executesyncparams), [`SQLiteExecuteSyncResult`](#sqliteexecutesyncresult) `Iterator`, and [`SQLiteStatement.finalizeSync()`](#finalizesync).\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n * @param source A string containing the SQL query.\n * @param params The parameters to bind to the prepared statement. You can pass values in array, object, or variadic arguments. See [`SQLiteBindValue`](#sqlitebindvalue) for more information about binding values.\n * @returns This function returns an [`IterableIterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator). You can use `for...of` to iterate over the rows from the SQLite query result.\n */\n public getEachSync<T>(source: string, params: SQLiteBindParams): IterableIterator<T>;\n /**\n * @hidden\n */\n public getEachSync<T>(source: string, ...params: SQLiteVariadicBindParams): IterableIterator<T>;\n public *getEachSync<T>(source: string, ...params: any[]): IterableIterator<T> {\n const statement = this.prepareSync(source);\n try {\n const result = statement.executeSync<T>(...params);\n for (const row of result) {\n yield row;\n }\n } finally {\n statement.finalizeSync();\n }\n }\n\n /**\n * A convenience wrapper around [`SQLiteDatabase.prepareSync()`](#preparesyncsource), [`SQLiteStatement.executeSync()`](#executesyncparams), [`SQLiteExecuteSyncResult.getAllSync()`](#getallsync), and [`SQLiteStatement.finalizeSync()`](#finalizesync).\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n * @param source A string containing the SQL query.\n * @param params The parameters to bind to the prepared statement. You can pass values in array, object, or variadic arguments. See [`SQLiteBindValue`](#sqlitebindvalue) for more information about binding values.\n */\n public getAllSync<T>(source: string, params: SQLiteBindParams): T[];\n /**\n * @hidden\n */\n public getAllSync<T>(source: string, ...params: SQLiteVariadicBindParams): T[];\n public getAllSync<T>(source: string, ...params: any[]): T[] {\n const statement = this.prepareSync(source);\n let allRows;\n try {\n const result = statement.executeSync<T>(...params);\n allRows = result.getAllSync();\n } finally {\n statement.finalizeSync();\n }\n return allRows;\n }\n\n //#endregion\n}\n\n/**\n * Open a database.\n *\n * @param databaseName The name of the database file to open.\n * @param options Open options.\n */\nexport async function openDatabaseAsync(\n databaseName: string,\n options?: SQLiteOpenOptions\n): Promise<SQLiteDatabase> {\n const openOptions = options ?? {};\n const nativeDatabase = new ExpoSQLite.NativeDatabase(databaseName, openOptions);\n await nativeDatabase.initAsync();\n return new SQLiteDatabase(databaseName, openOptions, nativeDatabase);\n}\n\n/**\n * Open a database.\n *\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n *\n * @param databaseName The name of the database file to open.\n * @param options Open options.\n */\nexport function openDatabaseSync(\n databaseName: string,\n options?: SQLiteOpenOptions\n): SQLiteDatabase {\n const openOptions = options ?? {};\n const nativeDatabase = new ExpoSQLite.NativeDatabase(databaseName, openOptions);\n nativeDatabase.initSync();\n return new SQLiteDatabase(databaseName, openOptions, nativeDatabase);\n}\n\n/**\n * Given a `Uint8Array` data and [deserialize to memory database](https://sqlite.org/c3ref/deserialize.html).\n *\n * @param serializedData The binary array to deserialize from [`SQLiteDatabase.serializeAsync()`](#serializeasyncdatabasename).\n * @param options Open options.\n */\nexport async function deserializeDatabaseAsync(\n serializedData: Uint8Array,\n options?: SQLiteOpenOptions\n): Promise<SQLiteDatabase> {\n const openOptions = options ?? {};\n const nativeDatabase = new ExpoSQLite.NativeDatabase(':memory:', openOptions, serializedData);\n await nativeDatabase.initAsync();\n return new SQLiteDatabase(':memory:', openOptions, nativeDatabase);\n}\n\n/**\n * Given a `Uint8Array` data and [deserialize to memory database](https://sqlite.org/c3ref/deserialize.html).\n *\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n *\n * @param serializedData The binary array to deserialize from [`SQLiteDatabase.serializeSync()`](#serializesyncdatabasename)\n * @param options Open options.\n */\nexport function deserializeDatabaseSync(\n serializedData: Uint8Array,\n options?: SQLiteOpenOptions\n): SQLiteDatabase {\n const openOptions = options ?? {};\n const nativeDatabase = new ExpoSQLite.NativeDatabase(':memory:', openOptions, serializedData);\n nativeDatabase.initSync();\n return new SQLiteDatabase(':memory:', openOptions, nativeDatabase);\n}\n\n/**\n * Delete a database file.\n *\n * @param databaseName The name of the database file to delete.\n */\nexport async function deleteDatabaseAsync(databaseName: string): Promise<void> {\n return await ExpoSQLite.deleteDatabaseAsync(databaseName);\n}\n\n/**\n * Delete a database file.\n *\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n *\n * @param databaseName The name of the database file to delete.\n */\nexport function deleteDatabaseSync(databaseName: string): void {\n return ExpoSQLite.deleteDatabaseSync(databaseName);\n}\n\n/**\n * The event payload for the listener of [`addDatabaseChangeListener`](#sqliteadddatabasechangelistenerlistener)\n */\nexport type DatabaseChangeEvent = {\n /** The database name. The value would be `main` by default and other database names if you use `ATTACH DATABASE` statement. */\n databaseName: string;\n\n /** The absolute file path to the database. */\n databaseFilePath: string;\n\n /** The table name. */\n tableName: string;\n\n /** The changed row ID. */\n rowId: number;\n};\n\n/**\n * Add a listener for database changes.\n * > Note: to enable this feature, you must set [`enableChangeListener` to `true`](#sqliteopenoptions) when opening the database.\n *\n * @param listener A function that receives the `databaseName`, `databaseFilePath`, `tableName` and `rowId` of the modified data.\n * @returns A `Subscription` object that you can call `remove()` on when you would like to unsubscribe the listener.\n */\nexport function addDatabaseChangeListener(\n listener: (event: DatabaseChangeEvent) => void\n): Subscription {\n return emitter.addListener('onDatabaseChange', listener);\n}\n\n/**\n * A new connection specific used for [`withExclusiveTransactionAsync`](#withexclusivetransactionasynctask).\n * @hidden not going to pull all the database methods to the document.\n */\nclass Transaction extends SQLiteDatabase {\n public static async createAsync(db: SQLiteDatabase): Promise<Transaction> {\n const options = { ...db.options, useNewConnection: true };\n const nativeDatabase = new ExpoSQLite.NativeDatabase(db.databaseName, options);\n await nativeDatabase.initAsync();\n return new Transaction(db.databaseName, options, nativeDatabase);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"SQLiteDatabase.js","sourceRoot":"","sources":["../src/SQLiteDatabase.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAgB,MAAM,mBAAmB,CAAC;AAE/D,OAAO,UAAU,MAAM,kBAAkB,CAAC;AAE1C,OAAO,EAKL,eAAe,GAEhB,MAAM,mBAAmB,CAAC;AAI3B,MAAM,OAAO,GAAG,IAAI,YAAY,CAAC,UAAU,CAAC,CAAC;AAE7C;;GAEG;AACH,MAAM,OAAO,cAAc;IAEP;IACA;IACC;IAHnB,YACkB,YAAoB,EACpB,OAA0B,EACzB,cAA8B;QAF/B,iBAAY,GAAZ,YAAY,CAAQ;QACpB,YAAO,GAAP,OAAO,CAAmB;QACzB,mBAAc,GAAd,cAAc,CAAgB;IAC9C,CAAC;IAEJ;;OAEG;IACI,oBAAoB;QACzB,OAAO,IAAI,CAAC,cAAc,CAAC,oBAAoB,EAAE,CAAC;IACpD,CAAC;IAED;;OAEG;IACI,UAAU;QACf,OAAO,IAAI,CAAC,cAAc,CAAC,UAA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AC;QACjC,OAAO,IAAI,WAAW,CAAC,EAAE,CAAC,YAAY,EAAE,OAAO,EAAE,cAAc,CAAC,CAAC;IACnE,CAAC;CACF","sourcesContent":["import { EventEmitter, Subscription } from 'expo-modules-core';\n\nimport ExpoSQLite from './ExpoSQLiteNext';\nimport { NativeDatabase, SQLiteOpenOptions } from './NativeDatabase';\nimport {\n SQLiteBindParams,\n SQLiteExecuteAsyncResult,\n SQLiteExecuteSyncResult,\n SQLiteRunResult,\n SQLiteStatement,\n SQLiteVariadicBindParams,\n} from './SQLiteStatement';\n\nexport { SQLiteOpenOptions };\n\nconst emitter = new EventEmitter(ExpoSQLite);\n\n/**\n * A SQLite database.\n */\nexport class SQLiteDatabase {\n constructor(\n public readonly databaseName: string,\n public readonly options: SQLiteOpenOptions,\n private readonly nativeDatabase: NativeDatabase\n ) {}\n\n /**\n * Asynchronous call to return whether the database is currently in a transaction.\n */\n public isInTransactionAsync(): Promise<boolean> {\n return this.nativeDatabase.isInTransactionAsync();\n }\n\n /**\n * Close the database.\n */\n public closeAsync(): Promise<void> {\n return this.nativeDatabase.closeAsync();\n }\n\n /**\n * Execute all SQL queries in the supplied string.\n * > Note: The queries are not escaped for you! Be careful when constructing your queries.\n *\n * @param source A string containing all the SQL queries.\n */\n public execAsync(source: string): Promise<void> {\n return this.nativeDatabase.execAsync(source);\n }\n\n /**\n * [Serialize the database](https://sqlite.org/c3ref/serialize.html) as `Uint8Array`.\n *\n * @param databaseName The name of the current attached databases. The default value is `main` which is the default database name.\n */\n public serializeAsync(databaseName: string = 'main'): Promise<Uint8Array> {\n return this.nativeDatabase.serializeAsync(databaseName);\n }\n\n /**\n * Create a [prepared SQLite statement](https://www.sqlite.org/c3ref/prepare.html).\n *\n * @param source A string containing the SQL query.\n */\n public async prepareAsync(source: string): Promise<SQLiteStatement> {\n const nativeStatement = new ExpoSQLite.NativeStatement();\n await this.nativeDatabase.prepareAsync(nativeStatement, source);\n return new SQLiteStatement(this.nativeDatabase, nativeStatement);\n }\n\n /**\n * Execute a transaction and automatically commit/rollback based on the `task` result.\n *\n * > **Note:** This transaction is not exclusive and can be interrupted by other async queries.\n * @example\n * ```ts\n * db.withTransactionAsync(async () => {\n * await db.execAsync('UPDATE test SET name = \"aaa\"');\n *\n * //\n * // We cannot control the order of async/await order, so order of execution is not guaranteed.\n * // The following UPDATE query out of transaction may be executed here and break the expectation.\n * //\n *\n * const result = await db.getAsync<{ name: string }>('SELECT name FROM Users');\n * expect(result?.name).toBe('aaa');\n * });\n * db.execAsync('UPDATE test SET name = \"bbb\"');\n * ```\n * If you worry about the order of execution, use `withExclusiveTransactionAsync` instead.\n *\n * @param task An async function to execute within a transaction.\n */\n public async withTransactionAsync(task: () => Promise<void>): Promise<void> {\n try {\n await this.execAsync('BEGIN');\n await task();\n await this.execAsync('COMMIT');\n } catch (e) {\n await this.execAsync('ROLLBACK');\n throw e;\n }\n }\n\n /**\n * Execute a transaction and automatically commit/rollback based on the `task` result.\n *\n * The transaction may be exclusive.\n * As long as the transaction is converted into a write transaction,\n * the other async write queries will abort with `database is locked` error.\n *\n * @param task An async function to execute within a transaction. Any queries inside the transaction must be executed on the `txn` object.\n * The `txn` object has the same interfaces as the [`SQLiteDatabase`](#sqlitedatabase) object. You can use `txn` like a [`SQLiteDatabase`](#sqlitedatabase) object.\n *\n * @example\n * ```ts\n * db.withExclusiveTransactionAsync(async (txn) => {\n * await txn.execAsync('UPDATE test SET name = \"aaa\"');\n * });\n * ```\n */\n public async withExclusiveTransactionAsync(\n task: (txn: Transaction) => Promise<void>\n ): Promise<void> {\n const transaction = await Transaction.createAsync(this);\n let error;\n try {\n await transaction.execAsync('BEGIN');\n await task(transaction);\n await transaction.execAsync('COMMIT');\n } catch (e) {\n await transaction.execAsync('ROLLBACK');\n error = e;\n } finally {\n await transaction.closeAsync();\n }\n if (error) {\n throw error;\n }\n }\n\n /**\n * Synchronous call to return whether the database is currently in a transaction.\n */\n public isInTransactionSync(): boolean {\n return this.nativeDatabase.isInTransactionSync();\n }\n\n /**\n * Close the database.\n */\n public closeSync(): void {\n return this.nativeDatabase.closeSync();\n }\n\n /**\n * Execute all SQL queries in the supplied string.\n *\n * > **Note:** The queries are not escaped for you! Be careful when constructing your queries.\n *\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n *\n * @param source A string containing all the SQL queries.\n */\n public execSync(source: string): void {\n return this.nativeDatabase.execSync(source);\n }\n\n /**\n * [Serialize the database](https://sqlite.org/c3ref/serialize.html) as `Uint8Array`.\n *\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n *\n * @param databaseName The name of the current attached databases. The default value is `main` which is the default database name.\n */\n public serializeSync(databaseName: string = 'main'): Uint8Array {\n return this.nativeDatabase.serializeSync(databaseName);\n }\n\n /**\n * Create a [prepared SQLite statement](https://www.sqlite.org/c3ref/prepare.html).\n *\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n *\n * @param source A string containing the SQL query.\n */\n public prepareSync(source: string): SQLiteStatement {\n const nativeStatement = new ExpoSQLite.NativeStatement();\n this.nativeDatabase.prepareSync(nativeStatement, source);\n return new SQLiteStatement(this.nativeDatabase, nativeStatement);\n }\n\n /**\n * Execute a transaction and automatically commit/rollback based on the `task` result.\n *\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n *\n * @param task An async function to execute within a transaction.\n */\n public withTransactionSync(task: () => void): void {\n try {\n this.execSync('BEGIN');\n task();\n this.execSync('COMMIT');\n } catch (e) {\n this.execSync('ROLLBACK');\n throw e;\n }\n }\n\n //#region Statement API shorthands\n\n /**\n * A convenience wrapper around [`SQLiteDatabase.prepareAsync()`](#prepareasyncsource), [`SQLiteStatement.executeAsync()`](#executeasyncparams), and [`SQLiteStatement.finalizeAsync()`](#finalizeasync).\n * @param source A string containing the SQL query.\n * @param params The parameters to bind to the prepared statement. You can pass values in array, object, or variadic arguments. See [`SQLiteBindValue`](#sqlitebindvalue) for more information about binding values.\n */\n public runAsync(source: string, params: SQLiteBindParams): Promise<SQLiteRunResult>;\n\n /**\n * @hidden\n */\n public runAsync(source: string, ...params: SQLiteVariadicBindParams): Promise<SQLiteRunResult>;\n public async runAsync(source: string, ...params: any[]): Promise<SQLiteRunResult> {\n const statement = await this.prepareAsync(source);\n let result: SQLiteExecuteAsyncResult<unknown>;\n try {\n result = await statement.executeAsync(...params);\n } finally {\n await statement.finalizeAsync();\n }\n return result;\n }\n\n /**\n * A convenience wrapper around [`SQLiteDatabase.prepareAsync()`](#prepareasyncsource), [`SQLiteStatement.executeAsync()`](#executeasyncparams), [`SQLiteExecuteAsyncResult.getFirstAsync()`](#getfirstasync), and [`SQLiteStatement.finalizeAsync()`](#finalizeasync).\n * @param source A string containing the SQL query.\n * @param params The parameters to bind to the prepared statement. You can pass values in array, object, or variadic arguments. See [`SQLiteBindValue`](#sqlitebindvalue) for more information about binding values.\n */\n public getFirstAsync<T>(source: string, params: SQLiteBindParams): Promise<T | null>;\n /**\n * @hidden\n */\n public getFirstAsync<T>(source: string, ...params: SQLiteVariadicBindParams): Promise<T | null>;\n public async getFirstAsync<T>(source: string, ...params: any[]): Promise<T | null> {\n const statement = await this.prepareAsync(source);\n let firstRow: T | null;\n try {\n const result = await statement.executeAsync<T>(...params);\n firstRow = await result.getFirstAsync();\n } finally {\n await statement.finalizeAsync();\n }\n return firstRow;\n }\n\n /**\n * A convenience wrapper around [`SQLiteDatabase.prepareAsync()`](#prepareasyncsource), [`SQLiteStatement.executeAsync()`](#executeasyncparams), [`SQLiteExecuteAsyncResult`](#sqliteexecuteasyncresult) `AsyncIterator`, and [`SQLiteStatement.finalizeAsync()`](#finalizeasync).\n * @param source A string containing the SQL query.\n * @param params The parameters to bind to the prepared statement. You can pass values in array, object, or variadic arguments. See [`SQLiteBindValue`](#sqlitebindvalue) for more information about binding values.\n * @returns Rather than returning Promise, this function returns an [`AsyncIterableIterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncIterator). You can use `for await...of` to iterate over the rows from the SQLite query result.\n */\n public getEachAsync<T>(source: string, params: SQLiteBindParams): AsyncIterableIterator<T>;\n /**\n * @hidden\n */\n public getEachAsync<T>(\n source: string,\n ...params: SQLiteVariadicBindParams\n ): AsyncIterableIterator<T>;\n public async *getEachAsync<T>(source: string, ...params: any[]): AsyncIterableIterator<T> {\n const statement = await this.prepareAsync(source);\n try {\n const result = await statement.executeAsync<T>(...params);\n for await (const row of result) {\n yield row;\n }\n } finally {\n await statement.finalizeAsync();\n }\n }\n\n /**\n * A convenience wrapper around [`SQLiteDatabase.prepareAsync()`](#prepareasyncsource), [`SQLiteStatement.executeAsync()`](#executeasyncparams), [`SQLiteExecuteAsyncResult.getAllAsync()`](#getallasync), and [`SQLiteStatement.finalizeAsync()`](#finalizeasync).\n * @param source A string containing the SQL query.\n * @param params The parameters to bind to the prepared statement. You can pass values in array, object, or variadic arguments. See [`SQLiteBindValue`](#sqlitebindvalue) for more information about binding values.\n * @example\n * ```ts\n * // For unnamed parameters, you pass values in an array.\n * db.getAllAsync('SELECT * FROM test WHERE intValue = ? AND name = ?', [1, 'Hello']);\n *\n * // For unnamed parameters, you pass values in variadic arguments.\n * db.getAllAsync('SELECT * FROM test WHERE intValue = ? AND name = ?', 1, 'Hello');\n *\n * // For named parameters, you should pass values in object.\n * db.getAllAsync('SELECT * FROM test WHERE intValue = $intValue AND name = $name', { $intValue: 1, $name: 'Hello' });\n * ```\n */\n public getAllAsync<T>(source: string, params: SQLiteBindParams): Promise<T[]>;\n /**\n * @hidden\n */\n public getAllAsync<T>(source: string, ...params: SQLiteVariadicBindParams): Promise<T[]>;\n public async getAllAsync<T>(source: string, ...params: any[]): Promise<T[]> {\n const statement = await this.prepareAsync(source);\n let allRows;\n try {\n const result = await statement.executeAsync<T>(...params);\n allRows = await result.getAllAsync();\n } finally {\n await statement.finalizeAsync();\n }\n return allRows;\n }\n\n /**\n * A convenience wrapper around [`SQLiteDatabase.prepareSync()`](#preparesyncsource), [`SQLiteStatement.executeSync()`](#executesyncparams), and [`SQLiteStatement.finalizeSync()`](#finalizesync).\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n * @param source A string containing the SQL query.\n * @param params The parameters to bind to the prepared statement. You can pass values in array, object, or variadic arguments. See [`SQLiteBindValue`](#sqlitebindvalue) for more information about binding values.\n */\n public runSync(source: string, params: SQLiteBindParams): SQLiteRunResult;\n /**\n * @hidden\n */\n public runSync(source: string, ...params: SQLiteVariadicBindParams): SQLiteRunResult;\n public runSync(source: string, ...params: any[]): SQLiteRunResult {\n const statement = this.prepareSync(source);\n let result: SQLiteExecuteSyncResult<unknown>;\n try {\n result = statement.executeSync(...params);\n } finally {\n statement.finalizeSync();\n }\n return result;\n }\n\n /**\n * A convenience wrapper around [`SQLiteDatabase.prepareSync()`](#preparesyncsource), [`SQLiteStatement.executeSync()`](#executesyncparams), [`SQLiteExecuteSyncResult.getFirstSync()`](#getfirstsync), and [`SQLiteStatement.finalizeSync()`](#finalizesync).\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n * @param source A string containing the SQL query.\n * @param params The parameters to bind to the prepared statement. You can pass values in array, object, or variadic arguments. See [`SQLiteBindValue`](#sqlitebindvalue) for more information about binding values.\n */\n public getFirstSync<T>(source: string, params: SQLiteBindParams): T | null;\n /**\n * @hidden\n */\n public getFirstSync<T>(source: string, ...params: SQLiteVariadicBindParams): T | null;\n public getFirstSync<T>(source: string, ...params: any[]): T | null {\n const statement = this.prepareSync(source);\n let firstRow: T | null;\n try {\n const result = statement.executeSync<T>(...params);\n firstRow = result.getFirstSync();\n } finally {\n statement.finalizeSync();\n }\n return firstRow;\n }\n\n /**\n * A convenience wrapper around [`SQLiteDatabase.prepareSync()`](#preparesyncsource), [`SQLiteStatement.executeSync()`](#executesyncparams), [`SQLiteExecuteSyncResult`](#sqliteexecutesyncresult) `Iterator`, and [`SQLiteStatement.finalizeSync()`](#finalizesync).\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n * @param source A string containing the SQL query.\n * @param params The parameters to bind to the prepared statement. You can pass values in array, object, or variadic arguments. See [`SQLiteBindValue`](#sqlitebindvalue) for more information about binding values.\n * @returns This function returns an [`IterableIterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator). You can use `for...of` to iterate over the rows from the SQLite query result.\n */\n public getEachSync<T>(source: string, params: SQLiteBindParams): IterableIterator<T>;\n /**\n * @hidden\n */\n public getEachSync<T>(source: string, ...params: SQLiteVariadicBindParams): IterableIterator<T>;\n public *getEachSync<T>(source: string, ...params: any[]): IterableIterator<T> {\n const statement = this.prepareSync(source);\n try {\n const result = statement.executeSync<T>(...params);\n for (const row of result) {\n yield row;\n }\n } finally {\n statement.finalizeSync();\n }\n }\n\n /**\n * A convenience wrapper around [`SQLiteDatabase.prepareSync()`](#preparesyncsource), [`SQLiteStatement.executeSync()`](#executesyncparams), [`SQLiteExecuteSyncResult.getAllSync()`](#getallsync), and [`SQLiteStatement.finalizeSync()`](#finalizesync).\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n * @param source A string containing the SQL query.\n * @param params The parameters to bind to the prepared statement. You can pass values in array, object, or variadic arguments. See [`SQLiteBindValue`](#sqlitebindvalue) for more information about binding values.\n */\n public getAllSync<T>(source: string, params: SQLiteBindParams): T[];\n /**\n * @hidden\n */\n public getAllSync<T>(source: string, ...params: SQLiteVariadicBindParams): T[];\n public getAllSync<T>(source: string, ...params: any[]): T[] {\n const statement = this.prepareSync(source);\n let allRows;\n try {\n const result = statement.executeSync<T>(...params);\n allRows = result.getAllSync();\n } finally {\n statement.finalizeSync();\n }\n return allRows;\n }\n\n //#endregion\n}\n\n/**\n * Open a database.\n *\n * @param databaseName The name of the database file to open.\n * @param options Open options.\n */\nexport async function openDatabaseAsync(\n databaseName: string,\n options?: SQLiteOpenOptions\n): Promise<SQLiteDatabase> {\n const openOptions = options ?? {};\n const nativeDatabase = new ExpoSQLite.NativeDatabase(databaseName, openOptions);\n await nativeDatabase.initAsync();\n return new SQLiteDatabase(databaseName, openOptions, nativeDatabase);\n}\n\n/**\n * Open a database.\n *\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n *\n * @param databaseName The name of the database file to open.\n * @param options Open options.\n */\nexport function openDatabaseSync(\n databaseName: string,\n options?: SQLiteOpenOptions\n): SQLiteDatabase {\n const openOptions = options ?? {};\n const nativeDatabase = new ExpoSQLite.NativeDatabase(databaseName, openOptions);\n nativeDatabase.initSync();\n return new SQLiteDatabase(databaseName, openOptions, nativeDatabase);\n}\n\n/**\n * Given a `Uint8Array` data and [deserialize to memory database](https://sqlite.org/c3ref/deserialize.html).\n *\n * @param serializedData The binary array to deserialize from [`SQLiteDatabase.serializeAsync()`](#serializeasyncdatabasename).\n * @param options Open options.\n */\nexport async function deserializeDatabaseAsync(\n serializedData: Uint8Array,\n options?: SQLiteOpenOptions\n): Promise<SQLiteDatabase> {\n const openOptions = options ?? {};\n const nativeDatabase = new ExpoSQLite.NativeDatabase(':memory:', openOptions, serializedData);\n await nativeDatabase.initAsync();\n return new SQLiteDatabase(':memory:', openOptions, nativeDatabase);\n}\n\n/**\n * Given a `Uint8Array` data and [deserialize to memory database](https://sqlite.org/c3ref/deserialize.html).\n *\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n *\n * @param serializedData The binary array to deserialize from [`SQLiteDatabase.serializeSync()`](#serializesyncdatabasename)\n * @param options Open options.\n */\nexport function deserializeDatabaseSync(\n serializedData: Uint8Array,\n options?: SQLiteOpenOptions\n): SQLiteDatabase {\n const openOptions = options ?? {};\n const nativeDatabase = new ExpoSQLite.NativeDatabase(':memory:', openOptions, serializedData);\n nativeDatabase.initSync();\n return new SQLiteDatabase(':memory:', openOptions, nativeDatabase);\n}\n\n/**\n * Delete a database file.\n *\n * @param databaseName The name of the database file to delete.\n */\nexport async function deleteDatabaseAsync(databaseName: string): Promise<void> {\n return await ExpoSQLite.deleteDatabaseAsync(databaseName);\n}\n\n/**\n * Delete a database file.\n *\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n *\n * @param databaseName The name of the database file to delete.\n */\nexport function deleteDatabaseSync(databaseName: string): void {\n return ExpoSQLite.deleteDatabaseSync(databaseName);\n}\n\n/**\n * The event payload for the listener of [`addDatabaseChangeListener`](#sqliteadddatabasechangelistenerlistener)\n */\nexport type DatabaseChangeEvent = {\n /** The database name. The value would be `main` by default and other database names if you use `ATTACH DATABASE` statement. */\n databaseName: string;\n\n /** The absolute file path to the database. */\n databaseFilePath: string;\n\n /** The table name. */\n tableName: string;\n\n /** The changed row ID. */\n rowId: number;\n};\n\n/**\n * Add a listener for database changes.\n * > Note: to enable this feature, you must set [`enableChangeListener` to `true`](#sqliteopenoptions) when opening the database.\n *\n * @param listener A function that receives the `databaseName`, `databaseFilePath`, `tableName` and `rowId` of the modified data.\n * @returns A `Subscription` object that you can call `remove()` on when you would like to unsubscribe the listener.\n */\nexport function addDatabaseChangeListener(\n listener: (event: DatabaseChangeEvent) => void\n): Subscription {\n return emitter.addListener('onDatabaseChange', listener);\n}\n\n/**\n * A new connection specific used for [`withExclusiveTransactionAsync`](#withexclusivetransactionasynctask).\n * @hidden not going to pull all the database methods to the document.\n */\nclass Transaction extends SQLiteDatabase {\n public static async createAsync(db: SQLiteDatabase): Promise<Transaction> {\n const options = { ...db.options, useNewConnection: true };\n const nativeDatabase = new ExpoSQLite.NativeDatabase(db.databaseName, options);\n await nativeDatabase.initAsync();\n return new Transaction(db.databaseName, options, nativeDatabase);\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SQLiteStatement.js","sourceRoot":"","sources":["../src/SQLiteStatement.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAMxE;;GAEG;AACH,MAAM,OAAO,eAAe;IAEP;IACA;IAFnB,YACmB,cAA8B,EAC9B,eAAgC;QADh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BAAiB;QACvB,IAAI,IAAI,CAAC,cAAc,IAAI,IAAI,EAAE,CAAC;YAChC,MAAM,cAAc,GAAG,IAAI,CAAC,cAAc,CAAC;YAC3C,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;YAC3B,OAAO,cAAc,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,IAAI,CAAC;QAC3D,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IAEO,kBAAkB;QACxB,IAAI,IAAI,CAAC,WAAW,IAAI,IAAI,EAAE,CAAC;YAC7B,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC,kBAAkB,EAAE,CAAC;QACzD,CAAC;QACD,OAAO,IAAI,CAAC,WAAW,CAAC;IAC1B,CAAC;CACF;AAED,SAAS,kBAAkB,CACzB,SAAkB,EAClB,WAA8B,EAC9B,YAAgC;IAEhC,OAAO,SAAS;QACd,CAAC,CAAE,YAAkB,CAAC,sCAAsC;QAC5D,CAAC,CAAC,UAAU,CAAI,WAAW,EAAE,YAAY,CAAC,CAAC;AAC/C,CAAC;AAED,SAAS,mBAAmB,CAC1B,SAAkB,EAClB,WAA8B,EAC9B,gBAAsC;IAEtC,OAAO,SAAS;QACd,CAAC,CAAE,gBAAwB,CAAC,0CAA0C;QACtE,CAAC,CAAC,WAAW,CAAI,WAAW,EAAE,gBAAgB,CAAC,CAAC;AACpD,CAAC;AAED,YAAY","sourcesContent":["import { NativeDatabase } from './NativeDatabase';\nimport {\n SQLiteBindParams,\n SQLiteBindValue,\n NativeStatement,\n SQLiteVariadicBindParams,\n type SQLiteAnyDatabase,\n type SQLiteColumnNames,\n type SQLiteColumnValues,\n type SQLiteRunResult,\n} from './NativeStatement';\nimport { composeRow, composeRows, normalizeParams } from './paramUtils';\n\nexport { SQLiteBindParams, SQLiteBindValue, SQLiteRunResult, SQLiteVariadicBindParams };\n\ntype ValuesOf<T extends object> = T[keyof T][];\n\n/**\n * A prepared statement returned by [`SQLiteDatabase.prepareAsync()`](#prepareasyncsource) or [`SQLiteDatabase.prepareSync()`](#preparesyncsource) that can be binded with parameters and executed.\n */\nexport class SQLiteStatement {\n constructor(\n private readonly nativeDatabase: NativeDatabase,\n private readonly nativeStatement: NativeStatement\n ) {}\n\n //#region Asynchronous API\n\n /**\n * Run the prepared statement and return the [`SQLiteExecuteAsyncResult`](#sqliteexecuteasyncresult) instance.\n * @param params The parameters to bind to the prepared statement. You can pass values in array, object, or variadic arguments. See [`SQLiteBindValue`](#sqlitebindvalue) for more information about binding values.\n */\n public executeAsync<T>(params: SQLiteBindParams): Promise<SQLiteExecuteAsyncResult<T>>;\n /**\n * @hidden\n */\n public executeAsync<T>(...params: SQLiteVariadicBindParams): Promise<SQLiteExecuteAsyncResult<T>>;\n public async executeAsync<T>(...params: unknown[]): Promise<SQLiteExecuteAsyncResult<T>> {\n const { lastInsertRowId, changes, firstRowValues } = await this.nativeStatement.runAsync(\n this.nativeDatabase,\n ...normalizeParams(...params)\n );\n return createSQLiteExecuteAsyncResult<T>(\n this.nativeDatabase,\n this.nativeStatement,\n firstRowValues,\n {\n rawResult: false,\n lastInsertRowId,\n changes,\n }\n );\n }\n\n /**\n * Similar to [`executeAsync()`](#executeasyncparams) but returns the raw value array result instead of the row objects.\n * @hidden Advanced use only.\n */\n public executeForRawResultAsync<T extends object>(\n params: SQLiteBindParams\n ): Promise<SQLiteExecuteAsyncResult<ValuesOf<T>>>;\n /**\n * @hidden\n */\n public executeForRawResultAsync<T extends object>(\n ...params: SQLiteVariadicBindParams\n ): Promise<SQLiteExecuteAsyncResult<ValuesOf<T>>>;\n public async executeForRawResultAsync<T extends object>(\n ...params: unknown[]\n ): Promise<SQLiteExecuteAsyncResult<ValuesOf<T>>> {\n const { lastInsertRowId, changes, firstRowValues } = await this.nativeStatement.runAsync(\n this.nativeDatabase,\n ...normalizeParams(...params)\n );\n return createSQLiteExecuteAsyncResult<ValuesOf<T>>(\n this.nativeDatabase,\n this.nativeStatement,\n firstRowValues,\n {\n rawResult: true,\n lastInsertRowId,\n changes,\n }\n );\n }\n\n /**\n * Get the column names of the prepared statement.\n */\n public getColumnNamesAsync(): Promise<string[]> {\n return this.nativeStatement.getColumnNamesAsync();\n }\n\n /**\n * Finalize the prepared statement. This will call the [`sqlite3_finalize()`](https://www.sqlite.org/c3ref/finalize.html) C function under the hood.\n *\n * Attempting to access a finalized statement will result in an error.\n * > **Note:** While expo-sqlite will automatically finalize any orphaned prepared statements upon closing the database, it is considered best practice to manually finalize prepared statements as soon as they are no longer needed. This helps to prevent resource leaks. You can use the `try...finally` statement to ensure that prepared statements are finalized even if an error occurs.\n */\n public async finalizeAsync(): Promise<void> {\n await this.nativeStatement.finalizeAsync(this.nativeDatabase);\n }\n\n //#endregion\n\n //#region Synchronous API\n\n /**\n * Run the prepared statement and return the [`SQLiteExecuteSyncResult`](#sqliteexecutesyncresult) instance.\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n * @param params The parameters to bind to the prepared statement. You can pass values in array, object, or variadic arguments. See [`SQLiteBindValue`](#sqlitebindvalue) for more information about binding values.\n */\n public executeSync<T>(params: SQLiteBindParams): SQLiteExecuteSyncResult<T>;\n /**\n * @hidden\n */\n public executeSync<T>(...params: SQLiteVariadicBindParams): SQLiteExecuteSyncResult<T>;\n public executeSync<T>(...params: unknown[]): SQLiteExecuteSyncResult<T> {\n const { lastInsertRowId, changes, firstRowValues } = this.nativeStatement.runSync(\n this.nativeDatabase,\n ...normalizeParams(...params)\n );\n return createSQLiteExecuteSyncResult<T>(\n this.nativeDatabase,\n this.nativeStatement,\n firstRowValues,\n {\n rawResult: false,\n lastInsertRowId,\n changes,\n }\n );\n }\n\n /**\n * Similar to [`executeSync()`](#executesyncparams) but returns the raw value array result instead of the row objects.\n * @hidden Advanced use only.\n */\n public executeForRawResultSync<T extends object>(\n params: SQLiteBindParams\n ): SQLiteExecuteSyncResult<ValuesOf<T>>;\n /**\n * @hidden\n */\n public executeForRawResultSync<T extends object>(\n ...params: SQLiteVariadicBindParams\n ): SQLiteExecuteSyncResult<ValuesOf<T>>;\n public executeForRawResultSync<T extends object>(\n ...params: unknown[]\n ): SQLiteExecuteSyncResult<ValuesOf<T>> {\n const { lastInsertRowId, changes, firstRowValues } = this.nativeStatement.runSync(\n this.nativeDatabase,\n ...normalizeParams(...params)\n );\n return createSQLiteExecuteSyncResult<ValuesOf<T>>(\n this.nativeDatabase,\n this.nativeStatement,\n firstRowValues,\n {\n rawResult: true,\n lastInsertRowId,\n changes,\n }\n );\n }\n\n /**\n * Get the column names of the prepared statement.\n */\n public getColumnNamesSync(): string[] {\n return this.nativeStatement.getColumnNamesSync();\n }\n\n /**\n * Finalize the prepared statement. This will call the [`sqlite3_finalize()`](https://www.sqlite.org/c3ref/finalize.html) C function under the hood.\n *\n * Attempting to access a finalized statement will result in an error.\n * > **Note:** While expo-sqlite will automatically finalize any orphaned prepared statements upon closing the database, it is considered best practice to manually finalize prepared statements as soon as they are no longer needed. This helps to prevent resource leaks. You can use the `try...finally` statement to ensure that prepared statements are finalized even if an error occurs.\n */\n public finalizeSync(): void {\n this.nativeStatement.finalizeSync(this.nativeDatabase);\n }\n\n //#endregion\n}\n\n/**\n * A result returned by [`SQLiteStatement.executeAsync()`](#executeasyncparams).\n *\n * @example\n * The result includes the [`lastInsertRowId`](https://www.sqlite.org/c3ref/last_insert_rowid.html) and [`changes`](https://www.sqlite.org/c3ref/changes.html) properties. You can get the information from the write operations.\n * ```ts\n * const statement = await db.prepareAsync('INSERT INTO test (value) VALUES (?)');\n * try {\n * const result = await statement.executeAsync(101);\n * console.log('lastInsertRowId:', result.lastInsertRowId);\n * console.log('changes:', result.changes);\n * } finally {\n * await statement.finalizeAsync();\n * }\n * ```\n *\n * @example\n * The result implements the [`AsyncIterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/asyncIterator) interface, so you can use it in `for await...of` loops.\n * ```ts\n * const statement = await db.prepareAsync('SELECT value FROM test WHERE value > ?');\n * try {\n * const result = await statement.executeAsync<{ value: number }>(100);\n * for await (const row of result) {\n * console.log('row value:', row.value);\n * }\n * } finally {\n * await statement.finalizeAsync();\n * }\n * ```\n *\n * @example\n * If your write operations also return values, you can mix all of them together.\n * ```ts\n * const statement = await db.prepareAsync('INSERT INTO test (name, value) VALUES (?, ?) RETURNING name');\n * try {\n * const result = await statement.executeAsync<{ name: string }>('John Doe', 101);\n * console.log('lastInsertRowId:', result.lastInsertRowId);\n * console.log('changes:', result.changes);\n * for await (const row of result) {\n * console.log('name:', row.name);\n * }\n * } finally {\n * await statement.finalizeAsync();\n * }\n * ```\n */\nexport interface SQLiteExecuteAsyncResult<T> extends AsyncIterableIterator<T> {\n /**\n * The last inserted row ID. Returned from the [`sqlite3_last_insert_rowid()`](https://www.sqlite.org/c3ref/last_insert_rowid.html) function.\n */\n readonly lastInsertRowId: number;\n\n /**\n * The number of rows affected. Returned from the [`sqlite3_changes()`](https://www.sqlite.org/c3ref/changes.html) function.\n */\n readonly changes: number;\n\n /**\n * Get the first row of the result set. This requires the SQLite cursor to be in its initial state. If you have already retrieved rows from the result set, you need to reset the cursor first by calling [`resetAsync()`](#resetasync). Otherwise, an error will be thrown.\n */\n getFirstAsync(): Promise<T | null>;\n\n /**\n * Get all rows of the result set. This requires the SQLite cursor to be in its initial state. If you have already retrieved rows from the result set, you need to reset the cursor first by calling [`resetAsync()`](#resetasync). Otherwise, an error will be thrown.\n */\n getAllAsync(): Promise<T[]>;\n\n /**\n * Reset the prepared statement cursor. This will call the [`sqlite3_reset()`](https://www.sqlite.org/c3ref/reset.html) C function under the hood.\n */\n resetAsync(): Promise<void>;\n}\n\n/**\n * A result returned by [`SQLiteStatement.executeSync()`](#executesyncparams).\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n\n * @example\n * The result includes the [`lastInsertRowId`](https://www.sqlite.org/c3ref/last_insert_rowid.html) and [`changes`](https://www.sqlite.org/c3ref/changes.html) properties. You can get the information from the write operations.\n * ```ts\n * const statement = db.prepareSync('INSERT INTO test (value) VALUES (?)');\n * try {\n * const result = statement.executeSync(101);\n * console.log('lastInsertRowId:', result.lastInsertRowId);\n * console.log('changes:', result.changes);\n * } finally {\n * statement.finalizeSync();\n * }\n * ```\n *\n * @example\n * The result implements the [`Iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) interface, so you can use it in `for...of` loops.\n * ```ts\n * const statement = db.prepareSync('SELECT value FROM test WHERE value > ?');\n * try {\n * const result = statement.executeSync<{ value: number }>(100);\n * for (const row of result) {\n * console.log('row value:', row.value);\n * }\n * } finally {\n * statement.finalizeSync();\n * }\n * ```\n *\n * @example\n * If your write operations also return values, you can mix all of them together.\n * ```ts\n * const statement = db.prepareSync('INSERT INTO test (name, value) VALUES (?, ?) RETURNING name');\n * try {\n * const result = statement.executeSync<{ name: string }>('John Doe', 101);\n * console.log('lastInsertRowId:', result.lastInsertRowId);\n * console.log('changes:', result.changes);\n * for (const row of result) {\n * console.log('name:', row.name);\n * }\n * } finally {\n * statement.finalizeSync();\n * }\n * ```\n */\nexport interface SQLiteExecuteSyncResult<T> extends IterableIterator<T> {\n /**\n * The last inserted row ID. Returned from the [`sqlite3_last_insert_rowid()`](https://www.sqlite.org/c3ref/last_insert_rowid.html) function.\n */\n readonly lastInsertRowId: number;\n\n /**\n * The number of rows affected. Returned from the [`sqlite3_changes()`](https://www.sqlite.org/c3ref/changes.html) function.\n */\n readonly changes: number;\n\n /**\n * Get the first row of the result set. This requires the SQLite cursor to be in its initial state. If you have already retrieved rows from the result set, you need to reset the cursor first by calling [`resetSync()`](#resetsync). Otherwise, an error will be thrown.\n */\n getFirstSync(): T | null;\n\n /**\n * Get all rows of the result set. This requires the SQLite cursor to be in its initial state. If you have already retrieved rows from the result set, you need to reset the cursor first by calling [`resetSync()`](#resetsync). Otherwise, an error will be thrown.\n */\n getAllSync(): T[];\n\n /**\n * Reset the prepared statement cursor. This will call the [`sqlite3_reset()`](https://www.sqlite.org/c3ref/reset.html) C function under the hood.\n */\n resetSync(): void;\n}\n\n//#region Internals for SQLiteExecuteAsyncResult and SQLiteExecuteSyncResult\n\ninterface SQLiteExecuteResultOptions {\n rawResult: boolean;\n lastInsertRowId: number;\n changes: number;\n}\n\n/**\n * Create the `SQLiteExecuteAsyncResult` instance.\n *\n * NOTE: Since Hermes does not support the `Symbol.asyncIterator` feature, we have to use an AsyncGenerator to implement the `AsyncIterableIterator` interface.\n * This is done by `Object.defineProperties` to add the properties to the AsyncGenerator.\n */\nasync function createSQLiteExecuteAsyncResult<T>(\n database: SQLiteAnyDatabase,\n statement: NativeStatement,\n firstRowValues: SQLiteColumnValues | null,\n options: SQLiteExecuteResultOptions\n): Promise<SQLiteExecuteAsyncResult<T>> {\n const instance = new SQLiteExecuteAsyncResultImpl<T>(\n database,\n statement,\n firstRowValues,\n options\n );\n const generator = instance.generatorAsync();\n Object.defineProperties(generator, {\n lastInsertRowId: {\n value: options.lastInsertRowId,\n enumerable: true,\n writable: false,\n configurable: true,\n },\n changes: { value: options.changes, enumerable: true, writable: false, configurable: true },\n getFirstAsync: {\n value: instance.getFirstAsync.bind(instance),\n enumerable: true,\n writable: false,\n configurable: true,\n },\n getAllAsync: {\n value: instance.getAllAsync.bind(instance),\n enumerable: true,\n writable: false,\n configurable: true,\n },\n resetAsync: {\n value: instance.resetAsync.bind(instance),\n enumerable: true,\n writable: false,\n configurable: true,\n },\n });\n\n return generator as SQLiteExecuteAsyncResult<T>;\n}\n\n/**\n * Create the `SQLiteExecuteSyncResult` instance.\n */\nfunction createSQLiteExecuteSyncResult<T>(\n database: SQLiteAnyDatabase,\n statement: NativeStatement,\n firstRowValues: SQLiteColumnValues | null,\n options: SQLiteExecuteResultOptions\n): SQLiteExecuteSyncResult<T> {\n const instance = new SQLiteExecuteSyncResultImpl<T>(database, statement, firstRowValues, options);\n const generator = instance.generatorSync();\n Object.defineProperties(generator, {\n lastInsertRowId: {\n value: options.lastInsertRowId,\n enumerable: true,\n writable: false,\n configurable: true,\n },\n changes: { value: options.changes, enumerable: true, writable: false, configurable: true },\n getFirstSync: {\n value: instance.getFirstSync.bind(instance),\n enumerable: true,\n writable: false,\n configurable: true,\n },\n getAllSync: {\n value: instance.getAllSync.bind(instance),\n enumerable: true,\n writable: false,\n configurable: true,\n },\n resetSync: {\n value: instance.resetSync.bind(instance),\n enumerable: true,\n writable: false,\n configurable: true,\n },\n });\n\n return generator as SQLiteExecuteSyncResult<T>;\n}\n\nclass SQLiteExecuteAsyncResultImpl<T> {\n private columnNames: string[] | null = null;\n private isStepCalled = false;\n\n constructor(\n private readonly database: SQLiteAnyDatabase,\n private readonly statement: NativeStatement,\n private firstRowValues: SQLiteColumnValues | null,\n public readonly options: SQLiteExecuteResultOptions\n ) {}\n\n async getFirstAsync(): Promise<T | null> {\n if (this.isStepCalled) {\n throw new Error(\n 'The SQLite cursor has been shifted and is unable to retrieve the first row without being reset. Invoke `resetAsync()` to reset the cursor first if you want to retrieve the first row.'\n );\n }\n this.isStepCalled = true;\n const columnNames = await this.getColumnNamesAsync();\n const firstRowValues = this.popFirstRowValues();\n if (firstRowValues != null) {\n return composeRowIfNeeded<T>(this.options.rawResult, columnNames, firstRowValues);\n }\n const firstRow = await this.statement.stepAsync(this.database);\n return firstRow != null\n ? composeRowIfNeeded<T>(this.options.rawResult, columnNames, firstRow)\n : null;\n }\n\n async getAllAsync(): Promise<T[]> {\n if (this.isStepCalled) {\n throw new Error(\n 'The SQLite cursor has been shifted and is unable to retrieve all rows without being reset. Invoke `resetAsync()` to reset the cursor first if you want to retrieve all rows.'\n );\n }\n this.isStepCalled = true;\n const firstRowValues = this.popFirstRowValues();\n if (firstRowValues == null) {\n // If the first row is empty, this SQL query may be a write operation. We should not call `statement.getAllAsync()` to write again.\n return [];\n }\n const columnNames = await this.getColumnNamesAsync();\n const allRows = await this.statement.getAllAsync(this.database);\n if (firstRowValues != null && firstRowValues.length > 0) {\n return composeRowsIfNeeded<T>(this.options.rawResult, columnNames, [\n firstRowValues,\n ...allRows,\n ]);\n }\n return composeRowsIfNeeded<T>(this.options.rawResult, columnNames, allRows);\n }\n\n async *generatorAsync(): AsyncIterableIterator<T> {\n this.isStepCalled = true;\n const columnNames = await this.getColumnNamesAsync();\n const firstRowValues = this.popFirstRowValues();\n if (firstRowValues != null) {\n yield composeRowIfNeeded<T>(this.options.rawResult, columnNames, firstRowValues);\n }\n\n let result;\n do {\n result = await this.statement.stepAsync(this.database);\n if (result != null) {\n yield composeRowIfNeeded<T>(this.options.rawResult, columnNames, result);\n }\n } while (result != null);\n }\n\n resetAsync(): Promise<void> {\n const result = this.statement.resetAsync(this.database);\n this.isStepCalled = false;\n return result;\n }\n\n private popFirstRowValues(): SQLiteColumnValues | null {\n if (this.firstRowValues != null) {\n const firstRowValues = this.firstRowValues;\n this.firstRowValues = null;\n return firstRowValues.length > 0 ? firstRowValues : null;\n }\n return null;\n }\n\n private async getColumnNamesAsync(): Promise<string[]> {\n if (this.columnNames == null) {\n this.columnNames = await this.statement.getColumnNamesAsync();\n }\n return this.columnNames;\n }\n}\n\nclass SQLiteExecuteSyncResultImpl<T> {\n private columnNames: string[] | null = null;\n private isStepCalled = false;\n\n constructor(\n private readonly database: SQLiteAnyDatabase,\n private readonly statement: NativeStatement,\n private firstRowValues: SQLiteColumnValues | null,\n public readonly options: SQLiteExecuteResultOptions\n ) {}\n\n getFirstSync(): T | null {\n if (this.isStepCalled) {\n throw new Error(\n 'The SQLite cursor has been shifted and is unable to retrieve the first row without being reset. Invoke `resetSync()` to reset the cursor first if you want to retrieve the first row.'\n );\n }\n const columnNames = this.getColumnNamesSync();\n const firstRowValues = this.popFirstRowValues();\n if (firstRowValues != null) {\n return composeRowIfNeeded<T>(this.options.rawResult, columnNames, firstRowValues);\n }\n const firstRow = this.statement.stepSync(this.database);\n return firstRow != null\n ? composeRowIfNeeded<T>(this.options.rawResult, columnNames, firstRow)\n : null;\n }\n\n getAllSync(): T[] {\n if (this.isStepCalled) {\n throw new Error(\n 'The SQLite cursor has been shifted and is unable to retrieve all rows without being reset. Invoke `resetSync()` to reset the cursor first if you want to retrieve all rows.'\n );\n }\n const firstRowValues = this.popFirstRowValues();\n if (firstRowValues == null) {\n // If the first row is empty, this SQL query may be a write operation. We should not call `statement.getAllAsync()` to write again.\n return [];\n }\n const columnNames = this.getColumnNamesSync();\n const allRows = this.statement.getAllSync(this.database);\n if (firstRowValues != null && firstRowValues.length > 0) {\n return composeRowsIfNeeded<T>(this.options.rawResult, columnNames, [\n firstRowValues,\n ...allRows,\n ]);\n }\n return composeRowsIfNeeded<T>(this.options.rawResult, columnNames, allRows);\n }\n\n *generatorSync(): IterableIterator<T> {\n const columnNames = this.getColumnNamesSync();\n const firstRowValues = this.popFirstRowValues();\n if (firstRowValues != null) {\n yield composeRowIfNeeded<T>(this.options.rawResult, columnNames, firstRowValues);\n }\n let result;\n do {\n result = this.statement.stepSync(this.database);\n if (result != null) {\n yield composeRowIfNeeded<T>(this.options.rawResult, columnNames, result);\n }\n } while (result != null);\n }\n\n resetSync(): void {\n const result = this.statement.resetSync(this.database);\n this.isStepCalled = false;\n return result;\n }\n\n private popFirstRowValues(): SQLiteColumnValues | null {\n if (this.firstRowValues != null) {\n const firstRowValues = this.firstRowValues;\n this.firstRowValues = null;\n return firstRowValues.length > 0 ? firstRowValues : null;\n }\n return null;\n }\n\n private getColumnNamesSync(): string[] {\n if (this.columnNames == null) {\n this.columnNames = this.statement.getColumnNamesSync();\n }\n return this.columnNames;\n }\n}\n\nfunction composeRowIfNeeded<T>(\n rawResult: boolean,\n columnNames: SQLiteColumnNames,\n columnValues: SQLiteColumnValues\n): T {\n return rawResult\n ? (columnValues as T) // T would be a ValuesOf<> from caller\n : composeRow<T>(columnNames, columnValues);\n}\n\nfunction composeRowsIfNeeded<T>(\n rawResult: boolean,\n columnNames: SQLiteColumnNames,\n columnValuesList: SQLiteColumnValues[]\n): T[] {\n return rawResult\n ? (columnValuesList as T[]) // T[] would be a ValuesOf<>[] from caller\n : composeRows<T>(columnNames, columnValuesList);\n}\n\n//#endregion\n"]}
|
|
1
|
+
{"version":3,"file":"SQLiteStatement.js","sourceRoot":"","sources":["../src/SQLiteStatement.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAMxE;;GAEG;AACH,MAAM,OAAO,eAAe;IAEP;IACA;IAFnB,YACmB,cAA8B,EAC9B,eAAgC;QADhC,mBAAc,GAAd,cAAc,CAAgB;QAC9B,oBAAe,GAAf,eAAe,CAAiB;IAChD,CAAC;IAaG,KAAK,CAAC,YAAY,CAAI,GAAG,MAAiB;QAC/C,MAAM,EAAE,eAAe,EAAE,OAAO,EAAE,cAAc,EAAE,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,QAAQ,CACtF,IAAI,CAAC,cAAc,EACnB,GAAG,eAAe,CAAC,GAAG,MAAM,CAAC,CAC9B,CAAC;QACF,OAAO,8BAA8B,CACnC,IAAI,CAAC,cAAc,EACnB,IAAI,CAAC,eAAe,EACpB,cAAc,EACd;YACE,SAAS,EAAE,KAAK;YAChB,eAAe;YACf,OAAO;SACR,CACF,CAAC;IACJ,CAAC;IAeM,KAAK,CAAC,wBAAwB,CACnC,GAAG,MAAiB;QAEpB,MAAM,EAAE,eAAe,EAAE,OAAO,EAAE,cAAc,EAAE,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,QAAQ,CACtF,IAAI,CAAC,cAAc,EACnB,GAAG,eAAe,CAAC,GAAG,MAAM,CAAC,CAC9B,CAAC;QACF,OAAO,8BAA8B,CACnC,IAAI,CAAC,cAAc,EACnB,IAAI,CAAC,eAAe,EACpB,cAAc,EACd;YACE,SAAS,EAAE,IAAI;YACf,eAAe;YACf,OAAO;SACR,CACF,CAAC;IACJ,CAAC;IAED;;OAEG;IACI,mBAAmB;QACxB,OAAO,IAAI,CAAC,eAAe,CAAC,mBAAmB,EAAE,CAAC;IACpD,CAA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;QACvD,IAAI,CAAC,YAAY,GAAG,KAAK,CAAC;QAC1B,OAAO,MAAM,CAAC;IAChB,CAAC;IAEO,iBAAiB;QACvB,IAAI,IAAI,CAAC,cAAc,IAAI,IAAI,EAAE;YAC/B,MAAM,cAAc,GAAG,IAAI,CAAC,cAAc,CAAC;YAC3C,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;YAC3B,OAAO,cAAc,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,IAAI,CAAC;SAC1D;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IAEO,kBAAkB;QACxB,IAAI,IAAI,CAAC,WAAW,IAAI,IAAI,EAAE;YAC5B,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC,kBAAkB,EAAE,CAAC;SACxD;QACD,OAAO,IAAI,CAAC,WAAW,CAAC;IAC1B,CAAC;CACF;AAED,SAAS,kBAAkB,CACzB,SAAkB,EAClB,WAA8B,EAC9B,YAAgC;IAEhC,OAAO,SAAS;QACd,CAAC,CAAE,YAAkB,CAAC,sCAAsC;QAC5D,CAAC,CAAC,UAAU,CAAI,WAAW,EAAE,YAAY,CAAC,CAAC;AAC/C,CAAC;AAED,SAAS,mBAAmB,CAC1B,SAAkB,EAClB,WAA8B,EAC9B,gBAAsC;IAEtC,OAAO,SAAS;QACd,CAAC,CAAE,gBAAwB,CAAC,0CAA0C;QACtE,CAAC,CAAC,WAAW,CAAI,WAAW,EAAE,gBAAgB,CAAC,CAAC;AACpD,CAAC;AAED,YAAY","sourcesContent":["import { NativeDatabase } from './NativeDatabase';\nimport {\n SQLiteBindParams,\n SQLiteBindValue,\n NativeStatement,\n SQLiteVariadicBindParams,\n type SQLiteAnyDatabase,\n type SQLiteColumnNames,\n type SQLiteColumnValues,\n type SQLiteRunResult,\n} from './NativeStatement';\nimport { composeRow, composeRows, normalizeParams } from './paramUtils';\n\nexport { SQLiteBindParams, SQLiteBindValue, SQLiteRunResult, SQLiteVariadicBindParams };\n\ntype ValuesOf<T extends object> = T[keyof T][];\n\n/**\n * A prepared statement returned by [`SQLiteDatabase.prepareAsync()`](#prepareasyncsource) or [`SQLiteDatabase.prepareSync()`](#preparesyncsource) that can be binded with parameters and executed.\n */\nexport class SQLiteStatement {\n constructor(\n private readonly nativeDatabase: NativeDatabase,\n private readonly nativeStatement: NativeStatement\n ) {}\n\n //#region Asynchronous API\n\n /**\n * Run the prepared statement and return the [`SQLiteExecuteAsyncResult`](#sqliteexecuteasyncresult) instance.\n * @param params The parameters to bind to the prepared statement. You can pass values in array, object, or variadic arguments. See [`SQLiteBindValue`](#sqlitebindvalue) for more information about binding values.\n */\n public executeAsync<T>(params: SQLiteBindParams): Promise<SQLiteExecuteAsyncResult<T>>;\n /**\n * @hidden\n */\n public executeAsync<T>(...params: SQLiteVariadicBindParams): Promise<SQLiteExecuteAsyncResult<T>>;\n public async executeAsync<T>(...params: unknown[]): Promise<SQLiteExecuteAsyncResult<T>> {\n const { lastInsertRowId, changes, firstRowValues } = await this.nativeStatement.runAsync(\n this.nativeDatabase,\n ...normalizeParams(...params)\n );\n return createSQLiteExecuteAsyncResult<T>(\n this.nativeDatabase,\n this.nativeStatement,\n firstRowValues,\n {\n rawResult: false,\n lastInsertRowId,\n changes,\n }\n );\n }\n\n /**\n * Similar to [`executeAsync()`](#executeasyncparams) but returns the raw value array result instead of the row objects.\n * @hidden Advanced use only.\n */\n public executeForRawResultAsync<T extends object>(\n params: SQLiteBindParams\n ): Promise<SQLiteExecuteAsyncResult<ValuesOf<T>>>;\n /**\n * @hidden\n */\n public executeForRawResultAsync<T extends object>(\n ...params: SQLiteVariadicBindParams\n ): Promise<SQLiteExecuteAsyncResult<ValuesOf<T>>>;\n public async executeForRawResultAsync<T extends object>(\n ...params: unknown[]\n ): Promise<SQLiteExecuteAsyncResult<ValuesOf<T>>> {\n const { lastInsertRowId, changes, firstRowValues } = await this.nativeStatement.runAsync(\n this.nativeDatabase,\n ...normalizeParams(...params)\n );\n return createSQLiteExecuteAsyncResult<ValuesOf<T>>(\n this.nativeDatabase,\n this.nativeStatement,\n firstRowValues,\n {\n rawResult: true,\n lastInsertRowId,\n changes,\n }\n );\n }\n\n /**\n * Get the column names of the prepared statement.\n */\n public getColumnNamesAsync(): Promise<string[]> {\n return this.nativeStatement.getColumnNamesAsync();\n }\n\n /**\n * Finalize the prepared statement. This will call the [`sqlite3_finalize()`](https://www.sqlite.org/c3ref/finalize.html) C function under the hood.\n *\n * Attempting to access a finalized statement will result in an error.\n * > **Note:** While expo-sqlite will automatically finalize any orphaned prepared statements upon closing the database, it is considered best practice to manually finalize prepared statements as soon as they are no longer needed. This helps to prevent resource leaks. You can use the `try...finally` statement to ensure that prepared statements are finalized even if an error occurs.\n */\n public async finalizeAsync(): Promise<void> {\n await this.nativeStatement.finalizeAsync(this.nativeDatabase);\n }\n\n //#endregion\n\n //#region Synchronous API\n\n /**\n * Run the prepared statement and return the [`SQLiteExecuteSyncResult`](#sqliteexecutesyncresult) instance.\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n * @param params The parameters to bind to the prepared statement. You can pass values in array, object, or variadic arguments. See [`SQLiteBindValue`](#sqlitebindvalue) for more information about binding values.\n */\n public executeSync<T>(params: SQLiteBindParams): SQLiteExecuteSyncResult<T>;\n /**\n * @hidden\n */\n public executeSync<T>(...params: SQLiteVariadicBindParams): SQLiteExecuteSyncResult<T>;\n public executeSync<T>(...params: unknown[]): SQLiteExecuteSyncResult<T> {\n const { lastInsertRowId, changes, firstRowValues } = this.nativeStatement.runSync(\n this.nativeDatabase,\n ...normalizeParams(...params)\n );\n return createSQLiteExecuteSyncResult<T>(\n this.nativeDatabase,\n this.nativeStatement,\n firstRowValues,\n {\n rawResult: false,\n lastInsertRowId,\n changes,\n }\n );\n }\n\n /**\n * Similar to [`executeSync()`](#executesyncparams) but returns the raw value array result instead of the row objects.\n * @hidden Advanced use only.\n */\n public executeForRawResultSync<T extends object>(\n params: SQLiteBindParams\n ): SQLiteExecuteSyncResult<ValuesOf<T>>;\n /**\n * @hidden\n */\n public executeForRawResultSync<T extends object>(\n ...params: SQLiteVariadicBindParams\n ): SQLiteExecuteSyncResult<ValuesOf<T>>;\n public executeForRawResultSync<T extends object>(\n ...params: unknown[]\n ): SQLiteExecuteSyncResult<ValuesOf<T>> {\n const { lastInsertRowId, changes, firstRowValues } = this.nativeStatement.runSync(\n this.nativeDatabase,\n ...normalizeParams(...params)\n );\n return createSQLiteExecuteSyncResult<ValuesOf<T>>(\n this.nativeDatabase,\n this.nativeStatement,\n firstRowValues,\n {\n rawResult: true,\n lastInsertRowId,\n changes,\n }\n );\n }\n\n /**\n * Get the column names of the prepared statement.\n */\n public getColumnNamesSync(): string[] {\n return this.nativeStatement.getColumnNamesSync();\n }\n\n /**\n * Finalize the prepared statement. This will call the [`sqlite3_finalize()`](https://www.sqlite.org/c3ref/finalize.html) C function under the hood.\n *\n * Attempting to access a finalized statement will result in an error.\n * > **Note:** While expo-sqlite will automatically finalize any orphaned prepared statements upon closing the database, it is considered best practice to manually finalize prepared statements as soon as they are no longer needed. This helps to prevent resource leaks. You can use the `try...finally` statement to ensure that prepared statements are finalized even if an error occurs.\n */\n public finalizeSync(): void {\n this.nativeStatement.finalizeSync(this.nativeDatabase);\n }\n\n //#endregion\n}\n\n/**\n * A result returned by [`SQLiteStatement.executeAsync()`](#executeasyncparams).\n *\n * @example\n * The result includes the [`lastInsertRowId`](https://www.sqlite.org/c3ref/last_insert_rowid.html) and [`changes`](https://www.sqlite.org/c3ref/changes.html) properties. You can get the information from the write operations.\n * ```ts\n * const statement = await db.prepareAsync('INSERT INTO test (value) VALUES (?)');\n * try {\n * const result = await statement.executeAsync(101);\n * console.log('lastInsertRowId:', result.lastInsertRowId);\n * console.log('changes:', result.changes);\n * } finally {\n * await statement.finalizeAsync();\n * }\n * ```\n *\n * @example\n * The result implements the [`AsyncIterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/asyncIterator) interface, so you can use it in `for await...of` loops.\n * ```ts\n * const statement = await db.prepareAsync('SELECT value FROM test WHERE value > ?');\n * try {\n * const result = await statement.executeAsync<{ value: number }>(100);\n * for await (const row of result) {\n * console.log('row value:', row.value);\n * }\n * } finally {\n * await statement.finalizeAsync();\n * }\n * ```\n *\n * @example\n * If your write operations also return values, you can mix all of them together.\n * ```ts\n * const statement = await db.prepareAsync('INSERT INTO test (name, value) VALUES (?, ?) RETURNING name');\n * try {\n * const result = await statement.executeAsync<{ name: string }>('John Doe', 101);\n * console.log('lastInsertRowId:', result.lastInsertRowId);\n * console.log('changes:', result.changes);\n * for await (const row of result) {\n * console.log('name:', row.name);\n * }\n * } finally {\n * await statement.finalizeAsync();\n * }\n * ```\n */\nexport interface SQLiteExecuteAsyncResult<T> extends AsyncIterableIterator<T> {\n /**\n * The last inserted row ID. Returned from the [`sqlite3_last_insert_rowid()`](https://www.sqlite.org/c3ref/last_insert_rowid.html) function.\n */\n readonly lastInsertRowId: number;\n\n /**\n * The number of rows affected. Returned from the [`sqlite3_changes()`](https://www.sqlite.org/c3ref/changes.html) function.\n */\n readonly changes: number;\n\n /**\n * Get the first row of the result set. This requires the SQLite cursor to be in its initial state. If you have already retrieved rows from the result set, you need to reset the cursor first by calling [`resetAsync()`](#resetasync). Otherwise, an error will be thrown.\n */\n getFirstAsync(): Promise<T | null>;\n\n /**\n * Get all rows of the result set. This requires the SQLite cursor to be in its initial state. If you have already retrieved rows from the result set, you need to reset the cursor first by calling [`resetAsync()`](#resetasync). Otherwise, an error will be thrown.\n */\n getAllAsync(): Promise<T[]>;\n\n /**\n * Reset the prepared statement cursor. This will call the [`sqlite3_reset()`](https://www.sqlite.org/c3ref/reset.html) C function under the hood.\n */\n resetAsync(): Promise<void>;\n}\n\n/**\n * A result returned by [`SQLiteStatement.executeSync()`](#executesyncparams).\n * > **Note:** Running heavy tasks with this function can block the JavaScript thread and affect performance.\n\n * @example\n * The result includes the [`lastInsertRowId`](https://www.sqlite.org/c3ref/last_insert_rowid.html) and [`changes`](https://www.sqlite.org/c3ref/changes.html) properties. You can get the information from the write operations.\n * ```ts\n * const statement = db.prepareSync('INSERT INTO test (value) VALUES (?)');\n * try {\n * const result = statement.executeSync(101);\n * console.log('lastInsertRowId:', result.lastInsertRowId);\n * console.log('changes:', result.changes);\n * } finally {\n * statement.finalizeSync();\n * }\n * ```\n *\n * @example\n * The result implements the [`Iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) interface, so you can use it in `for...of` loops.\n * ```ts\n * const statement = db.prepareSync('SELECT value FROM test WHERE value > ?');\n * try {\n * const result = statement.executeSync<{ value: number }>(100);\n * for (const row of result) {\n * console.log('row value:', row.value);\n * }\n * } finally {\n * statement.finalizeSync();\n * }\n * ```\n *\n * @example\n * If your write operations also return values, you can mix all of them together.\n * ```ts\n * const statement = db.prepareSync('INSERT INTO test (name, value) VALUES (?, ?) RETURNING name');\n * try {\n * const result = statement.executeSync<{ name: string }>('John Doe', 101);\n * console.log('lastInsertRowId:', result.lastInsertRowId);\n * console.log('changes:', result.changes);\n * for (const row of result) {\n * console.log('name:', row.name);\n * }\n * } finally {\n * statement.finalizeSync();\n * }\n * ```\n */\nexport interface SQLiteExecuteSyncResult<T> extends IterableIterator<T> {\n /**\n * The last inserted row ID. Returned from the [`sqlite3_last_insert_rowid()`](https://www.sqlite.org/c3ref/last_insert_rowid.html) function.\n */\n readonly lastInsertRowId: number;\n\n /**\n * The number of rows affected. Returned from the [`sqlite3_changes()`](https://www.sqlite.org/c3ref/changes.html) function.\n */\n readonly changes: number;\n\n /**\n * Get the first row of the result set. This requires the SQLite cursor to be in its initial state. If you have already retrieved rows from the result set, you need to reset the cursor first by calling [`resetSync()`](#resetsync). Otherwise, an error will be thrown.\n */\n getFirstSync(): T | null;\n\n /**\n * Get all rows of the result set. This requires the SQLite cursor to be in its initial state. If you have already retrieved rows from the result set, you need to reset the cursor first by calling [`resetSync()`](#resetsync). Otherwise, an error will be thrown.\n */\n getAllSync(): T[];\n\n /**\n * Reset the prepared statement cursor. This will call the [`sqlite3_reset()`](https://www.sqlite.org/c3ref/reset.html) C function under the hood.\n */\n resetSync(): void;\n}\n\n//#region Internals for SQLiteExecuteAsyncResult and SQLiteExecuteSyncResult\n\ninterface SQLiteExecuteResultOptions {\n rawResult: boolean;\n lastInsertRowId: number;\n changes: number;\n}\n\n/**\n * Create the `SQLiteExecuteAsyncResult` instance.\n *\n * NOTE: Since Hermes does not support the `Symbol.asyncIterator` feature, we have to use an AsyncGenerator to implement the `AsyncIterableIterator` interface.\n * This is done by `Object.defineProperties` to add the properties to the AsyncGenerator.\n */\nasync function createSQLiteExecuteAsyncResult<T>(\n database: SQLiteAnyDatabase,\n statement: NativeStatement,\n firstRowValues: SQLiteColumnValues | null,\n options: SQLiteExecuteResultOptions\n): Promise<SQLiteExecuteAsyncResult<T>> {\n const instance = new SQLiteExecuteAsyncResultImpl<T>(\n database,\n statement,\n firstRowValues,\n options\n );\n const generator = instance.generatorAsync();\n Object.defineProperties(generator, {\n lastInsertRowId: {\n value: options.lastInsertRowId,\n enumerable: true,\n writable: false,\n configurable: true,\n },\n changes: { value: options.changes, enumerable: true, writable: false, configurable: true },\n getFirstAsync: {\n value: instance.getFirstAsync.bind(instance),\n enumerable: true,\n writable: false,\n configurable: true,\n },\n getAllAsync: {\n value: instance.getAllAsync.bind(instance),\n enumerable: true,\n writable: false,\n configurable: true,\n },\n resetAsync: {\n value: instance.resetAsync.bind(instance),\n enumerable: true,\n writable: false,\n configurable: true,\n },\n });\n\n return generator as SQLiteExecuteAsyncResult<T>;\n}\n\n/**\n * Create the `SQLiteExecuteSyncResult` instance.\n */\nfunction createSQLiteExecuteSyncResult<T>(\n database: SQLiteAnyDatabase,\n statement: NativeStatement,\n firstRowValues: SQLiteColumnValues | null,\n options: SQLiteExecuteResultOptions\n): SQLiteExecuteSyncResult<T> {\n const instance = new SQLiteExecuteSyncResultImpl<T>(database, statement, firstRowValues, options);\n const generator = instance.generatorSync();\n Object.defineProperties(generator, {\n lastInsertRowId: {\n value: options.lastInsertRowId,\n enumerable: true,\n writable: false,\n configurable: true,\n },\n changes: { value: options.changes, enumerable: true, writable: false, configurable: true },\n getFirstSync: {\n value: instance.getFirstSync.bind(instance),\n enumerable: true,\n writable: false,\n configurable: true,\n },\n getAllSync: {\n value: instance.getAllSync.bind(instance),\n enumerable: true,\n writable: false,\n configurable: true,\n },\n resetSync: {\n value: instance.resetSync.bind(instance),\n enumerable: true,\n writable: false,\n configurable: true,\n },\n });\n\n return generator as SQLiteExecuteSyncResult<T>;\n}\n\nclass SQLiteExecuteAsyncResultImpl<T> {\n private columnNames: string[] | null = null;\n private isStepCalled = false;\n\n constructor(\n private readonly database: SQLiteAnyDatabase,\n private readonly statement: NativeStatement,\n private firstRowValues: SQLiteColumnValues | null,\n public readonly options: SQLiteExecuteResultOptions\n ) {}\n\n async getFirstAsync(): Promise<T | null> {\n if (this.isStepCalled) {\n throw new Error(\n 'The SQLite cursor has been shifted and is unable to retrieve the first row without being reset. Invoke `resetAsync()` to reset the cursor first if you want to retrieve the first row.'\n );\n }\n this.isStepCalled = true;\n const columnNames = await this.getColumnNamesAsync();\n const firstRowValues = this.popFirstRowValues();\n if (firstRowValues != null) {\n return composeRowIfNeeded<T>(this.options.rawResult, columnNames, firstRowValues);\n }\n const firstRow = await this.statement.stepAsync(this.database);\n return firstRow != null\n ? composeRowIfNeeded<T>(this.options.rawResult, columnNames, firstRow)\n : null;\n }\n\n async getAllAsync(): Promise<T[]> {\n if (this.isStepCalled) {\n throw new Error(\n 'The SQLite cursor has been shifted and is unable to retrieve all rows without being reset. Invoke `resetAsync()` to reset the cursor first if you want to retrieve all rows.'\n );\n }\n this.isStepCalled = true;\n const firstRowValues = this.popFirstRowValues();\n if (firstRowValues == null) {\n // If the first row is empty, this SQL query may be a write operation. We should not call `statement.getAllAsync()` to write again.\n return [];\n }\n const columnNames = await this.getColumnNamesAsync();\n const allRows = await this.statement.getAllAsync(this.database);\n if (firstRowValues != null && firstRowValues.length > 0) {\n return composeRowsIfNeeded<T>(this.options.rawResult, columnNames, [\n firstRowValues,\n ...allRows,\n ]);\n }\n return composeRowsIfNeeded<T>(this.options.rawResult, columnNames, allRows);\n }\n\n async *generatorAsync(): AsyncIterableIterator<T> {\n this.isStepCalled = true;\n const columnNames = await this.getColumnNamesAsync();\n const firstRowValues = this.popFirstRowValues();\n if (firstRowValues != null) {\n yield composeRowIfNeeded<T>(this.options.rawResult, columnNames, firstRowValues);\n }\n\n let result;\n do {\n result = await this.statement.stepAsync(this.database);\n if (result != null) {\n yield composeRowIfNeeded<T>(this.options.rawResult, columnNames, result);\n }\n } while (result != null);\n }\n\n resetAsync(): Promise<void> {\n const result = this.statement.resetAsync(this.database);\n this.isStepCalled = false;\n return result;\n }\n\n private popFirstRowValues(): SQLiteColumnValues | null {\n if (this.firstRowValues != null) {\n const firstRowValues = this.firstRowValues;\n this.firstRowValues = null;\n return firstRowValues.length > 0 ? firstRowValues : null;\n }\n return null;\n }\n\n private async getColumnNamesAsync(): Promise<string[]> {\n if (this.columnNames == null) {\n this.columnNames = await this.statement.getColumnNamesAsync();\n }\n return this.columnNames;\n }\n}\n\nclass SQLiteExecuteSyncResultImpl<T> {\n private columnNames: string[] | null = null;\n private isStepCalled = false;\n\n constructor(\n private readonly database: SQLiteAnyDatabase,\n private readonly statement: NativeStatement,\n private firstRowValues: SQLiteColumnValues | null,\n public readonly options: SQLiteExecuteResultOptions\n ) {}\n\n getFirstSync(): T | null {\n if (this.isStepCalled) {\n throw new Error(\n 'The SQLite cursor has been shifted and is unable to retrieve the first row without being reset. Invoke `resetSync()` to reset the cursor first if you want to retrieve the first row.'\n );\n }\n const columnNames = this.getColumnNamesSync();\n const firstRowValues = this.popFirstRowValues();\n if (firstRowValues != null) {\n return composeRowIfNeeded<T>(this.options.rawResult, columnNames, firstRowValues);\n }\n const firstRow = this.statement.stepSync(this.database);\n return firstRow != null\n ? composeRowIfNeeded<T>(this.options.rawResult, columnNames, firstRow)\n : null;\n }\n\n getAllSync(): T[] {\n if (this.isStepCalled) {\n throw new Error(\n 'The SQLite cursor has been shifted and is unable to retrieve all rows without being reset. Invoke `resetSync()` to reset the cursor first if you want to retrieve all rows.'\n );\n }\n const firstRowValues = this.popFirstRowValues();\n if (firstRowValues == null) {\n // If the first row is empty, this SQL query may be a write operation. We should not call `statement.getAllAsync()` to write again.\n return [];\n }\n const columnNames = this.getColumnNamesSync();\n const allRows = this.statement.getAllSync(this.database);\n if (firstRowValues != null && firstRowValues.length > 0) {\n return composeRowsIfNeeded<T>(this.options.rawResult, columnNames, [\n firstRowValues,\n ...allRows,\n ]);\n }\n return composeRowsIfNeeded<T>(this.options.rawResult, columnNames, allRows);\n }\n\n *generatorSync(): IterableIterator<T> {\n const columnNames = this.getColumnNamesSync();\n const firstRowValues = this.popFirstRowValues();\n if (firstRowValues != null) {\n yield composeRowIfNeeded<T>(this.options.rawResult, columnNames, firstRowValues);\n }\n let result;\n do {\n result = this.statement.stepSync(this.database);\n if (result != null) {\n yield composeRowIfNeeded<T>(this.options.rawResult, columnNames, result);\n }\n } while (result != null);\n }\n\n resetSync(): void {\n const result = this.statement.resetSync(this.database);\n this.isStepCalled = false;\n return result;\n }\n\n private popFirstRowValues(): SQLiteColumnValues | null {\n if (this.firstRowValues != null) {\n const firstRowValues = this.firstRowValues;\n this.firstRowValues = null;\n return firstRowValues.length > 0 ? firstRowValues : null;\n }\n return null;\n }\n\n private getColumnNamesSync(): string[] {\n if (this.columnNames == null) {\n this.columnNames = this.statement.getColumnNamesSync();\n }\n return this.columnNames;\n }\n}\n\nfunction composeRowIfNeeded<T>(\n rawResult: boolean,\n columnNames: SQLiteColumnNames,\n columnValues: SQLiteColumnValues\n): T {\n return rawResult\n ? (columnValues as T) // T would be a ValuesOf<> from caller\n : composeRow<T>(columnNames, columnValues);\n}\n\nfunction composeRowsIfNeeded<T>(\n rawResult: boolean,\n columnNames: SQLiteColumnNames,\n columnValuesList: SQLiteColumnValues[]\n): T[] {\n return rawResult\n ? (columnValuesList as T[]) // T[] would be a ValuesOf<>[] from caller\n : composeRows<T>(columnNames, columnValuesList);\n}\n\n//#endregion\n"]}
|
package/build/hooks.d.ts
CHANGED
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
2
|
import type { SQLiteOpenOptions } from './NativeDatabase';
|
|
3
3
|
import { type SQLiteDatabase } from './SQLiteDatabase';
|
|
4
|
+
export interface SQLiteProviderAssetSource {
|
|
5
|
+
/**
|
|
6
|
+
* The asset ID returned from the `require()` call.
|
|
7
|
+
*/
|
|
8
|
+
assetId: number;
|
|
9
|
+
/**
|
|
10
|
+
* Force overwrite the local database file even if it already exists.
|
|
11
|
+
* @default false
|
|
12
|
+
*/
|
|
13
|
+
forceOverwrite?: boolean;
|
|
14
|
+
}
|
|
4
15
|
export interface SQLiteProviderProps {
|
|
5
16
|
/**
|
|
6
17
|
* The name of the database file to open.
|
|
@@ -10,6 +21,14 @@ export interface SQLiteProviderProps {
|
|
|
10
21
|
* Open options.
|
|
11
22
|
*/
|
|
12
23
|
options?: SQLiteOpenOptions;
|
|
24
|
+
/**
|
|
25
|
+
* Import a bundled database file from the specified asset module.
|
|
26
|
+
* @example
|
|
27
|
+
* ```ts
|
|
28
|
+
* assetSource={{ assetId: require('./assets/db.db') }}
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
assetSource?: SQLiteProviderAssetSource;
|
|
13
32
|
/**
|
|
14
33
|
* The children to render.
|
|
15
34
|
*/
|
package/build/hooks.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../src/hooks.tsx"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../src/hooks.tsx"],"names":[],"mappings":"AACA,OAAO,KAAiE,MAAM,OAAO,CAAC;AAGtF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,EAAqB,KAAK,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAE1E,MAAM,WAAW,yBAAyB;IACxC;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;;OAGG;IACH,cAAc,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,MAAM,WAAW,mBAAmB;IAClC;;OAEG;IACH,YAAY,EAAE,MAAM,CAAC;IAErB;;OAEG;IACH,OAAO,CAAC,EAAE,iBAAiB,CAAC;IAE5B;;;;;;OAMG;IACH,WAAW,CAAC,EAAE,yBAAyB,CAAC;IAExC;;OAEG;IACH,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC;IAE1B;;;OAGG;IACH,MAAM,CAAC,EAAE,CAAC,EAAE,EAAE,cAAc,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAE/C;;;OAGG;IACH,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IAEjC;;;;;;;;;;;;;;;OAeG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB;AAOD;;;GAGG;AACH,wBAAgB,cAAc,CAAC,EAC7B,QAAQ,EACR,OAAO,EACP,WAAmB,EACnB,GAAG,KAAK,EACT,EAAE,mBAAmB,eAcrB;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,gBAAgB,IAAI,cAAc,CAMjD"}
|
package/build/hooks.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import { Asset } from 'expo-asset';
|
|
1
2
|
import React, { createContext, useContext, useEffect, useRef, useState } from 'react';
|
|
3
|
+
import ExpoSQLite from './ExpoSQLiteNext';
|
|
2
4
|
import { openDatabaseAsync } from './SQLiteDatabase';
|
|
3
5
|
/**
|
|
4
6
|
* Create a context for the SQLite database
|
|
@@ -48,23 +50,24 @@ export function useSQLiteContext() {
|
|
|
48
50
|
return context;
|
|
49
51
|
}
|
|
50
52
|
let databaseInstance = null;
|
|
51
|
-
function SQLiteProviderSuspense({ databaseName, options, children, onInit, }) {
|
|
53
|
+
function SQLiteProviderSuspense({ databaseName, options, assetSource, children, onInit, }) {
|
|
52
54
|
const databasePromise = getDatabaseAsync({
|
|
53
55
|
databaseName,
|
|
54
56
|
options,
|
|
57
|
+
assetSource,
|
|
55
58
|
onInit,
|
|
56
59
|
});
|
|
57
60
|
const database = use(databasePromise);
|
|
58
61
|
return <SQLiteContext.Provider value={database}>{children}</SQLiteContext.Provider>;
|
|
59
62
|
}
|
|
60
|
-
function SQLiteProviderNonSuspense({ databaseName, options, children, onInit, onError, }) {
|
|
63
|
+
function SQLiteProviderNonSuspense({ databaseName, options, assetSource, children, onInit, onError, }) {
|
|
61
64
|
const databaseRef = useRef(null);
|
|
62
65
|
const [loading, setLoading] = useState(true);
|
|
63
66
|
const [error, setError] = useState(null);
|
|
64
67
|
useEffect(() => {
|
|
65
68
|
async function setup() {
|
|
66
69
|
try {
|
|
67
|
-
const db = await openDatabaseWithInitAsync({ databaseName, options, onInit });
|
|
70
|
+
const db = await openDatabaseWithInitAsync({ databaseName, options, assetSource, onInit });
|
|
68
71
|
databaseRef.current = db;
|
|
69
72
|
setLoading(false);
|
|
70
73
|
}
|
|
@@ -100,7 +103,7 @@ function SQLiteProviderNonSuspense({ databaseName, options, children, onInit, on
|
|
|
100
103
|
}
|
|
101
104
|
return <SQLiteContext.Provider value={databaseRef.current}>{children}</SQLiteContext.Provider>;
|
|
102
105
|
}
|
|
103
|
-
function getDatabaseAsync({ databaseName, options, onInit, }) {
|
|
106
|
+
function getDatabaseAsync({ databaseName, options, assetSource, onInit, }) {
|
|
104
107
|
if (databaseInstance?.promise != null &&
|
|
105
108
|
databaseInstance?.databaseName === databaseName &&
|
|
106
109
|
databaseInstance?.options === options &&
|
|
@@ -114,11 +117,11 @@ function getDatabaseAsync({ databaseName, options, onInit, }) {
|
|
|
114
117
|
db.closeAsync();
|
|
115
118
|
})
|
|
116
119
|
.then(() => {
|
|
117
|
-
return openDatabaseWithInitAsync({ databaseName, options, onInit });
|
|
120
|
+
return openDatabaseWithInitAsync({ databaseName, options, assetSource, onInit });
|
|
118
121
|
});
|
|
119
122
|
}
|
|
120
123
|
else {
|
|
121
|
-
promise = openDatabaseWithInitAsync({ databaseName, options, onInit });
|
|
124
|
+
promise = openDatabaseWithInitAsync({ databaseName, options, assetSource, onInit });
|
|
122
125
|
}
|
|
123
126
|
databaseInstance = {
|
|
124
127
|
databaseName,
|
|
@@ -128,13 +131,23 @@ function getDatabaseAsync({ databaseName, options, onInit, }) {
|
|
|
128
131
|
};
|
|
129
132
|
return promise;
|
|
130
133
|
}
|
|
131
|
-
async function openDatabaseWithInitAsync({ databaseName, options, onInit, }) {
|
|
134
|
+
async function openDatabaseWithInitAsync({ databaseName, options, assetSource, onInit, }) {
|
|
135
|
+
if (assetSource != null) {
|
|
136
|
+
await importDatabaseFromAssetAsync(databaseName, assetSource);
|
|
137
|
+
}
|
|
132
138
|
const database = await openDatabaseAsync(databaseName, options);
|
|
133
139
|
if (onInit != null) {
|
|
134
140
|
await onInit(database);
|
|
135
141
|
}
|
|
136
142
|
return database;
|
|
137
143
|
}
|
|
144
|
+
async function importDatabaseFromAssetAsync(databaseName, assetSource) {
|
|
145
|
+
const asset = await Asset.fromModule(assetSource.assetId).downloadAsync();
|
|
146
|
+
if (!asset.localUri) {
|
|
147
|
+
throw new Error(`Unable to get the localUri from asset ${assetSource.assetId}`);
|
|
148
|
+
}
|
|
149
|
+
await ExpoSQLite.importAssetDatabaseAsync(databaseName, asset.localUri, assetSource.forceOverwrite ?? false);
|
|
150
|
+
}
|
|
138
151
|
// Referenced from https://github.com/reactjs/react.dev/blob/6570e6cd79a16ac3b1a2902632eddab7e6abb9ad/src/content/reference/react/Suspense.md
|
|
139
152
|
/**
|
|
140
153
|
* A custom hook like [`React.use`](https://react.dev/reference/react/use) hook using private Suspense implementation.
|
package/build/hooks.js.map
CHANGED
|
@@ -1 +1 @@
|
|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AC,MAAM,GAAG,SAAS,CAAC;IACnC,eAAe,CAAC,IAAI,CAClB,CAAC,MAAS,EAAE,EAAE;QACZ,eAAe,CAAC,MAAM,GAAG,WAAW,CAAC;QACrC,eAAe,CAAC,KAAK,GAAG,MAAM,CAAC;IACjC,CAAC,EACD,CAAC,MAAM,EAAE,EAAE;QACT,eAAe,CAAC,MAAM,GAAG,UAAU,CAAC;QACpC,eAAe,CAAC,MAAM,GAAG,MAAM,CAAC;IAClC,CAAC,CACF,CAAC;IACF,MAAM,eAAe,CAAC;AACxB,CAAC;AAED,SAAS,iBAAiB,CACxB,OAAwC;IAExC,OAAO,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,KAAK,IAAI,IAAI,QAAQ,IAAI,OAAO,CAAC;AAChF,CAAC;AAED,YAAY","sourcesContent":["import React, { createContext, useContext, useEffect, useRef, useState } from 'react';\n\nimport type { SQLiteOpenOptions } from './NativeDatabase';\nimport { openDatabaseAsync, type SQLiteDatabase } from './SQLiteDatabase';\n\nexport interface SQLiteProviderProps {\n /**\n * The name of the database file to open.\n */\n databaseName: string;\n\n /**\n * Open options.\n */\n options?: SQLiteOpenOptions;\n\n /**\n * The children to render.\n */\n children: React.ReactNode;\n\n /**\n * A custom initialization handler to run before rendering the children.\n * You can use this to run database migrations or other setup tasks.\n */\n onInit?: (db: SQLiteDatabase) => Promise<void>;\n\n /**\n * Handle errors from SQLiteProvider.\n * @default rethrow the error\n */\n onError?: (error: Error) => void;\n\n /**\n * Enable [`React.Suspense`](https://react.dev/reference/react/Suspense) integration.\n * @default false\n * @example\n * ```tsx\n * export default function App() {\n * return (\n * <Suspense fallback={<Text>Loading...</Text>}>\n * <SQLiteProvider databaseName=\"test.db\" useSuspense={true}>\n * <Main />\n * </SQLiteProvider>\n * </Suspense>\n * );\n * }\n * ```\n */\n useSuspense?: boolean;\n}\n\n/**\n * Create a context for the SQLite database\n */\nconst SQLiteContext = createContext<SQLiteDatabase | null>(null);\n\n/**\n * Context.Provider component that provides a SQLite database to all children.\n * All descendants of this component will be able to access the database using the [`useSQLiteContext`](#usesqlitecontext) hook.\n */\nexport function SQLiteProvider({\n children,\n onError,\n useSuspense = false,\n ...props\n}: SQLiteProviderProps) {\n if (onError != null && useSuspense) {\n throw new Error('Cannot use `onError` with `useSuspense`, use error boundaries instead.');\n }\n\n if (useSuspense) {\n return <SQLiteProviderSuspense {...props}>{children}</SQLiteProviderSuspense>;\n }\n\n return (\n <SQLiteProviderNonSuspense {...props} onError={onError}>\n {children}\n </SQLiteProviderNonSuspense>\n );\n}\n\n/**\n * A global hook for accessing the SQLite database across components.\n * This hook should only be used within a [`<SQLiteProvider>`](#sqliteprovider) component.\n *\n * @example\n * ```tsx\n * export default function App() {\n * return (\n * <SQLiteProvider databaseName=\"test.db\">\n * <Main />\n * </SQLiteProvider>\n * );\n * }\n *\n * export function Main() {\n * const db = useSQLiteContext();\n * console.log('sqlite version', db.getSync('SELECT sqlite_version()'));\n * return <View />\n * }\n * ```\n */\nexport function useSQLiteContext(): SQLiteDatabase {\n const context = useContext(SQLiteContext);\n if (context == null) {\n throw new Error('useSQLiteContext must be used within a <SQLiteProvider>');\n }\n return context;\n}\n\n//#region Internals\n\ntype DatabaseInstanceType = Pick<SQLiteProviderProps, 'databaseName' | 'options' | 'onInit'> & {\n promise: Promise<SQLiteDatabase> | null;\n};\n\nlet databaseInstance: DatabaseInstanceType | null = null;\n\nfunction SQLiteProviderSuspense({\n databaseName,\n options,\n children,\n onInit,\n}: Omit<SQLiteProviderProps, 'onError' | 'useSuspense'>) {\n const databasePromise = getDatabaseAsync({\n databaseName,\n options,\n onInit,\n });\n const database = use(databasePromise);\n return <SQLiteContext.Provider value={database}>{children}</SQLiteContext.Provider>;\n}\n\nfunction SQLiteProviderNonSuspense({\n databaseName,\n options,\n children,\n onInit,\n onError,\n}: Omit<SQLiteProviderProps, 'useSuspense'>) {\n const databaseRef = useRef<SQLiteDatabase | null>(null);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n useEffect(() => {\n async function setup() {\n try {\n const db = await openDatabaseWithInitAsync({ databaseName, options, onInit });\n databaseRef.current = db;\n setLoading(false);\n } catch (e) {\n setError(e);\n }\n }\n\n async function teardown(db: SQLiteDatabase | null) {\n try {\n await db?.closeAsync();\n } catch (e) {\n setError(e);\n }\n }\n\n setup();\n\n return () => {\n const db = databaseRef.current;\n teardown(db);\n databaseRef.current = null;\n setLoading(true);\n };\n }, [databaseName, options, onInit]);\n\n if (error != null) {\n const handler =\n onError ??\n ((e) => {\n throw e;\n });\n handler(error);\n }\n if (loading || !databaseRef.current) {\n return null;\n }\n return <SQLiteContext.Provider value={databaseRef.current}>{children}</SQLiteContext.Provider>;\n}\n\nfunction getDatabaseAsync({\n databaseName,\n options,\n onInit,\n}: Pick<SQLiteProviderProps, 'databaseName' | 'options' | 'onInit'>): Promise<SQLiteDatabase> {\n if (\n databaseInstance?.promise != null &&\n databaseInstance?.databaseName === databaseName &&\n databaseInstance?.options === options &&\n databaseInstance?.onInit === onInit\n ) {\n return databaseInstance.promise;\n }\n\n let promise: Promise<SQLiteDatabase>;\n if (databaseInstance?.promise != null) {\n promise = databaseInstance.promise\n .then((db) => {\n db.closeAsync();\n })\n .then(() => {\n return openDatabaseWithInitAsync({ databaseName, options, onInit });\n });\n } else {\n promise = openDatabaseWithInitAsync({ databaseName, options, onInit });\n }\n databaseInstance = {\n databaseName,\n options,\n onInit,\n promise,\n };\n return promise;\n}\n\nasync function openDatabaseWithInitAsync({\n databaseName,\n options,\n onInit,\n}: Pick<SQLiteProviderProps, 'databaseName' | 'options' | 'onInit'>): Promise<SQLiteDatabase> {\n const database = await openDatabaseAsync(databaseName, options);\n if (onInit != null) {\n await onInit(database);\n }\n return database;\n}\n\n//#endregion\n\n//#region Private Suspense API similar to `React.use`\n\n// Referenced from https://github.com/vercel/swr/blob/1d8110900d1aee3747199bfb377b149b7ff6848e/_internal/src/types.ts#L27-L31\ntype ReactUsePromise<T, E extends Error = Error> = Promise<T> & {\n status?: 'pending' | 'fulfilled' | 'rejected';\n value?: T;\n reason?: E;\n};\n\n// Referenced from https://github.com/reactjs/react.dev/blob/6570e6cd79a16ac3b1a2902632eddab7e6abb9ad/src/content/reference/react/Suspense.md\n/**\n * A custom hook like [`React.use`](https://react.dev/reference/react/use) hook using private Suspense implementation.\n */\nfunction use<T>(promise: Promise<T> | ReactUsePromise<T>) {\n if (isReactUsePromise(promise)) {\n if (promise.status === 'fulfilled') {\n if (promise.value === undefined) {\n throw new Error('[use] Unexpected undefined value from promise');\n }\n return promise.value;\n } else if (promise.status === 'rejected') {\n throw promise.reason;\n } else if (promise.status === 'pending') {\n throw promise;\n }\n throw new Error('[use] Promise is in an invalid state');\n }\n\n const suspensePromise = promise as ReactUsePromise<T>;\n suspensePromise.status = 'pending';\n suspensePromise.then(\n (result: T) => {\n suspensePromise.status = 'fulfilled';\n suspensePromise.value = result;\n },\n (reason) => {\n suspensePromise.status = 'rejected';\n suspensePromise.reason = reason;\n }\n );\n throw suspensePromise;\n}\n\nfunction isReactUsePromise<T>(\n promise: Promise<T> | ReactUsePromise<T>\n): promise is ReactUsePromise<T> {\n return typeof promise === 'object' && promise !== null && 'status' in promise;\n}\n\n//#endregion\n"]}
|
|
1
|
+
{"version":3,"file":"hooks.js","sourceRoot":"","sources":["../src/hooks.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,KAAK,EAAE,EAAE,aAAa,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAEtF,OAAO,UAAU,MAAM,kBAAkB,CAAC;AAE1C,OAAO,EAAE,iBAAiB,EAAuB,MAAM,kBAAkB,CAAC;AAuE1E;;GAEG;AACH,MAAM,aAAa,GAAG,aAAa,CAAwB,IAAI,CAAC,CAAC;AAEjE;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,EAC7B,QAAQ,EACR,OAAO,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MAAM,GAAG,SAAS,CAAC;IACnC,eAAe,CAAC,IAAI,CAClB,CAAC,MAAS,EAAE,EAAE;QACZ,eAAe,CAAC,MAAM,GAAG,WAAW,CAAC;QACrC,eAAe,CAAC,KAAK,GAAG,MAAM,CAAC;IACjC,CAAC,EACD,CAAC,MAAM,EAAE,EAAE;QACT,eAAe,CAAC,MAAM,GAAG,UAAU,CAAC;QACpC,eAAe,CAAC,MAAM,GAAG,MAAM,CAAC;IAClC,CAAC,CACF,CAAC;IACF,MAAM,eAAe,CAAC;AACxB,CAAC;AAED,SAAS,iBAAiB,CACxB,OAAwC;IAExC,OAAO,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,KAAK,IAAI,IAAI,QAAQ,IAAI,OAAO,CAAC;AAChF,CAAC;AAED,YAAY","sourcesContent":["import { Asset } from 'expo-asset';\nimport React, { createContext, useContext, useEffect, useRef, useState } from 'react';\n\nimport ExpoSQLite from './ExpoSQLiteNext';\nimport type { SQLiteOpenOptions } from './NativeDatabase';\nimport { openDatabaseAsync, type SQLiteDatabase } from './SQLiteDatabase';\n\nexport interface SQLiteProviderAssetSource {\n /**\n * The asset ID returned from the `require()` call.\n */\n assetId: number;\n\n /**\n * Force overwrite the local database file even if it already exists.\n * @default false\n */\n forceOverwrite?: boolean;\n}\n\nexport interface SQLiteProviderProps {\n /**\n * The name of the database file to open.\n */\n databaseName: string;\n\n /**\n * Open options.\n */\n options?: SQLiteOpenOptions;\n\n /**\n * Import a bundled database file from the specified asset module.\n * @example\n * ```ts\n * assetSource={{ assetId: require('./assets/db.db') }}\n * ```\n */\n assetSource?: SQLiteProviderAssetSource;\n\n /**\n * The children to render.\n */\n children: React.ReactNode;\n\n /**\n * A custom initialization handler to run before rendering the children.\n * You can use this to run database migrations or other setup tasks.\n */\n onInit?: (db: SQLiteDatabase) => Promise<void>;\n\n /**\n * Handle errors from SQLiteProvider.\n * @default rethrow the error\n */\n onError?: (error: Error) => void;\n\n /**\n * Enable [`React.Suspense`](https://react.dev/reference/react/Suspense) integration.\n * @default false\n * @example\n * ```tsx\n * export default function App() {\n * return (\n * <Suspense fallback={<Text>Loading...</Text>}>\n * <SQLiteProvider databaseName=\"test.db\" useSuspense={true}>\n * <Main />\n * </SQLiteProvider>\n * </Suspense>\n * );\n * }\n * ```\n */\n useSuspense?: boolean;\n}\n\n/**\n * Create a context for the SQLite database\n */\nconst SQLiteContext = createContext<SQLiteDatabase | null>(null);\n\n/**\n * Context.Provider component that provides a SQLite database to all children.\n * All descendants of this component will be able to access the database using the [`useSQLiteContext`](#usesqlitecontext) hook.\n */\nexport function SQLiteProvider({\n children,\n onError,\n useSuspense = false,\n ...props\n}: SQLiteProviderProps) {\n if (onError != null && useSuspense) {\n throw new Error('Cannot use `onError` with `useSuspense`, use error boundaries instead.');\n }\n\n if (useSuspense) {\n return <SQLiteProviderSuspense {...props}>{children}</SQLiteProviderSuspense>;\n }\n\n return (\n <SQLiteProviderNonSuspense {...props} onError={onError}>\n {children}\n </SQLiteProviderNonSuspense>\n );\n}\n\n/**\n * A global hook for accessing the SQLite database across components.\n * This hook should only be used within a [`<SQLiteProvider>`](#sqliteprovider) component.\n *\n * @example\n * ```tsx\n * export default function App() {\n * return (\n * <SQLiteProvider databaseName=\"test.db\">\n * <Main />\n * </SQLiteProvider>\n * );\n * }\n *\n * export function Main() {\n * const db = useSQLiteContext();\n * console.log('sqlite version', db.getSync('SELECT sqlite_version()'));\n * return <View />\n * }\n * ```\n */\nexport function useSQLiteContext(): SQLiteDatabase {\n const context = useContext(SQLiteContext);\n if (context == null) {\n throw new Error('useSQLiteContext must be used within a <SQLiteProvider>');\n }\n return context;\n}\n\n//#region Internals\n\ntype DatabaseInstanceType = Pick<SQLiteProviderProps, 'databaseName' | 'options' | 'onInit'> & {\n promise: Promise<SQLiteDatabase> | null;\n};\n\nlet databaseInstance: DatabaseInstanceType | null = null;\n\nfunction SQLiteProviderSuspense({\n databaseName,\n options,\n assetSource,\n children,\n onInit,\n}: Omit<SQLiteProviderProps, 'onError' | 'useSuspense'>) {\n const databasePromise = getDatabaseAsync({\n databaseName,\n options,\n assetSource,\n onInit,\n });\n const database = use(databasePromise);\n return <SQLiteContext.Provider value={database}>{children}</SQLiteContext.Provider>;\n}\n\nfunction SQLiteProviderNonSuspense({\n databaseName,\n options,\n assetSource,\n children,\n onInit,\n onError,\n}: Omit<SQLiteProviderProps, 'useSuspense'>) {\n const databaseRef = useRef<SQLiteDatabase | null>(null);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n useEffect(() => {\n async function setup() {\n try {\n const db = await openDatabaseWithInitAsync({ databaseName, options, assetSource, onInit });\n databaseRef.current = db;\n setLoading(false);\n } catch (e) {\n setError(e);\n }\n }\n\n async function teardown(db: SQLiteDatabase | null) {\n try {\n await db?.closeAsync();\n } catch (e) {\n setError(e);\n }\n }\n\n setup();\n\n return () => {\n const db = databaseRef.current;\n teardown(db);\n databaseRef.current = null;\n setLoading(true);\n };\n }, [databaseName, options, onInit]);\n\n if (error != null) {\n const handler =\n onError ??\n ((e) => {\n throw e;\n });\n handler(error);\n }\n if (loading || !databaseRef.current) {\n return null;\n }\n return <SQLiteContext.Provider value={databaseRef.current}>{children}</SQLiteContext.Provider>;\n}\n\nfunction getDatabaseAsync({\n databaseName,\n options,\n assetSource,\n onInit,\n}: Pick<\n SQLiteProviderProps,\n 'databaseName' | 'options' | 'assetSource' | 'onInit'\n>): Promise<SQLiteDatabase> {\n if (\n databaseInstance?.promise != null &&\n databaseInstance?.databaseName === databaseName &&\n databaseInstance?.options === options &&\n databaseInstance?.onInit === onInit\n ) {\n return databaseInstance.promise;\n }\n\n let promise: Promise<SQLiteDatabase>;\n if (databaseInstance?.promise != null) {\n promise = databaseInstance.promise\n .then((db) => {\n db.closeAsync();\n })\n .then(() => {\n return openDatabaseWithInitAsync({ databaseName, options, assetSource, onInit });\n });\n } else {\n promise = openDatabaseWithInitAsync({ databaseName, options, assetSource, onInit });\n }\n databaseInstance = {\n databaseName,\n options,\n onInit,\n promise,\n };\n return promise;\n}\n\nasync function openDatabaseWithInitAsync({\n databaseName,\n options,\n assetSource,\n onInit,\n}: Pick<\n SQLiteProviderProps,\n 'databaseName' | 'options' | 'assetSource' | 'onInit'\n>): Promise<SQLiteDatabase> {\n if (assetSource != null) {\n await importDatabaseFromAssetAsync(databaseName, assetSource);\n }\n const database = await openDatabaseAsync(databaseName, options);\n if (onInit != null) {\n await onInit(database);\n }\n return database;\n}\n\nasync function importDatabaseFromAssetAsync(\n databaseName: string,\n assetSource: SQLiteProviderAssetSource\n) {\n const asset = await Asset.fromModule(assetSource.assetId).downloadAsync();\n if (!asset.localUri) {\n throw new Error(`Unable to get the localUri from asset ${assetSource.assetId}`);\n }\n await ExpoSQLite.importAssetDatabaseAsync(\n databaseName,\n asset.localUri,\n assetSource.forceOverwrite ?? false\n );\n}\n\n//#endregion\n\n//#region Private Suspense API similar to `React.use`\n\n// Referenced from https://github.com/vercel/swr/blob/1d8110900d1aee3747199bfb377b149b7ff6848e/_internal/src/types.ts#L27-L31\ntype ReactUsePromise<T, E extends Error = Error> = Promise<T> & {\n status?: 'pending' | 'fulfilled' | 'rejected';\n value?: T;\n reason?: E;\n};\n\n// Referenced from https://github.com/reactjs/react.dev/blob/6570e6cd79a16ac3b1a2902632eddab7e6abb9ad/src/content/reference/react/Suspense.md\n/**\n * A custom hook like [`React.use`](https://react.dev/reference/react/use) hook using private Suspense implementation.\n */\nfunction use<T>(promise: Promise<T> | ReactUsePromise<T>) {\n if (isReactUsePromise(promise)) {\n if (promise.status === 'fulfilled') {\n if (promise.value === undefined) {\n throw new Error('[use] Unexpected undefined value from promise');\n }\n return promise.value;\n } else if (promise.status === 'rejected') {\n throw promise.reason;\n } else if (promise.status === 'pending') {\n throw promise;\n }\n throw new Error('[use] Promise is in an invalid state');\n }\n\n const suspensePromise = promise as ReactUsePromise<T>;\n suspensePromise.status = 'pending';\n suspensePromise.then(\n (result: T) => {\n suspensePromise.status = 'fulfilled';\n suspensePromise.value = result;\n },\n (reason) => {\n suspensePromise.status = 'rejected';\n suspensePromise.reason = reason;\n }\n );\n throw suspensePromise;\n}\n\nfunction isReactUsePromise<T>(\n promise: Promise<T> | ReactUsePromise<T>\n): promise is ReactUsePromise<T> {\n return typeof promise === 'object' && promise !== null && 'status' in promise;\n}\n\n//#endregion\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SQLite.d.ts","sourceRoot":"","sources":["../../src/legacy/SQLite.ts"],"names":[],"mappings":"AAAA,OAAO,oBAAoB,CAAC;AAM5B,OAAO,KAAK,EACV,KAAK,EACL,SAAS,EACT,cAAc,EACd,cAAc,EACd,eAAe,EACf,2BAA2B,EAC3B,mBAAmB,EACnB,sBAAsB,EACtB,2BAA2B,EAC5B,MAAM,gBAAgB,CAAC;AAYxB,gDAAgD;AAChD,qBAAa,cAAc;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,OAAO,CAAS;gBAEb,IAAI,EAAE,MAAM;IAIxB;;OAEG;IACH,IAAI,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,cAAc,GAAG,IAAI;IAgBzE;;;;OAIG;IACH,YAAY,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,cAAc,GAAG,IAAI;IAejF;;OAEG;IACG,SAAS,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE,QAAQ,EAAE,OAAO,GAAG,OAAO,CAAC,CAAC,cAAc,GAAG,SAAS,CAAC,EAAE,CAAC;IAa7F;;OAEG;IACH,KAAK,QAKS,
|
|
1
|
+
{"version":3,"file":"SQLite.d.ts","sourceRoot":"","sources":["../../src/legacy/SQLite.ts"],"names":[],"mappings":"AAAA,OAAO,oBAAoB,CAAC;AAM5B,OAAO,KAAK,EACV,KAAK,EACL,SAAS,EACT,cAAc,EACd,cAAc,EACd,eAAe,EACf,2BAA2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AAC,SAAS,GAAG,EAAE,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;IAC7C,EAAE,CAAC,WAAW,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;IACjD,EAAE,CAAC,gBAAgB,GAAG,EAAE,CAAC,GAAG,CAAC,gBAAgB,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;IAC3D,OAAO,EAAE,CAAC;AACZ,CAAC;AAED;;;GAGG;AACH,MAAM,OAAO,uBAAuB;IAEf;IACA;IAFnB,YACmB,EAAkB,EAClB,QAAiB;QADjB,OAAE,GAAF,EAAE,CAAgB;QAClB,aAAQ,GAAR,QAAQ,CAAS;IACjC,CAAC;IAEJ,KAAK,CAAC,eAAe,CAAC,YAAoB,EAAE,IAAwB;QAClE,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,EAAE,CAAC,SAAS,CACxC,CAAC,EAAE,GAAG,EAAE,YAAY,EAAE,IAAI,EAAE,IAAI,IAAI,EAAE,EAAE,CAAC,EACzC,IAAI,CAAC,QAAQ,CACd,CAAC;QACF,MAAM,MAAM,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC;QAC7B,IAAI,gBAAgB,CAAC,MAAM,CAAC,EAAE,CAAC;YAC7B,MAAM,MAAM,CAAC,KAAK,CAAC;QACrB,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AAED,SAAS,gBAAgB,CAAC,MAAkC;IAC1D,OAAO,OAAO,IAAI,MAAM,CAAC;AAC3B,CAAC","sourcesContent":["import './polyfillNextTick';\n\nimport customOpenDatabase from '@expo/websql/custom';\nimport { requireNativeModule } from 'expo-modules-core';\nimport { Platform } from 'react-native';\n\nimport type {\n Query,\n ResultSet,\n ResultSetError,\n SQLiteCallback,\n SQLStatementArg,\n SQLTransactionAsyncCallback,\n SQLTransactionAsync,\n SQLTransactionCallback,\n SQLTransactionErrorCallback,\n} from './SQLite.types';\n\nconst ExpoSQLite = requireNativeModule('ExpoSQLite');\n\nfunction zipObject(keys: string[], values: any[]) {\n const result = {};\n for (let i = 0; i < keys.length; i++) {\n result[keys[i]] = values[i];\n }\n return result;\n}\n\n/** The database returned by `openDatabase()` */\nexport class SQLiteDatabase {\n _name: string;\n _closed: boolean = false;\n\n constructor(name: string) {\n this._name = name;\n }\n\n /**\n * Executes the SQL statement and returns a callback resolving with the result.\n */\n exec(queries: Query[], readOnly: boolean, callback: SQLiteCallback): void {\n if (this._closed) {\n throw new Error(`The SQLite database is closed`);\n }\n\n ExpoSQLite.exec(this._name, queries.map(_serializeQuery), readOnly).then(\n (nativeResultSets) => {\n callback(null, nativeResultSets.map(_deserializeResultSet));\n },\n (error) => {\n // TODO: make the native API consistently reject with an error, not a string or other type\n callback(error instanceof Error ? error : new Error(error));\n }\n );\n }\n\n /**\n * Due to limitations on `Android` this function is provided to allow raw SQL queries to be\n * executed on the database. This will be less efficient than using the `exec` function, please use\n * only when necessary.\n */\n execRawQuery(queries: Query[], readOnly: boolean, callback: SQLiteCallback): void {\n if (Platform.OS === 'ios') {\n return this.exec(queries, readOnly, callback);\n }\n\n ExpoSQLite.execRawQuery(this._name, queries.map(_serializeQuery), readOnly).then(\n (nativeResultSets) => {\n callback(null, nativeResultSets.map(_deserializeResultSet));\n },\n (error) => {\n callback(error instanceof Error ? error : new Error(error));\n }\n );\n }\n\n /**\n * Executes the SQL statement and returns a Promise resolving with the result.\n */\n async execAsync(queries: Query[], readOnly: boolean): Promise<(ResultSetError | ResultSet)[]> {\n if (this._closed) {\n throw new Error(`The SQLite database is closed`);\n }\n\n const nativeResultSets = await ExpoSQLite.exec(\n this._name,\n queries.map(_serializeQuery),\n readOnly\n );\n return nativeResultSets.map(_deserializeResultSet);\n }\n\n /**\n * @deprecated Use `closeAsync()` instead.\n */\n close = this.closeAsync;\n\n /**\n * Close the database.\n */\n closeAsync(): Promise<void> {\n this._closed = true;\n return ExpoSQLite.close(this._name);\n }\n\n /**\n * Synchronously closes the database.\n */\n closeSync(): void {\n this._closed = true;\n return ExpoSQLite.closeSync(this._name);\n }\n\n /**\n * Delete the database file.\n * > The database has to be closed prior to deletion.\n */\n deleteAsync(): Promise<void> {\n if (!this._closed) {\n throw new Error(\n `Unable to delete '${this._name}' database that is currently open. Close it prior to deletion.`\n );\n }\n\n return ExpoSQLite.deleteAsync(this._name);\n }\n\n /**\n * Creates a new transaction with Promise support.\n * @param asyncCallback A `SQLTransactionAsyncCallback` function that can perform SQL statements in a transaction.\n * @param readOnly true if all the SQL statements in the callback are read only.\n */\n async transactionAsync(\n asyncCallback: SQLTransactionAsyncCallback,\n readOnly: boolean = false\n ): Promise<void> {\n await this.execAsync([{ sql: 'BEGIN;', args: [] }], false);\n try {\n const transaction = new ExpoSQLTransactionAsync(this, readOnly);\n await asyncCallback(transaction);\n await this.execAsync([{ sql: 'END;', args: [] }], false);\n } catch (e: unknown) {\n await this.execAsync([{ sql: 'ROLLBACK;', args: [] }], false);\n throw e;\n }\n }\n\n // @ts-expect-error: properties that are added from websql\n version: string;\n\n /**\n * Execute a database transaction.\n * @param callback A function representing the transaction to perform. Takes a Transaction\n * (see below) as its only parameter, on which it can add SQL statements to execute.\n * @param errorCallback Called if an error occurred processing this transaction. Takes a single\n * parameter describing the error.\n * @param successCallback Called when the transaction has completed executing on the database.\n */\n // @ts-expect-error: properties that are added from websql\n transaction(\n callback: SQLTransactionCallback,\n errorCallback?: SQLTransactionErrorCallback,\n successCallback?: () => void\n ): void;\n\n // @ts-expect-error: properties that are added from websql\n readTransaction(\n callback: SQLTransactionCallback,\n errorCallback?: SQLTransactionErrorCallback,\n successCallback?: () => void\n ): void;\n}\n\nfunction _serializeQuery(query: Query): Query | [string, any[]] {\n return Platform.OS === 'android'\n ? {\n sql: query.sql,\n args: query.args.map(_escapeBlob),\n }\n : [query.sql, query.args];\n}\n\nfunction _deserializeResultSet(nativeResult): ResultSet | ResultSetError {\n const [errorMessage, insertId, rowsAffected, columns, rows] = nativeResult;\n // TODO: send more structured error information from the native module so we can better construct\n // a SQLException object\n if (errorMessage !== null) {\n return { error: new Error(errorMessage) } as ResultSetError;\n }\n\n return {\n insertId,\n rowsAffected,\n rows: rows.map((row) => zipObject(columns, row)),\n };\n}\n\nfunction _escapeBlob<T>(data: T): T {\n if (typeof data === 'string') {\n /* eslint-disable no-control-regex */\n return data\n .replace(/\\u0002/g, '\\u0002\\u0002')\n .replace(/\\u0001/g, '\\u0001\\u0002')\n .replace(/\\u0000/g, '\\u0001\\u0001') as any;\n /* eslint-enable no-control-regex */\n } else {\n return data;\n }\n}\n\nconst _openExpoSQLiteDatabase = customOpenDatabase(SQLiteDatabase);\n\n// @needsAudit @docsMissing\n/**\n * Open a database, creating it if it doesn't exist, and return a `Database` object. On disk,\n * the database will be created under the app's [documents directory](./filesystem), i.e.\n * `${FileSystem.documentDirectory}/SQLite/${name}`.\n * > The `version`, `description` and `size` arguments are ignored, but are accepted by the function\n * for compatibility with the WebSQL specification.\n * @param name Name of the database file to open.\n * @param version\n * @param description\n * @param size\n * @param callback\n * @return\n */\nexport function openDatabase(\n name: string,\n version: string = '1.0',\n description: string = name,\n size: number = 1,\n callback?: (db: SQLiteDatabase) => void\n): SQLiteDatabase {\n if (name === undefined) {\n throw new TypeError(`The database name must not be undefined`);\n }\n const db = _openExpoSQLiteDatabase(name, version, description, size, callback);\n db.exec = db._db.exec.bind(db._db);\n db.execRawQuery = db._db.execRawQuery.bind(db._db);\n db.execAsync = db._db.execAsync.bind(db._db);\n db.closeAsync = db._db.closeAsync.bind(db._db);\n db.closeSync = db._db.closeSync.bind(db._db);\n db.deleteAsync = db._db.deleteAsync.bind(db._db);\n db.transactionAsync = db._db.transactionAsync.bind(db._db);\n return db;\n}\n\n/**\n * Internal data structure for the async transaction API.\n * @internal\n */\nexport class ExpoSQLTransactionAsync implements SQLTransactionAsync {\n constructor(\n private readonly db: SQLiteDatabase,\n private readonly readOnly: boolean\n ) {}\n\n async executeSqlAsync(sqlStatement: string, args?: SQLStatementArg[]): Promise<ResultSet> {\n const resultSets = await this.db.execAsync(\n [{ sql: sqlStatement, args: args ?? [] }],\n this.readOnly\n );\n const result = resultSets[0];\n if (isResultSetError(result)) {\n throw result.error;\n }\n return result;\n }\n}\n\nfunction isResultSetError(result: ResultSet | ResultSetError): result is ResultSetError {\n return 'error' in result;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"SQLite.js","sourceRoot":"","sources":["../../src/legacy/SQLite.ts"],"names":[],"mappings":"AAAA,OAAO,oBAAoB,CAAC;AAE5B,OAAO,kBAAkB,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAcxC,MAAM,UAAU,GAAG,mBAAmB,CAAC,YAAY,CAAC,CAAC;AAErD,SAAS,SAAS,CAAC,IAAc,EAAE,MAAa;IAC9C,MAAM,MAAM,GAAG,EAAE,CAAC;IAClB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACpC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;KAC7B;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,gDAAgD;AAChD,MAAM,OAAO,cAAc;IACzB,KAAK,CAAS;IACd,OAAO,GAAY,KAAK,CAAC;IAEzB,YAAY,IAAY;QACtB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;IACpB,CAAC;IAED;;OAEG;IACH,IAAI,CAAC,OAAgB,EAAE,QAAiB,EAAE,QAAwB;QAChE,IAAI,IAAI,CAAC,OAAO,EAAE;YAChB,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;SAClD;QAED,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,KA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;;GAGG;AACH,MAAM,OAAO,uBAAuB;IAEf;IACA;IAFnB,YACmB,EAAkB,EAClB,QAAiB;QADjB,OAAE,GAAF,EAAE,CAAgB;QAClB,aAAQ,GAAR,QAAQ,CAAS;IACjC,CAAC;IAEJ,KAAK,CAAC,eAAe,CAAC,YAAoB,EAAE,IAAwB;QAClE,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,EAAE,CAAC,SAAS,CACxC,CAAC,EAAE,GAAG,EAAE,YAAY,EAAE,IAAI,EAAE,IAAI,IAAI,EAAE,EAAE,CAAC,EACzC,IAAI,CAAC,QAAQ,CACd,CAAC;QACF,MAAM,MAAM,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC;QAC7B,IAAI,gBAAgB,CAAC,MAAM,CAAC,EAAE;YAC5B,MAAM,MAAM,CAAC,KAAK,CAAC;SACpB;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AAED,SAAS,gBAAgB,CAAC,MAAkC;IAC1D,OAAO,OAAO,IAAI,MAAM,CAAC;AAC3B,CAAC","sourcesContent":["import './polyfillNextTick';\n\nimport customOpenDatabase from '@expo/websql/custom';\nimport { requireNativeModule } from 'expo-modules-core';\nimport { Platform } from 'react-native';\n\nimport type {\n Query,\n ResultSet,\n ResultSetError,\n SQLiteCallback,\n SQLStatementArg,\n SQLTransactionAsyncCallback,\n SQLTransactionAsync,\n SQLTransactionCallback,\n SQLTransactionErrorCallback,\n} from './SQLite.types';\n\nconst ExpoSQLite = requireNativeModule('ExpoSQLite');\n\nfunction zipObject(keys: string[], values: any[]) {\n const result = {};\n for (let i = 0; i < keys.length; i++) {\n result[keys[i]] = values[i];\n }\n return result;\n}\n\n/** The database returned by `openDatabase()` */\nexport class SQLiteDatabase {\n _name: string;\n _closed: boolean = false;\n\n constructor(name: string) {\n this._name = name;\n }\n\n /**\n * Executes the SQL statement and returns a callback resolving with the result.\n */\n exec(queries: Query[], readOnly: boolean, callback: SQLiteCallback): void {\n if (this._closed) {\n throw new Error(`The SQLite database is closed`);\n }\n\n ExpoSQLite.exec(this._name, queries.map(_serializeQuery), readOnly).then(\n (nativeResultSets) => {\n callback(null, nativeResultSets.map(_deserializeResultSet));\n },\n (error) => {\n // TODO: make the native API consistently reject with an error, not a string or other type\n callback(error instanceof Error ? error : new Error(error));\n }\n );\n }\n\n /**\n * Due to limitations on `Android` this function is provided to allow raw SQL queries to be\n * executed on the database. This will be less efficient than using the `exec` function, please use\n * only when necessary.\n */\n execRawQuery(queries: Query[], readOnly: boolean, callback: SQLiteCallback): void {\n if (Platform.OS === 'ios') {\n return this.exec(queries, readOnly, callback);\n }\n\n ExpoSQLite.execRawQuery(this._name, queries.map(_serializeQuery), readOnly).then(\n (nativeResultSets) => {\n callback(null, nativeResultSets.map(_deserializeResultSet));\n },\n (error) => {\n callback(error instanceof Error ? error : new Error(error));\n }\n );\n }\n\n /**\n * Executes the SQL statement and returns a Promise resolving with the result.\n */\n async execAsync(queries: Query[], readOnly: boolean): Promise<(ResultSetError | ResultSet)[]> {\n if (this._closed) {\n throw new Error(`The SQLite database is closed`);\n }\n\n const nativeResultSets = await ExpoSQLite.exec(\n this._name,\n queries.map(_serializeQuery),\n readOnly\n );\n return nativeResultSets.map(_deserializeResultSet);\n }\n\n /**\n * @deprecated Use `closeAsync()` instead.\n */\n close = this.closeAsync;\n\n /**\n * Close the database.\n */\n closeAsync(): Promise<void> {\n this._closed = true;\n return ExpoSQLite.close(this._name);\n }\n\n /**\n * Synchronously closes the database.\n */\n closeSync(): void {\n this._closed = true;\n return ExpoSQLite.closeSync(this._name);\n }\n\n /**\n * Delete the database file.\n * > The database has to be closed prior to deletion.\n */\n deleteAsync(): Promise<void> {\n if (!this._closed) {\n throw new Error(\n `Unable to delete '${this._name}' database that is currently open. Close it prior to deletion.`\n );\n }\n\n return ExpoSQLite.deleteAsync(this._name);\n }\n\n /**\n * Creates a new transaction with Promise support.\n * @param asyncCallback A `SQLTransactionAsyncCallback` function that can perform SQL statements in a transaction.\n * @param readOnly true if all the SQL statements in the callback are read only.\n */\n async transactionAsync(\n asyncCallback: SQLTransactionAsyncCallback,\n readOnly: boolean = false\n ): Promise<void> {\n await this.execAsync([{ sql: 'BEGIN;', args: [] }], false);\n try {\n const transaction = new ExpoSQLTransactionAsync(this, readOnly);\n await asyncCallback(transaction);\n await this.execAsync([{ sql: 'END;', args: [] }], false);\n } catch (e: unknown) {\n await this.execAsync([{ sql: 'ROLLBACK;', args: [] }], false);\n throw e;\n }\n }\n\n // @ts-expect-error: properties that are added from websql\n version: string;\n\n /**\n * Execute a database transaction.\n * @param callback A function representing the transaction to perform. Takes a Transaction\n * (see below) as its only parameter, on which it can add SQL statements to execute.\n * @param errorCallback Called if an error occurred processing this transaction. Takes a single\n * parameter describing the error.\n * @param successCallback Called when the transaction has completed executing on the database.\n */\n // @ts-expect-error: properties that are added from websql\n transaction(\n callback: SQLTransactionCallback,\n errorCallback?: SQLTransactionErrorCallback,\n successCallback?: () => void\n ): void;\n\n // @ts-expect-error: properties that are added from websql\n readTransaction(\n callback: SQLTransactionCallback,\n errorCallback?: SQLTransactionErrorCallback,\n successCallback?: () => void\n ): void;\n}\n\nfunction _serializeQuery(query: Query): Query | [string, any[]] {\n return Platform.OS === 'android'\n ? {\n sql: query.sql,\n args: query.args.map(_escapeBlob),\n }\n : [query.sql, query.args];\n}\n\nfunction _deserializeResultSet(nativeResult): ResultSet | ResultSetError {\n const [errorMessage, insertId, rowsAffected, columns, rows] = nativeResult;\n // TODO: send more structured error information from the native module so we can better construct\n // a SQLException object\n if (errorMessage !== null) {\n return { error: new Error(errorMessage) } as ResultSetError;\n }\n\n return {\n insertId,\n rowsAffected,\n rows: rows.map((row) => zipObject(columns, row)),\n };\n}\n\nfunction _escapeBlob<T>(data: T): T {\n if (typeof data === 'string') {\n /* eslint-disable no-control-regex */\n return data\n .replace(/\\u0002/g, '\\u0002\\u0002')\n .replace(/\\u0001/g, '\\u0001\\u0002')\n .replace(/\\u0000/g, '\\u0001\\u0001') as any;\n /* eslint-enable no-control-regex */\n } else {\n return data;\n }\n}\n\nconst _openExpoSQLiteDatabase = customOpenDatabase(SQLiteDatabase);\n\n// @needsAudit @docsMissing\n/**\n * Open a database, creating it if it doesn't exist, and return a `Database` object. On disk,\n * the database will be created under the app's [documents directory](./filesystem), i.e.\n * `${FileSystem.documentDirectory}/SQLite/${name}`.\n * > The `version`, `description` and `size` arguments are ignored, but are accepted by the function\n * for compatibility with the WebSQL specification.\n * @param name Name of the database file to open.\n * @param version\n * @param description\n * @param size\n * @param callback\n * @return\n */\nexport function openDatabase(\n name: string,\n version: string = '1.0',\n description: string = name,\n size: number = 1,\n callback?: (db: SQLiteDatabase) => void\n): SQLiteDatabase {\n if (name === undefined) {\n throw new TypeError(`The database name must not be undefined`);\n }\n const db = _openExpoSQLiteDatabase(name, version, description, size, callback);\n db.exec = db._db.exec.bind(db._db);\n db.execRawQuery = db._db.execRawQuery.bind(db._db);\n db.execAsync = db._db.execAsync.bind(db._db);\n db.closeAsync = db._db.closeAsync.bind(db._db);\n db.closeSync = db._db.closeSync.bind(db._db);\n db.deleteAsync = db._db.deleteAsync.bind(db._db);\n db.transactionAsync = db._db.transactionAsync.bind(db._db);\n return db;\n}\n\n/**\n * Internal data structure for the async transaction API.\n * @internal\n */\nexport class ExpoSQLTransactionAsync implements SQLTransactionAsync {\n constructor(\n private readonly db: SQLiteDatabase,\n private readonly readOnly: boolean\n ) {}\n\n async executeSqlAsync(sqlStatement: string, args?: SQLStatementArg[]): Promise<ResultSet> {\n const resultSets = await this.db.execAsync(\n [{ sql: sqlStatement, args: args ?? [] }],\n this.readOnly\n );\n const result = resultSets[0];\n if (isResultSetError(result)) {\n throw result.error;\n }\n return result;\n }\n}\n\nfunction isResultSetError(result: ResultSet | ResultSetError): result is ResultSetError {\n return 'error' in result;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SQLite.web.js","sourceRoot":"","sources":["../../src/legacy/SQLite.web.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAIxD,MAAM,UAAU,YAAY,CAC1B,IAAY,EACZ,UAAkB,KAAK,EACvB,cAAsB,IAAI,EAC1B,OAAe,CAAC,EAChB,QAA2B;IAE3B,MAAM,WAAW,GAAW,MAAgB,CAAC;IAC7C,IAAI,cAAc,IAAI,WAAW,IAAI,WAAW,CAAC,YAAY,EAAE
|
|
1
|
+
{"version":3,"file":"SQLite.web.js","sourceRoot":"","sources":["../../src/legacy/SQLite.web.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAIxD,MAAM,UAAU,YAAY,CAC1B,IAAY,EACZ,UAAkB,KAAK,EACvB,cAAsB,IAAI,EAC1B,OAAe,CAAC,EAChB,QAA2B;IAE3B,MAAM,WAAW,GAAW,MAAgB,CAAC;IAC7C,IAAI,cAAc,IAAI,WAAW,IAAI,WAAW,CAAC,YAAY,EAAE;QAC7D,OAAO,WAAW,CAAC,YAAY,CAAC,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;KAC7E;IACD,MAAM,IAAI,mBAAmB,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAC;AAC1D,CAAC","sourcesContent":["import { UnavailabilityError } from 'expo-modules-core';\n\nimport { Window, DatabaseCallback } from './SQLite.types';\n\nexport function openDatabase(\n name: string,\n version: string = '1.0',\n description: string = name,\n size: number = 1,\n callback?: DatabaseCallback\n) {\n const typedWindow: Window = window as Window;\n if ('openDatabase' in typedWindow && typedWindow.openDatabase) {\n return typedWindow.openDatabase(name, version, description, size, callback);\n }\n throw new UnavailabilityError('window', 'openDatabase');\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"polyfillNextTick.js","sourceRoot":"","sources":["../../src/legacy/polyfillNextTick.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE
|
|
1
|
+
{"version":3,"file":"polyfillNextTick.js","sourceRoot":"","sources":["../../src/legacy/polyfillNextTick.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE;IACrB,OAAO,CAAC,QAAQ,GAAG,CAAC,QAAQ,EAAE,GAAG,IAAI,EAAE,EAAE;QACvC,UAAU,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;IACzC,CAAC,CAAC;CACH","sourcesContent":["/**\n * Defines a small polyfill for process.nextTick. Eventually we'd like to replace this polyfill with\n * a native implementation with the correct timing semantics.\n */\n\ndeclare const process: Record<string, any>;\n\nif (!process.nextTick) {\n process.nextTick = (callback, ...args) => {\n setTimeout(() => callback(...args), 0);\n };\n}\n"]}
|
package/build/paramUtils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"paramUtils.js","sourceRoot":"","sources":["../src/paramUtils.ts"],"names":[],"mappings":"AASA;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAC7B,GAAG,MAAa;IAEhB,IAAI,UAAU,GAAG,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAE,MAAM,CAAC,CAAC,CAAsB,CAAC;IAC9E,IAAI,UAAU,IAAI,IAAI,EAAE
|
|
1
|
+
{"version":3,"file":"paramUtils.js","sourceRoot":"","sources":["../src/paramUtils.ts"],"names":[],"mappings":"AASA;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAC7B,GAAG,MAAa;IAEhB,IAAI,UAAU,GAAG,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAE,MAAM,CAAC,CAAC,CAAsB,CAAC;IAC9E,IAAI,UAAU,IAAI,IAAI,EAAE;QACtB,UAAU,GAAG,EAAE,CAAC;KACjB;IACD,IACE,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AE;QAC3C,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,GAAG,YAAY,CAAC,CAAC,CAAC,CAAC;KACvC;IACD,OAAO,GAAQ,CAAC;AAClB,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,WAAW,CACzB,WAA8B,EAC9B,gBAAsC;IAEtC,IAAI,gBAAgB,CAAC,MAAM,KAAK,CAAC,EAAE;QACjC,OAAO,EAAE,CAAC;KACX;IACD,IAAI,WAAW,CAAC,MAAM,KAAK,gBAAgB,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE;QACrD,yFAAyF;QACzF,MAAM,IAAI,KAAK,CACb,kDAAkD,WAAW,CAAC,MAAM,aAAa,gBAAgB,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAC9G,CAAC;KACH;IACD,MAAM,OAAO,GAAQ,EAAE,CAAC;IACxB,KAAK,MAAM,YAAY,IAAI,gBAAgB,EAAE;QAC3C,MAAM,GAAG,GAAG,EAAE,CAAC;QACf,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,WAAW,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YAC3C,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,GAAG,YAAY,CAAC,CAAC,CAAC,CAAC;SACvC;QACD,OAAO,CAAC,IAAI,CAAC,GAAQ,CAAC,CAAC;KACxB;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import {\n SQLiteBindBlobParams,\n SQLiteBindParams,\n SQLiteBindPrimitiveParams,\n SQLiteBindValue,\n type SQLiteColumnNames,\n type SQLiteColumnValues,\n} from './NativeStatement';\n\n/**\n * Normalize the bind params to data structure that can be passed to native module.\n * The data structure is a tuple of [primitiveParams, blobParams, shouldPassAsArray].\n * @hidden\n */\nexport function normalizeParams(\n ...params: any[]\n): [SQLiteBindPrimitiveParams, SQLiteBindBlobParams, boolean] {\n let bindParams = params.length > 1 ? params : (params[0] as SQLiteBindParams);\n if (bindParams == null) {\n bindParams = [];\n }\n if (\n typeof bindParams !== 'object' ||\n bindParams instanceof ArrayBuffer ||\n ArrayBuffer.isView(bindParams)\n ) {\n bindParams = [bindParams];\n }\n const shouldPassAsArray = Array.isArray(bindParams);\n if (Array.isArray(bindParams)) {\n bindParams = bindParams.reduce<Record<string, SQLiteBindValue>>((acc, value, index) => {\n acc[index] = value;\n return acc;\n }, {});\n }\n\n const primitiveParams: SQLiteBindPrimitiveParams = {};\n const blobParams: SQLiteBindBlobParams = {};\n for (const key in bindParams) {\n const value = bindParams[key];\n if (value instanceof Uint8Array) {\n blobParams[key] = value;\n } else {\n primitiveParams[key] = value;\n }\n }\n\n return [primitiveParams, blobParams, shouldPassAsArray];\n}\n\n/**\n * Compose `columnNames` and `columnValues` to an row object.\n * @hidden\n */\nexport function composeRow<T>(columnNames: SQLiteColumnNames, columnValues: SQLiteColumnValues): T {\n const row = {};\n if (columnNames.length !== columnValues.length) {\n throw new Error(\n `Column names and values count mismatch. Names: ${columnNames.length}, Values: ${columnValues.length}`\n );\n }\n for (let i = 0; i < columnNames.length; i++) {\n row[columnNames[i]] = columnValues[i];\n }\n return row as T;\n}\n\n/**\n * Compose `columnNames` and `columnValuesList` to an array of row objects.\n * @hidden\n */\nexport function composeRows<T>(\n columnNames: SQLiteColumnNames,\n columnValuesList: SQLiteColumnValues[]\n): T[] {\n if (columnValuesList.length === 0) {\n return [];\n }\n if (columnNames.length !== columnValuesList[0].length) {\n // We only check the first row because SQLite returns the same column count for all rows.\n throw new Error(\n `Column names and values count mismatch. Names: ${columnNames.length}, Values: ${columnValuesList[0].length}`\n );\n }\n const results: T[] = [];\n for (const columnValues of columnValuesList) {\n const row = {};\n for (let i = 0; i < columnNames.length; i++) {\n row[columnNames[i]] = columnValues[i];\n }\n results.push(row as T);\n }\n return results;\n}\n"]}
|
package/ios/ExpoSQLite.podspec
CHANGED
|
@@ -3,7 +3,7 @@ require 'json'
|
|
|
3
3
|
package = JSON.parse(File.read(File.join(__dir__, '..', 'package.json')))
|
|
4
4
|
podfile_properties = JSON.parse(File.read("#{Pod::Config.instance.installation_root}/Podfile.properties.json")) rescue {}
|
|
5
5
|
|
|
6
|
-
sqliteVersion = '3.
|
|
6
|
+
sqliteVersion = '3.45.3+1'
|
|
7
7
|
|
|
8
8
|
Pod::Spec.new do |s|
|
|
9
9
|
s.name = 'ExpoSQLite'
|
|
@@ -19,6 +19,7 @@ Pod::Spec.new do |s|
|
|
|
19
19
|
s.dependency 'ExpoModulesCore'
|
|
20
20
|
|
|
21
21
|
s.dependency 'sqlite3', "~> #{sqliteVersion}"
|
|
22
|
+
s.dependency 'sqlite3/bytecodevtab', "~> #{sqliteVersion}"
|
|
22
23
|
unless podfile_properties['expo.sqlite.enableFTS'] === 'false'
|
|
23
24
|
s.dependency 'sqlite3/fts', "~> #{sqliteVersion}"
|
|
24
25
|
s.dependency 'sqlite3/fts5', "~> #{sqliteVersion}"
|
|
@@ -46,6 +46,22 @@ public final class SQLiteModuleNext: Module {
|
|
|
46
46
|
try deleteDatabase(databaseName: databaseName)
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
+
AsyncFunction("importAssetDatabaseAsync") { (databaseName: String, assetDatabasePath: String, forceOverwrite: Bool) in
|
|
50
|
+
guard let path = pathForDatabaseName(name: databaseName) else {
|
|
51
|
+
throw Exceptions.FileSystemModuleNotFound()
|
|
52
|
+
}
|
|
53
|
+
let fileManager = FileManager.default
|
|
54
|
+
if fileManager.fileExists(atPath: path.absoluteString) && !forceOverwrite {
|
|
55
|
+
return
|
|
56
|
+
}
|
|
57
|
+
guard let assetPath = URL(string: assetDatabasePath)?.path,
|
|
58
|
+
fileManager.fileExists(atPath: assetPath) else {
|
|
59
|
+
throw DatabaseNotFoundException(assetDatabasePath)
|
|
60
|
+
}
|
|
61
|
+
try? fileManager.removeItem(atPath: path.absoluteString)
|
|
62
|
+
try fileManager.copyItem(atPath: assetPath, toPath: path.absoluteString)
|
|
63
|
+
}
|
|
64
|
+
|
|
49
65
|
// swiftlint:disable:next closure_body_length
|
|
50
66
|
Class(NativeDatabase.self) {
|
|
51
67
|
Constructor { (databaseName: String, options: OpenDatabaseOptions, serializedData: Data?) -> NativeDatabase in
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "expo-sqlite",
|
|
3
|
-
"version": "14.0.
|
|
3
|
+
"version": "14.0.2",
|
|
4
4
|
"description": "Provides access to a database that can be queried through a WebSQL-like API (https://www.w3.org/TR/webdatabase/). The database is persisted across restarts of your app.",
|
|
5
5
|
"main": "build/index.js",
|
|
6
6
|
"types": "build/index.d.ts",
|
|
@@ -61,5 +61,5 @@
|
|
|
61
61
|
"peerDependencies": {
|
|
62
62
|
"expo": "*"
|
|
63
63
|
},
|
|
64
|
-
"gitHead": "
|
|
64
|
+
"gitHead": "0897aeadb926491a457bcd67d83360956994ee82"
|
|
65
65
|
}
|
package/src/ExpoSQLiteNext.ts
CHANGED
|
@@ -21,6 +21,14 @@ export default {
|
|
|
21
21
|
throw new Error('Unimplemented');
|
|
22
22
|
},
|
|
23
23
|
|
|
24
|
+
importAssetDatabaseAsync(
|
|
25
|
+
databaseName: string,
|
|
26
|
+
assetDatabasePath: string,
|
|
27
|
+
forceOverwrite: boolean
|
|
28
|
+
): Promise<void> {
|
|
29
|
+
throw new Error('Unimplemented');
|
|
30
|
+
},
|
|
31
|
+
|
|
24
32
|
//#region EventEmitter implementations
|
|
25
33
|
|
|
26
34
|
addListener() {
|
package/src/hooks.tsx
CHANGED
|
@@ -1,8 +1,23 @@
|
|
|
1
|
+
import { Asset } from 'expo-asset';
|
|
1
2
|
import React, { createContext, useContext, useEffect, useRef, useState } from 'react';
|
|
2
3
|
|
|
4
|
+
import ExpoSQLite from './ExpoSQLiteNext';
|
|
3
5
|
import type { SQLiteOpenOptions } from './NativeDatabase';
|
|
4
6
|
import { openDatabaseAsync, type SQLiteDatabase } from './SQLiteDatabase';
|
|
5
7
|
|
|
8
|
+
export interface SQLiteProviderAssetSource {
|
|
9
|
+
/**
|
|
10
|
+
* The asset ID returned from the `require()` call.
|
|
11
|
+
*/
|
|
12
|
+
assetId: number;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Force overwrite the local database file even if it already exists.
|
|
16
|
+
* @default false
|
|
17
|
+
*/
|
|
18
|
+
forceOverwrite?: boolean;
|
|
19
|
+
}
|
|
20
|
+
|
|
6
21
|
export interface SQLiteProviderProps {
|
|
7
22
|
/**
|
|
8
23
|
* The name of the database file to open.
|
|
@@ -14,6 +29,15 @@ export interface SQLiteProviderProps {
|
|
|
14
29
|
*/
|
|
15
30
|
options?: SQLiteOpenOptions;
|
|
16
31
|
|
|
32
|
+
/**
|
|
33
|
+
* Import a bundled database file from the specified asset module.
|
|
34
|
+
* @example
|
|
35
|
+
* ```ts
|
|
36
|
+
* assetSource={{ assetId: require('./assets/db.db') }}
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
39
|
+
assetSource?: SQLiteProviderAssetSource;
|
|
40
|
+
|
|
17
41
|
/**
|
|
18
42
|
* The children to render.
|
|
19
43
|
*/
|
|
@@ -120,12 +144,14 @@ let databaseInstance: DatabaseInstanceType | null = null;
|
|
|
120
144
|
function SQLiteProviderSuspense({
|
|
121
145
|
databaseName,
|
|
122
146
|
options,
|
|
147
|
+
assetSource,
|
|
123
148
|
children,
|
|
124
149
|
onInit,
|
|
125
150
|
}: Omit<SQLiteProviderProps, 'onError' | 'useSuspense'>) {
|
|
126
151
|
const databasePromise = getDatabaseAsync({
|
|
127
152
|
databaseName,
|
|
128
153
|
options,
|
|
154
|
+
assetSource,
|
|
129
155
|
onInit,
|
|
130
156
|
});
|
|
131
157
|
const database = use(databasePromise);
|
|
@@ -135,6 +161,7 @@ function SQLiteProviderSuspense({
|
|
|
135
161
|
function SQLiteProviderNonSuspense({
|
|
136
162
|
databaseName,
|
|
137
163
|
options,
|
|
164
|
+
assetSource,
|
|
138
165
|
children,
|
|
139
166
|
onInit,
|
|
140
167
|
onError,
|
|
@@ -146,7 +173,7 @@ function SQLiteProviderNonSuspense({
|
|
|
146
173
|
useEffect(() => {
|
|
147
174
|
async function setup() {
|
|
148
175
|
try {
|
|
149
|
-
const db = await openDatabaseWithInitAsync({ databaseName, options, onInit });
|
|
176
|
+
const db = await openDatabaseWithInitAsync({ databaseName, options, assetSource, onInit });
|
|
150
177
|
databaseRef.current = db;
|
|
151
178
|
setLoading(false);
|
|
152
179
|
} catch (e) {
|
|
@@ -189,8 +216,12 @@ function SQLiteProviderNonSuspense({
|
|
|
189
216
|
function getDatabaseAsync({
|
|
190
217
|
databaseName,
|
|
191
218
|
options,
|
|
219
|
+
assetSource,
|
|
192
220
|
onInit,
|
|
193
|
-
}: Pick<
|
|
221
|
+
}: Pick<
|
|
222
|
+
SQLiteProviderProps,
|
|
223
|
+
'databaseName' | 'options' | 'assetSource' | 'onInit'
|
|
224
|
+
>): Promise<SQLiteDatabase> {
|
|
194
225
|
if (
|
|
195
226
|
databaseInstance?.promise != null &&
|
|
196
227
|
databaseInstance?.databaseName === databaseName &&
|
|
@@ -207,10 +238,10 @@ function getDatabaseAsync({
|
|
|
207
238
|
db.closeAsync();
|
|
208
239
|
})
|
|
209
240
|
.then(() => {
|
|
210
|
-
return openDatabaseWithInitAsync({ databaseName, options, onInit });
|
|
241
|
+
return openDatabaseWithInitAsync({ databaseName, options, assetSource, onInit });
|
|
211
242
|
});
|
|
212
243
|
} else {
|
|
213
|
-
promise = openDatabaseWithInitAsync({ databaseName, options, onInit });
|
|
244
|
+
promise = openDatabaseWithInitAsync({ databaseName, options, assetSource, onInit });
|
|
214
245
|
}
|
|
215
246
|
databaseInstance = {
|
|
216
247
|
databaseName,
|
|
@@ -224,8 +255,15 @@ function getDatabaseAsync({
|
|
|
224
255
|
async function openDatabaseWithInitAsync({
|
|
225
256
|
databaseName,
|
|
226
257
|
options,
|
|
258
|
+
assetSource,
|
|
227
259
|
onInit,
|
|
228
|
-
}: Pick<
|
|
260
|
+
}: Pick<
|
|
261
|
+
SQLiteProviderProps,
|
|
262
|
+
'databaseName' | 'options' | 'assetSource' | 'onInit'
|
|
263
|
+
>): Promise<SQLiteDatabase> {
|
|
264
|
+
if (assetSource != null) {
|
|
265
|
+
await importDatabaseFromAssetAsync(databaseName, assetSource);
|
|
266
|
+
}
|
|
229
267
|
const database = await openDatabaseAsync(databaseName, options);
|
|
230
268
|
if (onInit != null) {
|
|
231
269
|
await onInit(database);
|
|
@@ -233,6 +271,21 @@ async function openDatabaseWithInitAsync({
|
|
|
233
271
|
return database;
|
|
234
272
|
}
|
|
235
273
|
|
|
274
|
+
async function importDatabaseFromAssetAsync(
|
|
275
|
+
databaseName: string,
|
|
276
|
+
assetSource: SQLiteProviderAssetSource
|
|
277
|
+
) {
|
|
278
|
+
const asset = await Asset.fromModule(assetSource.assetId).downloadAsync();
|
|
279
|
+
if (!asset.localUri) {
|
|
280
|
+
throw new Error(`Unable to get the localUri from asset ${assetSource.assetId}`);
|
|
281
|
+
}
|
|
282
|
+
await ExpoSQLite.importAssetDatabaseAsync(
|
|
283
|
+
databaseName,
|
|
284
|
+
asset.localUri,
|
|
285
|
+
assetSource.forceOverwrite ?? false
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
|
|
236
289
|
//#endregion
|
|
237
290
|
|
|
238
291
|
//#region Private Suspense API similar to `React.use`
|