Skip to content

Commit 9e3a25d

Browse files
author
Isaque Neves
committed
fix insertGetId for mysql and add more tests
1 parent 852f17e commit 9e3a25d

9 files changed

+187
-24
lines changed

CHANGELOG.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,4 +68,8 @@ final manager = Manager();
6868

6969
## 2.2.0
7070

71-
- add fromRaw (sub-query as from), joinSub (method to join a query to a sub-query)
71+
- add fromRaw (sub-query as from), joinSub (method to join a query to a sub-query)
72+
73+
## 3.0.0
74+
75+
- 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

example/bin/mysql_example.dart

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ void main(List<String> args) async {
1212
'password': 'dart',
1313
// for SSL conection
1414
'sslmode': 'require',
15-
// not implemented
15+
// options not implemented
1616
// 'options': {
1717
// PDO_MYSQL_ATTR_SSL_VERIFY_SERVER_CERT: false,
1818
// PDO_MYSQL_ATTR_SSL_KEY: '/certs/client-key.pem',
@@ -55,6 +55,8 @@ void main(List<String> args) async {
5555
await db.table('contacts').insert({'id_client': 1, 'tel': '27772339'});
5656
await db.table('contacts').insert({'id_client': 2, 'tel': '99705498'});
5757

58+
final id = await db.table('clients').insertGetId({'name': 'Jack'});
59+
print('id: $id');
5860
var res = await db
5961
.table('clients')
6062
.selectRaw('id,name,tel')

example/bin/postgre_v2_example.dart

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ void main(List<String> args) async {
1414
'charset': 'win1252',
1515
'prefix': '',
1616
'schema': ['public'],
17-
//'sslmode' => 'prefer',
17+
//'sslmode' : 'require',
1818
});
1919

2020
manager.setAsGlobal();

example/bin/postgre_v3_example.dart

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,18 @@ void main(List<String> args) async {
1515
'charset': 'win1252',
1616
'prefix': '',
1717
'schema': ['public'],
18-
//'sslmode' => 'prefer',
18+
//'sslmode' : 'require',
19+
'pool': true,
20+
'poolsize': 50,
1921
});
2022

2123
manager.setAsGlobal();
2224

2325
final db = await manager.connection();
24-
// final res = await db.table('test_table').limit(1).get();
26+
2527
await db.execute('DROP TABLE public.test_table');
26-
await db.execute('''CREATE TABLE public.test_table ( id int4 NOT NULL, name char(255) );''');
28+
await db.execute(
29+
'''CREATE TABLE public.test_table ( id int4 NOT NULL, name char(255) );''');
2730

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

3437
print('res $res');
3538

39+
for (var i = 0; i < 1000000; i++) {
40+
final stopwatch = new Stopwatch()..start();
41+
final res = await db.table('test_table').select(['name']).limit(1).get();
42+
43+
print('executed in ${stopwatch.elapsed.inMilliseconds}ms');
44+
print('res $res');
45+
//await Future.delayed(Duration(milliseconds: 1000));
46+
}
47+
3648
exit(0);
3749
}

example/bin/postgre_v3_example2.dart

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import 'dart:io';
2+
3+
import 'package:eloquent/eloquent.dart';
4+
5+
void main(List<String> args) async {
6+
for (var i = 0; i < 1000000; i++) {
7+
final stopwatch = new Stopwatch()..start();
8+
final db = await getConn();
9+
final res = await db.table('test_table').select(['name']).limit(1).get();
10+
db.disconnect();
11+
print('executed in ${stopwatch.elapsed.inMilliseconds}ms');
12+
print('res $res');
13+
//await Future.delayed(Duration(milliseconds: 1000));
14+
}
15+
16+
exit(0);
17+
}
18+
19+
Future<Connection> getConn() async {
20+
final manager = Manager();
21+
manager.addConnection({
22+
'driver': 'pgsql',
23+
'driver_implementation': 'postgres_v3',
24+
'host': 'localhost',
25+
'port': '5435',
26+
'database': 'siamweb',
27+
'username': 'dart',
28+
'password': 'dart',
29+
'charset': 'win1252',
30+
'prefix': '',
31+
'schema': ['public'],
32+
//'sslmode' : 'require',
33+
// 'pool': true,
34+
// 'poolsize': 50,
35+
});
36+
manager.setAsGlobal();
37+
final db = await manager.connection();
38+
return db;
39+
}

