All Projects → ospfranco → react-native-quick-sqlite

ospfranco / react-native-quick-sqlite

Licence: MIT License
Fast SQLite for react-native.

Programming Languages

c
50402 projects - #5 most used programming language
C++
36643 projects - #6 most used programming language
typescript
32286 projects
java
68154 projects - #9 most used programming language
CMake
9771 projects
objective c
16641 projects - #2 most used programming language

Projects that are alternatives of or similar to react-native-quick-sqlite

Android dbinspector
Android library for viewing and sharing in app databases.
Stars: ✭ 881 (+268.62%)
Mutual labels:  sqlite, db, sqlite3
Choochoo
Training Diary
Stars: ✭ 186 (-22.18%)
Mutual labels:  sqlite, sqlite3
Sqlittle
Pure Go SQLite file reader
Stars: ✭ 171 (-28.45%)
Mutual labels:  sqlite, sqlite3
React Native Sqlite 2
SQLite3 Native Plugin for React Native for iOS, Android, Windows and macOS.
Stars: ✭ 217 (-9.21%)
Mutual labels:  sqlite, sqlite3
Esp32 arduino sqlite3 lib
Sqlite3 Arduino library for ESP32
Stars: ✭ 167 (-30.13%)
Mutual labels:  sqlite, sqlite3
Sqlite Parquet Vtable
A SQLite vtable extension to read Parquet files
Stars: ✭ 167 (-30.13%)
Mutual labels:  sqlite, sqlite3
Better Sqlite3
The fastest and simplest library for SQLite3 in Node.js.
Stars: ✭ 2,778 (+1062.34%)
Mutual labels:  sqlite, sqlite3
Genomicsqlite
Genomics Extension for SQLite
Stars: ✭ 90 (-62.34%)
Mutual labels:  sqlite, sqlite3
Sqleet
SQLite3 encryption that sucks less
Stars: ✭ 244 (+2.09%)
Mutual labels:  sqlite, sqlite3
Mikro Orm
TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL and SQLite databases.
Stars: ✭ 3,874 (+1520.92%)
Mutual labels:  sqlite, sqlite3
sqllex
The most pythonic ORM (for SQLite and PostgreSQL). Seriously, try it out!
Stars: ✭ 80 (-66.53%)
Mutual labels:  db, sqlite3
Myutils
🙏 提供时间轴转星座|生肖工具、系统存储空间获取工具、文件大小格式化工具、获取指定文件大小工具、AES加密解码工具(支持android端平台加密解密,java端和android端相互加密解密)、SharePreference操作工具、 File文件操作工具、日期获取和计算工具、界面跳转Intent操作工具、字符串验证和数值转换操作工具、手机震动工具、系统资源操作工具、网络检测工具、 wifi操作工具、单位换算工具、zip压缩和解压操作工具、XML解析操作工具(只支持几种指定格式)、图片加载和处理工具,数据库操作(增删改查)工具、Base64编码解码工具、MD5加密工具。
Stars: ✭ 130 (-45.61%)
Mutual labels:  sqlite, db
Sqhell.vim
An SQL wrapper for vim
Stars: ✭ 113 (-52.72%)
Mutual labels:  sqlite, sqlite3
Rom Sql
SQL support for rom-rb
Stars: ✭ 169 (-29.29%)
Mutual labels:  sqlite, sqlite3
Sqlite3 Encryption
The easiest way to build SQLite3 with encryption support on Windows. Compilation of DLL, SLL or shell is now a matter of minutes
Stars: ✭ 102 (-57.32%)
Mutual labels:  sqlite, sqlite3
Pydbgen
Random dataframe and database table generator
Stars: ✭ 191 (-20.08%)
Mutual labels:  sqlite, sqlite3
go-sqlite
Low-level Go interface to SQLite 3
Stars: ✭ 268 (+12.13%)
Mutual labels:  sqlite, sqlite3
Electron With Sqlite3
Sample application for ElectronJS working with Sqlite3
Stars: ✭ 83 (-65.27%)
Mutual labels:  sqlite, sqlite3
Electrocrud
Database CRUD Application Built on Electron | MySQL, Postgres, SQLite
Stars: ✭ 1,267 (+430.13%)
Mutual labels:  sqlite, sqlite3
Db
Data access layer for PostgreSQL, CockroachDB, MySQL, SQLite and MongoDB with ORM-like features.
Stars: ✭ 2,832 (+1084.94%)
Mutual labels:  sqlite, db

screenshot

With TypeORM

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

Low level bindings only

    yarn add react-native-quick-sqlite
    npx pod-install


Quick SQLite embeds the latest version of SQLite and provides a low-level API to execute SQL queries, uses fast bindings via JSI. By using an embedded SQLite you get access the latest security patches and latest features.

Inspired/compatible with react-native-sqlite-storage and react-native-sqlite2.

Gotchas

  • Javascript cannot represent integers larger than 53 bits, be careful when loading data if it came from other systems. Read more.
  • It's not possible to use a browser to debug a JSI app, use Flipper (for android Flipper also has SQLite Database explorer).
  • Your app will now include C++, you will need to install the NDK on your machine for android.

API

