-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Connection.php
1671 lines (1456 loc) · 49.3 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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Doctrine\DBAL;
use Closure;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Cache\ArrayStatement;
use Doctrine\DBAL\Cache\CacheException;
use Doctrine\DBAL\Cache\QueryCacheProfile;
use Doctrine\DBAL\Cache\ResultCacheStatement;
use Doctrine\DBAL\Driver\Connection as DriverConnection;
use Doctrine\DBAL\Driver\PingableConnection;
use Doctrine\DBAL\Driver\ResultStatement;
use Doctrine\DBAL\Driver\ServerInfoAwareConnection;
use Doctrine\DBAL\Driver\Statement as DriverStatement;
use Doctrine\DBAL\Exception\InvalidArgumentException;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Query\Expression\ExpressionBuilder;
use Doctrine\DBAL\Query\QueryBuilder;
use Doctrine\DBAL\Schema\AbstractSchemaManager;
use Doctrine\DBAL\Types\Type;
use Exception;
use Throwable;
use function array_key_exists;
use function assert;
use function func_get_args;
use function implode;
use function is_int;
use function is_string;
use function key;
/**
* A wrapper around a Doctrine\DBAL\Driver\Connection that adds features like
* events, transaction isolation levels, configuration, emulated transaction nesting,
* lazy connecting and more.
*/
class Connection implements DriverConnection
{
/**
* Constant for transaction isolation level READ UNCOMMITTED.
*
* @deprecated Use TransactionIsolationLevel::READ_UNCOMMITTED.
*/
public const TRANSACTION_READ_UNCOMMITTED = TransactionIsolationLevel::READ_UNCOMMITTED;
/**
* Constant for transaction isolation level READ COMMITTED.
*
* @deprecated Use TransactionIsolationLevel::READ_COMMITTED.
*/
public const TRANSACTION_READ_COMMITTED = TransactionIsolationLevel::READ_COMMITTED;
/**
* Constant for transaction isolation level REPEATABLE READ.
*
* @deprecated Use TransactionIsolationLevel::REPEATABLE_READ.
*/
public const TRANSACTION_REPEATABLE_READ = TransactionIsolationLevel::REPEATABLE_READ;
/**
* Constant for transaction isolation level SERIALIZABLE.
*
* @deprecated Use TransactionIsolationLevel::SERIALIZABLE.
*/
public const TRANSACTION_SERIALIZABLE = TransactionIsolationLevel::SERIALIZABLE;
/**
* Represents an array of ints to be expanded by Doctrine SQL parsing.
*/
public const PARAM_INT_ARRAY = ParameterType::INTEGER + self::ARRAY_PARAM_OFFSET;
/**
* Represents an array of strings to be expanded by Doctrine SQL parsing.
*/
public const PARAM_STR_ARRAY = ParameterType::STRING + self::ARRAY_PARAM_OFFSET;
/**
* Offset by which PARAM_* constants are detected as arrays of the param type.
*/
public const ARRAY_PARAM_OFFSET = 100;
/**
* The wrapped driver connection.
*
* @var \Doctrine\DBAL\Driver\Connection|null
*/
protected $_conn;
/** @var Configuration */
protected $_config;
/** @var EventManager */
protected $_eventManager;
/** @var ExpressionBuilder */
protected $_expr;
/**
* Whether or not a connection has been established.
*
* @var bool
*/
private $isConnected = false;
/**
* The current auto-commit mode of this connection.
*
* @var bool
*/
private $autoCommit = true;
/**
* The transaction nesting level.
*
* @var int
*/
private $transactionNestingLevel = 0;
/**
* The currently active transaction isolation level.
*
* @var int
*/
private $transactionIsolationLevel;
/**
* If nested transactions should use savepoints.
*
* @var bool
*/
private $nestTransactionsWithSavepoints = false;
/**
* The parameters used during creation of the Connection instance.
*
* @var mixed[]
*/
private $params = [];
/**
* The DatabasePlatform object that provides information about the
* database platform used by the connection.
*
* @var AbstractPlatform
*/
private $platform;
/**
* The schema manager.
*
* @var AbstractSchemaManager|null
*/
protected $_schemaManager;
/**
* The used DBAL driver.
*
* @var Driver
*/
protected $_driver;
/**
* Flag that indicates whether the current transaction is marked for rollback only.
*
* @var bool
*/
private $isRollbackOnly = false;
/** @var int */
protected $defaultFetchMode = FetchMode::ASSOCIATIVE;
/**
* Initializes a new instance of the Connection class.
*
* @param mixed[] $params The connection parameters.
* @param Driver $driver The driver to use.
* @param Configuration|null $config The configuration, optional.
* @param EventManager|null $eventManager The event manager, optional.
*
* @throws DBALException
*/
public function __construct(
array $params,
Driver $driver,
?Configuration $config = null,
?EventManager $eventManager = null
) {
$this->_driver = $driver;
$this->params = $params;
if (isset($params['pdo'])) {
$this->_conn = $params['pdo'];
$this->isConnected = true;
unset($this->params['pdo']);
}
if (isset($params['platform'])) {
if (! $params['platform'] instanceof Platforms\AbstractPlatform) {
throw DBALException::invalidPlatformType($params['platform']);
}
$this->platform = $params['platform'];
unset($this->params['platform']);
}
// Create default config and event manager if none given
if (! $config) {
$config = new Configuration();
}
if (! $eventManager) {
$eventManager = new EventManager();
}
$this->_config = $config;
$this->_eventManager = $eventManager;
$this->_expr = new Query\Expression\ExpressionBuilder($this);
$this->autoCommit = $config->getAutoCommit();
}
/**
* Gets the parameters used during instantiation.
*
* @return mixed[]
*/
public function getParams()
{
return $this->params;
}
/**
* Gets the name of the database this Connection is connected to.
*
* @return string
*/
public function getDatabase()
{
return $this->_driver->getDatabase($this);
}
/**
* Gets the hostname of the currently connected database.
*
* @return string|null
*/
public function getHost()
{
return $this->params['host'] ?? null;
}
/**
* Gets the port of the currently connected database.
*
* @return mixed
*/
public function getPort()
{
return $this->params['port'] ?? null;
}
/**
* Gets the username used by this connection.
*
* @return string|null
*/
public function getUsername()
{
return $this->params['user'] ?? null;
}
/**
* Gets the password used by this connection.
*
* @return string|null
*/
public function getPassword()
{
return $this->params['password'] ?? null;
}
/**
* Gets the DBAL driver instance.
*
* @return Driver
*/
public function getDriver()
{
return $this->_driver;
}
/**
* Gets the Configuration used by the Connection.
*
* @return Configuration
*/
public function getConfiguration()
{
return $this->_config;
}
/**
* Gets the EventManager used by the Connection.
*
* @return EventManager
*/
public function getEventManager()
{
return $this->_eventManager;
}
/**
* Gets the DatabasePlatform for the connection.
*
* @return AbstractPlatform
*
* @throws DBALException
*/
public function getDatabasePlatform()
{
if ($this->platform === null) {
$this->detectDatabasePlatform();
}
return $this->platform;
}
/**
* Gets the ExpressionBuilder for the connection.
*
* @return ExpressionBuilder
*/
public function getExpressionBuilder()
{
return $this->_expr;
}
/**
* Establishes the connection with the database.
*
* @return bool TRUE if the connection was successfully established, FALSE if
* the connection is already open.
*/
public function connect()
{
if ($this->isConnected) {
return false;
}
$driverOptions = $this->params['driverOptions'] ?? [];
$user = $this->params['user'] ?? null;
$password = $this->params['password'] ?? null;
$this->_conn = $this->_driver->connect($this->params, $user, $password, $driverOptions);
$this->isConnected = true;
if ($this->autoCommit === false) {
$this->beginTransaction();
}
if ($this->_eventManager->hasListeners(Events::postConnect)) {
$eventArgs = new Event\ConnectionEventArgs($this);
$this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
}
return true;
}
/**
* Detects and sets the database platform.
*
* Evaluates custom platform class and version in order to set the correct platform.
*
* @throws DBALException If an invalid platform was specified for this connection.
*/
private function detectDatabasePlatform()
{
$version = $this->getDatabasePlatformVersion();
if ($version !== null) {
assert($this->_driver instanceof VersionAwarePlatformDriver);
$this->platform = $this->_driver->createDatabasePlatformForVersion($version);
} else {
$this->platform = $this->_driver->getDatabasePlatform();
}
$this->platform->setEventManager($this->_eventManager);
}
/**
* Returns the version of the related platform if applicable.
*
* Returns null if either the driver is not capable to create version
* specific platform instances, no explicit server version was specified
* or the underlying driver connection cannot determine the platform
* version without having to query it (performance reasons).
*
* @return string|null
*
* @throws Exception
*/
private function getDatabasePlatformVersion()
{
// Driver does not support version specific platforms.
if (! $this->_driver instanceof VersionAwarePlatformDriver) {
return null;
}
// Explicit platform version requested (supersedes auto-detection).
if (isset($this->params['serverVersion'])) {
return $this->params['serverVersion'];
}
// If not connected, we need to connect now to determine the platform version.
if ($this->_conn === null) {
try {
$this->connect();
} catch (Throwable $originalException) {
if (empty($this->params['dbname'])) {
throw $originalException;
}
// The database to connect to might not yet exist.
// Retry detection without database name connection parameter.
$databaseName = $this->params['dbname'];
$this->params['dbname'] = null;
try {
$this->connect();
} catch (Throwable $fallbackException) {
// Either the platform does not support database-less connections
// or something else went wrong.
// Reset connection parameters and rethrow the original exception.
$this->params['dbname'] = $databaseName;
throw $originalException;
}
// Reset connection parameters.
$this->params['dbname'] = $databaseName;
$serverVersion = $this->getServerVersion();
// Close "temporary" connection to allow connecting to the real database again.
$this->close();
return $serverVersion;
}
}
return $this->getServerVersion();
}
/**
* Returns the database server version if the underlying driver supports it.
*
* @return string|null
*/
private function getServerVersion()
{
$connection = $this->getWrappedConnection();
// Automatic platform version detection.
if ($connection instanceof ServerInfoAwareConnection && ! $connection->requiresQueryForServerVersion()) {
return $connection->getServerVersion();
}
// Unable to detect platform version.
return null;
}
/**
* Returns the current auto-commit mode for this connection.
*
* @see setAutoCommit
*
* @return bool True if auto-commit mode is currently enabled for this connection, false otherwise.
*/
public function isAutoCommit()
{
return $this->autoCommit === true;
}
/**
* Sets auto-commit mode for this connection.
*
* If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual
* transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by a call to either
* the method commit or the method rollback. By default, new connections are in auto-commit mode.
*
* NOTE: If this method is called during a transaction and the auto-commit mode is changed, the transaction is
* committed. If this method is called and the auto-commit mode is not changed, the call is a no-op.
*
* @see isAutoCommit
*
* @param bool $autoCommit True to enable auto-commit mode; false to disable it.
*/
public function setAutoCommit($autoCommit)
{
$autoCommit = (bool) $autoCommit;
// Mode not changed, no-op.
if ($autoCommit === $this->autoCommit) {
return;
}
$this->autoCommit = $autoCommit;
// Commit all currently active transactions if any when switching auto-commit mode.
if ($this->isConnected !== true || $this->transactionNestingLevel === 0) {
return;
}
$this->commitAll();
}
/**
* Sets the fetch mode.
*
* @param int $fetchMode
*
* @return void
*/
public function setFetchMode($fetchMode)
{
$this->defaultFetchMode = $fetchMode;
}
/**
* Prepares and executes an SQL query and returns the first row of the result
* as an associative array.
*
* @param string $statement The SQL query.
* @param mixed[] $params The query parameters.
* @param int[]|string[] $types The query parameter types.
*
* @return mixed[]|false False is returned if no rows are found.
*
* @throws DBALException
*/
public function fetchAssoc($statement, array $params = [], array $types = [])
{
return $this->executeQuery($statement, $params, $types)->fetch(FetchMode::ASSOCIATIVE);
}
/**
* Prepares and executes an SQL query and returns the first row of the result
* as a numerically indexed array.
*
* @param string $statement The SQL query to be executed.
* @param mixed[] $params The prepared statement params.
* @param int[]|string[] $types The query parameter types.
*
* @return mixed[]|false False is returned if no rows are found.
*/
public function fetchArray($statement, array $params = [], array $types = [])
{
return $this->executeQuery($statement, $params, $types)->fetch(FetchMode::NUMERIC);
}
/**
* Prepares and executes an SQL query and returns the value of a single column
* of the first row of the result.
*
* @param string $statement The SQL query to be executed.
* @param mixed[] $params The prepared statement params.
* @param int $column The 0-indexed column number to retrieve.
* @param int[]|string[] $types The query parameter types.
*
* @return mixed|false False is returned if no rows are found.
*
* @throws DBALException
*/
public function fetchColumn($statement, array $params = [], $column = 0, array $types = [])
{
return $this->executeQuery($statement, $params, $types)->fetchColumn($column);
}
/**
* Whether an actual connection to the database is established.
*
* @return bool
*/
public function isConnected()
{
return $this->isConnected;
}
/**
* Checks whether a transaction is currently active.
*
* @return bool TRUE if a transaction is currently active, FALSE otherwise.
*/
public function isTransactionActive()
{
return $this->transactionNestingLevel > 0;
}
/**
* Adds identifier condition to the query components
*
* @param mixed[] $identifier Map of key columns to their values
* @param string[] $columns Column names
* @param mixed[] $values Column values
* @param string[] $conditions Key conditions
*
* @throws DBALException
*/
private function addIdentifierCondition(
array $identifier,
array &$columns,
array &$values,
array &$conditions
) : void {
$platform = $this->getDatabasePlatform();
foreach ($identifier as $columnName => $value) {
if ($value === null) {
$conditions[] = $platform->getIsNullExpression($columnName);
continue;
}
$columns[] = $columnName;
$values[] = $value;
$conditions[] = $columnName . ' = ?';
}
}
/**
* Executes an SQL DELETE statement on a table.
*
* Table expression and columns are not escaped and are not safe for user-input.
*
* @param string $tableExpression The expression of the table on which to delete.
* @param mixed[] $identifier The deletion criteria. An associative array containing column-value pairs.
* @param int[]|string[] $types The types of identifiers.
*
* @return int The number of affected rows.
*
* @throws DBALException
* @throws InvalidArgumentException
*/
public function delete($tableExpression, array $identifier, array $types = [])
{
if (empty($identifier)) {
throw InvalidArgumentException::fromEmptyCriteria();
}
$columns = $values = $conditions = [];
$this->addIdentifierCondition($identifier, $columns, $values, $conditions);
return $this->executeUpdate(
'DELETE FROM ' . $tableExpression . ' WHERE ' . implode(' AND ', $conditions),
$values,
is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types
);
}
/**
* Closes the connection.
*
* @return void
*/
public function close()
{
$this->_conn = null;
$this->isConnected = false;
}
/**
* Sets the transaction isolation level.
*
* @param int $level The level to set.
*
* @return int
*/
public function setTransactionIsolation($level)
{
$this->transactionIsolationLevel = $level;
return $this->executeUpdate($this->getDatabasePlatform()->getSetTransactionIsolationSQL($level));
}
/**
* Gets the currently active transaction isolation level.
*
* @return int The current transaction isolation level.
*/
public function getTransactionIsolation()
{
if ($this->transactionIsolationLevel === null) {
$this->transactionIsolationLevel = $this->getDatabasePlatform()->getDefaultTransactionIsolationLevel();
}
return $this->transactionIsolationLevel;
}
/**
* Executes an SQL UPDATE statement on a table.
*
* Table expression and columns are not escaped and are not safe for user-input.
*
* @param string $tableExpression The expression of the table to update quoted or unquoted.
* @param mixed[] $data An associative array containing column-value pairs.
* @param mixed[] $identifier The update criteria. An associative array containing column-value pairs.
* @param int[]|string[] $types Types of the merged $data and $identifier arrays in that order.
*
* @return int The number of affected rows.
*
* @throws DBALException
*/
public function update($tableExpression, array $data, array $identifier, array $types = [])
{
$columns = $values = $conditions = $set = [];
foreach ($data as $columnName => $value) {
$columns[] = $columnName;
$values[] = $value;
$set[] = $columnName . ' = ?';
}
$this->addIdentifierCondition($identifier, $columns, $values, $conditions);
if (is_string(key($types))) {
$types = $this->extractTypeValues($columns, $types);
}
$sql = 'UPDATE ' . $tableExpression . ' SET ' . implode(', ', $set)
. ' WHERE ' . implode(' AND ', $conditions);
return $this->executeUpdate($sql, $values, $types);
}
/**
* Inserts a table row with specified data.
*
* Table expression and columns are not escaped and are not safe for user-input.
*
* @param string $tableExpression The expression of the table to insert data into, quoted or unquoted.
* @param mixed[] $data An associative array containing column-value pairs.
* @param int[]|string[] $types Types of the inserted data.
*
* @return int The number of affected rows.
*
* @throws DBALException
*/
public function insert($tableExpression, array $data, array $types = [])
{
if (empty($data)) {
return $this->executeUpdate('INSERT INTO ' . $tableExpression . ' () VALUES ()');
}
$columns = [];
$values = [];
$set = [];
foreach ($data as $columnName => $value) {
$columns[] = $columnName;
$values[] = $value;
$set[] = '?';
}
return $this->executeUpdate(
'INSERT INTO ' . $tableExpression . ' (' . implode(', ', $columns) . ')' .
' VALUES (' . implode(', ', $set) . ')',
$values,
is_string(key($types)) ? $this->extractTypeValues($columns, $types) : $types
);
}
/**
* Extract ordered type list from an ordered column list and type map.
*
* @param int[]|string[] $columnList
* @param int[]|string[] $types
*
* @return int[]|string[]
*/
private function extractTypeValues(array $columnList, array $types)
{
$typeValues = [];
foreach ($columnList as $columnIndex => $columnName) {
$typeValues[] = $types[$columnName] ?? ParameterType::STRING;
}
return $typeValues;
}
/**
* Quotes a string so it can be safely used as a table or column name, even if
* it is a reserved name.
*
* Delimiting style depends on the underlying database platform that is being used.
*
* NOTE: Just because you CAN use quoted identifiers does not mean
* you SHOULD use them. In general, they end up causing way more
* problems than they solve.
*
* @param string $str The name to be quoted.
*
* @return string The quoted name.
*/
public function quoteIdentifier($str)
{
return $this->getDatabasePlatform()->quoteIdentifier($str);
}
/**
* {@inheritDoc}
*/
public function quote($input, $type = null)
{
$connection = $this->getWrappedConnection();
[$value, $bindingType] = $this->getBindingInfo($input, $type);
return $connection->quote($value, $bindingType);
}
/**
* Prepares and executes an SQL query and returns the result as an associative array.
*
* @param string $sql The SQL query.
* @param mixed[] $params The query parameters.
* @param int[]|string[] $types The query parameter types.
*
* @return mixed[]
*/
public function fetchAll($sql, array $params = [], $types = [])
{
return $this->executeQuery($sql, $params, $types)->fetchAll();
}
/**
* Prepares an SQL statement.
*
* @param string $statement The SQL statement to prepare.
*
* @return DriverStatement The prepared statement.
*
* @throws DBALException
*/
public function prepare($statement)
{
try {
$stmt = new Statement($statement, $this);
} catch (Throwable $ex) {
throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $statement);
}
$stmt->setFetchMode($this->defaultFetchMode);
return $stmt;
}
/**
* Executes an, optionally parametrized, SQL query.
*
* If the query is parametrized, a prepared statement is used.
* If an SQLLogger is configured, the execution is logged.
*
* @param string $query The SQL query to execute.
* @param mixed[] $params The parameters to bind to the query, if any.
* @param int[]|string[] $types The types the previous parameters are in.
* @param QueryCacheProfile|null $qcp The query cache profile, optional.
*
* @return ResultStatement The executed statement.
*
* @throws DBALException
*/
public function executeQuery($query, array $params = [], $types = [], ?QueryCacheProfile $qcp = null)
{
if ($qcp !== null) {
return $this->executeCacheQuery($query, $params, $types, $qcp);
}
$connection = $this->getWrappedConnection();
$logger = $this->_config->getSQLLogger();
if ($logger) {
$logger->startQuery($query, $params, $types);
}
try {
if ($params) {
[$query, $params, $types] = SQLParserUtils::expandListParameters($query, $params, $types);
$stmt = $connection->prepare($query);
if ($types) {
$this->_bindTypedValues($stmt, $params, $types);
$stmt->execute();
} else {
$stmt->execute($params);
}
} else {
$stmt = $connection->query($query);
}
} catch (Throwable $ex) {
throw DBALException::driverExceptionDuringQuery($this->_driver, $ex, $query, $this->resolveParams($params, $types));
}
$stmt->setFetchMode($this->defaultFetchMode);
if ($logger) {
$logger->stopQuery();
}
return $stmt;
}
/**
* Executes a caching query.
*
* @param string $query The SQL query to execute.
* @param mixed[] $params The parameters to bind to the query, if any.
* @param int[]|string[] $types The types the previous parameters are in.
* @param QueryCacheProfile $qcp The query cache profile.
*
* @return ResultStatement
*
* @throws CacheException
*/
public function executeCacheQuery($query, $params, $types, QueryCacheProfile $qcp)
{
$resultCache = $qcp->getResultCacheDriver() ?? $this->_config->getResultCacheImpl();
if ($resultCache === null) {
throw CacheException::noResultDriverConfigured();
}
[$cacheKey, $realKey] = $qcp->generateCacheKeys($query, $params, $types, $this->getParams());
// fetch the row pointers entry
$data = $resultCache->fetch($cacheKey);
if ($data !== false) {
// is the real key part of this row pointers map or is the cache only pointing to other cache keys?
if (isset($data[$realKey])) {
$stmt = new ArrayStatement($data[$realKey]);
} elseif (array_key_exists($realKey, $data)) {
$stmt = new ArrayStatement([]);
}
}
if (! isset($stmt)) {
$stmt = new ResultCacheStatement($this->executeQuery($query, $params, $types), $resultCache, $cacheKey, $realKey, $qcp->getLifetime());
}
$stmt->setFetchMode($this->defaultFetchMode);
return $stmt;
}
/**
* Executes an, optionally parametrized, SQL query and returns the result,
* applying a given projection/transformation function on each row of the result.
*
* @param string $query The SQL query to execute.
* @param mixed[] $params The parameters, if any.
* @param Closure $function The transformation function that is applied on each row.
* The function receives a single parameter, an array, that
* represents a row of the result set.
*
* @return mixed[] The projected result of the query.
*/
public function project($query, array $params, Closure $function)
{
$result = [];
$stmt = $this->executeQuery($query, $params);
while ($row = $stmt->fetch()) {
$result[] = $function($row);
}
$stmt->closeCursor();
return $result;
}
/**
* Executes an SQL statement, returning a result set as a Statement object.
*
* @return \Doctrine\DBAL\Driver\Statement
*
* @throws DBALException
*/
public function query()
{
$connection = $this->getWrappedConnection();
$args = func_get_args();
$logger = $this->_config->getSQLLogger();
if ($logger) {
$logger->startQuery($args[0]);
}