Document how to existing databases on web

This commit is contained in:
Simon Binder 2024-01-30 22:48:04 +01:00
parent 3e894f9502
commit b58e97f99c
No known key found for this signature in database
GPG Key ID: 7891917E4147B8C0
3 changed files with 42 additions and 0 deletions

View File

@ -1,6 +1,7 @@
import 'package:drift/drift.dart';
import 'package:drift/wasm.dart';
import 'package:drift/web.dart';
import 'package:drift_docs/src/external_apis.dart';
import 'package:sqlite3/wasm.dart';
typedef _$MyWebDatabase = GeneratedDatabase;
@ -44,6 +45,25 @@ class MyWebDatabase extends _$MyWebDatabase {
}
// #enddocregion connect
DatabaseConnection connectWithExisting() {
// #docregion existing
return DatabaseConnection.delayed(Future(() async {
final result = await WasmDatabase.open(
databaseName: 'my_app_db', // prefer to only use valid identifiers here
sqlite3Uri: Uri.parse('sqlite3.wasm'),
driftWorkerUri: Uri.parse('drift_worker.dart.js'),
initializeDatabase: () async {
final data = await rootBundle.load('my_database');
return data.buffer.asUint8List();
},
);
// ...
return result.resolvedExecutor;
}));
// #enddocregion existing
}
// #docregion migrate-wasm
// If you've previously opened your database like this
Future<WasmDatabase> customDatabase() async {

View File

@ -0,0 +1,10 @@
// Stubs for external APIs we want to reference in Snippets without being able
// to depend on them.
import 'dart:typed_data';
abstract class AssetBundle {
Future<ByteData> load(String key);
}
AssetBundle get rootBundle => throw 'stub';

View File

@ -217,6 +217,18 @@ export 'unsupported.dart'
A ready example of this construct can also be found [here](https://github.com/simolus3/drift/blob/develop/examples/app/lib/database/connection/connection.dart).
## Using existing databases
You can use existing database with Drift on the web by importing the `initializeDatabase`
function on `WasmDatabase.open`.
This function will be called when attempting to open a database that doesn't exist yet,
allowing the initial sqlite3 file to be provided instead:
{% include "blocks/snippet" snippets = snippets name = "existing" %}
Please be aware that this only works for the default journal mode, WAL is not supported
on the web and WAL databases can't be imported with `initializeDatabase` either.
## Examples
The drift repository contains a two small web applications using drift on the web: