|
| 1 | +import 'package:mysql_client/mysql_client.dart'; |
| 2 | + |
| 3 | +import 'connection_info.dart'; |
| 4 | +import 'migration.dart'; |
| 5 | + |
| 6 | +class FeMySql { |
| 7 | + // 工厂构造函数,用于创建单例实例 |
| 8 | + factory FeMySql({ConnectionInfo? connectionInfo}) { |
| 9 | + return _instance.._init(connectionInfo); |
| 10 | + } |
| 11 | + // 私有构造方法,确保只能在类内部创建实例 |
| 12 | + FeMySql._(); |
| 13 | + |
| 14 | + // 单例实例 |
| 15 | + static final FeMySql _instance = FeMySql._(); |
| 16 | + |
| 17 | + late MySQLConnection _conn; |
| 18 | + List<Migration>? migrations; |
| 19 | + |
| 20 | + // 内部初始化方法 |
| 21 | + Future<void> _init(ConnectionInfo? connectionInfo) async { |
| 22 | + _conn = await MySQLConnection.createConnection( |
| 23 | + host: connectionInfo!.host, |
| 24 | + port: connectionInfo.port, |
| 25 | + userName: connectionInfo.userName, |
| 26 | + password: connectionInfo.password, |
| 27 | + databaseName: connectionInfo.databaseName, |
| 28 | + ); |
| 29 | + await _conn.connect(); |
| 30 | + } |
| 31 | + |
| 32 | + FeMySql addMigrations(List<Migration> migrations) { |
| 33 | + this.migrations = migrations; |
| 34 | + return this; |
| 35 | + } |
| 36 | + |
| 37 | + Future<void> migrate() async { |
| 38 | + if (migrations == null) { |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + final version = await getVersion() ?? 0; |
| 43 | + final lastVersion = migrations!.last.targetVersion; |
| 44 | + |
| 45 | + if (version == lastVersion) { |
| 46 | + return; |
| 47 | + } |
| 48 | + |
| 49 | + for (final migration in migrations!) { |
| 50 | + if (version < migration.targetVersion) { |
| 51 | + await migration.execute(_conn); |
| 52 | + await setVersion(migration.targetVersion); |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + Future<int?> getVersion() async { |
| 58 | + final result = await _conn.execute('SELECT version FROM version'); |
| 59 | + if (result.isEmpty) { |
| 60 | + return null; |
| 61 | + } |
| 62 | + |
| 63 | + return result.first as int; |
| 64 | + } |
| 65 | + |
| 66 | + Future<void> setVersion(int targetVersion) async { |
| 67 | + await _conn.execute('UPDATE version SET version = $targetVersion'); |
| 68 | + } |
| 69 | +} |
0 commit comments