React-native-quick-sqlite - ⚡️ The fastest SQLite implementation for react-native.

Overview

React Native Quick SQLite

The **fastest** SQLite implementation for react-native.

Frame 2

    Copy typeORM patch-package from example dir
    npm i react-native-quick-sqlite typeorm
    npx pod-install
    Enable decorators and configure babel
  


Quick SQLite uses JSI, removes all the overhead of intercommunication between JavaScript code and C++ code, making CRUDing entities from SQLite super fast!

Big ❤️ to react-native-sqlite-storage and react-native-sqlite2, this library also provides a WebSQL interface.

If you are using quick-sqlite in your app, please get in touch or open a PR with a modified README (with your company/product logo, would love to showcase you!

GOTCHAS

  • It's not possible to use the browser debugger with JSI, use Flipper, on android Flipper also has an integrated database explorer you can use to debug your sqlite database, you will have to configure your database path though. 130516553-15c18d0f-65ad-44cf-8235-a4d6f41859e2
  • Your app will now include C++, you will need to install the NDK on your machine for android. (unless you know how to generate an AAR, feel free to open a PR)
  • If you want to run the example project on android, you will have to change the paths on the android/CMakeLists.txt file, they are already there, just uncomment them.
  • This library supports SQLite BLOBs which are mapped to JS ArrayBuffers, check out the sample project on how to use it
  • Starting with version 2.0.0 the library no longer throws errors when an invalid statement is passed, but rather returns an object with a status enum property, where 0 signals a succesful execution and 1 an incorrect execution (this is to keep typeorm from exploding when an incorrect query is executed)

Use TypeORM

The recommended way to use this package is to use TypeORM with patch-package. TypeORM already has a sqlite-storage driver. In the example project on the patch folder you can a find a patch for TypeORM, it basically just replaces all the react-native-sqlite-storage strings in TypeORM with react-native-quick-sqlite.

Follow the instructions to make TypeORM work with rn (enable decorators, configure babel, etc), then apply the patch via patch-package and you should be good to go.

Low level API

It is also possible to directly execute SQL against the db:

interface ISQLite {
  open: (dbName: string, location?: string) => any;
  close: (dbName: string, location?: string) => any;
  executeSql: (
    dbName: string,
    query: string,
    params: any[] | undefined
  ) => {
    status: 0 | 1; // 0 for correct execution
    message: string; // if status === 1, here you will find error description
    rows: any[];
    insertId?: number;
  };
}

In your code

// If you want to register the (globalThis) types for the low level API do an empty import
import 'react-native-quick-sqlite';

// `sqlite` is a globally registered object, so you can directly call it from anywhere in your javascript
// The methods `throw` when an execution error happens, so try/catch them
try {
  sqlite.open('myDatabase', 'databases');
} catch (e) {
  console.log(e); // [react-native-quick-sqlite]: Could not open database file: ERR XXX
}

JSI Cheatsheet

If you want to learn how to make your own JSI module and also get a reference guide for all things C++/JSI you can buy my JSI/C++ Cheatsheet

License

react-native-quick-sqlite is licensed under MIT.

Comments
  • Issues with reading JSON strings in SQLite rows

    Issues with reading JSON strings in SQLite rows

    Hi,

    I was using expo-sqlite package with TypeORM package in my React Native app, and I decided to change the adapter to this package.

    Everything mostly works, however some of my content are stored using simple-json data type in TypeORM, which uses JSON.stringify to store JSON data in SQLite. When reading this data from SQLite using this package, some of the content are terminated unexpectedly. Not everything. But some of them for example are missing the final } in the string...

    Do you have any ideas where this issue may be coming from? Thanks!

    opened by sallar 26
  • Unable to use a populated database file in iOS

    Unable to use a populated database file in iOS

    I am trying to use my existing DB file which I setup following the guide on rn-sqlite page

    The code which I am trying to run is this, everything works fine with sqlite library

    const db = QuickSQLite.open('prepop.db');
    
    console.log('db', db.status);
    // the db gets opened 0
    
    const res = QuickSQLite.executeSql(
      'prepop.db',
      'SELECT * from employees',
      undefined,
    );
    
    // {"message": "[react-native-quick-sqlite] SQL execution error: no such table: employees", "rows": {"_array": [], "item": [Function item], "length": 0}, "status": 1}
    
    opened by ShivamJoker 25
  • Refactor to promise based and easier APIs

    Refactor to promise based and easier APIs

    I was using raw queries the other day and realized it is kinda awkward to use some of the methods. Also the fact that devs are using the TypeORM wrapper bothers me. I've refactored the code to throw errors (no point in fighting the JS patterns) which makes the code and APIs a bit easier to read/understand. This is however a major refactoring. @EduFrazao would you be willing to give a hand to test this changes?

    opened by ospfranco 20
  • Avoid global scope

    Avoid global scope

    The term sqlite is sufficiently common as to be inconvenient (for me) to be taken globally. It would be nice if I could import {sqlite as myOtherSqlite} from 'react-native-quick-sqlite';.

    Potentially register global object (that is what you need for JSI, yes?) as rnQuickSqlite, which no one else is likely to use, and export const sqlite = rnQuickSqlite; for named imports from this lib.

    opened by alpha0010 17
  • Support for SQLite Compile-Time Options?

    Support for SQLite Compile-Time Options?

    Looking at this library as a replacement for react-native-sqlite-storage in a project I'm working on and first impressions are great.

    I've got requirements for enabling FTS5 and Geopoly extensions. This seems possible with this library as opposed to RNSS since the SQLite source is compiled from /cpp for both iOS and Android, instead of using the phone's SQLite. Is there any method of setting compile-time options for enabling specific extensions (e.g. SQLITE_ENABLE_GEOPOLY) ?

    The closest I have reached is presuming that you can set options somewhere in 'CMakeLists.txt' for Android and the podspec for iOS, but I've not been having any luck.

    Thanks.

    opened by HaydenPWoods 16
  • Enable JSON1 on Android

    Enable JSON1 on Android

    Hi, Is there a way to enable JSON1 module for Android in order to use json_extract in SQL queries ?

    This also can be a good point about the cross-platform compatibility since iOS manage it already. Thanks for help.

    opened by LaGregance 15
  • Don't allow partial transactions to commit

    Don't allow partial transactions to commit

    This prevents partial transactions from committing.

    Before this change, if a consuming application caught an error and didn't rethrow it (or a different error), the transaction would commit, leaving the consuming application to clean up bad data. This moves the COMMIT and ROLLBACK calls into the finally blocks for transactions so consuming applications can implement their own error handling and can't accidentally forget to throw an error if one is caught.

    Note: the main change for this PR is 3c983cd. The commits leading to it add a missing development dependency and add prettier.

    Closes #92.

    opened by cmoel 14
  • Using with TypeORM

    Using with TypeORM

    Description

    Hey! Thanks for making this great package. I'm attempting to use it with TypeORM but getting the following error when initializing

    Screen Shot 2022-08-13 at 12 21 58 PM
    1. I have this package, typeorm, reflect-metadata and the required babel plugins installed (tried clearing all cache already)
    2. I did the patch mentioned in the readme by adding "./package.json": "./package.json" to the TypeORM package.json file

    DataSource setup:

    datasource = new DataSource({
        type: 'react-native',
        database: '<db_name>',
        location: 'default',
        // seems like the error is coming from here
        driver: require('react-native-quick-sqlite'),
        entities: [...],
        synchronize: true,
      });
    

    Also looks like the latest commit commented out the TypeORM code from the example project, so I was wondering if the readme is up to date on the necessary steps for getting setup

    Additonal info

    "react-native": "0.68.2",

    opened by eylamf 12
  • Trouble with the interface for `transactionAsync`

    Trouble with the interface for `transactionAsync`

    I'm trying to use the Async Transactions API and I'm running into a couple issues. It's possible I'm doing it wrong but it doesn't seem like it right now.

    After opening the database, I'm purposefully raising an error, hoping to catch it on the JavaScript side:

    db.transactionAsync(tx =>
      tx
        .executeAsync("insert into dogs (name) values (?)", ["Sam"])
        .then(res =>
          tx.executeAsync("insert into people (dog_id, name) values (?, ?)", [
            res.insertId,
            "Kirsten",
          ]),
        )
        .then(() => tx.executeAsync(selectAll, []))
        .catch(e => console.log("ERROR", e)),
    )
    

    I haven't defined the people table yet so an error is raised.

    SQL execution error: no such table: people
    

    Which is what I expect. I'd like to catch this error rather than have a fatal React Native error:

    Screen Shot 2022-10-20 at 20 25 43

    Also, the database is locked after this failure and I'm not sure how to get around that. I assume it's because I was in the middle of a transaction when it failed?

    Screen Shot 2022-10-20 at 20 49 18

    Lastly, the code snippet doesn't type check. I get this TypeScript error:

    Type 'Promise<void | QueryResult>' is not assignable to type 'Promise<void>'.
      Type 'void | QueryResult' is not assignable to type 'void'.
        Type 'QueryResult' is not assignable to type 'void'.
    

    To fix this, I'm adding a Promise.resolve call as the last step, which doesn't feel quite right:

    db.transactionAsync(tx =>
      tx
        .executeAsync("insert into dogs (name) values (?)", ["Sam"])
        .then(res =>
          tx.executeAsync("insert into people (dog_id, name) values (?, ?)", [
            res.insertId,
            "Kirsten",
          ]),
        )
        .then(() => tx.executeAsync(selectAll, []))
        .then(() => Promise.resolve())                // <----- Added this
        .catch(e => console.log("ERROR", e)),
    )
    

    I wonder if the typings should be updated to return either Promise<QueryResult> or Promise<void>?

    opened by cmoel 11
  • Throw JSError React Native version independent

    Throw JSError React Native version independent

    Removes the version dependent JSError throwing as discussed in https://github.com/ospfranco/react-native-quick-sqlite/pull/83 because the interface changed with https://github.com/facebook/react-native/commit/0035cc9292aca15f07a9d2c51e3e340d5162d5e0. Tested on iOS with RN 0.67.4 and 0.70.0-rc.4 without errors.

    opened by VolkerLieber 11
  • Make it compatible with React Native 0.70

    Make it compatible with React Native 0.70

    throwJSError has been replaced by throwOrDie as per https://github.com/facebook/react-native/commit/0035cc9292aca15f07a9d2c51e3e340d5162d5e0

    This works, but it break backward compatibility with RN < 0.70. What would be the best way to provide backward compatibility as well?

    opened by andreibarabas 10
  • Testing Strategy Question

    Testing Strategy Question

    How do you typically test code that depends on react-native-quick-sqlite?

    Right now, we generally don't write tests near react-native-quick-sqlite or else we crudely stub the library.

    I'd like to improve our testing in this area, but I'm faced with either re-implementing quick-sqlite for node or maybe doing something with detox.

    opened by joshuanapoli 1
  • App crashes after writing multiple blobs

    App crashes after writing multiple blobs

    To reproduce:

    1. npx react-native init BlobRepro --template react-native-template-typescript && cd BlobRepro
    2. yarn add react-native-quick-sqlite && npx pod-install
    3. Add a function to write maby blobs, e.g.:
      const dbTest = () => {
        const db = open({name: 'test_data.sqlite'});
        const res = db.execute('CREATE TABLE TEST (data blob)')
        // console.log({res})
    
        const arr = [...Array(100).keys()];
        console.log({a: arr})
        arr.forEach(i => {
          const res2 = db.execute('INSERT INTO TEST (data) VALUES (?)', [new ArrayBuffer(8)])
          console.log({res2})
        });
    
        db.close()
      }
    
    1. yarn start --reset-cache , yarn ios
    2. Run the test code, e.g. via <Button title='dbTest' onPress={dbTest} />
    3. Observe app crashes:
    Screen Shot 2022-10-11 at 7 37 02 PM 7. Observe only some of the data is present in the sqlite database: Screen Shot 2022-10-11 at 7 39 04 PM
    opened by elliotsayes 14
