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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
|
<?php
namespace Doctrine\DBAL\Query;
use Doctrine\DBAL\Cache\QueryCacheProfile;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Exception;
use Doctrine\DBAL\ParameterType;
use Doctrine\DBAL\Query\Expression\CompositeExpression;
use Doctrine\DBAL\Query\Expression\ExpressionBuilder;
use Doctrine\DBAL\Result;
use Doctrine\DBAL\Statement;
use Doctrine\DBAL\Types\Type;
use Doctrine\Deprecations\Deprecation;
use function array_key_exists;
use function array_keys;
use function array_unshift;
use function count;
use function func_get_args;
use function func_num_args;
use function implode;
use function is_array;
use function is_object;
use function key;
use function strtoupper;
use function substr;
/**
* QueryBuilder class is responsible to dynamically create SQL queries.
*
* Important: Verify that every feature you use will work with your database vendor.
* SQL Query Builder does not attempt to validate the generated SQL at all.
*
* The query builder does no validation whatsoever if certain features even work with the
* underlying database vendor. Limit queries and joins are NOT applied to UPDATE and DELETE statements
* even if some vendors such as MySQL support it.
*/
class QueryBuilder
{
/** @deprecated */
public const SELECT = 0;
/** @deprecated */
public const DELETE = 1;
/** @deprecated */
public const UPDATE = 2;
/** @deprecated */
public const INSERT = 3;
/** @deprecated */
public const STATE_DIRTY = 0;
/** @deprecated */
public const STATE_CLEAN = 1;
/**
* The DBAL Connection.
*/
private Connection $connection;
/*
* The default values of SQL parts collection
*/
private const SQL_PARTS_DEFAULTS = [
'select' => [],
'distinct' => false,
'from' => [],
'join' => [],
'set' => [],
'where' => null,
'groupBy' => [],
'having' => null,
'orderBy' => [],
'values' => [],
];
/**
* The array of SQL parts collected.
*
* @var mixed[]
*/
private array $sqlParts = self::SQL_PARTS_DEFAULTS;
/**
* The complete SQL string for this query.
*/
private ?string $sql = null;
/**
* The query parameters.
*
* @var list<mixed>|array<string, mixed>
*/
private $params = [];
/**
* The parameter type map of this query.
*
* @var array<int, int|string|Type|null>|array<string, int|string|Type|null>
*/
private array $paramTypes = [];
/**
* The type of query this is. Can be select, update or delete.
*/
private int $type = self::SELECT;
/**
* The state of the query object. Can be dirty or clean.
*/
private int $state = self::STATE_CLEAN;
/**
* The index of the first result to retrieve.
*/
private int $firstResult = 0;
/**
* The maximum number of results to retrieve or NULL to retrieve all results.
*/
private ?int $maxResults = null;
/**
* The counter of bound parameters used with {@see bindValue).
*/
private int $boundCounter = 0;
/**
* The query cache profile used for caching results.
*/
private ?QueryCacheProfile $resultCacheProfile = null;
/**
* Initializes a new <tt>QueryBuilder</tt>.
*
* @param Connection $connection The DBAL Connection.
*/
public function __construct(Connection $connection)
{
$this->connection = $connection;
}
/**
* Gets an ExpressionBuilder used for object-oriented construction of query expressions.
* This producer method is intended for convenient inline usage. Example:
*
* <code>
* $qb = $conn->createQueryBuilder()
* ->select('u')
* ->from('users', 'u')
* ->where($qb->expr()->eq('u.id', 1));
* </code>
*
* For more complex expression construction, consider storing the expression
* builder object in a local variable.
*
* @return ExpressionBuilder
*/
public function expr()
{
return $this->connection->getExpressionBuilder();
}
/**
* Gets the type of the currently built query.
*
* @deprecated If necessary, track the type of the query being built outside of the builder.
*
* @return int
*/
public function getType()
{
Deprecation::trigger(
'doctrine/dbal',
'https://github.com/doctrine/dbal/pull/5551',
'Relying on the type of the query being built is deprecated.'
. ' If necessary, track the type of the query being built outside of the builder.',
);
return $this->type;
}
/**
* Gets the associated DBAL Connection for this query builder.
*
* @deprecated Use the connection used to instantiate the builder instead.
*
* @return Connection
*/
public function getConnection()
{
Deprecation::trigger(
'doctrine/dbal',
'https://github.com/doctrine/dbal/pull/5780',
'%s is deprecated. Use the connection used to instantiate the builder instead.',
__METHOD__,
);
return $this->connection;
}
/**
* Gets the state of this query builder instance.
*
* @deprecated The builder state is an internal concern.
*
* @return int Either QueryBuilder::STATE_DIRTY or QueryBuilder::STATE_CLEAN.
*/
public function getState()
{
Deprecation::trigger(
'doctrine/dbal',
'https://github.com/doctrine/dbal/pull/5551',
'Relying on the query builder state is deprecated as it is an internal concern.',
);
return $this->state;
}
/**
* Prepares and executes an SQL query and returns the first row of the result
* as an associative array.
*
* @return array<string, mixed>|false False is returned if no rows are found.
*
* @throws Exception
*/
public function fetchAssociative()
{
return $this->executeQuery()->fetchAssociative();
}
/**
* Prepares and executes an SQL query and returns the first row of the result
* as a numerically indexed array.
*
* @return array<int, mixed>|false False is returned if no rows are found.
*
* @throws Exception
*/
public function fetchNumeric()
{
return $this->executeQuery()->fetchNumeric();
}
/**
* Prepares and executes an SQL query and returns the value of a single column
* of the first row of the result.
*
* @return mixed|false False is returned if no rows are found.
*
* @throws Exception
*/
public function fetchOne()
{
return $this->executeQuery()->fetchOne();
}
/**
* Prepares and executes an SQL query and returns the result as an array of numeric arrays.
*
* @return array<int,array<int,mixed>>
*
* @throws Exception
*/
public function fetchAllNumeric(): array
{
return $this->executeQuery()->fetchAllNumeric();
}
/**
* Prepares and executes an SQL query and returns the result as an array of associative arrays.
*
* @return array<int,array<string,mixed>>
*
* @throws Exception
*/
public function fetchAllAssociative(): array
{
return $this->executeQuery()->fetchAllAssociative();
}
/**
* Prepares and executes an SQL query and returns the result as an associative array with the keys
* mapped to the first column and the values mapped to the second column.
*
* @return array<mixed,mixed>
*
* @throws Exception
*/
public function fetchAllKeyValue(): array
{
return $this->executeQuery()->fetchAllKeyValue();
}
/**
* Prepares and executes an SQL query and returns the result as an associative array with the keys mapped
* to the first column and the values being an associative array representing the rest of the columns
* and their values.
*
* @return array<mixed,array<string,mixed>>
*
* @throws Exception
*/
public function fetchAllAssociativeIndexed(): array
{
return $this->executeQuery()->fetchAllAssociativeIndexed();
}
/**
* Prepares and executes an SQL query and returns the result as an array of the first column values.
*
* @return array<int,mixed>
*
* @throws Exception
*/
public function fetchFirstColumn(): array
{
return $this->executeQuery()->fetchFirstColumn();
}
/**
* Executes an SQL query (SELECT) and returns a Result.
*
* @throws Exception
*/
public function executeQuery(): Result
{
return $this->connection->executeQuery(
$this->getSQL(),
$this->params,
$this->paramTypes,
$this->resultCacheProfile,
);
}
/**
* Executes an SQL statement and returns the number of affected rows.
*
* Should be used for INSERT, UPDATE and DELETE
*
* @return int The number of affected rows.
*
* @throws Exception
*/
public function executeStatement(): int
{
return $this->connection->executeStatement($this->getSQL(), $this->params, $this->paramTypes);
}
/**
* Executes this query using the bound parameters and their types.
*
* @deprecated Use {@see executeQuery()} or {@see executeStatement()} instead.
*
* @return Result|int|string
*
* @throws Exception
*/
public function execute()
{
if ($this->type === self::SELECT) {
Deprecation::trigger(
'doctrine/dbal',
'https://github.com/doctrine/dbal/pull/4578',
'QueryBuilder::execute() is deprecated, use QueryBuilder::executeQuery() for SQL queries instead.',
);
return $this->executeQuery();
}
Deprecation::trigger(
'doctrine/dbal',
'https://github.com/doctrine/dbal/pull/4578',
'QueryBuilder::execute() is deprecated, use QueryBuilder::executeStatement() for SQL statements instead.',
);
return $this->connection->executeStatement($this->getSQL(), $this->params, $this->paramTypes);
}
/**
* Gets the complete SQL string formed by the current specifications of this QueryBuilder.
*
* <code>
* $qb = $em->createQueryBuilder()
* ->select('u')
* ->from('User', 'u')
* echo $qb->getSQL(); // SELECT u FROM User u
* </code>
*
* @return string The SQL query string.
*/
public function getSQL()
{
if ($this->sql !== null && $this->state === self::STATE_CLEAN) {
return $this->sql;
}
switch ($this->type) {
case self::INSERT:
$sql = $this->getSQLForInsert();
break;
case self::DELETE:
$sql = $this->getSQLForDelete();
break;
case self::UPDATE:
$sql = $this->getSQLForUpdate();
break;
case self::SELECT:
default:
$sql = $this->getSQLForSelect();
break;
}
$this->state = self::STATE_CLEAN;
$this->sql = $sql;
return $sql;
}
/**
* Sets a query parameter for the query being constructed.
*
* <code>
* $qb = $conn->createQueryBuilder()
* ->select('u')
* ->from('users', 'u')
* ->where('u.id = :user_id')
* ->setParameter('user_id', 1);
* </code>
*
* @param int|string $key Parameter position or name
* @param mixed $value Parameter value
* @param int|string|Type|null $type Parameter type
*
* @return $this This QueryBuilder instance.
*/
public function setParameter($key, $value, $type = ParameterType::STRING)
{
if ($type !== null) {
$this->paramTypes[$key] = $type;
} else {
Deprecation::trigger(
'doctrine/dbal',
'https://github.com/doctrine/dbal/pull/5550',
'Using NULL as prepared statement parameter type is deprecated.'
. 'Omit or use Parameter::STRING instead',
);
}
$this->params[$key] = $value;
return $this;
}
/**
* Sets a collection of query parameters for the query being constructed.
*
* <code>
* $qb = $conn->createQueryBuilder()
* ->select('u')
* ->from('users', 'u')
* ->where('u.id = :user_id1 OR u.id = :user_id2')
* ->setParameters(array(
* 'user_id1' => 1,
* 'user_id2' => 2
* ));
* </code>
*
* @param list<mixed>|array<string, mixed> $params Parameters to set
* @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types Parameter types
*
* @return $this This QueryBuilder instance.
*/
public function setParameters(array $params, array $types = [])
{
$this->paramTypes = $types;
$this->params = $params;
return $this;
}
/**
* Gets all defined query parameters for the query being constructed indexed by parameter index or name.
*
* @return list<mixed>|array<string, mixed> The currently defined query parameters
*/
public function getParameters()
{
return $this->params;
}
/**
* Gets a (previously set) query parameter of the query being constructed.
*
* @param mixed $key The key (index or name) of the bound parameter.
*
* @return mixed The value of the bound parameter.
*/
public function getParameter($key)
{
return $this->params[$key] ?? null;
}
/**
* Gets all defined query parameter types for the query being constructed indexed by parameter index or name.
*
* @return array<int, int|string|Type|null>|array<string, int|string|Type|null> The currently defined
* query parameter types
*/
public function getParameterTypes()
{
return $this->paramTypes;
}
/**
* Gets a (previously set) query parameter type of the query being constructed.
*
* @param int|string $key The key of the bound parameter type
*
* @return int|string|Type The value of the bound parameter type
*/
public function getParameterType($key)
{
return $this->paramTypes[$key] ?? ParameterType::STRING;
}
/**
* Sets the position of the first result to retrieve (the "offset").
*
* @param int $firstResult The first result to return.
*
* @return $this This QueryBuilder instance.
*/
public function setFirstResult($firstResult)
{
$this->state = self::STATE_DIRTY;
$this->firstResult = $firstResult;
return $this;
}
/**
* Gets the position of the first result the query object was set to retrieve (the "offset").
*
* @return int The position of the first result.
*/
public function getFirstResult()
{
return $this->firstResult;
}
/**
* Sets the maximum number of results to retrieve (the "limit").
*
* @param int|null $maxResults The maximum number of results to retrieve or NULL to retrieve all results.
*
* @return $this This QueryBuilder instance.
*/
public function setMaxResults($maxResults)
{
$this->state = self::STATE_DIRTY;
$this->maxResults = $maxResults;
return $this;
}
/**
* Gets the maximum number of results the query object was set to retrieve (the "limit").
* Returns NULL if all results will be returned.
*
* @return int|null The maximum number of results.
*/
public function getMaxResults()
{
return $this->maxResults;
}
/**
* Either appends to or replaces a single, generic query part.
*
* The available parts are: 'select', 'from', 'set', 'where',
* 'groupBy', 'having' and 'orderBy'.
*
* @param string $sqlPartName
* @param mixed $sqlPart
* @param bool $append
*
* @return $this This QueryBuilder instance.
*/
public function add($sqlPartName, $sqlPart, $append = false)
{
$isArray = is_array($sqlPart);
$isMultiple = is_array($this->sqlParts[$sqlPartName]);
if ($isMultiple && ! $isArray) {
$sqlPart = [$sqlPart];
}
$this->state = self::STATE_DIRTY;
if ($append) {
if (
$sqlPartName === 'orderBy'
|| $sqlPartName === 'groupBy'
|| $sqlPartName === 'select'
|| $sqlPartName === 'set'
) {
foreach ($sqlPart as $part) {
$this->sqlParts[$sqlPartName][] = $part;
}
} elseif ($isArray && is_array($sqlPart[key($sqlPart)])) {
$key = key($sqlPart);
$this->sqlParts[$sqlPartName][$key][] = $sqlPart[$key];
} elseif ($isMultiple) {
$this->sqlParts[$sqlPartName][] = $sqlPart;
} else {
$this->sqlParts[$sqlPartName] = $sqlPart;
}
return $this;
}
$this->sqlParts[$sqlPartName] = $sqlPart;
return $this;
}
/**
* Specifies an item that is to be returned in the query result.
* Replaces any previously specified selections, if any.
*
* USING AN ARRAY ARGUMENT IS DEPRECATED. Pass each value as an individual argument.
*
* <code>
* $qb = $conn->createQueryBuilder()
* ->select('u.id', 'p.id')
* ->from('users', 'u')
* ->leftJoin('u', 'phonenumbers', 'p', 'u.id = p.user_id');
* </code>
*
* @param string|string[]|null $select The selection expression. USING AN ARRAY OR NULL IS DEPRECATED.
* Pass each value as an individual argument.
*
* @return $this This QueryBuilder instance.
*/
public function select($select = null/*, string ...$selects*/)
{
$this->type = self::SELECT;
if ($select === null) {
return $this;
}
if (is_array($select)) {
Deprecation::trigger(
'doctrine/dbal',
'https://github.com/doctrine/dbal/issues/3837',
'Passing an array for the first argument to QueryBuilder::select() is deprecated, ' .
'pass each value as an individual variadic argument instead.',
);
}
$selects = is_array($select) ? $select : func_get_args();
return $this->add('select', $selects);
}
/**
* Adds DISTINCT to the query.
*
* <code>
* $qb = $conn->createQueryBuilder()
* ->select('u.id')
* ->distinct()
* ->from('users', 'u')
* </code>
*
* @return $this This QueryBuilder instance.
*/
public function distinct(): self
{
$this->sqlParts['distinct'] = true;
return $this;
}
/**
* Adds an item that is to be returned in the query result.
*
* USING AN ARRAY ARGUMENT IS DEPRECATED. Pass each value as an individual argument.
*
* <code>
* $qb = $conn->createQueryBuilder()
* ->select('u.id')
* ->addSelect('p.id')
* ->from('users', 'u')
* ->leftJoin('u', 'phonenumbers', 'u.id = p.user_id');
* </code>
*
* @param string|string[]|null $select The selection expression. USING AN ARRAY OR NULL IS DEPRECATED.
* Pass each value as an individual argument.
*
* @return $this This QueryBuilder instance.
*/
public function addSelect($select = null/*, string ...$selects*/)
{
$this->type = self::SELECT;
if ($select === null) {
return $this;
}
if (is_array($select)) {
Deprecation::trigger(
'doctrine/dbal',
'https://github.com/doctrine/dbal/issues/3837',
'Passing an array for the first argument to QueryBuilder::addSelect() is deprecated, ' .
'pass each value as an individual variadic argument instead.',
);
}
$selects = is_array($select) ? $select : func_get_args();
return $this->add('select', $selects, true);
}
/**
* Turns the query being built into a bulk delete query that ranges over
* a certain table.
*
* <code>
* $qb = $conn->createQueryBuilder()
* ->delete('users', 'u')
* ->where('u.id = :user_id')
* ->setParameter(':user_id', 1);
* </code>
*
* @param string $delete The table whose rows are subject to the deletion.
* @param string $alias The table alias used in the constructed query.
*
* @return $this This QueryBuilder instance.
*/
public function delete($delete = null, $alias = null)
{
$this->type = self::DELETE;
if ($delete === null) {
return $this;
}
return $this->add('from', [
'table' => $delete,
'alias' => $alias,
]);
}
/**
* Turns the query being built into a bulk update query that ranges over
* a certain table
*
* <code>
* $qb = $conn->createQueryBuilder()
* ->update('counters', 'c')
* ->set('c.value', 'c.value + 1')
* ->where('c.id = ?');
* </code>
*
* @param string $update The table whose rows are subject to the update.
* @param string $alias The table alias used in the constructed query.
*
* @return $this This QueryBuilder instance.
*/
public function update($update = null, $alias = null)
{
$this->type = self::UPDATE;
if ($update === null) {
return $this;
}
return $this->add('from', [
'table' => $update,
'alias' => $alias,
]);
}
/**
* Turns the query being built into an insert query that inserts into
* a certain table
*
* <code>
* $qb = $conn->createQueryBuilder()
* ->insert('users')
* ->values(
* array(
* 'name' => '?',
* 'password' => '?'
* )
* );
* </code>
*
* @param string $insert The table into which the rows should be inserted.
*
* @return $this This QueryBuilder instance.
*/
public function insert($insert = null)
{
$this->type = self::INSERT;
if ($insert === null) {
return $this;
}
return $this->add('from', ['table' => $insert]);
}
/**
* Creates and adds a query root corresponding to the table identified by the
* given alias, forming a cartesian product with any existing query roots.
*
* <code>
* $qb = $conn->createQueryBuilder()
* ->select('u.id')
* ->from('users', 'u')
* </code>
*
* @param string $from The table.
* @param string|null $alias The alias of the table.
*
* @return $this This QueryBuilder instance.
*/
public function from($from, $alias = null)
{
return $this->add('from', [
'table' => $from,
'alias' => $alias,
], true);
}
/**
* Creates and adds a join to the query.
*
* <code>
* $qb = $conn->createQueryBuilder()
* ->select('u.name')
* ->from('users', 'u')
* ->join('u', 'phonenumbers', 'p', 'p.is_primary = 1');
* </code>
*
* @param string $fromAlias The alias that points to a from clause.
* @param string $join The table name to join.
* @param string $alias The alias of the join table.
* @param string $condition The condition for the join.
*
* @return $this This QueryBuilder instance.
*/
public function join($fromAlias, $join, $alias, $condition = null)
{
return $this->innerJoin($fromAlias, $join, $alias, $condition);
}
/**
* Creates and adds a join to the query.
*
* <code>
* $qb = $conn->createQueryBuilder()
* ->select('u.name')
* ->from('users', 'u')
* ->innerJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
* </code>
*
* @param string $fromAlias The alias that points to a from clause.
* @param string $join The table name to join.
* @param string $alias The alias of the join table.
* @param string $condition The condition for the join.
*
* @return $this This QueryBuilder instance.
*/
public function innerJoin($fromAlias, $join, $alias, $condition = null)
{
return $this->add('join', [
$fromAlias => [
'joinType' => 'inner',
'joinTable' => $join,
'joinAlias' => $alias,
'joinCondition' => $condition,
],
], true);
}
/**
* Creates and adds a left join to the query.
*
* <code>
* $qb = $conn->createQueryBuilder()
* ->select('u.name')
* ->from('users', 'u')
* ->leftJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
* </code>
*
* @param string $fromAlias The alias that points to a from clause.
* @param string $join The table name to join.
* @param string $alias The alias of the join table.
* @param string $condition The condition for the join.
*
* @return $this This QueryBuilder instance.
*/
public function leftJoin($fromAlias, $join, $alias, $condition = null)
{
return $this->add('join', [
$fromAlias => [
'joinType' => 'left',
'joinTable' => $join,
'joinAlias' => $alias,
'joinCondition' => $condition,
],
], true);
}
/**
* Creates and adds a right join to the query.
*
* <code>
* $qb = $conn->createQueryBuilder()
* ->select('u.name')
* ->from('users', 'u')
* ->rightJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
* </code>
*
* @param string $fromAlias The alias that points to a from clause.
* @param string $join The table name to join.
* @param string $alias The alias of the join table.
* @param string $condition The condition for the join.
*
* @return $this This QueryBuilder instance.
*/
public function rightJoin($fromAlias, $join, $alias, $condition = null)
{
return $this->add('join', [
$fromAlias => [
'joinType' => 'right',
'joinTable' => $join,
'joinAlias' => $alias,
'joinCondition' => $condition,
],
], true);
}
/**
* Sets a new value for a column in a bulk update query.
*
* <code>
* $qb = $conn->createQueryBuilder()
* ->update('counters', 'c')
* ->set('c.value', 'c.value + 1')
* ->where('c.id = ?');
* </code>
*
* @param string $key The column to set.
* @param string $value The value, expression, placeholder, etc.
*
* @return $this This QueryBuilder instance.
*/
public function set($key, $value)
{
return $this->add('set', $key . ' = ' . $value, true);
}
/**
* Specifies one or more restrictions to the query result.
* Replaces any previously specified restrictions, if any.
*
* <code>
* $qb = $conn->createQueryBuilder()
* ->select('c.value')
* ->from('counters', 'c')
* ->where('c.id = ?');
*
* // You can optionally programmatically build and/or expressions
* $qb = $conn->createQueryBuilder();
*
* $or = $qb->expr()->orx();
* $or->add($qb->expr()->eq('c.id', 1));
* $or->add($qb->expr()->eq('c.id', 2));
*
* $qb->update('counters', 'c')
* ->set('c.value', 'c.value + 1')
* ->where($or);
* </code>
*
* @param mixed $predicates The restriction predicates.
*
* @return $this This QueryBuilder instance.
*/
public function where($predicates)
{
if (! (func_num_args() === 1 && $predicates instanceof CompositeExpression)) {
$predicates = CompositeExpression::and(...func_get_args());
}
return $this->add('where', $predicates);
}
/**
* Adds one or more restrictions to the query results, forming a logical
* conjunction with any previously specified restrictions.
*
* <code>
* $qb = $conn->createQueryBuilder()
* ->select('u')
* ->from('users', 'u')
* ->where('u.username LIKE ?')
* ->andWhere('u.is_active = 1');
* </code>
*
* @see where()
*
* @param mixed $where The query restrictions.
*
* @return $this This QueryBuilder instance.
*/
public function andWhere($where)
{
$args = func_get_args();
$where = $this->getQueryPart('where');
if ($where instanceof CompositeExpression && $where->getType() === CompositeExpression::TYPE_AND) {
$where = $where->with(...$args);
} else {
array_unshift($args, $where);
$where = CompositeExpression::and(...$args);
}
return $this->add('where', $where, true);
}
/**
* Adds one or more restrictions to the query results, forming a logical
* disjunction with any previously specified restrictions.
*
* <code>
* $qb = $em->createQueryBuilder()
* ->select('u.name')
* ->from('users', 'u')
* ->where('u.id = 1')
* ->orWhere('u.id = 2');
* </code>
*
* @see where()
*
* @param mixed $where The WHERE statement.
*
* @return $this This QueryBuilder instance.
*/
public function orWhere($where)
{
$args = func_get_args();
$where = $this->getQueryPart('where');
if ($where instanceof CompositeExpression && $where->getType() === CompositeExpression::TYPE_OR) {
$where = $where->with(...$args);
} else {
array_unshift($args, $where);
$where = CompositeExpression::or(...$args);
}
return $this->add('where', $where, true);
}
/**
* Specifies a grouping over the results of the query.
* Replaces any previously specified groupings, if any.
*
* USING AN ARRAY ARGUMENT IS DEPRECATED. Pass each value as an individual argument.
*
* <code>
* $qb = $conn->createQueryBuilder()
* ->select('u.name')
* ->from('users', 'u')
* ->groupBy('u.id');
* </code>
*
* @param string|string[] $groupBy The grouping expression. USING AN ARRAY IS DEPRECATED.
* Pass each value as an individual argument.
*
* @return $this This QueryBuilder instance.
*/
public function groupBy($groupBy/*, string ...$groupBys*/)
{
if (is_array($groupBy) && count($groupBy) === 0) {
return $this;
}
if (is_array($groupBy)) {
Deprecation::trigger(
'doctrine/dbal',
'https://github.com/doctrine/dbal/issues/3837',
'Passing an array for the first argument to QueryBuilder::groupBy() is deprecated, ' .
'pass each value as an individual variadic argument instead.',
);
}
$groupBy = is_array($groupBy) ? $groupBy : func_get_args();
return $this->add('groupBy', $groupBy, false);
}
/**
* Adds a grouping expression to the query.
*
* USING AN ARRAY ARGUMENT IS DEPRECATED. Pass each value as an individual argument.
*
* <code>
* $qb = $conn->createQueryBuilder()
* ->select('u.name')
* ->from('users', 'u')
* ->groupBy('u.lastLogin')
* ->addGroupBy('u.createdAt');
* </code>
*
* @param string|string[] $groupBy The grouping expression. USING AN ARRAY IS DEPRECATED.
* Pass each value as an individual argument.
*
* @return $this This QueryBuilder instance.
*/
public function addGroupBy($groupBy/*, string ...$groupBys*/)
{
if (is_array($groupBy) && count($groupBy) === 0) {
return $this;
}
if (is_array($groupBy)) {
Deprecation::trigger(
'doctrine/dbal',
'https://github.com/doctrine/dbal/issues/3837',
'Passing an array for the first argument to QueryBuilder::addGroupBy() is deprecated, ' .
'pass each value as an individual variadic argument instead.',
);
}
$groupBy = is_array($groupBy) ? $groupBy : func_get_args();
return $this->add('groupBy', $groupBy, true);
}
/**
* Sets a value for a column in an insert query.
*
* <code>
* $qb = $conn->createQueryBuilder()
* ->insert('users')
* ->values(
* array(
* 'name' => '?'
* )
* )
* ->setValue('password', '?');
* </code>
*
* @param string $column The column into which the value should be inserted.
* @param string $value The value that should be inserted into the column.
*
* @return $this This QueryBuilder instance.
*/
public function setValue($column, $value)
{
$this->sqlParts['values'][$column] = $value;
return $this;
}
/**
* Specifies values for an insert query indexed by column names.
* Replaces any previous values, if any.
*
* <code>
* $qb = $conn->createQueryBuilder()
* ->insert('users')
* ->values(
* array(
* 'name' => '?',
* 'password' => '?'
* )
* );
* </code>
*
* @param mixed[] $values The values to specify for the insert query indexed by column names.
*
* @return $this This QueryBuilder instance.
*/
public function values(array $values)
{
return $this->add('values', $values);
}
/**
* Specifies a restriction over the groups of the query.
* Replaces any previous having restrictions, if any.
*
* @param mixed $having The restriction over the groups.
*
* @return $this This QueryBuilder instance.
*/
public function having($having)
{
if (! (func_num_args() === 1 && $having instanceof CompositeExpression)) {
$having = CompositeExpression::and(...func_get_args());
}
return $this->add('having', $having);
}
/**
* Adds a restriction over the groups of the query, forming a logical
* conjunction with any existing having restrictions.
*
* @param mixed $having The restriction to append.
*
* @return $this This QueryBuilder instance.
*/
public function andHaving($having)
{
$args = func_get_args();
$having = $this->getQueryPart('having');
if ($having instanceof CompositeExpression && $having->getType() === CompositeExpression::TYPE_AND) {
$having = $having->with(...$args);
} else {
array_unshift($args, $having);
$having = CompositeExpression::and(...$args);
}
return $this->add('having', $having);
}
/**
* Adds a restriction over the groups of the query, forming a logical
* disjunction with any existing having restrictions.
*
* @param mixed $having The restriction to add.
*
* @return $this This QueryBuilder instance.
*/
public function orHaving($having)
{
$args = func_get_args();
$having = $this->getQueryPart('having');
if ($having instanceof CompositeExpression && $having->getType() === CompositeExpression::TYPE_OR) {
$having = $having->with(...$args);
} else {
array_unshift($args, $having);
$having = CompositeExpression::or(...$args);
}
return $this->add('having', $having);
}
/**
* Specifies an ordering for the query results.
* Replaces any previously specified orderings, if any.
*
* @param string $sort The ordering expression.
* @param string $order The ordering direction.
*
* @return $this This QueryBuilder instance.
*/
public function orderBy($sort, $order = null)
{
return $this->add('orderBy', $sort . ' ' . ($order ?? 'ASC'), false);
}
/**
* Adds an ordering to the query results.
*
* @param string $sort The ordering expression.
* @param string $order The ordering direction.
*
* @return $this This QueryBuilder instance.
*/
public function addOrderBy($sort, $order = null)
{
return $this->add('orderBy', $sort . ' ' . ($order ?? 'ASC'), true);
}
/**
* Gets a query part by its name.
*
* @param string $queryPartName
*
* @return mixed
*/
public function getQueryPart($queryPartName)
{
return $this->sqlParts[$queryPartName];
}
/**
* Gets all query parts.
*
* @return mixed[]
*/
public function getQueryParts()
{
return $this->sqlParts;
}
/**
* Resets SQL parts.
*
* @param string[]|null $queryPartNames
*
* @return $this This QueryBuilder instance.
*/
public function resetQueryParts($queryPartNames = null)
{
$queryPartNames ??= array_keys($this->sqlParts);
foreach ($queryPartNames as $queryPartName) {
$this->resetQueryPart($queryPartName);
}
return $this;
}
/**
* Resets a single SQL part.
*
* @param string $queryPartName
*
* @return $this This QueryBuilder instance.
*/
public function resetQueryPart($queryPartName)
{
$this->sqlParts[$queryPartName] = self::SQL_PARTS_DEFAULTS[$queryPartName];
$this->state = self::STATE_DIRTY;
return $this;
}
/** @throws QueryException */
private function getSQLForSelect(): string
{
$query = 'SELECT ' . ($this->sqlParts['distinct'] ? 'DISTINCT ' : '') .
implode(', ', $this->sqlParts['select']);
$query .= ($this->sqlParts['from'] ? ' FROM ' . implode(', ', $this->getFromClauses()) : '')
. ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string) $this->sqlParts['where']) : '')
. ($this->sqlParts['groupBy'] ? ' GROUP BY ' . implode(', ', $this->sqlParts['groupBy']) : '')
. ($this->sqlParts['having'] !== null ? ' HAVING ' . ((string) $this->sqlParts['having']) : '')
. ($this->sqlParts['orderBy'] ? ' ORDER BY ' . implode(', ', $this->sqlParts['orderBy']) : '');
if ($this->isLimitQuery()) {
return $this->connection->getDatabasePlatform()->modifyLimitQuery(
$query,
$this->maxResults,
$this->firstResult,
);
}
return $query;
}
/**
* @return string[]
*
* @throws QueryException
*/
private function getFromClauses(): array
{
$fromClauses = [];
$knownAliases = [];
// Loop through all FROM clauses
foreach ($this->sqlParts['from'] as $from) {
if ($from['alias'] === null) {
$tableSql = $from['table'];
$tableReference = $from['table'];
} else {
$tableSql = $from['table'] . ' ' . $from['alias'];
$tableReference = $from['alias'];
}
$knownAliases[$tableReference] = true;
$fromClauses[$tableReference] = $tableSql . $this->getSQLForJoins($tableReference, $knownAliases);
}
$this->verifyAllAliasesAreKnown($knownAliases);
return $fromClauses;
}
/**
* @param array<string,true> $knownAliases
*
* @throws QueryException
*/
private function verifyAllAliasesAreKnown(array $knownAliases): void
{
foreach ($this->sqlParts['join'] as $fromAlias => $joins) {
if (! isset($knownAliases[$fromAlias])) {
throw QueryException::unknownAlias($fromAlias, array_keys($knownAliases));
}
}
}
private function isLimitQuery(): bool
{
return $this->maxResults !== null || $this->firstResult !== 0;
}
/**
* Converts this instance into an INSERT string in SQL.
*/
private function getSQLForInsert(): string
{
return 'INSERT INTO ' . $this->sqlParts['from']['table'] .
' (' . implode(', ', array_keys($this->sqlParts['values'])) . ')' .
' VALUES(' . implode(', ', $this->sqlParts['values']) . ')';
}
/**
* Converts this instance into an UPDATE string in SQL.
*/
private function getSQLForUpdate(): string
{
$table = $this->sqlParts['from']['table']
. ($this->sqlParts['from']['alias'] ? ' ' . $this->sqlParts['from']['alias'] : '');
return 'UPDATE ' . $table
. ' SET ' . implode(', ', $this->sqlParts['set'])
. ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string) $this->sqlParts['where']) : '');
}
/**
* Converts this instance into a DELETE string in SQL.
*/
private function getSQLForDelete(): string
{
$table = $this->sqlParts['from']['table']
. ($this->sqlParts['from']['alias'] ? ' ' . $this->sqlParts['from']['alias'] : '');
return 'DELETE FROM ' . $table
. ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string) $this->sqlParts['where']) : '');
}
/**
* Gets a string representation of this QueryBuilder which corresponds to
* the final SQL query being constructed.
*
* @return string The string representation of this QueryBuilder.
*/
public function __toString()
{
return $this->getSQL();
}
/**
* Creates a new named parameter and bind the value $value to it.
*
* This method provides a shortcut for {@see Statement::bindValue()}
* when using prepared statements.
*
* The parameter $value specifies the value that you want to bind. If
* $placeholder is not provided createNamedParameter() will automatically
* create a placeholder for you. An automatic placeholder will be of the
* name ':dcValue1', ':dcValue2' etc.
*
* Example:
* <code>
* $value = 2;
* $q->eq( 'id', $q->createNamedParameter( $value ) );
* $stmt = $q->executeQuery(); // executed with 'id = 2'
* </code>
*
* @link http://www.zetacomponents.org
*
* @param mixed $value
* @param int|string|Type|null $type
* @param string $placeHolder The name to bind with. The string must start with a colon ':'.
*
* @return string the placeholder name used.
*/
public function createNamedParameter($value, $type = ParameterType::STRING, $placeHolder = null)
{
if ($placeHolder === null) {
$this->boundCounter++;
$placeHolder = ':dcValue' . $this->boundCounter;
}
$this->setParameter(substr($placeHolder, 1), $value, $type);
return $placeHolder;
}
/**
* Creates a new positional parameter and bind the given value to it.
*
* Attention: If you are using positional parameters with the query builder you have
* to be very careful to bind all parameters in the order they appear in the SQL
* statement , otherwise they get bound in the wrong order which can lead to serious
* bugs in your code.
*
* Example:
* <code>
* $qb = $conn->createQueryBuilder();
* $qb->select('u.*')
* ->from('users', 'u')
* ->where('u.username = ' . $qb->createPositionalParameter('Foo', ParameterType::STRING))
* ->orWhere('u.username = ' . $qb->createPositionalParameter('Bar', ParameterType::STRING))
* </code>
*
* @param mixed $value
* @param int|string|Type|null $type
*
* @return string
*/
public function createPositionalParameter($value, $type = ParameterType::STRING)
{
$this->setParameter($this->boundCounter, $value, $type);
$this->boundCounter++;
return '?';
}
/**
* @param string $fromAlias
* @param array<string,true> $knownAliases
*
* @throws QueryException
*/
private function getSQLForJoins($fromAlias, array &$knownAliases): string
{
$sql = '';
if (isset($this->sqlParts['join'][$fromAlias])) {
foreach ($this->sqlParts['join'][$fromAlias] as $join) {
if (array_key_exists($join['joinAlias'], $knownAliases)) {
throw QueryException::nonUniqueAlias((string) $join['joinAlias'], array_keys($knownAliases));
}
$sql .= ' ' . strtoupper($join['joinType'])
. ' JOIN ' . $join['joinTable'] . ' ' . $join['joinAlias'];
if ($join['joinCondition'] !== null) {
$sql .= ' ON ' . $join['joinCondition'];
}
$knownAliases[$join['joinAlias']] = true;
}
foreach ($this->sqlParts['join'][$fromAlias] as $join) {
$sql .= $this->getSQLForJoins($join['joinAlias'], $knownAliases);
}
}
return $sql;
}
/**
* Deep clone of all expression objects in the SQL parts.
*
* @return void
*/
public function __clone()
{
foreach ($this->sqlParts as $part => $elements) {
if (is_array($this->sqlParts[$part])) {
foreach ($this->sqlParts[$part] as $idx => $element) {
if (! is_object($element)) {
continue;
}
$this->sqlParts[$part][$idx] = clone $element;
}
} elseif (is_object($elements)) {
$this->sqlParts[$part] = clone $elements;
}
}
foreach ($this->params as $name => $param) {
if (! is_object($param)) {
continue;
}
$this->params[$name] = clone $param;
}
}
/**
* Enables caching of the results of this query, for given amount of seconds
* and optionally specified witch key to use for the cache entry.
*
* @return $this
*/
public function enableResultCache(QueryCacheProfile $cacheProfile): self
{
$this->resultCacheProfile = $cacheProfile;
return $this;
}
/**
* Disables caching of the results of this query.
*
* @return $this
*/
public function disableResultCache(): self
{
$this->resultCacheProfile = null;
return $this;
}
}
|