lib/src/pdo/postgres_v3/postgres_v3_pdo.dart

Lines changed: 36 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ class PostgresV3PDO extends PDOInterface {
3232
}
3333

3434
/// postgres V3 Connection
35-
late Connection connection;
35+
late dynamic connection;
3636

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

5959
// dsnParser.sslmode?.toString() == 'require'
60+
final endpoint = Endpoint(
61+
host: dsnParser.host,
62+
port: dsnParser.port,
63+
database: dsnParser.database,
64+
username: user,
65+
password: password,
66+
);
6067

61-
connection = await Connection.open(
62-
Endpoint(
63-
host: dsnParser.host,
64-
port: dsnParser.port,
65-
database: dsnParser.database,
66-
username: user,
67-
password: password,
68-
),
69-
settings: ConnectionSettings(
68+
final sslMode = dsnParser.sslmode?.toString() == 'require'
69+
? SslMode.require
70+
: SslMode.disable;
71+
72+
if (dsnParser.pool == true) {
73+
connection = Pool.withEndpoints(
74+
[endpoint],
75+
settings: PoolSettings(
76+
maxConnectionCount: dsnParser.poolSize,
7077
encoding: _getEncoding(dsnParser.charset ?? 'utf8'),
71-
sslMode: dsnParser.sslmode?.toString() == 'require'
72-
? SslMode.require
73-
: SslMode.disable,
74-
));
78+
sslMode: sslMode,
79+
),
80+
);
81+
82+
await (connection as Pool)
83+
.execute('''SET client_encoding = '${dsnParser.charset}';''');
84+
} else {
85+
connection = await Connection.open(endpoint,
86+
settings: ConnectionSettings(
87+
encoding: _getEncoding(dsnParser.charset ?? 'utf8'),
88+
sslMode: sslMode,
89+
));
90+
91+
await (connection as Connection)
92+
.execute('''SET client_encoding = '${dsnParser.charset}';''');
93+
}
7594

76-
await connection
77-
.execute('''SET client_encoding = '${dsnParser.charset}';''');
7895
return this;
7996
}
8097

@@ -112,6 +129,8 @@ class PostgresV3PDO extends PDOInterface {
112129
timeoutInSeconds = PostgresV3PDO.defaultTimeoutInSeconds;
113130
}
114131

132+
// final conn = connection is Pool ? connection as Pool : connection as Connection;
133+
115134
final rs = await connection.execute(
116135
Sql.indexed(query, substitution: '?'),
117136
parameters: params,
@@ -132,7 +151,7 @@ class PostgresV3PDO extends PDOInterface {
132151
maps.add(map);
133152
}
134153
}
135-
154+
136155
final pdoResult = PDOResults(maps, rs.affectedRows);
137156
return pdoResult;
138157
}

lib/src/query/grammars/query_mysql_grammar.dart

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,28 @@ class QueryMySqlGrammar extends QueryGrammar {
7979
return value;
8080
}
8181

82+
///
83+
/// Compile an insert and get ID statement into SQL.
84+
///
85+
/// [query] QueryBuilder
86+
/// [values] Map<String,dynamic>
87+
/// @param String $sequence
88+
/// `Return` String
89+
///
90+
@override
91+
String compileInsertGetId(
92+
QueryBuilder query, Map<String, dynamic> values, String? sequence) {
93+
if (sequence == null) {
94+
sequence = 'id';
95+
}
96+
97+
// return this.compileInsert(query, values) +
98+
// ' returning ' +
99+
// this.wrap(sequence);
100+
101+
return this.compileInsert(query, values);
102+
}
103+
82104
///
83105
/// Compile an update statement into SQL.
84106
///

