-
Notifications
You must be signed in to change notification settings - Fork 1
/
Connection.php
504 lines (435 loc) · 10 KB
/
Connection.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
<?php
/*
* This file is part of the ICanBoogie package.
*
* (c) Olivier Laviale <olivier.laviale@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ICanBoogie\ActiveRecord;
use ICanBoogie\Accessor\AccessorTrait;
use ICanBoogie\ActiveRecord\ConnectionOptions as Options;
/**
* A connection to a database.
*
* @property-read string $charset The character set used to communicate with the database. Defaults to "utf8".
* @property-read string $collate The collation of the character set. Defaults to "utf8_general_ci".
* @property-read Driver $driver
* @property-read string $driver_name Name of the PDO driver.
* @property-read string $id Identifier of the database connection.
* @property-read string $table_name_prefix The prefix to prepend to every table name.
*/
class Connection extends \PDO implements Driver
{
use AccessorTrait;
static private $drivers_mapping = [
'mysql' => Driver\MySQLDriver::class,
'sqlite' => Driver\SQLiteDriver::class
];
/**
* Connection identifier.
*
* @var string
*/
private $id;
/**
* @return string
*/
protected function get_id(): string
{
return $this->id;
}
/**
* Prefix to prepend to every table name.
*
* If set to "dev", all table names will be named like "dev_nodes", "dev_contents", etc.
* This is a convenient way of creating a namespace for tables in a shared database.
* By default, the prefix is the empty string, that is there is not prefix.
*
* @var string
*/
private $table_name_prefix = Options::DEFAULT_TABLE_NAME_PREFIX;
/**
* @return string
*/
protected function get_table_name_prefix(): string
{
return $this->table_name_prefix;
}
/**
* Charset for the connection. Also used to specify the charset while creating tables.
*
* @var string
*/
private $charset = Options::DEFAULT_CHARSET;
/**
* @return string
*/
protected function get_charset(): string
{
return $this->charset;
}
/**
* Used to specify the collate while creating tables.
*
* @var string
*/
private $collate = Options::DEFAULT_COLLATE;
/**
* @return string
*/
protected function get_collate(): string
{
return $this->collate;
}
/**
* Timezone of the connection.
*
* @var string
*/
private $timezone = Options::DEFAULT_TIMEZONE;
/**
* @return string
*/
protected function get_timezone(): string
{
return $this->timezone;
}
/**
* Driver name for the connection.
*
* @var string
*/
private $driver_name;
/**
* @return string
*/
protected function get_driver_name(): string
{
return $this->driver_name;
}
/**
* @var Driver
*/
private $driver;
/**
* @return Driver
*/
protected function lazy_get_driver(): Driver
{
return $this->resolve_driver($this->driver_name);
}
/**
* The number of database queries and executions, used for statistics purpose.
*
* @var int
*/
public $queries_count = 0;
/**
* The number of micro seconds spent per request.
*
* @var array[]
*/
public $profiling = [];
/**
* Establish a connection to a database.
*
* Custom options can be specified using the driver-specific connection options. See
* {@link Options}.
*
* @link http://www.php.net/manual/en/pdo.construct.php
* @link http://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html
*
* @param string $dsn
* @param string $username
* @param string $password
* @param array $options
*/
public function __construct(string $dsn, string $username = null, string $password = null, array $options = [])
{
unset($this->driver);
$this->driver_name = $this->resolve_driver_name($dsn);
$this->apply_options($options);
$this->before_connection($options);
parent::__construct($dsn, $username, $password, $options);
$this->after_connection();
}
/**
* Alias to {@link query}.
*
* @param array ...$args
*
* @return Statement
*/
public function __invoke(...$args): Statement
{
return $this->query(...$args);
}
/**
* Resolve the driver name from the DSN string.
*
* @param string $dsn
*
* @return string
*/
protected function resolve_driver_name(string $dsn): string
{
return explode(':', $dsn, 2)[0];
}
/**
* Resolves driver class.
*
* @param string $driver_name
*
* @return string
*
* @throws DriverNotDefined
*/
protected function resolve_driver_class(string $driver_name): string
{
if (empty(self::$drivers_mapping[$driver_name]))
{
throw new DriverNotDefined($driver_name);
}
return self::$drivers_mapping[$driver_name];
}
/**
* Resolves a {@link Driver} implementation.
*
* @param string $driver_name
*
* @return Driver
*/
protected function resolve_driver(string $driver_name): Driver
{
$driver_class = $this->resolve_driver_class($driver_name);
return new $driver_class(function() { return $this; });
}
/**
* Applies options to the instance.
*
* @param array $options
*/
protected function apply_options(array $options)
{
$options = Options::normalize($options);
$this->id = $options[Options::ID];
$this->table_name_prefix = $options[Options::TABLE_NAME_PREFIX];
if ($this->table_name_prefix)
{
$this->table_name_prefix .= '_';
}
list($this->charset, $this->collate) = extract_charset_and_collate($options[Options::CHARSET_AND_COLLATE]);
$this->timezone = $options[Options::TIMEZONE];
}
/**
* Called before the connection.
*
* May alter the options according to the driver.
*
* @param array $options
*/
protected function before_connection(array &$options)
{
if ($this->driver_name != 'mysql')
{
return;
}
$init_command = 'SET NAMES ' . $this->charset;
if ($this->timezone)
{
$init_command .= ', time_zone = "' . $this->timezone . '"';
}
$options += [
self::MYSQL_ATTR_INIT_COMMAND => $init_command
];
}
protected function after_connection()
{
$this->setAttribute(self::ATTR_ERRMODE, self::ERRMODE_EXCEPTION);
$this->setAttribute(self::ATTR_STATEMENT_CLASS, [ Statement::class ]);
}
/**
* Overrides the method to resolve the statement before it is prepared, then set its fetch
* mode and connection.
*
* @inheritdoc
*
* @throws StatementNotValid if the statement cannot be prepared.
*/
public function prepare($statement, $options = [])
{
$statement = $this->resolve_statement($statement);
try
{
/* @var $statement Statement */
$statement = parent::prepare($statement, $options);
}
catch (\PDOException $e)
{
throw new StatementNotValid($statement, 500, $e);
}
$statement->connection = $this;
if (isset($options['mode']))
{
$mode = (array) $options['mode'];
$statement->mode(...$mode);
}
return $statement;
}
/**
* Overrides the method in order to prepare (and resolve) the statement and execute it with
* the specified arguments and options.
*
* @inheritdoc
*
* @return Statement
*/
public function query(string $statement, array $args = [], array $options = []): Statement
{
$statement = $this->prepare($statement, $options);
$statement->execute($args);
return $statement;
}
/**
* Executes a statement.
*
* The statement is resolved using the {@link resolve_statement()} method before it is
* executed.
*
* The execution of the statement is wrapped in a try/catch block. {@link PDOException} are
* caught and {@link StatementNotValid} exception are thrown with additional information
* instead.
*
* Using this method increments the `queries_by_connection` stat.
*
* @inheritdoc
*
* @throws StatementNotValid if the statement cannot be executed.
*/
public function exec($statement)
{
$statement = $this->resolve_statement($statement);
try
{
$this->queries_count++;
return parent::exec($statement);
}
catch (\PDOException $e)
{
throw new StatementNotValid($statement, 500, $e);
}
}
/**
* Replaces placeholders with their value.
*
* The following placeholders are supported:
*
* - `{prefix}`: replaced by the {@link $table_name_prefix} property.
* - `{charset}`: replaced by the {@link $charset} property.
* - `{collate}`: replaced by the {@link $collate} property.
*
* @param string $statement
*
* @return string The resolved statement.
*/
public function resolve_statement(string $statement): string
{
return strtr($statement, [
'{prefix}' => $this->table_name_prefix,
'{charset}' => $this->charset,
'{collate}' => $this->collate
]);
}
/**
* Alias for the `beginTransaction()` method.
*
* @see \PDO::beginTransaction()
*/
public function begin()
{
return $this->beginTransaction();
}
/**
* @inheritdoc
*
* @codeCoverageIgnore
*/
public function quote_string($string)
{
return $this->driver->quote_string($string);
}
/**
* @inheritdoc
*
* @codeCoverageIgnore
*/
public function quote_identifier($identifier)
{
return $this->driver->quote_identifier($identifier);
}
/**
* @inheritdoc
*
* @codeCoverageIgnore
*/
public function cast_value($value, string $type = null)
{
return $this->driver->cast_value($value, $type);
}
/**
* @inheritdoc
*
* @codeCoverageIgnore
*/
public function render_column(SchemaColumn $column): string
{
return $this->driver->render_column($column);
}
/**
* @inheritdoc
*
* @codeCoverageIgnore
*/
public function create_table(string $unprefixed_name, Schema $schema)
{
$this->driver->create_table($unprefixed_name, $schema);
}
/**
* @inheritdoc
*
* @codeCoverageIgnore
*/
public function create_indexes(string $unprefixed_table_name, Schema $schema)
{
$this->driver->create_indexes($unprefixed_table_name, $schema);
}
/**
* @inheritdoc
*
* @codeCoverageIgnore
*/
public function create_unique_indexes(string $unprefixed_table_name, Schema $schema)
{
$this->driver->create_unique_indexes($unprefixed_table_name, $schema);
}
/**
* @inheritdoc
*
* @codeCoverageIgnore
*/
public function table_exists(string $unprefixed_name): bool
{
return $this->driver->table_exists($unprefixed_name);
}
/**
* @inheritdoc
*
* @codeCoverageIgnore
*/
public function optimize()
{
$this->driver->optimize();
}
}