diff --git a/CHANGELOG.md b/CHANGELOG.md index 3dbc95c..cce8689 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -94,4 +94,33 @@ final manager = Manager(); ## 3.3.0 -- **Breaking change**: decode timestamp without timezone as local DateTime and decode timestamp with timezone respecting the timezone defined in the connection \ No newline at end of file +- add option to decode timestamp without timezone and date as local DateTime and decode timestamp with timezone respecting the timezone defined in the connection +```dart + final manager = Manager(); + manager.addConnection({ + 'driver': 'pgsql', + 'driver_implementation': 'postgres_v3', // postgres | dargres | postgres_v3 + 'timezone': 'America/Sao_Paulo', + // If true, decodes the timestamp with timezone (timestamptz) as UTC = default + // If false, decodes the timestamp with timezone using the timezone defined in the connection. + 'forceDecodeTimestamptzAsUTC': false, + // If true, decodes the timestamp without timezone (timestamp) as UTC. + // If false, decodes the timestamp without timezone as local datetime. + 'forceDecodeTimestampAsUTC': false, + // If true, decodes the date as UTC. + // If false, decodes the date as local datetime. + 'forceDecodeDateAsUTC': false, + 'pool': true, + 'poolsize': 2, + 'host': 'localhost', + 'port': '5435', + 'database': 'siamweb', + 'username': 'dart', + 'password': 'dart', + 'charset': 'win1252', + 'prefix': '', + 'schema': ['public'], + // require | disable + //'sslmode' : 'require', + }); +``` \ No newline at end of file diff --git a/README.md b/README.md index 5c57c6f..844cb25 100644 --- a/README.md +++ b/README.md @@ -240,4 +240,40 @@ void main(List args) async { exit(0); } +``` + +## example of all settings + +```dart + final manager = Manager(); + manager.addConnection({ + 'driver': 'pgsql', + 'driver_implementation': 'postgres_v3', // postgres | dargres | postgres_v3 + // set connection time zone UTC = default + 'timezone': 'America/Sao_Paulo', + // If true, decodes the timestamp with timezone (timestamptz) as UTC = default + // If false, decodes the timestamp with timezone using the timezone defined in the connection. + 'forceDecodeTimestamptzAsUTC': false, + // If true, decodes the timestamp without timezone (timestamp) as UTC. + // If false, decodes the timestamp without timezone as local datetime. + 'forceDecodeTimestampAsUTC': false, + // If true, decodes the date as UTC. + // If false, decodes the date as local datetime. + 'forceDecodeDateAsUTC': false, + // enable connection pool + 'pool': true, + // Connection pool maximum connection count + 'poolsize': 2, + 'host': 'localhost', + 'port': '5435', + 'database': 'siamweb', + 'username': 'dart', + 'password': 'dart', + // + 'charset': 'win1252', + 'prefix': '', + 'schema': ['public'], + // require | disable + //'sslmode' : 'require', + }); ``` \ No newline at end of file diff --git a/example/bin/postgre_v2_example.dart b/example/bin/postgre_v2_example.dart index bdd0da9..1abc53b 100644 --- a/example/bin/postgre_v2_example.dart +++ b/example/bin/postgre_v2_example.dart @@ -6,6 +6,13 @@ void main(List args) async { final manager = Manager(); manager.addConnection({ 'driver': 'pgsql', + 'driver_implementation': 'postgres_v3', // postgres | dargres | postgres_v3 + 'timezone': 'America/Sao_Paulo', + 'forceDecodeTimestamptzAsUTC': false, + 'forceDecodeTimestampAsUTC': false, + 'forceDecodeDateAsUTC': false, + 'pool': true, + 'poolsize': 2, 'host': 'localhost', 'port': '5435', 'database': 'siamweb', @@ -19,14 +26,27 @@ void main(List args) async { manager.setAsGlobal(); - final db = await manager.connection(); + final connection = await manager.connection(); - final res = await db.transaction((ctx) async { - await ctx.table('test_table').insert({'id':10,'name':'Jane Doe'}); - final res = await ctx.table('test_table').limit(2).get(); - return res; - }); + var results = + await connection.select("select current_timestamp, current_date "); + print('results: ${results}'); + var currentTimestamp = results.first['current_timestamp'] as DateTime; + print('dafault: $currentTimestamp ${currentTimestamp.timeZoneName}'); + print('local: ${currentTimestamp.toLocal()}'); + + // await connection.execute("set timezone to 'America/Sao_Paulo'"); + // results = await connection.execute("select current_timestamp"); + // currentTimestamp = results.first.first as DateTime; + // print( + // 'America/Sao_Paulo: $currentTimestamp ${currentTimestamp.timeZoneName}'); + + // final res = await db.transaction((ctx) async { + // await ctx.table('test_table').insert({'id':10,'name':'Jane Doe'}); + // final res = await ctx.table('test_table').limit(2).get(); + // return res; + // }); + // print('res $res'); - print('res $res'); exit(0); } diff --git a/lib/eloquent.dart b/lib/eloquent.dart index 390646a..94a2b36 100644 --- a/lib/eloquent.dart +++ b/lib/eloquent.dart @@ -5,8 +5,6 @@ export 'src/query/query_builder.dart'; export 'src/query/join_clause.dart'; - - export 'src/grammar.dart'; //BaseGrammar export 'src/query/grammars/query_grammar.dart'; export 'src/query/processors/processor.dart'; @@ -40,9 +38,9 @@ export 'src/exceptions/query_exception.dart'; //PDO - 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/pdo_config.dart'; export '/src/pdo/core/constants.dart'; diff --git a/lib/src/capsule/manager.dart b/lib/src/capsule/manager.dart index c197d99..9d64708 100644 --- a/lib/src/capsule/manager.dart +++ b/lib/src/capsule/manager.dart @@ -152,7 +152,11 @@ class Manager { /// @param array $config /// @param string $name /// @return void - /// + /// + /// ```dart + /// + /// ``` + /// void addConnection(Map config, [String name = 'default']) { var connections = this.container['config']['database.connections']; if (connections == null) { diff --git a/lib/src/connectors/connector.dart b/lib/src/connectors/connector.dart index ecfd132..7e028e6 100644 --- a/lib/src/connectors/connector.dart +++ b/lib/src/connectors/connector.dart @@ -16,7 +16,6 @@ abstract class Connector with DetectsLostConnections { /// Map getOptions(Map config) { var optionsP = config['options']; - //return array_diff_key(options, optionsP) + $options; //Utils.map_merge_sd(options, optionsP); if (optionsP != null) { @@ -33,18 +32,5 @@ abstract class Connector with DetectsLostConnections { /// @param array $options /// @return \PDO /// - dynamic createConnection( - String dsn, Map config, Map options); - // var username = config['username']; - //var password = config['password']; - - // try { - // $pdo = new PDO($dsn, $username, $password, $options); - // } catch (Exception e) { - // $pdo = $this->tryAgainIfCausedByLostConnection( - // $e, $dsn, $username, $password, $options - // ); - // } - - //} + dynamic createConnection(Map config); } diff --git a/lib/src/connectors/mysql_connector.dart b/lib/src/connectors/mysql_connector.dart index 4adc2dd..65d7793 100644 --- a/lib/src/connectors/mysql_connector.dart +++ b/lib/src/connectors/mysql_connector.dart @@ -17,10 +17,9 @@ class MySqlConnector extends Connector implements ConnectorInterface { /// @return PostgreSQLConnection \PDO /// Future connect(Map config) async { - final dsn = getDsn(config); - final options = getOptions(config); - - final connection = await createConnection(dsn, config, options); + //final dsn = getDsn(config); + //final options = getOptions(config); + final connection = await createConnection(config); if (config.containsKey('database') && config['database'] != null) { await connection.execute("use `${config['database']}`;"); @@ -150,18 +149,12 @@ class MySqlConnector extends Connector implements ConnectorInterface { /// @return \PDO /// Aqui que cria a conexão com o Banco de Dados de fato /// - Future createConnection(String dsn, Map config, - Map options) async { - final username = config['username']; - final password = config['password']; - + Future createConnection(Map config) async { late PDOInterface pdo; - // if (config['driver_implementation'] == 'postgres') { - // pdo = MySqlClientPDO(dsn, username, password, options); - + final pdoConfig = PDOConfig.fromMap(config); - pdo = MySqlClientPDO(dsn, username, password,options); + pdo = MySqlClientPDO(pdoConfig); await pdo.connect(); diff --git a/lib/src/connectors/postgres_connector.dart b/lib/src/connectors/postgres_connector.dart index 88db64f..f306d6a 100644 --- a/lib/src/connectors/postgres_connector.dart +++ b/lib/src/connectors/postgres_connector.dart @@ -22,11 +22,9 @@ class PostgresConnector extends Connector implements ConnectorInterface { // using the configuration option specified by the developer. We will also // set the default character set on the connections to UTF-8 by default. - var dsn = getDsn(config); - - var options = getOptions(config); - - var connection = await createConnection(dsn, config, options); + //var dsn = getDsn(config); + //var options = getOptions(config); + var connection = await createConnection(config); // if (config.containsKey('charset') && config['charset'] != null) { // var charset = config['charset']; @@ -157,29 +155,22 @@ class PostgresConnector extends Connector implements ConnectorInterface { /// @return \PDO /// Aqui que cria a conexão com o Banco de Dados de fato /// - Future createConnection(String dsn, Map config, - Map options) async { - final username = config['username']; - final password = config['password']; - // var host = config['host']; - // var port = config['port']; //5432 - // var database = config['database']; - // try { - // $pdo = new PDO($dsn, $username, $password, $options); - // } catch (Exception e) { - // $pdo = $this->tryAgainIfCausedByLostConnection( - // $e, $dsn, $username, $password, $options - // ); - // } + Future createConnection(Map config) async { + //print('postgres_connector@createConnection config: $config'); + + if (config.containsKey('schema')) { + config['schema'] = formatSchema(config['schema']); + } + final pdoConfig = PDOConfig.fromMap(config); late PDOInterface pdo; if (config['driver_implementation'] == 'postgres') { - pdo = PostgresPDO(dsn, username, password, options); + pdo = PostgresPDO(pdoConfig); } else if (config['driver_implementation'] == 'postgres_v3') { - pdo = PostgresV3PDO(dsn, username, password, options); + pdo = PostgresV3PDO(pdoConfig); } else if (config['driver_implementation'] == 'dargres') { - pdo = DargresPDO(dsn, username, password, options); + pdo = DargresPDO(pdoConfig); } else { - pdo = PostgresPDO(dsn, username, password, options); + pdo = PostgresPDO(pdoConfig); } await pdo.connect(); return pdo; diff --git a/lib/src/pdo/core/pdo_config.dart b/lib/src/pdo/core/pdo_config.dart new file mode 100644 index 0000000..ed26835 --- /dev/null +++ b/lib/src/pdo/core/pdo_config.dart @@ -0,0 +1,110 @@ +class PDOConfig { + final String driver; + final String host; + final int port; + final String database; + final String? username; + final String? password; + final bool? isUnixSocket; + /// win1252 | utf8 | utf8mb4_general_ci + final String? charset; + + /// enable pool ? + final bool? pool; + final int? poolSize; + String? applicationName; + final bool? allowReconnect; + + /// require | disable + String? sslmode; + /// UTC | America/Sao_Paulo + String? timezone; + String? schema; + + /// If true, decodes the timestamp with timezone (timestamptz) as UTC. + /// If false, decodes the timestamp with timezone using the timezone defined in the connection. + bool forceDecodeTimestamptzAsUTC = true; + + /// If true, decodes the timestamp without timezone (timestamp) as UTC. + /// If false, decodes the timestamp without timezone as local datetime. + bool forceDecodeTimestampAsUTC = true; + + /// If true, decodes the date as UTC. + /// If false, decodes the date as local datetime. + bool forceDecodeDateAsUTC = true; + + PDOConfig({ + required this.driver, + required this.host, + this.port = 5432, + required this.database, + this.username, + this.password, + this.isUnixSocket = false, + this.pool = false, + this.poolSize = 1, + this.applicationName, + this.charset = 'utf8', + this.allowReconnect, + this.sslmode, + this.timezone, + this.schema, + this.forceDecodeTimestamptzAsUTC = true, + this.forceDecodeTimestampAsUTC = true, + this.forceDecodeDateAsUTC = true, + }); + + Map toMap() { + return { + 'driver': driver, + 'host': host, + 'port': port, + 'database': database, + 'username': username, + 'password': password, + 'isUnixSocket': isUnixSocket, + 'charset': charset, + 'pool': pool, + 'poolsize': poolSize, + 'applicationName': applicationName, + 'allowReconnect': allowReconnect, + 'sslmode': sslmode, + 'timezone': timezone, + 'schema': schema, + 'forceDecodeTimestamptzAsUTC': forceDecodeTimestamptzAsUTC, + 'forceDecodeTimestampAsUTC': forceDecodeTimestampAsUTC, + 'forceDecodeDateAsUTC': forceDecodeDateAsUTC, + }; + } + + factory PDOConfig.fromMap(Map map) { + final config = PDOConfig( + driver: map['driver'], + host: map['host'], + port: map['port'] is int ? map['port'] : int.parse(map['port']), + database: map['database'], + username: map['username'], + password: map['password'], + isUnixSocket: map['is_unix_socket'], + charset: map['charset'], + pool: map['pool'], + poolSize: map['poolsize'], + applicationName: map['application_name'], + allowReconnect: map['allowreconnect'], + sslmode: map['sslmode'], + timezone: map['timezone'], + schema: map['schema'], + ); + if (map['forceDecodeTimestamptzAsUTC'] is bool) { + config.forceDecodeTimestamptzAsUTC = map['forceDecodeTimestamptzAsUTC']; + } + if (map['forceDecodeTimestampAsUTC'] is bool) { + config.forceDecodeTimestampAsUTC = map['forceDecodeTimestampAsUTC']; + } + if (map['forceDecodeDateAsUTC'] is bool) { + config.forceDecodeDateAsUTC = map['forceDecodeDateAsUTC']; + } + + return config; + } +} diff --git a/lib/src/pdo/dargres/dargres_pdo.dart b/lib/src/pdo/dargres/dargres_pdo.dart index bd5ef57..12b164a 100644 --- a/lib/src/pdo/dargres/dargres_pdo.dart +++ b/lib/src/pdo/dargres/dargres_pdo.dart @@ -1,5 +1,4 @@ import 'package:dargres/dargres.dart' as dargres; -import 'package:eloquent/src/utils/dsn_parser.dart'; import 'package:eloquent/eloquent.dart'; import 'dargres_pdo_transaction.dart'; @@ -7,24 +6,17 @@ class DargresPDO extends PDOInterface { /// default query Timeout = 30 seconds static const defaultTimeout = const Duration(seconds: 30); - String dsn; - String user; - String password; - String dbname = ''; - int port = 5432; - String driver = 'pgsql'; - String host = 'localhost'; - dynamic attributes; + PDOConfig config; /// Creates a PDO instance representing a connection to a database /// Example /// - /// var dsn = "pgsql:host=$host;port=5432;dbname=$db;"; - /// Example: "pgsql:host=$host;dbname=$db;charset=utf8"; - /// var pdo = new PDO($dsn, $user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); + /// + /// Example: Map config = {'host': 'localhost','port':5432,'database':'teste'}; + /// var pdo = new PDO(PDOConfig.fromMap(config)); /// await pdo.connect(); /// - DargresPDO(this.dsn, this.user, this.password, [this.attributes]) { + DargresPDO(this.config) { super.pdoInstance = this; } @@ -33,30 +25,35 @@ class DargresPDO extends PDOInterface { //called from postgres_connector.dart Future connect() async { - final dsnParser = DSNParser(dsn, DsnType.pdoPostgreSql); + final timeZone = dargres.TimeZoneSettings(config.timezone ?? 'UTC'); + timeZone.forceDecodeTimestamptzAsUTC = config.forceDecodeTimestamptzAsUTC; + timeZone.forceDecodeTimestampAsUTC = config.forceDecodeTimestampAsUTC; + timeZone.forceDecodeDateAsUTC = config.forceDecodeDateAsUTC; - if (dsnParser.pool == true) { + if (config.pool == true) { final settings = dargres.ConnectionSettings( - user: user, - database: dsnParser.database, - host: dsnParser.host, - port: dsnParser.port, - password: password, - textCharset: dsnParser.charset ?? 'utf8', - applicationName: dsnParser.applicationName, + user: config.username ?? '', + database: config.database, + host: config.host, + port: config.port, + password: config.password, + textCharset: config.charset ?? 'utf8', + applicationName: config.applicationName, allowAttemptToReconnect: false, + timeZone: timeZone, ); - connection = dargres.PostgreSqlPool(dsnParser.poolSize, settings, - allowAttemptToReconnect: dsnParser.allowReconnect); + connection = dargres.PostgreSqlPool(config.poolSize ?? 1, settings, + allowAttemptToReconnect: config.allowReconnect ?? false); } else { - connection = dargres.CoreConnection(user, - database: dsnParser.database, - host: dsnParser.host, - port: dsnParser.port, - password: password, + connection = dargres.CoreConnection(config.username ?? '', + database: config.database, + host: config.host, + port: config.port, + password: config.password, allowAttemptToReconnect: false, // sslContext: sslContext, - textCharset: dsnParser.charset ?? 'utf8'); + textCharset: config.charset ?? 'utf8', + timeZone: timeZone); await connection!.connect(); } diff --git a/lib/src/pdo/mysql_client/mysql_client_pdo.dart b/lib/src/pdo/mysql_client/mysql_client_pdo.dart index fc19c2a..7705a0d 100644 --- a/lib/src/pdo/mysql_client/mysql_client_pdo.dart +++ b/lib/src/pdo/mysql_client/mysql_client_pdo.dart @@ -1,6 +1,7 @@ +import 'package:eloquent/src/pdo/core/pdo_config.dart'; import 'package:eloquent/src/pdo/core/pdo_interface.dart'; import 'package:eloquent/src/pdo/core/pdo_result.dart'; -import 'package:eloquent/src/utils/dsn_parser.dart'; + import 'package:mysql_client/mysql_client.dart'; import 'mysql_client_pdo_transaction.dart'; @@ -8,24 +9,17 @@ class MySqlClientPDO extends PDOInterface { /// default query Timeout = 30 seconds static const defaultTimeoutInSeconds = 30; - String dsn; - String user; - String password; - String dbname = ''; - int port = 3306; - String driver = 'mysql_client'; - String host = 'localhost'; - Map? attributes; + PDOConfig config; /// Creates a PDO instance representing a connection to a database /// Example /// - /// var dsn = "mysql:host=localhost;port=3306;dbname=banco_teste;"; - /// Example: "mysql:host=localhost;port=3306;dbname=banco_teste;"; - /// var pdo = new PDO($dsn, $user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); + /// + /// Example: Map config = {'host': 'localhost','port':5432,'database':'teste'}; + /// var pdo = new PDO(PDOConfig.fromMap(config)); /// await pdo.connect(); /// - MySqlClientPDO(this.dsn, this.user, this.password, [this.attributes]) { + MySqlClientPDO(this.config) { super.pdoInstance = this; } @@ -34,40 +28,31 @@ class MySqlClientPDO extends PDOInterface { //called from postgres_connector.dart Future 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) { + if (config.pool == true) { connection = MySQLConnectionPool( - host: dsnParser.host, - port: dsnParser.port, - databaseName: dsnParser.database, - userName: user, - password: password, - collation: dsnParser.charset ?? 'utf8mb4_general_ci', - maxConnections: dsnParser.poolSize, - secure: dsnParser.sslmode?.toString() == 'require', + host: config.host, + port: config.port, + databaseName: config.database, + userName: config.username ?? '', + password: config.password, + collation: config.charset ?? 'utf8mb4_general_ci', + maxConnections: config.poolSize ?? 1, + secure: config.sslmode?.toString() == 'require', ); } else { connection = await MySQLConnection.createConnection( - host: dsnParser.host, - port: dsnParser.port, - databaseName: dsnParser.database, - userName: user, - password: password, - collation: dsnParser.charset ?? 'utf8mb4_general_ci', - secure: dsnParser.sslmode?.toString() == 'require', + host: config.host, + port: config.port, + databaseName: config.database, + userName: config.username ?? '', + password: config.password ?? '', + collation: config.charset ?? 'utf8mb4_general_ci', + secure: config.sslmode?.toString() == 'require', ); } if (connection is MySQLConnection) { await (connection as MySQLConnection).connect(); } - //else if(connection is MySQLConnectionPool){ - //await (connection as MySQLConnectionPool).; - //} return this; } diff --git a/lib/src/pdo/postgres/dependencies/postgres_pool/postgres_pool.dart b/lib/src/pdo/postgres/dependencies/postgres_pool/postgres_pool.dart index 7b89157..1ae9606 100644 --- a/lib/src/pdo/postgres/dependencies/postgres_pool/postgres_pool.dart +++ b/lib/src/pdo/postgres/dependencies/postgres_pool/postgres_pool.dart @@ -281,7 +281,7 @@ class PgPoolSettings { int maxQueryCount = 1024 * 1024; /// Timezone for the connetion - String timeZone = 'UTC'; + TimeZoneSettings timeZone = TimeZoneSettings('UTC'); Encoding encoding = utf8; @@ -501,7 +501,7 @@ class PgPool implements PostgreSQLExecutionContext { isUnixSocket: _url.isUnixSocket, timeoutInSeconds: settings.connectTimeout.inSeconds, queryTimeoutInSeconds: settings.queryTimeout.inSeconds, - timeZone: TimeZoneSettings(settings.timeZone), + timeZone: settings.timeZone, encoding: settings.encoding, ); await c.open(); diff --git a/lib/src/pdo/postgres/postgres_pdo.dart b/lib/src/pdo/postgres/postgres_pdo.dart index 001affd..1ae53c4 100644 --- a/lib/src/pdo/postgres/postgres_pdo.dart +++ b/lib/src/pdo/postgres/postgres_pdo.dart @@ -1,5 +1,5 @@ import 'dart:convert'; -import 'package:eloquent/src/utils/dsn_parser.dart'; + import 'package:eloquent/eloquent.dart'; import 'package:enough_convert/windows.dart'; import 'postgres_pdo_transaction.dart'; @@ -11,24 +11,17 @@ class PostgresPDO extends PDOInterface { /// default query Timeout = 30 seconds static const defaultTimeoutInSeconds = 30; - String dsn; - String user; - String password; - String dbname = ''; - int port = 5432; - String driver = 'pgsql'; - String host = 'localhost'; - dynamic attributes; + PDOConfig config; /// Creates a PDO instance representing a connection to a database /// Example /// - /// var dsn = "pgsql:host=$host;port=5432;dbname=$db;"; - /// Example: "pgsql:host=$host;dbname=$db;charset=utf8"; - /// var pdo = new PDO($dsn, $user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); + /// + /// Example: Map config = {'host': 'localhost','port':5432,'database':'teste'}; + /// var pdo = new PDO(PDOConfig.fromMap(config)); /// await pdo.connect(); /// - PostgresPDO(this.dsn, this.user, this.password, [this.attributes]) { + PostgresPDO(this.config) { super.pdoInstance = this; } @@ -55,56 +48,59 @@ class PostgresPDO extends PDOInterface { //called from postgres_connector.dart Future connect() async { - final dsnParser = DSNParser(dsn, DsnType.pdoPostgreSql); + final timeZone = TimeZoneSettings(config.timezone ?? 'UTC'); + timeZone.forceDecodeTimestamptzAsUTC = config.forceDecodeTimestamptzAsUTC; + timeZone.forceDecodeTimestampAsUTC = config.forceDecodeTimestampAsUTC; + timeZone.forceDecodeDateAsUTC = config.forceDecodeDateAsUTC; - if (dsnParser.pool == true) { + if (config.pool == true) { final endpoint = PgEndpoint( - host: dsnParser.host, - port: dsnParser.port, - database: dsnParser.database, - username: user, - password: password, + host: config.host, + port: config.port, + database: config.database, + username: config.username, + password: config.password, ); final settings = PgPoolSettings(); - settings.encoding = _getEncoding(dsnParser.charset ?? 'utf8'); - settings.maxConnectionCount = dsnParser.poolSize; + settings.encoding = _getEncoding(config.charset ?? 'utf8'); + settings.maxConnectionCount = config.poolSize ?? 1; settings.onOpen = (conn) async { - await _onOpen(conn, dsnParser); + await _onOpen(conn, config); }; + settings.timeZone = timeZone; connection = PgPool(endpoint, settings: settings); //print('dsnParser.pool ${dsnParser.pool} $connection'); } else { connection = PostgreSQLConnection( - dsnParser.host, - dsnParser.port, - dsnParser.database, - username: user, - password: password, - encoding: _getEncoding(dsnParser.charset ?? 'utf8'), + config.host, + config.port, + config.database, + username: config.username, + password: config.password, + timeZone: timeZone, + encoding: _getEncoding(config.charset ?? 'utf8'), ); final conn = connection as PostgreSQLConnection; await conn.open(); - await _onOpen(conn, dsnParser); + await _onOpen(conn, config); } return this; } /// inicializa configurações ao conectar com o banco de dados - Future _onOpen( - PostgreSQLExecutionContext conn, DSNParser dsnParser) async { - if (dsnParser.charset != null) { - await conn.execute("SET client_encoding = '${dsnParser.charset}'"); + Future _onOpen(PostgreSQLExecutionContext conn, PDOConfig conf) async { + if (conf.charset != null) { + await conn.execute("SET client_encoding = '${conf.charset}'"); } - if (dsnParser.schema != null) { - await conn.execute("SET search_path TO ${dsnParser.schema}"); + if (conf.schema != null) { + await conn.execute("SET search_path TO ${conf.schema}"); } - if (dsnParser.timezone != null) { - await conn.execute("SET timezone TO '${dsnParser.timezone}'"); + if (conf.timezone != null) { + await conn.execute("SET timezone TO '${conf.timezone}'"); } - if (dsnParser.applicationName != null) { - await conn - .execute("SET application_name TO '${dsnParser.applicationName}'"); + if (conf.applicationName != null) { + await conn.execute("SET application_name TO '${conf.applicationName}'"); } } diff --git a/lib/src/pdo/postgres_v3/postgres_v3_pdo.dart b/lib/src/pdo/postgres_v3/postgres_v3_pdo.dart index 4fc3484..01e03a8 100644 --- a/lib/src/pdo/postgres_v3/postgres_v3_pdo.dart +++ b/lib/src/pdo/postgres_v3/postgres_v3_pdo.dart @@ -1,7 +1,9 @@ import 'dart:convert'; + +import 'package:eloquent/src/pdo/core/pdo_config.dart'; import 'package:eloquent/src/pdo/core/pdo_interface.dart'; import 'package:eloquent/src/pdo/core/pdo_result.dart'; -import 'package:eloquent/src/utils/dsn_parser.dart'; + import 'package:enough_convert/windows.dart'; import 'package:postgres/postgres.dart'; import 'postgres_v3_pdo_transaction.dart'; @@ -10,24 +12,17 @@ class PostgresV3PDO extends PDOInterface { /// default query Timeout = 30 seconds static const defaultTimeoutInSeconds = 30; - String dsn; - String user; - String password; - String dbname = ''; - int port = 5432; - String driver = 'pgsql'; - String host = 'localhost'; - Map? attributes; + PDOConfig config; /// Creates a PDO instance representing a connection to a database /// Example /// - /// var dsn = "pgsql:host=$host;port=5432;dbname=$db;"; - /// Example: "pgsql:host=$host;dbname=$db;charset=utf8"; - /// var pdo = new PDO($dsn, $user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); + /// + /// Example: Map config = {'host': 'localhost','port':5432,'database':'teste'}; + /// var pdo = new PDO(PDOConfig.fromMap(config)); /// await pdo.connect(); /// - PostgresV3PDO(this.dsn, this.user, this.password, [this.attributes]) { + PostgresV3PDO(this.config) { super.pdoInstance = this; } @@ -54,43 +49,46 @@ class PostgresV3PDO extends PDOInterface { //called from postgres_connector.dart Future connect() async { - final dsnParser = DSNParser(dsn, DsnType.pdoPostgreSql); - final endpoint = Endpoint( - host: dsnParser.host, - port: dsnParser.port, - database: dsnParser.database, - username: user, - password: password, + host: config.host, + port: config.port, + database: config.database, + username: config.username, + password: config.password, ); - final sslMode = dsnParser.sslmode?.toString() == 'require' + final sslMode = config.sslmode?.toString() == 'require' ? SslMode.require : SslMode.disable; - if (dsnParser.pool == true) { + final timeZone = TimeZoneSettings(config.timezone ?? 'UTC'); + timeZone.forceDecodeTimestamptzAsUTC = config.forceDecodeTimestamptzAsUTC; + timeZone.forceDecodeTimestampAsUTC = config.forceDecodeTimestampAsUTC; + timeZone.forceDecodeDateAsUTC = config.forceDecodeDateAsUTC; + + if (config.pool == true) { connection = Pool.withEndpoints( [endpoint], settings: PoolSettings( - applicationName: dsnParser.applicationName, - timeZone: TimeZoneSettings(dsnParser.timezone ?? 'UTC'), + applicationName: config.applicationName, + timeZone: timeZone, onOpen: (conn) async { - await _onOpen(conn, dsnParser); + await _onOpen(conn, config); }, - maxConnectionCount: dsnParser.poolSize, - encoding: _getEncoding(dsnParser.charset ?? 'utf8'), + maxConnectionCount: config.poolSize, + encoding: _getEncoding(config.charset ?? 'utf8'), sslMode: sslMode, ), ); } else { connection = await Connection.open(endpoint, settings: ConnectionSettings( - applicationName: dsnParser.applicationName, - timeZone: TimeZoneSettings(dsnParser.timezone ?? 'UTC'), + applicationName: config.applicationName, + timeZone: timeZone, onOpen: (conn) async { - await _onOpen(conn, dsnParser); + await _onOpen(conn, config); }, - encoding: _getEncoding(dsnParser.charset ?? 'utf8'), + encoding: _getEncoding(config.charset ?? 'utf8'), sslMode: sslMode, )); } @@ -99,7 +97,7 @@ class PostgresV3PDO extends PDOInterface { } /// inicializa configurações ao conectar com o banco de dados - Future _onOpen(Connection conn, DSNParser dsnParser) async { + Future _onOpen(Connection conn, PDOConfig dsnParser) async { if (dsnParser.charset != null) { await conn.execute("SET client_encoding = '${dsnParser.charset}'"); } diff --git a/pubspec.yaml b/pubspec.yaml index 319496c..17d3abc 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -10,30 +10,30 @@ environment: dependencies: intl: '>=0.17.0 <3.0.0' #dargres: ^2.2.4 - dargres: ^3.1.0 - # dargres: - # path: ../dargres - - enough_convert: '>=1.6.0 <2.0.0' - + dargres: ^3.1.2 + #dargres: + #path: ../dargres + enough_convert: '>=1.6.0 <2.0.0' #postgres: #path: ../postgresql-dart # postgres v2 - postgres_fork: ^2.8.0 - # postgres_fork: - # path: ../postgresql-fork - + postgres_fork: ^2.8.3 + #postgres_fork: + #path: ../postgresql-fork mysql_client: ^0.0.27 # postgres v3 #postgres: ^3.1.2 - # postgres: - # path: ../postgresql-v3 + #postgres: + #path: ../postgresql-v3 postgres: git: ref: master url: https://github.com/insinfo/postgresql-dart.git +# dependency_overrides: +# pg_timezone: +# path: ../pg_timezone dev_dependencies: test: ^1.17.12