platform/angel_orm_generator/test/common.dart

58 lines
1.7 KiB
Dart
Raw Normal View History

2017-07-09 16:53:35 +00:00
import 'dart:async';
import 'dart:io';
2018-12-03 13:41:14 +00:00
import 'package:angel_orm/angel_orm.dart';
2017-07-09 16:53:35 +00:00
import 'package:postgres/postgres.dart';
2018-12-03 13:41:14 +00:00
Future<PostgresExecutor> connectToPostgres(Iterable<String> schemas) async {
2017-07-09 16:53:35 +00:00
var conn = new PostgreSQLConnection('127.0.0.1', 5432, 'angel_orm_test',
username: Platform.environment['POSTGRES_USERNAME'] ?? 'postgres',
password: Platform.environment['POSTGRES_PASSWORD'] ?? 'password');
await conn.open();
2017-08-01 05:45:54 +00:00
for (var s in schemas)
2018-12-03 16:50:43 +00:00
await conn.execute(await new File('test/migrations/$s.sql').readAsString());
2017-07-09 16:53:35 +00:00
2018-12-03 13:41:14 +00:00
return new PostgresExecutor(conn);
}
class PostgresExecutor extends QueryExecutor {
2018-12-08 02:03:03 +00:00
PostgreSQLExecutionContext connection;
2018-12-03 13:41:14 +00:00
PostgresExecutor(this.connection);
2018-12-08 02:03:03 +00:00
Future close() => (connection as PostgreSQLConnection).close();
2018-12-03 13:41:14 +00:00
@override
2018-12-31 12:22:05 +00:00
Future<List<List>> query(
String query, Map<String, dynamic> substitutionValues,
[List<String> returningFields]) {
2018-12-03 16:50:43 +00:00
if (returningFields != null) {
var fields = returningFields.join(', ');
var returning = 'RETURNING $fields';
query = '$query $returning';
}
2018-12-31 12:22:05 +00:00
if (!Platform.environment.containsKey('STFU')) {
print('Running: $query');
if (substitutionValues.isNotEmpty) print('Values: $substitutionValues');
}
return connection.query(query, substitutionValues: substitutionValues);
2018-12-03 13:41:14 +00:00
}
2018-12-08 02:03:03 +00:00
@override
Future<T> transaction<T>(FutureOr<T> Function() f) async {
2018-12-08 04:13:49 +00:00
if (connection is! PostgreSQLConnection) return await f();
2018-12-08 02:03:03 +00:00
var old = connection;
T result;
try {
await (connection as PostgreSQLConnection).transaction((ctx) async {
connection = ctx;
result = await f();
});
} finally {
connection = old;
return result;
}
}
2017-07-09 16:53:35 +00:00
}