|
| 1 | +import 'dart:typed_data'; |
| 2 | + |
| 3 | +import 'package:mysql_utils/mysql_utils.dart'; |
| 4 | +import 'package:test/test.dart'; |
| 5 | + |
| 6 | +void main() { |
| 7 | + late MysqlUtils db; |
| 8 | + setUpAll(() async { |
| 9 | + db = MysqlUtils( |
| 10 | + settings: MysqlUtilsSettings( |
| 11 | + host: '127.0.0.1', |
| 12 | + port: 3306, |
| 13 | + user: 'your_user', |
| 14 | + password: 'your_password', |
| 15 | + db: 'testdb', |
| 16 | + secure: true, |
| 17 | + // prefix: '', |
| 18 | + // maxConnections: 1000, |
| 19 | + // timeoutMs: 10000, |
| 20 | + // sqlEscape: true, |
| 21 | + pool: false, |
| 22 | + //collation: 'utf8mb4_general_ci', |
| 23 | + // debug: true, |
| 24 | + // securityContext: SecurityContext(), |
| 25 | + // onBadCertificate: (certificate) => true, |
| 26 | + ), |
| 27 | + errorLog: (error) { |
| 28 | + print(error); |
| 29 | + }, |
| 30 | + sqlLog: (sql) { |
| 31 | + print(sql); |
| 32 | + }, |
| 33 | + connectInit: (db1) async { |
| 34 | + print('whenComplete'); |
| 35 | + }, |
| 36 | + ); |
| 37 | + }); |
| 38 | + |
| 39 | + tearDownAll(() async { |
| 40 | + await db.close(); |
| 41 | + }); |
| 42 | + |
| 43 | + test('Execute: create table ', () async { |
| 44 | + await db.query("DROP TABLE IF EXISTS `test_data3`"); |
| 45 | + await db.query(''' |
| 46 | + CREATE TABLE test_data3 ( |
| 47 | + id BINARY(16) PRIMARY KEY NOT NULL DEFAULT (UUID_TO_BIN(UUID())), |
| 48 | + name VARCHAR(255) |
| 49 | + ); |
| 50 | + '''); |
| 51 | + }); |
| 52 | + |
| 53 | + test('Execute: insert data ', () async { |
| 54 | + await db.query('INSERT INTO test_data3 (name) VALUES ("binary data test")'); |
| 55 | + final result = await db.query("SELECT (id) FROM test_data3"); |
| 56 | + final row = result.rows.first; |
| 57 | + final uuid = binaryToUuid(row['id']); |
| 58 | + |
| 59 | + final result2 = await db.query("SELECT BIN_TO_UUID(id) as UUID FROM test_data3"); |
| 60 | + final row2 = result2.rows.first; |
| 61 | + |
| 62 | + expect(uuid, row2['UUID']); |
| 63 | + }); |
| 64 | + |
| 65 | + test('Execute: drop table ', () async { |
| 66 | + await db.query("DROP TABLE IF EXISTS `test_data3`"); |
| 67 | + }); |
| 68 | +} |
| 69 | + |
| 70 | +String binaryToUuid(String idStr) { |
| 71 | + final bytes = Uint8List.fromList(idStr.codeUnits); |
| 72 | + assert(bytes.length == 16); |
| 73 | + String hex = _bytesToHex(bytes); |
| 74 | + return '${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}'; |
| 75 | +} |
| 76 | + |
| 77 | +String _bytesToHex(List<int> bytes) { |
| 78 | + final buffer = StringBuffer(); |
| 79 | + for (final byte in bytes) { |
| 80 | + buffer.write(byte.toRadixString(16).padLeft(2, '0')); |
| 81 | + } |
| 82 | + return buffer.toString(); |
| 83 | +} |
0 commit comments