diff --git a/angel_orm_mysql/lib/angel_orm_mysql.dart b/angel_orm_mysql/lib/angel_orm_mysql.dart index e69de29b..bc497842 100644 --- a/angel_orm_mysql/lib/angel_orm_mysql.dart +++ b/angel_orm_mysql/lib/angel_orm_mysql.dart @@ -0,0 +1,68 @@ +import 'dart:async'; +import 'package:angel_orm/angel_orm.dart'; +import 'package:angel_orm/src/query.dart'; +import 'package:logging/logging.dart'; +import 'package:pool/pool.dart'; +import 'package:sqljocky5/connection/connection.dart'; +import 'package:sqljocky5/sqljocky.dart'; + +class MySqlExecutor extends QueryExecutor { + final MySqlConnection _connection; + Transaction _transaction; + + MySqlExecutor(this._connection); + + @override + Future> query( + String tableName, String query, Map substitutionValues, + [List returningFields]) { + // Change @id -> ? + for (var name in substitutionValues.keys) { + query = query.replaceAll('@$name', '?'); + } + + if (returningFields?.isNotEmpty != true) { + return _connection + .prepared(query, substitutionValues.values) + .then((results) => results.map((r) => r.toList()).toList()); + } else { + return Future(() async { + _transaction ??= await _connection.begin(); + + try { + var writeResults = + await _transaction.prepared(query, substitutionValues.values); + var fieldSet = returningFields.map((s) => '`$s`').join(','); + var readResults = await _transaction.prepared( + 'select $fieldSet from $tableName where id = ?;', + [writeResults.insertId]); + var mapped = readResults.map((r) => r.toList()).toList(); + await _transaction.commit(); + return mapped; + } catch (_) { + await _transaction?.rollback(); + rethrow; + } + }); + } + } + + @override + Future transaction(FutureOr Function() f) { + if (_transaction != null) { + return Future.sync(f); + } else { + return Future(() async { + try { + _transaction = await _connection.begin(); + var result = await f(); + await _transaction.commit(); + return result; + } catch (_) { + await _transaction?.rollback(); + rethrow; + } + }); + } + } +}