-
Notifications
You must be signed in to change notification settings - Fork 11
Sqlite Prototype #43
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Sqlite Prototype #43
Changes from all commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
4c54552
Prototype for impl with sqlite3_web package
simolus3 872f1f6
Merge remote-tracking branch 'upstream/alpha-web-prerelease' into web…
simolus3 e5e2d04
Support locks in shared worker
simolus3 d063f94
Implement autocommit
simolus3 ba23fb9
Fix more web tests
simolus3 d2779df
update items
stevensJourney a05478a
add note for broken close call
stevensJourney f9fbb8c
update dart sdk for test
stevensJourney 102cdeb
update from alpha branch
stevensJourney 3b16668
update sqlite_web package
stevensJourney 99432d2
js dev dependency. remove web locks
stevensJourney 48f1241
add export for sqlite3_web
stevensJourney 295c58b
added test for deleting of data on close
stevensJourney decb557
update sqlite3_web package
stevensJourney 1116795
update from master
stevensJourney 3b5bdfc
use getSourceTables test for both web and native
stevensJourney c47b324
use defined testUtils for generateSourceTableTests
stevensJourney 562deaa
comment
stevensJourney ce5cef0
merge in latest changes
stevensJourney 94b7b95
fix late initialization error
stevensJourney 3dc27b7
export wasm
stevensJourney 1032954
Custom requests for executing in transactions (#46)
mugikhan b77b55a
added comments
stevensJourney File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
# Developing Instructions | ||
|
||
## Testing | ||
|
||
Running tests for the `web` platform requires some preparation to be executed. The `sqlite3.wasm` and `db_worker.js` files need to be available in the Git ignored `./assets` folder. | ||
|
||
See the [test action](./.github/workflows/test.yaml) for the latest steps. | ||
|
||
On your local machine run the commands from the `Install SQLite`, `Compile WebWorker` and `Run Tests` steps. |
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
/// Re-exports [sqlite3 WASM](https://pub.dev/packages/sqlite3) to expose sqlite3 without | ||
/// adding it as a direct dependency. | ||
library; | ||
|
||
export 'package:sqlite3/wasm.dart'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
/// Re-exports [sqlite3_web](https://pub.dev/packages/sqlite3_web) to expose sqlite3_web without | ||
/// adding it as a direct dependency. | ||
library; | ||
|
||
export 'package:sqlite3_web/sqlite3_web.dart'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
// Items required for extending custom web workers | ||
export './src/web/worker/worker_utils.dart'; | ||
export './src/web/protocol.dart'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,282 @@ | ||
import 'dart:async'; | ||
import 'dart:js_interop'; | ||
|
||
import 'package:sqlite3/common.dart'; | ||
import 'package:sqlite3_web/sqlite3_web.dart'; | ||
import 'package:sqlite_async/mutex.dart'; | ||
import 'package:sqlite_async/sqlite_async.dart'; | ||
import 'package:sqlite_async/src/common/sqlite_database.dart'; | ||
import 'package:sqlite_async/src/sqlite_connection.dart'; | ||
import 'package:sqlite_async/src/sqlite_queries.dart'; | ||
import 'package:sqlite_async/src/update_notification.dart'; | ||
import 'package:sqlite_async/src/utils/shared_utils.dart'; | ||
import 'protocol.dart'; | ||
|
||
class WebDatabase | ||
with SqliteQueries, SqliteDatabaseMixin | ||
implements SqliteDatabase { | ||
final Database _database; | ||
final Mutex? _mutex; | ||
|
||
@override | ||
bool closed = false; | ||
|
||
WebDatabase(this._database, this._mutex); | ||
|
||
@override | ||
Future<void> close() async { | ||
await _database.dispose(); | ||
closed = true; | ||
} | ||
|
||
@override | ||
Future<bool> getAutoCommit() async { | ||
final response = await _database.customRequest( | ||
CustomDatabaseMessage(CustomDatabaseMessageKind.getAutoCommit)); | ||
return (response as JSBoolean?)?.toDart ?? false; | ||
} | ||
|
||
@override | ||
Future<void> initialize() { | ||
return Future.value(); | ||
} | ||
|
||
@override | ||
Future<void> get isInitialized => initialize(); | ||
|
||
@override | ||
|
||
/// Not relevant for web. | ||
Never isolateConnectionFactory() { | ||
throw UnimplementedError(); | ||
} | ||
|
||
@override | ||
|
||
/// Not supported on web. There is only 1 connection. | ||
int get maxReaders => throw UnimplementedError(); | ||
|
||
@override | ||
|
||
/// Not relevant for web. | ||
Never get openFactory => throw UnimplementedError(); | ||
|
||
@override | ||
Future<T> readLock<T>(Future<T> Function(SqliteReadContext tx) callback, | ||
{Duration? lockTimeout, String? debugContext}) async { | ||
if (_mutex case var mutex?) { | ||
return await mutex.lock(() async { | ||
final context = _SharedContext(this); | ||
try { | ||
return await callback(context); | ||
} finally { | ||
context.markClosed(); | ||
} | ||
}); | ||
} else { | ||
// No custom mutex, coordinate locks through shared worker. | ||
await _database.customRequest( | ||
CustomDatabaseMessage(CustomDatabaseMessageKind.requestSharedLock)); | ||
|
||
try { | ||
return await callback(_SharedContext(this)); | ||
} finally { | ||
await _database.customRequest( | ||
CustomDatabaseMessage(CustomDatabaseMessageKind.releaseLock)); | ||
} | ||
} | ||
} | ||
|
||
@override | ||
Stream<UpdateNotification> get updates => | ||
_database.updates.map((event) => UpdateNotification({event.tableName})); | ||
|
||
@override | ||
Future<T> writeTransaction<T>( | ||
Future<T> Function(SqliteWriteContext tx) callback, | ||
{Duration? lockTimeout}) { | ||
return writeLock( | ||
(writeContext) => | ||
internalWriteTransaction(writeContext, (context) async { | ||
// All execute calls done in the callback will be checked for the | ||
// autocommit state | ||
return callback(_ExclusiveTransactionContext(this, writeContext)); | ||
}), | ||
debugContext: 'writeTransaction()', | ||
lockTimeout: lockTimeout); | ||
} | ||
|
||
@override | ||
|
||
/// Internal writeLock which intercepts transaction context's to verify auto commit is not active | ||
Future<T> writeLock<T>(Future<T> Function(SqliteWriteContext tx) callback, | ||
{Duration? lockTimeout, String? debugContext}) async { | ||
if (_mutex case var mutex?) { | ||
return await mutex.lock(() async { | ||
final context = _ExclusiveContext(this); | ||
try { | ||
return await callback(context); | ||
} finally { | ||
context.markClosed(); | ||
} | ||
}); | ||
} else { | ||
// No custom mutex, coordinate locks through shared worker. | ||
await _database.customRequest(CustomDatabaseMessage( | ||
CustomDatabaseMessageKind.requestExclusiveLock)); | ||
final context = _ExclusiveContext(this); | ||
try { | ||
return await callback(context); | ||
} finally { | ||
context.markClosed(); | ||
await _database.customRequest( | ||
CustomDatabaseMessage(CustomDatabaseMessageKind.releaseLock)); | ||
} | ||
} | ||
} | ||
} | ||
|
||
class _SharedContext implements SqliteReadContext { | ||
final WebDatabase _database; | ||
bool _contextClosed = false; | ||
|
||
_SharedContext(this._database); | ||
|
||
@override | ||
bool get closed => _contextClosed || _database.closed; | ||
|
||
@override | ||
Future<T> computeWithDatabase<T>( | ||
Future<T> Function(CommonDatabase db) compute) { | ||
// Can't be implemented: The database may live on another worker. | ||
throw UnimplementedError(); | ||
} | ||
|
||
@override | ||
Future<Row> get(String sql, [List<Object?> parameters = const []]) async { | ||
final results = await getAll(sql, parameters); | ||
return results.single; | ||
} | ||
|
||
@override | ||
Future<ResultSet> getAll(String sql, | ||
[List<Object?> parameters = const []]) async { | ||
return await wrapSqliteException( | ||
() => _database._database.select(sql, parameters)); | ||
} | ||
|
||
@override | ||
Future<bool> getAutoCommit() async { | ||
return _database.getAutoCommit(); | ||
} | ||
|
||
@override | ||
Future<Row?> getOptional(String sql, | ||
[List<Object?> parameters = const []]) async { | ||
final results = await getAll(sql, parameters); | ||
return results.singleOrNull; | ||
} | ||
|
||
void markClosed() { | ||
_contextClosed = true; | ||
} | ||
} | ||
|
||
class _ExclusiveContext extends _SharedContext implements SqliteWriteContext { | ||
_ExclusiveContext(super.database); | ||
|
||
@override | ||
Future<ResultSet> execute(String sql, | ||
[List<Object?> parameters = const []]) async { | ||
return wrapSqliteException( | ||
() => _database._database.select(sql, parameters)); | ||
} | ||
|
||
@override | ||
Future<void> executeBatch( | ||
String sql, List<List<Object?>> parameterSets) async { | ||
return wrapSqliteException(() async { | ||
for (final set in parameterSets) { | ||
mugikhan marked this conversation as resolved.
Show resolved
Hide resolved
|
||
// use execute instead of select to avoid transferring rows from the | ||
// worker to this context. | ||
await _database._database.execute(sql, set); | ||
} | ||
}); | ||
} | ||
} | ||
|
||
class _ExclusiveTransactionContext extends _ExclusiveContext { | ||
SqliteWriteContext baseContext; | ||
_ExclusiveTransactionContext(super.database, this.baseContext); | ||
|
||
@override | ||
bool get closed => baseContext.closed; | ||
|
||
@override | ||
Future<ResultSet> execute(String sql, | ||
[List<Object?> parameters = const []]) async { | ||
// Operations inside transactions are executed with custom requests | ||
// in order to verify that the connection does not have autocommit enabled. | ||
// The worker will check if autocommit = true before executing the SQL. | ||
// An exception will be thrown if autocommit is enabled. | ||
// The custom request which does the above will return the ResultSet as a formatted | ||
// JavaScript object. This is the converted into a Dart ResultSet. | ||
return await wrapSqliteException(() async { | ||
var res = await _database._database.customRequest(CustomDatabaseMessage( | ||
CustomDatabaseMessageKind.executeInTransaction, sql, parameters)); | ||
var result = | ||
Map<String, dynamic>.from((res as JSObject).dartify() as Map); | ||
final columnNames = [ | ||
for (final entry in result['columnNames']) entry as String | ||
]; | ||
final rawTableNames = result['tableNames']; | ||
final tableNames = rawTableNames != null | ||
? [ | ||
for (final entry in (rawTableNames as List<Object?>)) | ||
entry as String | ||
] | ||
: null; | ||
|
||
final rows = <List<Object?>>[]; | ||
for (final row in (result['rows'] as List<Object?>)) { | ||
final dartRow = <Object?>[]; | ||
|
||
for (final column in (row as List<Object?>)) { | ||
dartRow.add(column); | ||
} | ||
|
||
rows.add(dartRow); | ||
} | ||
final resultSet = ResultSet(columnNames, tableNames, rows); | ||
return resultSet; | ||
}); | ||
} | ||
|
||
@override | ||
Future<void> executeBatch( | ||
String sql, List<List<Object?>> parameterSets) async { | ||
return await wrapSqliteException(() async { | ||
for (final set in parameterSets) { | ||
await _database._database.customRequest(CustomDatabaseMessage( | ||
CustomDatabaseMessageKind.executeBatchInTransaction, sql, set)); | ||
} | ||
return; | ||
}); | ||
} | ||
} | ||
|
||
/// Throws SqliteException if the Remote Exception is a SqliteException | ||
Future<T> wrapSqliteException<T>(Future<T> Function() callback) async { | ||
try { | ||
return await callback(); | ||
} on RemoteException catch (ex) { | ||
if (ex.toString().contains('SqliteException')) { | ||
RegExp regExp = RegExp(r'SqliteException\((\d+)\)'); | ||
// Drift wraps these in remote errors | ||
throw SqliteException( | ||
int.parse(regExp.firstMatch(ex.message)?.group(1) ?? '0'), | ||
ex.message); | ||
} | ||
rethrow; | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.