Skip to content

Commit

Permalink
implement sslmode for mysql
Browse files Browse the repository at this point in the history
  • Loading branch information
Isaque Neves committed Dec 28, 2023
1 parent 7ebf0be commit 852f17e
Show file tree
Hide file tree
Showing 10 changed files with 62 additions and 23 deletions.
12 changes: 11 additions & 1 deletion example/bin/mysql_example.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@ void main(List<String> args) async {
'database': 'banco_teste',
'username': 'dart',
'password': 'dart',
// for SSL conection
'sslmode': 'require',
// not implemented
// 'options': {
// PDO_MYSQL_ATTR_SSL_VERIFY_SERVER_CERT: false,
// PDO_MYSQL_ATTR_SSL_KEY: '/certs/client-key.pem',
// PDO_MYSQL_ATTR_SSL_CERT: '/certs/client-cert.pem',
// PDO_MYSQL_ATTR_SSL_CA: '/certs/ca.pem',
// },
// to enable pool of conections
// 'pool': true,
// 'poolsize': 2,
});
Expand All @@ -18,7 +28,7 @@ void main(List<String> args) async {

final db = await manager.connection();

await db.execute('DROP TABLE clients');
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,
Expand Down
2 changes: 2 additions & 0 deletions lib/eloquent.dart
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,5 @@ export 'src/exceptions/query_exception.dart';
export 'src/pdo/core/pdo_execution_context.dart';
export 'src/pdo/core/pdo_result.dart';
export 'src/pdo/core/pdo_interface.dart';

export '/src/pdo/core/constants.dart';
7 changes: 4 additions & 3 deletions lib/src/connectors/connector.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,21 @@ abstract class Connector with DetectsLostConnections {
///
/// @var array
///
Map<String, dynamic> options = {};
Map<dynamic, dynamic> options = {};

///
/// Get the PDO options based on the configuration.
///
/// @param array $config
/// @return array
///
Map<String, dynamic> getOptions(Map<String, dynamic> config) {
Map<dynamic, dynamic> getOptions(Map<dynamic, dynamic> config) {
var optionsP = config['options'];

//return array_diff_key(options, optionsP) + $options;
//Utils.map_merge_sd(options, optionsP);
if (optionsP != null) {
return Utils.map_merge_sd(options, optionsP);
return {...options, ...optionsP};
}
return options;
}
Expand Down
8 changes: 4 additions & 4 deletions lib/src/connectors/mysql_connector.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class MySqlConnector extends Connector implements ConnectorInterface {
///
/// @var array
///
Map<String, dynamic> options = {};
Map<dynamic, dynamic> options = {};

///
/// Establish a database connection.
Expand Down Expand Up @@ -150,8 +150,8 @@ class MySqlConnector extends Connector implements ConnectorInterface {
/// @return \PDO
/// Aqui que cria a conexão com o Banco de Dados de fato
///
Future<PDOInterface> createConnection(String dsn, Map<String, dynamic> config,
Map<String, dynamic> options) async {
Future<PDOInterface> createConnection(String dsn, Map<dynamic, dynamic> config,
Map<dynamic, dynamic> options) async {
final username = config['username'];
final password = config['password'];

Expand All @@ -161,7 +161,7 @@ class MySqlConnector extends Connector implements ConnectorInterface {
// pdo = MySqlClientPDO(dsn, username, password, options);


pdo = MySqlClientPDO(dsn, username, password);
pdo = MySqlClientPDO(dsn, username, password,options);

await pdo.connect();

Expand Down
4 changes: 2 additions & 2 deletions lib/src/connectors/postgres_connector.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ class PostgresConnector extends Connector implements ConnectorInterface {
///
/// @var array
///
Map<String, dynamic> options = {};
Map<dynamic, dynamic> options = {};

///
/// Establish a database connection.
Expand Down Expand Up @@ -142,7 +142,7 @@ class PostgresConnector extends Connector implements ConnectorInterface {
/// Aqui que cria a conexão com o Banco de Dados de fato
///
Future<PDOInterface> createConnection(String dsn, Map<String, dynamic> config,
Map<String, dynamic> options) async {
Map<dynamic, dynamic> options) async {
final username = config['username'];
final password = config['password'];
// var host = config['host'];
Expand Down
4 changes: 4 additions & 0 deletions lib/src/pdo/core/constants.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const PDO_MYSQL_ATTR_SSL_VERIFY_SERVER_CERT = 1014; //false;
const PDO_MYSQL_ATTR_SSL_KEY = 1007; //'/certs/client-key.pem';
const PDO_MYSQL_ATTR_SSL_CERT = 1008; //'/certs/client-cert.pem';
const PDO_MYSQL_ATTR_SSL_CA = 1009; //'/certs/ca.pem';
5 changes: 4 additions & 1 deletion lib/src/pdo/core/pdo_execution_context.dart
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import 'package:eloquent/src/pdo/core/pdo_interface.dart';
import 'pdo_result.dart';



abstract class PDOExecutionContext {
late PDOInterface pdoInstance;

/// Executa uma instrução SQL e retornar o número de linhas afetadas
Future<int> execute(String statement, [int? timeoutInSeconds]);
Future<PDOResults> query(String query, [dynamic params, int? timeoutInSeconds]);
Future<PDOResults> query(String query,
[dynamic params, int? timeoutInSeconds]);
}
10 changes: 7 additions & 3 deletions lib/src/pdo/mysql_client/mysql_client_pdo.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class MySqlClientPDO extends PDOInterface {
int port = 3306;
String driver = 'mysql_client';
String host = 'localhost';
dynamic attributes;
Map<dynamic, dynamic>? attributes;

/// Creates a PDO instance representing a connection to a database
/// Example
Expand All @@ -35,6 +35,10 @@ class MySqlClientPDO extends PDOInterface {
//called from postgres_connector.dart
Future<MySqlClientPDO> connect() async {
final dsnParser = DSNParser(dsn, DsnType.pdoPostgreSql);
// print('MySqlClientPDO@connect dsnParser: $dsnParser');
// print('MySqlClientPDO@connect sslmode: ${dsnParser.sslmode}');
// print('MySqlClientPDO@connect sslmode: ${dsnParser.sslmode?.toString() == 'require'}');
//print('MySqlClientPDO@connect options: $attributes');

if (dsnParser.pool == true) {
connection = MySQLConnectionPool(
Expand All @@ -45,7 +49,7 @@ class MySqlClientPDO extends PDOInterface {
password: password,
collation: dsnParser.charset ?? 'utf8mb4_general_ci',
maxConnections: dsnParser.poolSize,
secure: false,
secure: dsnParser.sslmode?.toString() == 'require',
);
} else {
connection = await MySQLConnection.createConnection(
Expand All @@ -55,7 +59,7 @@ class MySqlClientPDO extends PDOInterface {
userName: user,
password: password,
collation: dsnParser.charset ?? 'utf8mb4_general_ci',
secure: false,
secure: dsnParser.sslmode?.toString() == 'require',
);
}
if (connection is MySQLConnection) {
Expand Down
22 changes: 14 additions & 8 deletions lib/src/pdo/postgres_v3/postgres_v3_pdo.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class PostgresV3PDO extends PDOInterface {
int port = 5432;
String driver = 'pgsql';
String host = 'localhost';
dynamic attributes;
Map<dynamic, dynamic>? attributes;

/// Creates a PDO instance representing a connection to a database
/// Example
Expand Down Expand Up @@ -56,6 +56,8 @@ class PostgresV3PDO extends PDOInterface {
Future<PostgresV3PDO> connect() async {
final dsnParser = DSNParser(dsn, DsnType.pdoPostgreSql);

// dsnParser.sslmode?.toString() == 'require'

connection = await Connection.open(
Endpoint(
host: dsnParser.host,
Expand All @@ -66,15 +68,18 @@ class PostgresV3PDO extends PDOInterface {
),
settings: ConnectionSettings(
encoding: _getEncoding(dsnParser.charset ?? 'utf8'),
sslMode: SslMode.disable,
sslMode: dsnParser.sslmode?.toString() == 'require'
? SslMode.require
: SslMode.disable,
));

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

Future<T> runInTransaction<T>(Future<T> operation(PostgresV3PDOTransaction ctx),
Future<T> runInTransaction<T>(
Future<T> operation(PostgresV3PDOTransaction ctx),
[int? timeoutInSeconds]) async {
if (timeoutInSeconds == null) {
timeoutInSeconds = defaultTimeoutInSeconds;
Expand All @@ -85,7 +90,7 @@ class PostgresV3PDO extends PDOInterface {
return operation(pdoCtx);
});

return res ;
return res;
}

/// Executa uma instrução SQL e retornar o número de linhas afetadas
Expand Down Expand Up @@ -116,16 +121,17 @@ class PostgresV3PDO extends PDOInterface {
final rows = rs.map((row) => row.toColumnMap()).toList();
final maps = <Map<String, dynamic>>[];
if (rows.isNotEmpty) {
for (final row in rows) {
for (final row in rows) {
final map = <String, dynamic>{};
for (final col in row.entries) {
final key = col.key;
final value = col.value is UndecodedBytes ? col.value.asString : col.value;
final value =
col.value is UndecodedBytes ? col.value.asString : col.value;
map.addAll({key: value});
}
maps.add(map);
maps.add(map);
}
}
}

final pdoResult = PDOResults(maps, rs.affectedRows);
return pdoResult;
Expand Down
11 changes: 10 additions & 1 deletion lib/src/utils/dsn_parser.dart
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ class DSNParser {
int get poolSize => int.tryParse(dsnParts['poolsize'] ?? '') ?? 1;
bool get allowReconnect => dsnParts['allowreconnect'].toString() == 'true';
String? get applicationName => dsnParts['application_name'];
String? get sslmode => dsnParts['sslmode'];
Map<String, dynamic>? get options => dsnParts['options'];

Map<String, dynamic> get params => dsnParts['params'];

Expand Down Expand Up @@ -103,7 +105,6 @@ class DSNParser {
if (parts.join().contains('pool=')) {
dsnParts['pool'] =
parts.lastWhere((p) => p.contains('pool=')).split('=').last;

}
if (parts.join().contains('poolsize=')) {
dsnParts['poolsize'] =
Expand All @@ -121,6 +122,14 @@ class DSNParser {
.split('=')
.last;
}
if (parts.join().contains('sslmode=')) {
dsnParts['sslmode'] =
parts.lastWhere((p) => p.contains('sslmode=')).split('=').last;
}
if (parts.join().contains('options=')) {
dsnParts['options'] =
parts.lastWhere((p) => p.contains('options=')).split('=').last;
}
} else if (dsnType == DsnType.heroku) {
var patternString = '^' +
'(?:' +
Expand Down

0 comments on commit 852f17e

Please sign in to comment.