|
| 1 | +import 'dart:async'; |
| 2 | +import 'dart:convert'; |
| 3 | + |
| 4 | +import 'package:sqlite3/sqlite3.dart'; |
| 5 | + |
| 6 | +import 'sqlite_connection.dart'; |
| 7 | + |
| 8 | +class SqliteMigrations { |
| 9 | + String migrationTable; |
| 10 | + List<SqliteMigration> migrations = []; |
| 11 | + SqliteMigration? createDatabase; |
| 12 | + |
| 13 | + SqliteMigrations({this.migrationTable = "_migrations"}); |
| 14 | + |
| 15 | + add(SqliteMigration migration) { |
| 16 | + assert( |
| 17 | + migrations.isEmpty || migrations.last.toVersion < migration.toVersion); |
| 18 | + |
| 19 | + final down = migration.downMigration; |
| 20 | + if (down != null) { |
| 21 | + if (migrations.isEmpty) { |
| 22 | + if (down.toVersion != 0) { |
| 23 | + throw MigrationError( |
| 24 | + 'Down migration for first migration must have toVersion = 0'); |
| 25 | + } |
| 26 | + } else { |
| 27 | + if (down.toVersion > migrations.last.toVersion) { |
| 28 | + throw MigrationError( |
| 29 | + 'Down migration for ${migration.toVersion} must have a toVersion <= ${migrations.last.toVersion}'); |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + migrations.add(migration); |
| 35 | + } |
| 36 | + |
| 37 | + get version { |
| 38 | + return migrations.isEmpty ? 0 : migrations.last.toVersion; |
| 39 | + } |
| 40 | + |
| 41 | + Future<int> getCurrentVersion(SqliteWriteContext db) async { |
| 42 | + try { |
| 43 | + final currentVersionRow = await db.getOptional( |
| 44 | + 'SELECT ifnull(max(id), 0) as version FROM $migrationTable'); |
| 45 | + int currentVersion = |
| 46 | + currentVersionRow == null ? 0 : currentVersionRow['version']; |
| 47 | + return currentVersion; |
| 48 | + } on SqliteException catch (e) { |
| 49 | + if (e.message.contains('no such table')) { |
| 50 | + return 0; |
| 51 | + } |
| 52 | + rethrow; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + _validateCreateDatabase() { |
| 57 | + if (createDatabase != null) { |
| 58 | + if (createDatabase!.downMigration != null) { |
| 59 | + throw MigrationError("createDatabase may not contain down migrations"); |
| 60 | + } |
| 61 | + |
| 62 | + var hasMatchingVersion = migrations |
| 63 | + .where((element) => element.toVersion == createDatabase!.toVersion) |
| 64 | + .isNotEmpty; |
| 65 | + if (!hasMatchingVersion) { |
| 66 | + throw MigrationError( |
| 67 | + "createDatabase.version (${createDatabase!.toVersion} must match a migration version"); |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + Future<void> migrate(SqliteConnection db) async { |
| 73 | + _validateCreateDatabase(); |
| 74 | + |
| 75 | + await db.writeTransaction((tx) async { |
| 76 | + await tx.execute( |
| 77 | + 'CREATE TABLE IF NOT EXISTS $migrationTable(id INTEGER PRIMARY KEY, down_migrations TEXT)'); |
| 78 | + |
| 79 | + int currentVersion = await getCurrentVersion(tx); |
| 80 | + |
| 81 | + if (currentVersion == version) { |
| 82 | + return; |
| 83 | + } |
| 84 | + |
| 85 | + // Handle down migrations |
| 86 | + while (currentVersion > version) { |
| 87 | + final migrationRow = await tx.getOptional( |
| 88 | + 'SELECT id, down_migrations FROM $migrationTable WHERE id > ? ORDER BY id DESC LIMIT 1', |
| 89 | + [version]); |
| 90 | + |
| 91 | + if (migrationRow == null || migrationRow['down_migrations'] == null) { |
| 92 | + throw MigrationError( |
| 93 | + 'No down migration found from $currentVersion to $version'); |
| 94 | + } |
| 95 | + |
| 96 | + final migrations = jsonDecode(migrationRow['down_migrations']); |
| 97 | + for (var migration in migrations) { |
| 98 | + await tx.execute(migration['sql'], migration['params']); |
| 99 | + } |
| 100 | + |
| 101 | + // Refresh version |
| 102 | + int prevVersion = currentVersion; |
| 103 | + currentVersion = await getCurrentVersion(tx); |
| 104 | + if (prevVersion == currentVersion) { |
| 105 | + throw MigrationError( |
| 106 | + 'Database down from version $currentVersion to $version failed - version not updated after dow migration'); |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + // Clean setup |
| 111 | + if (currentVersion == 0 && createDatabase != null) { |
| 112 | + await createDatabase!.fn(tx); |
| 113 | + |
| 114 | + // Still need to persist the migrations |
| 115 | + for (var migration in migrations) { |
| 116 | + if (migration.toVersion <= createDatabase!.toVersion) { |
| 117 | + await _persistMigration(migration, tx, migrationTable); |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + currentVersion = await getCurrentVersion(tx); |
| 122 | + } |
| 123 | + |
| 124 | + // Up migrations |
| 125 | + for (var migration in migrations) { |
| 126 | + if (migration.toVersion > currentVersion) { |
| 127 | + await migration.fn(tx); |
| 128 | + await _persistMigration(migration, tx, migrationTable); |
| 129 | + } |
| 130 | + } |
| 131 | + }); |
| 132 | + } |
| 133 | +} |
| 134 | + |
| 135 | +Future<void> _persistMigration(SqliteMigration migration, SqliteWriteContext db, |
| 136 | + String migrationTable) async { |
| 137 | + final down = migration.downMigration; |
| 138 | + if (down != null) { |
| 139 | + List<_SqliteMigrationStatement> statements = down._statements; |
| 140 | + statements.insert( |
| 141 | + 0, |
| 142 | + _SqliteMigrationStatement( |
| 143 | + 'DELETE FROM $migrationTable WHERE id > ${down.toVersion}')); |
| 144 | + |
| 145 | + var json = jsonEncode(statements); |
| 146 | + await db.execute( |
| 147 | + 'INSERT INTO $migrationTable(id, down_migrations) VALUES(?, ?)', |
| 148 | + [migration.toVersion, json]); |
| 149 | + } else { |
| 150 | + await db.execute( |
| 151 | + 'INSERT INTO $migrationTable(id, down_migrations) VALUES(?, ?)', |
| 152 | + [migration.toVersion, null]); |
| 153 | + } |
| 154 | +} |
| 155 | + |
| 156 | +class MigrationError extends Error { |
| 157 | + final String message; |
| 158 | + |
| 159 | + MigrationError(this.message); |
| 160 | + |
| 161 | + @override |
| 162 | + String toString() { |
| 163 | + return 'MigrationError: $message'; |
| 164 | + } |
| 165 | +} |
| 166 | + |
| 167 | +typedef SqliteMigrationFunction = FutureOr<void> Function( |
| 168 | + SqliteWriteContext tx); |
| 169 | + |
| 170 | +class SqliteMigration { |
| 171 | + final SqliteMigrationFunction fn; |
| 172 | + final int toVersion; |
| 173 | + |
| 174 | + /// Optional: Add a down migration to allow this migration to be reverted |
| 175 | + /// if the user installs an older version. |
| 176 | + SqliteDownMigration? downMigration; |
| 177 | + |
| 178 | + SqliteMigration(this.toVersion, this.fn, {this.downMigration}); |
| 179 | +} |
| 180 | + |
| 181 | +class _SqliteMigrationStatement { |
| 182 | + final String sql; |
| 183 | + final List<Object?> params; |
| 184 | + |
| 185 | + _SqliteMigrationStatement(this.sql, [this.params = const []]); |
| 186 | + |
| 187 | + Map<String, dynamic> toJson() { |
| 188 | + return {'sql': sql, 'params': params}; |
| 189 | + } |
| 190 | +} |
| 191 | + |
| 192 | +class SqliteDownMigration { |
| 193 | + final int toVersion; |
| 194 | + final List<_SqliteMigrationStatement> _statements = []; |
| 195 | + |
| 196 | + SqliteDownMigration({required this.toVersion}); |
| 197 | + |
| 198 | + add(String sql, [List<Object?>? params]) { |
| 199 | + _statements.add(_SqliteMigrationStatement(sql, params ?? [])); |
| 200 | + } |
| 201 | +} |
0 commit comments