xref: /expo/packages/expo-sqlite/build/SQLite.js (revision 331b8461)
1import './polyfillNextTick';
2import customOpenDatabase from '@expo/websql/custom';
3import { requireNativeModule } from 'expo-modules-core';
4import { Platform } from 'react-native';
5const ExpoSQLite = requireNativeModule('ExpoSQLite');
6function zipObject(keys, values) {
7    const result = {};
8    for (let i = 0; i < keys.length; i++) {
9        result[keys[i]] = values[i];
10    }
11    return result;
12}
13/** The database returned by `openDatabase()` */
14export class SQLiteDatabase {
15    _name;
16    _closed = false;
17    constructor(name) {
18        this._name = name;
19    }
20    /**
21     * Executes the SQL statement and returns a callback resolving with the result.
22     */
23    exec(queries, readOnly, callback) {
24        if (this._closed) {
25            throw new Error(`The SQLite database is closed`);
26        }
27        ExpoSQLite.exec(this._name, queries.map(_serializeQuery), readOnly).then((nativeResultSets) => {
28            callback(null, nativeResultSets.map(_deserializeResultSet));
29        }, (error) => {
30            // TODO: make the native API consistently reject with an error, not a string or other type
31            callback(error instanceof Error ? error : new Error(error));
32        });
33    }
34    /**
35     * Executes the SQL statement and returns a Promise resolving with the result.
36     */
37    async execAsync(queries, readOnly) {
38        if (this._closed) {
39            throw new Error(`The SQLite database is closed`);
40        }
41        const nativeResultSets = await ExpoSQLite.exec(this._name, queries.map(_serializeQuery), readOnly);
42        return nativeResultSets.map(_deserializeResultSet);
43    }
44    /**
45     * @deprecated Use `closeAsync()` instead.
46     */
47    close = this.closeAsync;
48    /**
49     * Close the database.
50     */
51    closeAsync() {
52        this._closed = true;
53        return ExpoSQLite.close(this._name);
54    }
55    /**
56     * Delete the database file.
57     * > The database has to be closed prior to deletion.
58     */
59    deleteAsync() {
60        if (!this._closed) {
61            throw new Error(`Unable to delete '${this._name}' database that is currently open. Close it prior to deletion.`);
62        }
63        return ExpoSQLite.deleteAsync(this._name);
64    }
65    /**
66     * Creates a new transaction with Promise support.
67     * @param asyncCallback A `SQLTransactionAsyncCallback` function that can perform SQL statements in a transaction.
68     * @param readOnly true if all the SQL statements in the callback are read only.
69     */
70    async transactionAsync(asyncCallback, readOnly = false) {
71        await this.execAsync([{ sql: 'BEGIN;', args: [] }], false);
72        try {
73            const transaction = new ExpoSQLTransactionAsync(this, readOnly);
74            await asyncCallback(transaction);
75            await this.execAsync([{ sql: 'END;', args: [] }], false);
76        }
77        catch (e) {
78            await this.execAsync([{ sql: 'ROLLBACK;', args: [] }], false);
79            throw e;
80        }
81    }
82    // @ts-expect-error: properties that are added from websql
83    version;
84}
85function _serializeQuery(query) {
86    return Platform.OS === 'android'
87        ? {
88            sql: query.sql,
89            args: query.args.map(_escapeBlob),
90        }
91        : [query.sql, query.args];
92}
93function _deserializeResultSet(nativeResult) {
94    const [errorMessage, insertId, rowsAffected, columns, rows] = nativeResult;
95    // TODO: send more structured error information from the native module so we can better construct
96    // a SQLException object
97    if (errorMessage !== null) {
98        return { error: new Error(errorMessage) };
99    }
100    return {
101        insertId,
102        rowsAffected,
103        rows: rows.map((row) => zipObject(columns, row)),
104    };
105}
106function _escapeBlob(data) {
107    if (typeof data === 'string') {
108        /* eslint-disable no-control-regex */
109        return data
110            .replace(/\u0002/g, '\u0002\u0002')
111            .replace(/\u0001/g, '\u0001\u0002')
112            .replace(/\u0000/g, '\u0001\u0001');
113        /* eslint-enable no-control-regex */
114    }
115    else {
116        return data;
117    }
118}
119const _openExpoSQLiteDatabase = customOpenDatabase(SQLiteDatabase);
120// @needsAudit @docsMissing
121/**
122 * Open a database, creating it if it doesn't exist, and return a `Database` object. On disk,
123 * the database will be created under the app's [documents directory](./filesystem), i.e.
124 * `${FileSystem.documentDirectory}/SQLite/${name}`.
125 * > The `version`, `description` and `size` arguments are ignored, but are accepted by the function
126 * for compatibility with the WebSQL specification.
127 * @param name Name of the database file to open.
128 * @param version
129 * @param description
130 * @param size
131 * @param callback
132 * @return
133 */
134export function openDatabase(name, version = '1.0', description = name, size = 1, callback) {
135    if (name === undefined) {
136        throw new TypeError(`The database name must not be undefined`);
137    }
138    const db = _openExpoSQLiteDatabase(name, version, description, size, callback);
139    db.exec = db._db.exec.bind(db._db);
140    db.execAsync = db._db.execAsync.bind(db._db);
141    db.closeAsync = db._db.closeAsync.bind(db._db);
142    db.deleteAsync = db._db.deleteAsync.bind(db._db);
143    db.transactionAsync = db._db.transactionAsync.bind(db._db);
144    return db;
145}
146/**
147 * Internal data structure for the async transaction API.
148 * @internal
149 */
150export class ExpoSQLTransactionAsync {
151    db;
152    readOnly;
153    constructor(db, readOnly) {
154        this.db = db;
155        this.readOnly = readOnly;
156    }
157    async executeSqlAsync(sqlStatement, args) {
158        const resultSets = await this.db.execAsync([{ sql: sqlStatement, args: args ?? [] }], this.readOnly);
159        return resultSets[0];
160    }
161}
162//# sourceMappingURL=SQLite.js.map