lib/src/query/processors/mysql_processor.dart

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,26 @@ class MySqlProcessor extends Processor {
1414

1515
// return array_map(mapping, results);
1616
// }
17+
18+
///
19+
/// Process an "insert get ID" query.
20+
///
21+
/// @param \Illuminate\Database\Query\Builder $query
22+
/// @param string $sql
23+
/// @param array $values
24+
/// @param string $sequence
25+
/// @return int
26+
///
27+
Future<dynamic> processInsertGetId(
28+
QueryBuilder query, String sql, List values,
29+
[String sequence = 'id']) async {
30+
await query.getConnection().insert(sql, values);
31+
final resp =
32+
await query.getConnection().select('SELECT LAST_INSERT_ID() as id;');
33+
final id = resp.isNotEmpty ? resp.first['id'] : null;
34+
return id;
35+
//var id = query.getConnection().getPdo().lastInsertId(sequence);
36+
//return is_numeric($id) ? (int) $id : $id;
37+
//return -1;
38+
}
1739
}

test/mysql_query_test.dart

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ void main() {
1212
'database': 'banco_teste',
1313
'username': 'dart',
1414
'password': 'dart',
15+
//'sslmode': 'require',
1516
// 'pool': true,
1617
// 'poolsize': 2,
1718
});
@@ -24,6 +25,48 @@ void main() {
2425
final res = await db.execute(''' SELECT 'TEST' ''');
2526
expect(res, [0]);
2627
});
27-
28+
29+
test('select', () async {
30+
await db.execute('DROP TABLE IF EXISTS clients');
31+
await db.execute(
32+
''' CREATE TABLE IF NOT EXISTS clients ( id int NOT NULL AUTO_INCREMENT, name varchar(255) NOT NULL,
33+
PRIMARY KEY (id)
34+
); ''');
35+
await db.table('clients').insert({'name': 'John Doe'});
36+
final res = await db.table('clients').where('id','=',1).first();
37+
expect(res, {'id': 1, 'name': 'John Doe'});
38+
});
39+
40+
test('insert', () async {
41+
await db.execute('DROP TABLE IF EXISTS clients');
42+
await db.execute(
43+
''' CREATE TABLE IF NOT EXISTS clients ( id int NOT NULL AUTO_INCREMENT, name varchar(255) NOT NULL,
44+
PRIMARY KEY (id)
45+
); ''');
46+
final res = await db.table('clients').insert({'name': 'John Doe'});
47+
expect(res, []);
48+
});
49+
50+
test('insert and get id', () async {
51+
await db.execute('DROP TABLE IF EXISTS clients');
52+
await db.execute(
53+
''' CREATE TABLE IF NOT EXISTS clients ( id int NOT NULL AUTO_INCREMENT, name varchar(255) NOT NULL,
54+
PRIMARY KEY (id)
55+
); ''');
56+
final res = await db.table('clients').insertGetId({'name': 'John Doe'});
57+
expect(res, 1);
58+
});
59+
60+
test('update', () async {
61+
await db.execute('DROP TABLE IF EXISTS clients');
62+
await db.execute(
63+
''' CREATE TABLE IF NOT EXISTS clients ( id int NOT NULL AUTO_INCREMENT, name varchar(255) NOT NULL,
64+
PRIMARY KEY (id)
65+
); ''');
66+
await db.table('clients').insert({'name': 'John Doe'});
67+
await db.table('clients').where('id','=',1).update({'name': 'John Doe 2'});
68+
final res = await db.table('clients').where('id','=',1).first();
69+
expect(res, {'id': 1, 'name': 'John Doe 2'});
70+
});
2871
});
2972
}

0 commit comments

Comments
 (0)