原文: Announcing react-native-sqlite-2@3.0.1! - DEV Community 👩💻👨💻
InkdropというアプリをReact Nativeで作っていて、PouchDBを動かすためにWebSQL互換のライブラリが必要だったのでreact-native-sqlite-2を作りました。
なんで?
すでにreact-native-sqlite-storageというSQLiteを扱うためのライブラリが存在しますが、拙作の方には少しアドバンテージがあります:
-
React Native側の問題により、
\u0000
混じりの文字列が格納できない.- PouchDBがインデックス構築時にドキュメントIDにNull文字を多用するので、この問題の解決は重要です。
- PouchDBで添付ファイルを格納する動作が不安定: #6037.
本ライブラリはこれらの問題を解決します。
What's new in 3.x
Androidにとって大きな改善点があります!
より新しいSQLite3をAndroidで
最新のAndroid OSのバージョンであっても、標準で搭載されているSQLiteのバージョンはいくつか古いものです。
iOSの方が新しいものが使えるのに。
React Native SQLite 2はこのアップデートによってsqlite-androidを使うようになり、SQLiteの新機能が使えるようになりました:
これでiOSでは出来たのにAndroidでは実装できないという悩みが減ります。
自分はFTS5が使いたかった。これはビルドフラグが単純に付いてないだけだったけど。
以降は使い方です。
Getting started
Add react-native-sqlite-2 to your dependencies:
$ npm install react-native-sqlite-2 --save
Link native dependencies
From react-native 0.60 autolinking will take care of the link step but don't forget to run pod install
.
$ react-native link react-native-sqlite-2
iOS
If using cocoapods in the ios/
directory run
$ pod install
Android
Please make sure AndroidX is enabled in your project by editting android/gradle.properties
and adding 2 lines:
android.useAndroidX=true
android.enableJetifier=true
Usage
import SQLite from "react-native-sqlite-2";
const db = SQLite.openDatabase("test.db", "1.0", "", 1);
db.transaction(function(txn) {
txn.executeSql("DROP TABLE IF EXISTS Users", []);
txn.executeSql(
"CREATE TABLE IF NOT EXISTS Users(user_id INTEGER PRIMARY KEY NOT NULL, name VARCHAR(30))",
[]
);
txn.executeSql("INSERT INTO Users (name) VALUES (:name)", ["nora"]);
txn.executeSql("INSERT INTO Users (name) VALUES (:name)", ["takuya"]);
txn.executeSql("SELECT * FROM `users`", [], function(tx, res) {
for (let i = 0; i < res.rows.length; ++i) {
console.log("item:", res.rows.item(i));
}
});
});
There is a test app in the test directory.
Using with PouchDB
It can be used with pouchdb-adapter-react-native-sqlite.
import PouchDB from "pouchdb-react-native";
import SQLite from "react-native-sqlite-2";
import SQLiteAdapterFactory from "pouchdb-adapter-react-native-sqlite";
const SQLiteAdapter = SQLiteAdapterFactory(SQLite);
PouchDB.plugin(SQLiteAdapter);
var db = new PouchDB("mydb", { adapter: "react-native-sqlite" });
Further informations
- GitHub repos: https://github.com/craftzdog/react-native-sqlite-2
- Inkdrop - Markdown note-taking app: https://inkdrop.app/
- Twitter: https://twitter.com/craftzdog