interface QueryResult {
  status?: 0 | 1; // 0 for correct execution
  insertId?: number;
  rowsAffected: number;
  message?: string;
  rows?: {
    /** Raw array with all dataset */
    _array: any[];
    /** The length of the dataset */
    length: number;
  };
  /**
   * Query metadata, available only for select query results
   */
  metadata?: ColumnMetadata[];
}

/**
 * Column metadata
 * Describes some information about columns fetched by the query
 * columnDeclaredType - declared column type for this column, when fetched directly from a table or a View resulting from a table column. "UNKNOWN" for dynamic values, like function returned ones.
 */
interface ColumnMetadata = {
  columnName: string;
  columnDeclaredType: string;
  columnIndex: number;
};

interface BatchQueryResult {
  status?: 0 | 1;
  rowsAffected?: number;
  message?: string;
}

interface ISQLite {
  open: (dbName: string, location?: string) => { status: 0 | 1 };
  close: (dbName: string) => { status: 0 | 1 };
  executeSql: (
    dbName: string,
    query: string,
    params: any[] | undefined
  ) => QueryResult;
  asyncExecuteSql: (
    dbName: string,
    query: string,
    params: any[] | undefined,
    cb: (res: QueryResult) => void
  ) => void;
  executeSqlBatch: (
    dbName: string,
    commands: SQLBatchParams[]
  ) => BatchQueryResult;
  asyncExecuteSqlBatch: (
    dbName: string,
    commands: SQLBatchParams[],
    cb: (res: BatchQueryResult) => void
  ) => void;
  loadSqlFile: (dbName: string, location: string) => FileLoadResult;
  asyncLoadSqlFile: (
    dbName: string,
    location: string,
    cb: (res: FileLoadResult) => void
  ) => void;
}

Usage

Import as early as possible, auto-installs bindings in a thread-safe manner.

// Thanks to @mrousavy for this installation method, see one example: https://github.com/mrousavy/react-native-mmkv/blob/75b425db530e26cf10c7054308583d03ff01851f/src/createMMKV.ts#L56
import 'react-native-quick-sqlite';

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

// status === 1, operation failed
if (dbOpenResult.status) {
  console.error('Database could not be opened');
}

Simple queries

The basic query is synchronous, it will block rendering on large operations, below there are async versions.

let { status, rows } = sqlite.executeSql(
  'myDatabase',
  'SELECT somevalue FROM sometable'
);
if (!status) {
  rows.forEach((row) => {
    console.log(row);
  });
}

let { status, rowsAffected } = sqlite.executeSql(
  'myDatabase',
  'UPDATE sometable SET somecolumn = ? where somekey = ?',
  [0, 1]
);
if (!status) {
  console.log(`Update affected ${rowsAffected} rows`);
}

Transactions

Transactions are supported. However, due to the library being opinionated and mostly not throwing errors you need to return a boolean (true for correct execution, false for incorrect execution) to either commit or rollback the transaction.

JSI bindings are fast but there is still some overhead calling executeSql for single queries, if you want to execute a large set of commands as fast as possible you should use the executeSqlBatch method below, it still uses transactions, but only transmits data between JS and native once.

sqlite.transaction('myDatabase', (tx) => {
  const {
    status,
  } = tx.executeSql('UPDATE sometable SET somecolumn = ? where somekey = ?', [
    0,
    1,
  ]);

  if (status) {
    return false;
  }

  return true;
});

Batch operation

Batch execution allows transactional execution of a set of commands

const commands = [
  ['CREATE TABLE TEST (id integer)'],
  ['INSERT INTO TABLE TEST (id) VALUES (?)', [1]][
    ('INSERT INTO TABLE TEST (id) VALUES (?)', [2])
  ][('INSERT INTO TABLE TEST (id) VALUES (?)', [[3], [4], [5], [6]])],
];
const result = sqlite.executeSqlBatch('myDatabase', commands);
if (!result.status) {
  // result.status undefined or 0 === success
  console.log(`Batch affected ${result.rowsAffected} rows`);
}

Dynamic Column Metadata

In some scenarios, dynamic applications may need to get some metadata information about the returned result set.

This can be done testing the returned data directly, but in some cases may not be enough, for example when data is stored outside sqlite datatypes. When fetching data directly from tables or views linked to table columns, SQLite is able to identify the table declared types:

let { status, metadata } = sqlite.executeSql(
  'myDatabase',
  'SELECT int_column_1, bol_column_2 FROM sometable'
);
if (!status) {
  metadata.forEach((column) => {
    // Output:
    // int_column_1 - INTEGER
    // bol_column_2 - BOOLEAN
    console.log(`${column.columnName} - ${column.columnDeclaredType}`);
  });
}

Async operations

You might have too much SQL to process and it will cause your application to freeze. There are async versions for some of the operations. This will offload the SQLite processing to a different thread.

sqlite.asyncExecuteSql(
  'myDatabase',
  'SELECT * FROM "User";',
  [],
  ({ status, rows }) => {
    if (status === 0) {
      console.log('users', rows);
    }
  }
);

Use TypeORM

This package offers a low-level API to raw execute SQL queries. I strongly recommend 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.

Follow the instructions to make TypeORM work with React Native (enable decorators, configure babel, etc), then apply the example patch via patch-package.

More

If you want to learn how to make your own JSI module buy my JSI/C++ Cheatsheet, I'm also available for freelance work!

License

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].