Skip to content

Commit

Permalink
add option to decode timestamp without timezone and date as local Dat…
Browse files Browse the repository at this point in the history
…eTime and decode timestamp with timezone respecting the timezone defined in the connection
  • Loading branch information
Isaque Neves committed Jul 24, 2024
1 parent dd67289 commit b670e5e
Show file tree
Hide file tree
Showing 15 changed files with 361 additions and 218 deletions.
31 changes: 30 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
- 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',
});
```
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,4 +240,40 @@ void main(List<String> 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',
});
```
34 changes: 27 additions & 7 deletions example/bin/postgre_v2_example.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ void main(List<String> 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',
Expand All @@ -19,14 +26,27 @@ void main(List<String> 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);
}
4 changes: 1 addition & 3 deletions lib/eloquent.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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';
6 changes: 5 additions & 1 deletion lib/src/capsule/manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,11 @@ class Manager {
/// @param array $config
/// @param string $name
/// @return void
///
///
/// ```dart
///
/// ```
///
void addConnection(Map<String, dynamic> config, [String name = 'default']) {
var connections = this.container['config']['database.connections'];
if (connections == null) {
Expand Down
16 changes: 1 addition & 15 deletions lib/src/connectors/connector.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ abstract class Connector with DetectsLostConnections {
///
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) {
Expand All @@ -33,18 +32,5 @@ abstract class Connector with DetectsLostConnections {
/// @param array $options
/// @return \PDO
///
dynamic createConnection(
String dsn, Map<String, dynamic> config, Map<String, dynamic> 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<String, dynamic> config);
}
19 changes: 6 additions & 13 deletions lib/src/connectors/mysql_connector.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,9 @@ class MySqlConnector extends Connector implements ConnectorInterface {
/// @return PostgreSQLConnection \PDO
///
Future<PDOInterface> connect(Map<String, dynamic> 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']}`;");
Expand Down Expand Up @@ -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<PDOInterface> createConnection(String dsn, Map<dynamic, dynamic> config,
Map<dynamic, dynamic> options) async {
final username = config['username'];
final password = config['password'];

Future<PDOInterface> createConnection(Map<String, dynamic> 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();

Expand Down
37 changes: 14 additions & 23 deletions lib/src/connectors/postgres_connector.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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'];
Expand Down Expand Up @@ -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<PDOInterface> createConnection(String dsn, Map<String, dynamic> config,
Map<dynamic, dynamic> 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<PDOInterface> createConnection(Map<String, dynamic> 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;
Expand Down
110 changes: 110 additions & 0 deletions lib/src/pdo/core/pdo_config.dart
Original file line number Diff line number Diff line change
@@ -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<String, dynamic> toMap() {
return <String, dynamic>{
'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<String, dynamic> 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;
}
}
Loading

0 comments on commit b670e5e

Please sign in to comment.