59 lines
1.5 KiB
Dart
59 lines
1.5 KiB
Dart
import 'dart:ffi';
|
|
import 'dart:io';
|
|
|
|
import 'package:jadb/search.dart';
|
|
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
|
import 'package:sqlite3/open.dart';
|
|
|
|
Future<Database> openLocalDb({
|
|
String? libsqlitePath,
|
|
String? jadbPath,
|
|
bool readWrite = false,
|
|
bool verifyTablesExist = true,
|
|
bool walMode = false,
|
|
}) async {
|
|
libsqlitePath ??= Platform.environment['LIBSQLITE_PATH'];
|
|
jadbPath ??= Platform.environment['JADB_PATH'];
|
|
jadbPath ??= Directory.current.uri.resolve('jadb.sqlite').path;
|
|
|
|
libsqlitePath = (libsqlitePath == null)
|
|
? null
|
|
: File(libsqlitePath).resolveSymbolicLinksSync();
|
|
jadbPath = File(jadbPath).resolveSymbolicLinksSync();
|
|
|
|
if (libsqlitePath == null) {
|
|
throw Exception('LIBSQLITE_PATH is not set');
|
|
}
|
|
|
|
if (!File(libsqlitePath).existsSync()) {
|
|
throw Exception('LIBSQLITE_PATH does not exist: $libsqlitePath');
|
|
}
|
|
|
|
if (!File(jadbPath).existsSync()) {
|
|
throw Exception('JADB_PATH does not exist: $jadbPath');
|
|
}
|
|
|
|
final db =
|
|
await createDatabaseFactoryFfi(
|
|
ffiInit: () =>
|
|
open.overrideForAll(() => DynamicLibrary.open(libsqlitePath!)),
|
|
).openDatabase(
|
|
jadbPath,
|
|
options: OpenDatabaseOptions(
|
|
onConfigure: (db) async {
|
|
if (walMode) {
|
|
await db.execute('PRAGMA journal_mode = WAL');
|
|
}
|
|
await db.execute('PRAGMA foreign_keys = ON');
|
|
},
|
|
readOnly: !readWrite,
|
|
),
|
|
);
|
|
|
|
if (verifyTablesExist) {
|
|
await db.jadbVerifyTables();
|
|
}
|
|
|
|
return db;
|
|
}
|