Skip to content

Commit

Permalink
fix insertGetId for mysql and add more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Isaque Neves committed Dec 28, 2023
1 parent 852f17e commit 9e3a25d
Show file tree
Hide file tree
Showing 9 changed files with 187 additions and 24 deletions.
6 changes: 5 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,8 @@ final manager = Manager();

## 2.2.0

- add fromRaw (sub-query as from), joinSub (method to join a query to a sub-query)
- add fromRaw (sub-query as from), joinSub (method to join a query to a sub-query)

## 3.0.0

- implemented support for mysql through the 'mysql_client' package and also implemented support for posgress with the postgres v3 package, now you can choose the driver implementation through ``` 'driver_implementation': 'postgres_v3', ``` in addConnection method
4 changes: 3 additions & 1 deletion example/bin/mysql_example.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ void main(List<String> args) async {
'password': 'dart',
// for SSL conection
'sslmode': 'require',
// not implemented
// options not implemented
// 'options': {
// PDO_MYSQL_ATTR_SSL_VERIFY_SERVER_CERT: false,
// PDO_MYSQL_ATTR_SSL_KEY: '/certs/client-key.pem',
Expand Down Expand Up @@ -55,6 +55,8 @@ void main(List<String> args) async {
await db.table('contacts').insert({'id_client': 1, 'tel': '27772339'});
await db.table('contacts').insert({'id_client': 2, 'tel': '99705498'});

final id = await db.table('clients').insertGetId({'name': 'Jack'});
print('id: $id');
var res = await db
.table('clients')
.selectRaw('id,name,tel')
Expand Down
2 changes: 1 addition & 1 deletion example/bin/postgre_v2_example.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ void main(List<String> args) async {
'charset': 'win1252',
'prefix': '',
'schema': ['public'],
//'sslmode' => 'prefer',
//'sslmode' : 'require',
});

manager.setAsGlobal();
Expand Down
18 changes: 15 additions & 3 deletions example/bin/postgre_v3_example.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,18 @@ void main(List<String> args) async {
'charset': 'win1252',
'prefix': '',
'schema': ['public'],
//'sslmode' => 'prefer',
//'sslmode' : 'require',
'pool': true,
'poolsize': 50,
});

manager.setAsGlobal();

final db = await manager.connection();
// final res = await db.table('test_table').limit(1).get();

await db.execute('DROP TABLE public.test_table');
await db.execute('''CREATE TABLE public.test_table ( id int4 NOT NULL, name char(255) );''');
await db.execute(
'''CREATE TABLE public.test_table ( id int4 NOT NULL, name char(255) );''');