Releases(4.0.8)
  • 4.0.8(Sep 29, 2022)

    You can now easily enable compile-time SQLite extensions by specifying compilation flags. Check out the README for more instructions on how to achieve this.

    Source code(tar.gz)
    Source code(zip)
  • 4.0.7(Sep 6, 2022)

  • 4.0.3(Aug 1, 2022)

    Starting 0.69 RN embeds AAR versions of certain dependencies, which forced changes on the build gradle to handle multiple .aar files. Which in turn caused to break the library for older versions. I modified the build.gradle script to make it work with older RN versions.

    Source code(tar.gz)
    Source code(zip)
  • 3.1.0(May 3, 2022)

    Transactions were internally supported via batchExecuteSql method, but now there is a new transaction method. It's more idiomatic and useful if you need to check intermediate results. It's only meant for sync callbacks, an async version will be implemented next.

    Source code(tar.gz)
    Source code(zip)
  • 3.0.4(Apr 15, 2022)

    Column metadata is now returned when performing select queries. Should help when the data has been coerced to basic types but the SQL field is different.

    Source code(tar.gz)
    Source code(zip)
  • 3.0.2(Mar 17, 2022)

    After a lot of work, we have finally managed to add async callbacks to the library! 🎉

    Thanks a lot to @EduFrazao whose help has been vital to getting this working! Also, to @sergeymild, who's repo showed us how to do async callbacks with the JSI.

    Changes

    • Methods now have async equivalents, if you don't want to block your UI while SQLite processes your data
    • SQLite has been bumped to version 3.38.1

    Please open an issue if you are facing any sort of bug, this was a major refactoring of the library.

    Source code(tar.gz)
    Source code(zip)
  • 3.0.0(Mar 5, 2022)

    Added a couple of new methods:

    • batch execute SQL
    • load and execute a SQL file

    Also a big refactoring was done, the methods no longer throw errors at all, everything returns a response object with a status field

    Source code(tar.gz)
    Source code(zip)
  • 2.0.2(Feb 24, 2022)

  • 1.0.5(Oct 15, 2021)

  • 1.0.0(Aug 4, 2021)

