| 
 | 1 | +import 'dart:async';  | 
 | 2 | + | 
 | 3 | +import 'package:sqlite_async/sqlite3_common.dart';  | 
 | 4 | + | 
 | 5 | +/// Wrap a CommonDatabase to throttle its updates stream.  | 
 | 6 | +/// This is so that we can throttle the updates _within_  | 
 | 7 | +/// the worker process, avoiding mass notifications over  | 
 | 8 | +/// the MessagePort.  | 
 | 9 | +class ThrottledCommonDatabase extends CommonDatabase {  | 
 | 10 | +  final CommonDatabase _db;  | 
 | 11 | +  final StreamController<bool> _transactionController =  | 
 | 12 | +      StreamController.broadcast();  | 
 | 13 | + | 
 | 14 | +  ThrottledCommonDatabase(this._db);  | 
 | 15 | + | 
 | 16 | +  @override  | 
 | 17 | +  int get userVersion => _db.userVersion;  | 
 | 18 | + | 
 | 19 | +  @override  | 
 | 20 | +  set userVersion(int userVersion) {  | 
 | 21 | +    _db.userVersion = userVersion;  | 
 | 22 | +  }  | 
 | 23 | + | 
 | 24 | +  @override  | 
 | 25 | +  bool get autocommit => _db.autocommit;  | 
 | 26 | + | 
 | 27 | +  @override  | 
 | 28 | +  DatabaseConfig get config => _db.config;  | 
 | 29 | + | 
 | 30 | +  @override  | 
 | 31 | +  void createAggregateFunction<V>(  | 
 | 32 | +      {required String functionName,  | 
 | 33 | +      required AggregateFunction<V> function,  | 
 | 34 | +      AllowedArgumentCount argumentCount = const AllowedArgumentCount.any(),  | 
 | 35 | +      bool deterministic = false,  | 
 | 36 | +      bool directOnly = true}) {  | 
 | 37 | +    _db.createAggregateFunction(functionName: functionName, function: function);  | 
 | 38 | +  }  | 
 | 39 | + | 
 | 40 | +  @override  | 
 | 41 | +  void createCollation(  | 
 | 42 | +      {required String name, required CollatingFunction function}) {  | 
 | 43 | +    _db.createCollation(name: name, function: function);  | 
 | 44 | +  }  | 
 | 45 | + | 
 | 46 | +  @override  | 
 | 47 | +  void createFunction(  | 
 | 48 | +      {required String functionName,  | 
 | 49 | +      required ScalarFunction function,  | 
 | 50 | +      AllowedArgumentCount argumentCount = const AllowedArgumentCount.any(),  | 
 | 51 | +      bool deterministic = false,  | 
 | 52 | +      bool directOnly = true}) {  | 
 | 53 | +    _db.createFunction(functionName: functionName, function: function);  | 
 | 54 | +  }  | 
 | 55 | + | 
 | 56 | +  @override  | 
 | 57 | +  void dispose() {  | 
 | 58 | +    _db.dispose();  | 
 | 59 | +  }  | 
 | 60 | + | 
 | 61 | +  @override  | 
 | 62 | +  void execute(String sql, [List<Object?> parameters = const []]) {  | 
 | 63 | +    _db.execute(sql, parameters);  | 
 | 64 | +  }  | 
 | 65 | + | 
 | 66 | +  @override  | 
 | 67 | +  int getUpdatedRows() {  | 
 | 68 | +    // ignore: deprecated_member_use  | 
 | 69 | +    return _db.getUpdatedRows();  | 
 | 70 | +  }  | 
 | 71 | + | 
 | 72 | +  @override  | 
 | 73 | +  int get lastInsertRowId => _db.lastInsertRowId;  | 
 | 74 | + | 
 | 75 | +  @override  | 
 | 76 | +  CommonPreparedStatement prepare(String sql,  | 
 | 77 | +      {bool persistent = false, bool vtab = true, bool checkNoTail = false}) {  | 
 | 78 | +    return _db.prepare(sql,  | 
 | 79 | +        persistent: persistent, vtab: vtab, checkNoTail: checkNoTail);  | 
 | 80 | +  }  | 
 | 81 | + | 
 | 82 | +  @override  | 
 | 83 | +  List<CommonPreparedStatement> prepareMultiple(String sql,  | 
 | 84 | +      {bool persistent = false, bool vtab = true}) {  | 
 | 85 | +    return _db.prepareMultiple(sql, persistent: persistent, vtab: vtab);  | 
 | 86 | +  }  | 
 | 87 | + | 
 | 88 | +  @override  | 
 | 89 | +  ResultSet select(String sql, [List<Object?> parameters = const []]) {  | 
 | 90 | +    bool preAutocommit = _db.autocommit;  | 
 | 91 | +    final result = _db.select(sql, parameters);  | 
 | 92 | +    bool postAutocommit = _db.autocommit;  | 
 | 93 | +    if (!preAutocommit && postAutocommit) {  | 
 | 94 | +      _transactionController.add(true);  | 
 | 95 | +    }  | 
 | 96 | +    return result;  | 
 | 97 | +  }  | 
 | 98 | + | 
 | 99 | +  @override  | 
 | 100 | +  int get updatedRows => _db.updatedRows;  | 
 | 101 | + | 
 | 102 | +  @override  | 
 | 103 | +  Stream<SqliteUpdate> get updates {  | 
 | 104 | +    return throttledUpdates(_db, _transactionController.stream);  | 
 | 105 | +  }  | 
 | 106 | +}  | 
 | 107 | + | 
 | 108 | +/// This throttles the database update stream to:  | 
 | 109 | +/// 1. Trigger max once every 1ms.  | 
 | 110 | +/// 2. Only trigger _after_ transactions.  | 
 | 111 | +Stream<SqliteUpdate> throttledUpdates(  | 
 | 112 | +    CommonDatabase source, Stream transactionStream) {  | 
 | 113 | +  StreamController<SqliteUpdate>? controller;  | 
 | 114 | +  Set<String> insertedTables = {};  | 
 | 115 | +  Set<String> updatedTables = {};  | 
 | 116 | +  Set<String> deletedTables = {};  | 
 | 117 | +  var paused = false;  | 
 | 118 | + | 
 | 119 | +  Timer? updateDebouncer;  | 
 | 120 | + | 
 | 121 | +  void maybeFireUpdates() {  | 
 | 122 | +    updateDebouncer?.cancel();  | 
 | 123 | +    updateDebouncer = null;  | 
 | 124 | + | 
 | 125 | +    if (paused) {  | 
 | 126 | +      // Continue collecting updates, but don't fire any  | 
 | 127 | +      return;  | 
 | 128 | +    }  | 
 | 129 | + | 
 | 130 | +    if (!source.autocommit) {  | 
 | 131 | +      // Inside a transaction - do not fire updates  | 
 | 132 | +      return;  | 
 | 133 | +    }  | 
 | 134 | + | 
 | 135 | +    if (updatedTables.isNotEmpty) {  | 
 | 136 | +      for (var tableName in updatedTables) {  | 
 | 137 | +        controller!.add(SqliteUpdate(SqliteUpdateKind.update, tableName, 0));  | 
 | 138 | +      }  | 
 | 139 | + | 
 | 140 | +      updatedTables.clear();  | 
 | 141 | +    }  | 
 | 142 | + | 
 | 143 | +    if (insertedTables.isNotEmpty) {  | 
 | 144 | +      for (var tableName in insertedTables) {  | 
 | 145 | +        controller!.add(SqliteUpdate(SqliteUpdateKind.insert, tableName, 0));  | 
 | 146 | +      }  | 
 | 147 | + | 
 | 148 | +      insertedTables.clear();  | 
 | 149 | +    }  | 
 | 150 | + | 
 | 151 | +    if (deletedTables.isNotEmpty) {  | 
 | 152 | +      for (var tableName in deletedTables) {  | 
 | 153 | +        controller!.add(SqliteUpdate(SqliteUpdateKind.delete, tableName, 0));  | 
 | 154 | +      }  | 
 | 155 | + | 
 | 156 | +      deletedTables.clear();  | 
 | 157 | +    }  | 
 | 158 | +  }  | 
 | 159 | + | 
 | 160 | +  void collectUpdate(SqliteUpdate event) {  | 
 | 161 | +    if (event.kind == SqliteUpdateKind.insert) {  | 
 | 162 | +      insertedTables.add(event.tableName);  | 
 | 163 | +    } else if (event.kind == SqliteUpdateKind.update) {  | 
 | 164 | +      updatedTables.add(event.tableName);  | 
 | 165 | +    } else if (event.kind == SqliteUpdateKind.delete) {  | 
 | 166 | +      deletedTables.add(event.tableName);  | 
 | 167 | +    }  | 
 | 168 | + | 
 | 169 | +    updateDebouncer ??=  | 
 | 170 | +        Timer(const Duration(milliseconds: 1), maybeFireUpdates);  | 
 | 171 | +  }  | 
 | 172 | + | 
 | 173 | +  StreamSubscription? txSubscription;  | 
 | 174 | +  StreamSubscription? sourceSubscription;  | 
 | 175 | + | 
 | 176 | +  controller = StreamController(onListen: () {  | 
 | 177 | +    txSubscription = transactionStream.listen((event) {  | 
 | 178 | +      maybeFireUpdates();  | 
 | 179 | +    }, onError: (error) {  | 
 | 180 | +      controller?.addError(error);  | 
 | 181 | +    });  | 
 | 182 | + | 
 | 183 | +    sourceSubscription = source.updates.listen(collectUpdate, onError: (error) {  | 
 | 184 | +      controller?.addError(error);  | 
 | 185 | +    });  | 
 | 186 | +  }, onPause: () {  | 
 | 187 | +    paused = true;  | 
 | 188 | +  }, onResume: () {  | 
 | 189 | +    paused = false;  | 
 | 190 | +    maybeFireUpdates();  | 
 | 191 | +  }, onCancel: () {  | 
 | 192 | +    txSubscription?.cancel();  | 
 | 193 | +    sourceSubscription?.cancel();  | 
 | 194 | +  });  | 
 | 195 | + | 
 | 196 | +  return controller.stream;  | 
 | 197 | +}  | 
0 commit comments