|
| 1 | +import 'package:sqlite3/common.dart'; |
| 2 | +import 'package:sqlite_async/sqlite_async.dart'; |
| 3 | + |
| 4 | +/// A database implementation that delegates everything to a single connection. |
| 5 | +/// |
| 6 | +/// This doesn't provide an automatic connection pool or the web worker |
| 7 | +/// management, but it can still be useful in cases like unit tests where those |
| 8 | +/// features might not be necessary. Since only a single sqlite connection is |
| 9 | +/// used internally, this also allows using in-memory databases. |
| 10 | +final class SingleConnectionDatabase |
| 11 | + with SqliteQueries, SqliteDatabaseMixin |
| 12 | + implements SqliteDatabase { |
| 13 | + final SqliteConnection connection; |
| 14 | + |
| 15 | + SingleConnectionDatabase(this.connection); |
| 16 | + |
| 17 | + @override |
| 18 | + Future<void> close() => connection.close(); |
| 19 | + |
| 20 | + @override |
| 21 | + bool get closed => connection.closed; |
| 22 | + |
| 23 | + @override |
| 24 | + Future<bool> getAutoCommit() => connection.getAutoCommit(); |
| 25 | + |
| 26 | + @override |
| 27 | + Future<void> get isInitialized => Future.value(); |
| 28 | + |
| 29 | + @override |
| 30 | + IsolateConnectionFactory<CommonDatabase> isolateConnectionFactory() { |
| 31 | + throw UnsupportedError( |
| 32 | + "SqliteDatabase.singleConnection instances can't be used across " |
| 33 | + 'isolates.'); |
| 34 | + } |
| 35 | + |
| 36 | + @override |
| 37 | + int get maxReaders => 1; |
| 38 | + |
| 39 | + @override |
| 40 | + AbstractDefaultSqliteOpenFactory<CommonDatabase> get openFactory => |
| 41 | + throw UnimplementedError(); |
| 42 | + |
| 43 | + @override |
| 44 | + Future<T> readLock<T>(Future<T> Function(SqliteReadContext tx) callback, |
| 45 | + {Duration? lockTimeout, String? debugContext}) { |
| 46 | + return connection.readLock(callback, |
| 47 | + lockTimeout: lockTimeout, debugContext: debugContext); |
| 48 | + } |
| 49 | + |
| 50 | + @override |
| 51 | + Stream<UpdateNotification> get updates => |
| 52 | + connection.updates ?? const Stream.empty(); |
| 53 | + |
| 54 | + @override |
| 55 | + Future<T> writeLock<T>(Future<T> Function(SqliteWriteContext tx) callback, |
| 56 | + {Duration? lockTimeout, String? debugContext}) { |
| 57 | + return connection.writeLock(callback, |
| 58 | + lockTimeout: lockTimeout, debugContext: debugContext); |
| 59 | + } |
| 60 | +} |
0 commit comments