Skip to content

Commit

Permalink
Document how to existing databases on web
Browse files Browse the repository at this point in the history
  • Loading branch information
simolus3 committed Jan 30, 2024
1 parent 3e894f9 commit b58e97f
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
20 changes: 20 additions & 0 deletions docs/lib/snippets/platforms/web.dart
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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 {
Expand Down
10 changes: 10 additions & 0 deletions docs/lib/src/external_apis.dart
Original file line number Diff line number Diff line change
@@ -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';
12 changes: 12 additions & 0 deletions docs/pages/docs/Platforms/web.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down

0 comments on commit b58e97f

Please sign in to comment.