Owner
Oscar Franco
Full-Stack Freelance Dev
Oscar Franco
The fastest database-library on Android OS.

Android SQLite3 NDK 封装 Demo下载 (操作:按钮新增 按钮查询 点按编辑 长按删除) 写在前面 sqlite3 开源、集成简单(现在的版本只有2个文件 sqlite3.h sqlite3.c) 这个库抽离自 Telegram 的开源代码、作者:DrKLO 我个人感觉 Tele

水银灯、 2 Dec 27, 2021
A lightweight header-only C++11 library for quick and easy SQL querying with QtSql classes.

EasyQtSql EasyQtSql is a lightweight header-only C++11 library for quick and easy SQL querying with QtSql classes. Features: Header only C++11 library

null 53 Dec 30, 2022
❤️ SQLite ORM light header only library for modern C++

SQLite ORM SQLite ORM light header only library for modern C++ Status Branch Travis Appveyor master dev Advantages No raw string queries Intuitive syn

Yevgeniy Zakharov 1.7k Dec 30, 2022
SQLean: all the missing SQLite functions

SQLite has very few functions compared to other DBMS. SQLite authors see this as a feature rather than a bug, because SQLite has extension mechanism in place.

Anton Zhiyanov 2.1k Jan 8, 2023
An SQLite binding for node.js with built-in encryption, focused on simplicity and (async) performance