final res = await db.transaction((ctx) async {
await ctx.table('test_table').insert({'id': 11, 'name': 'Jane Doe'});
Expand All @@ -33,5 +36,14 @@ void main(List<String> args) async {

print('res $res');

for (var i = 0; i < 1000000; i++) {
final stopwatch = new Stopwatch()..start();
final res = await db.table('test_table').select(['name']).limit(1).get();

print('executed in ${stopwatch.elapsed.inMilliseconds}ms');
print('res $res');
//await Future.delayed(Duration(milliseconds: 1000));
}

exit(0);
}
39 changes: 39 additions & 0 deletions example/bin/postgre_v3_example2.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import 'dart:io';

import 'package:eloquent/eloquent.dart';

void main(List<String> args) async {
for (var i = 0; i < 1000000; i++) {
final stopwatch = new Stopwatch()..start();
final db = await getConn();
final res = await db.table('test_table').select(['name']).limit(1).get();
db.disconnect();
print('executed in ${stopwatch.elapsed.inMilliseconds}ms');
print('res $res');
//await Future.delayed(Duration(milliseconds: 1000));
}

exit(0);
}

Future<Connection> getConn() async {
final manager = Manager();
manager.addConnection({
'driver': 'pgsql',
'driver_implementation': 'postgres_v3',
'host': 'localhost',
'port': '5435',
'database': 'siamweb',
'username': 'dart',
'password': 'dart',
'charset': 'win1252',
'prefix': '',
'schema': ['public'],
//'sslmode' : 'require',
// 'pool': true,
// 'poolsize': 50,
});
manager.setAsGlobal();
final db = await manager.connection();
return db;
}
53 changes: 36 additions & 17 deletions lib/src/pdo/postgres_v3/postgres_v3_pdo.dart
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class PostgresV3PDO extends PDOInterface {
}

/// postgres V3 Connection
late Connection connection;
late dynamic connection;

Encoding _getEncoding(String encoding) {
switch (encoding.toLowerCase()) {
Expand All @@ -57,24 +57,41 @@ class PostgresV3PDO extends PDOInterface {
final dsnParser = DSNParser(dsn, DsnType.pdoPostgreSql);

// dsnParser.sslmode?.toString() == 'require'
final endpoint = Endpoint(
host: dsnParser.host,
port: dsnParser.port,
database: dsnParser.database,
username: user,
password: password,
);

connection = await Connection.open(
Endpoint(
host: dsnParser.host,
port: dsnParser.port,
database: dsnParser.database,
username: user,
password: password,
),
settings: ConnectionSettings(
final sslMode = dsnParser.sslmode?.toString() == 'require'
? SslMode.require
: SslMode.disable;

if (dsnParser.pool == true) {
connection = Pool.withEndpoints(
[endpoint],
settings: PoolSettings(
maxConnectionCount: dsnParser.poolSize,
encoding: _getEncoding(dsnParser.charset ?? 'utf8'),
sslMode: dsnParser.sslmode?.toString() == 'require'
? SslMode.require
: SslMode.disable,
));
sslMode: sslMode,
),
);

await (connection as Pool)
.execute('''SET client_encoding = '${dsnParser.charset}';''');
} else {
connection = await Connection.open(endpoint,
settings: ConnectionSettings(
encoding: _getEncoding(dsnParser.charset ?? 'utf8'),
sslMode: sslMode,
));

await (connection as Connection)
.execute('''SET client_encoding = '${dsnParser.charset}';''');
}

await connection
.execute('''SET client_encoding = '${dsnParser.charset}';''');
return this;
}

Expand Down Expand Up @@ -112,6 +129,8 @@ class PostgresV3PDO extends PDOInterface {
timeoutInSeconds = PostgresV3PDO.defaultTimeoutInSeconds;
}

// final conn = connection is Pool ? connection as Pool : connection as Connection;

final rs = await connection.execute(
Sql.indexed(query, substitution: '?'),
parameters: params,
Expand All @@ -132,7 +151,7 @@ class PostgresV3PDO extends PDOInterface {
maps.add(map);
}
}

final pdoResult = PDOResults(maps, rs.affectedRows);
return pdoResult;
}
Expand Down
22 changes: 22 additions & 0 deletions lib/src/query/grammars/query_mysql_grammar.dart
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,28 @@ class QueryMySqlGrammar extends QueryGrammar {
return value;
}

///
/// Compile an insert and get ID statement into SQL.
///
/// [query] QueryBuilder
/// [values] Map<String,dynamic>
/// @param String $sequence
/// `Return` String
///
@override
String compileInsertGetId(
QueryBuilder query, Map<String, dynamic> values, String? sequence) {
if (sequence == null) {
sequence = 'id';
}

// return this.compileInsert(query, values) +
// ' returning ' +
// this.wrap(sequence);

return this.compileInsert(query, values);
}

///
/// Compile an update statement into SQL.
///
Expand Down
22 changes: 22 additions & 0 deletions lib/src/query/processors/mysql_processor.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,26 @@ class MySqlProcessor extends Processor {

// return array_map(mapping, results);
// }

///
/// Process an "insert get ID" query.
///
/// @param \Illuminate\Database\Query\Builder $query
/// @param string $sql
/// @param array $values
/// @param string $sequence
/// @return int
///
Future<dynamic> processInsertGetId(
QueryBuilder query, String sql, List values,
[String sequence = 'id']) async {
await query.getConnection().insert(sql, values);
final resp =
await query.getConnection().select('SELECT LAST_INSERT_ID() as id;');
final id = resp.isNotEmpty ? resp.first['id'] : null;
return id;
//var id = query.getConnection().getPdo().lastInsertId(sequence);
//return is_numeric($id) ? (int) $id : $id;
//return -1;
}
}
45 changes: 44 additions & 1 deletion test/mysql_query_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ void main() {
'database': 'banco_teste',
'username': 'dart',
'password': 'dart',
//'sslmode': 'require',
// 'pool': true,
// 'poolsize': 2,
});
Expand All @@ -24,6 +25,48 @@ void main() {
final res = await db.execute(''' SELECT 'TEST' ''');
expect(res, [0]);
});


test('select', () async {
await db.execute('DROP TABLE IF EXISTS clients');
await db.execute(
''' CREATE TABLE IF NOT EXISTS clients ( id int NOT NULL AUTO_INCREMENT, name varchar(255) NOT NULL,
PRIMARY KEY (id)
); ''');
await db.table('clients').insert({'name': 'John Doe'});
final res = await db.table('clients').where('id','=',1).first();
expect(res, {'id': 1, 'name': 'John Doe'});
});

test('insert', () async {
await db.execute('DROP TABLE IF EXISTS clients');
await db.execute(
''' CREATE TABLE IF NOT EXISTS clients ( id int NOT NULL AUTO_INCREMENT, name varchar(255) NOT NULL,
PRIMARY KEY (id)
); ''');
final res = await db.table('clients').insert({'name': 'John Doe'});
expect(res, []);
});

test('insert and get id', () async {
await db.execute('DROP TABLE IF EXISTS clients');
await db.execute(
''' CREATE TABLE IF NOT EXISTS clients ( id int NOT NULL AUTO_INCREMENT, name varchar(255) NOT NULL,
PRIMARY KEY (id)
); ''');
final res = await db.table('clients').insertGetId({'name': 'John Doe'});
expect(res, 1);
});

test('update', () async {
await db.execute('DROP TABLE IF EXISTS clients');
await db.execute(
''' CREATE TABLE IF NOT EXISTS clients ( id int NOT NULL AUTO_INCREMENT, name varchar(255) NOT NULL,
PRIMARY KEY (id)
); ''');
await db.table('clients').insert({'name': 'John Doe'});
await db.table('clients').where('id','=',1).update({'name': 'John Doe 2'});
final res = await db.table('clients').where('id','=',1).first();
expect(res, {'id': 1, 'name': 'John Doe 2'});
});
});
}

0 comments on commit 9e3a25d

Please sign in to comment.