Setting up Sqlite in an expo application
To get started with sqlite install the module using the following command:
shell
npx expo install expo-sqlite
Ensure the native module is installed properly by running the following command:
shell
yarn ios yarn android
Lets install Drizzle and drizzle studio for accessing and editing data in our sqlite tables
shell
yarn add drizzle-orm yarn add -D drizzle-kit npx expo install expo-drizzle-studio-plugin
For the app to properly work, Expo requires SQL migrations bundled. Drizzle kit can help with generating those migrations.
To get started with migrations:
shell
yarn add babel-plugin-inline-import
Update babel.config.js
typescript
module.exports = function(api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
plugins: [["inline-import", { "extensions": [".sql"] }]]
};
};
Update metro.config.js
typescript
const { getDefaultConfig } = require('expo/metro-config');
/** @type {import('expo/metro-config').MetroConfig} */
const config = getDefaultConfig(__dirname);
config.resolver.sourceExts.push('sql');
module.exports = config;
Create a new file in the root of the project folder
shell
touch drizzle.config.ts
Add following to drizzle config file created
typescript
import type { Config } from 'drizzle-kit';
export default {
schema: './db/schema.ts',
out: './drizzle',
dialect: 'sqlite',
driver: 'expo',
} satisfies Config;
To generate migrations run
shell
npx drizzle-kit generate
Finally add migrations to app
typescript
import {openDatabaseSync} from "expo-sqlite/next";
import {drizzle} from "drizzle-orm/expo-sqlite/";
import {useDrizzleStudio} from "expo-drizzle-studio-plugin";
import {useMigrations} from "drizzle-orm/expo-sqlite/migrator";
import migrations from "../../drizzle/migrations";
const useDb = () => {
const expo = openDatabaseSync("mySQLiteDB.db");
const db = drizzle(expo);
useDrizzleStudio(expo);
useMigrations(db, migrations);
return {
db,
}
}
export {
useDb,
}
Drizzle Studio displaying tables and its data