@dataql/react-native
Version:
DataQL React Native SDK with offline-first capabilities and clean API
64 lines (55 loc) • 1.73 kB
text/typescript
import { drizzle } from "drizzle-orm/expo-sqlite";
import { openDatabaseSync } from "expo-sqlite";
import { useMigrations } from "drizzle-orm/expo-sqlite/migrator";
import * as schema from "./schema";
import type { DataQLReactNativeConfig } from "../types";
export class DatabaseClient {
private db: ReturnType<typeof drizzle>;
private expoDb: any;
private config: DataQLReactNativeConfig;
constructor(config: DataQLReactNativeConfig) {
this.config = config;
// Provide default database name if not specified
const databaseName = config.databaseName || `dataql_${Date.now()}`;
this.expoDb = openDatabaseSync(databaseName, {
enableChangeListener: config.enableChangeListener ?? true,
});
this.db = drizzle(this.expoDb, { schema });
}
getDatabase() {
return this.db;
}
getExpoDatabase() {
return this.expoDb;
}
async initializeDatabase() {
try {
// Create tables if they don't exist
// This will be handled by migrations in production
if (this.config.debug) {
console.log("DataQL: Initializing database");
}
return true;
} catch (error) {
console.error("DataQL: Failed to initialize database:", error);
return false;
}
}
async close() {
try {
if (this.expoDb && this.expoDb.closeSync) {
this.expoDb.closeSync();
}
} catch (error) {
console.error("DataQL: Error closing database:", error);
}
}
}
// Hook for handling migrations - fix return type annotation
export function useDatabaseMigrations(
db: ReturnType<typeof drizzle>,
migrations: any
): ReturnType<typeof useMigrations> {
return useMigrations(db, migrations);
}
export default DatabaseClient;