Description An SQLite (more accurately SQLite3MultipleCiphers) binding for node.js focused on simplicity and (async) performance. When dealing with en

mscdex 14 May 15, 2022
Yet another SQLite wrapper for Nim

Yet another SQLite wrapper for Nim Features: Design for ARC/ORC, you don’t need to close the connection manually Use importdb macro to create helper f

Code Hz 9 Jan 4, 2023
A friendly and lightweight C++ database library for MySQL, PostgreSQL, SQLite and ODBC.

QTL QTL is a C ++ library for accessing SQL databases and currently supports MySQL, SQLite, PostgreSQL and ODBC. QTL is a lightweight library that con

null 173 Dec 12, 2022
Fork of sqlite4java with updated SQLite and very basic compiler hardening enabled.

Download latest version: sqlite4java-392 with SQLite 3.8.7, Windows/Linux/Mac OS X/Android binaries OSGi bundle 1.0.392 with sqlite4java-392 Files for

GrapheneOS 6 Oct 26, 2022
An updated fork of sqlite_protobuf, a SQLite extension for extracting values from serialized Protobuf messages.

This fork of sqlite_protobuf fixes some issues (e.g., #15) and removes the test suite that we do not use. It also comes with proto_table, a C library

Backtrace Labs 18 Oct 19, 2022
Serverless SQLite database read from and write to Object Storage Service, run on FaaS platform.

serverless-sqlite Serverless SQLite database read from and write to Object Storage Service, run on FaaS platform. NOTES: This repository is still in t

老雷 7 May 12, 2022
Verneuil is a VFS extension for SQLite that asynchronously replicates databases to S3-compatible blob stores.

Verneuil: streaming replication for sqlite Verneuil1 [vɛʁnœj] is a VFS (OS abstraction layer) for sqlite that accesses local database files like the d

Backtrace Labs 307 Dec 21, 2022
C++ ORM for SQLite

Hiberlite ORM C++ object-relational mapping with API inspired by the awesome Boost.Serialization - that means almost no API to learn. Usage Just compi

Paul Korzhyk 651 Dec 28, 2022
The C++14 wrapper around sqlite library

sqlite modern cpp wrapper This library is a lightweight modern wrapper around sqlite C api . #include<iostream> #include <sqlite_modern_cpp.h> using n

null 720 Dec 29, 2022
Unofficial git mirror of SQLite sources (see link for build instructions)

SQLite Source Repository This repository contains the complete source code for the SQLite database engine. Some test scripts are also included. Howeve

null 2k Dec 25, 2022
A hook for Project Zomboid that intercepts files access for savegames and puts them in an SQLite DB instead.

ZomboidDB This project consists of a library and patcher that results in file calls for your savegame(s) being transparently intercepted and redirecte

Oliver 7 Aug 27, 2022
Lightweight C++ wrapper for SQLite

NLDatabase Lightweight C++ wrapper for SQLite. Requirements C++11 compiler SQLite 3 Usage Let's open a database file and read some rows: #include "NLD

Raven 0 Sep 20, 2019
Writing a sqlite clone from scratch in C++

如何用C++实现一个简易数据库 基于cstack/db_tutorial C语言版本 KCNyu 2022/2/2 作为笔者写的第一个系列型教程,还是选择基于前人的教程经验以及添加一些自己个人的探索。也许有很多纰漏之处,希望大家指正。 1. 数据库是什么? 数据库是“按照数据结构来组织、存储和管理数

shengyu.li 69 Dec 27, 2022
YugabyteDB is a high-performance, cloud-native distributed SQL database that aims to support all PostgreSQL features

YugabyteDB is a high-performance, cloud-native distributed SQL database that aims to support all PostgreSQL features. It is best to fit for cloud-native OLTP (i.e. real-time, business-critical) applications that need absolute data correctness and require at least one of the following: scalability, high tolerance to failures, or globally-distributed deployments.

yugabyte 7.4k Jan 7, 2023
pgagroal is a high-performance protocol-native connection pool for PostgreSQL.

pgagroal is a high-performance protocol-native connection pool for PostgreSQL.

Agroal 555 Dec 27, 2022