| 1: | <?php |
| 2: | |
| 3: | declare(strict_types=1); |
| 4: | |
| 5: | namespace Atk4\Data\Persistence\Sql; |
| 6: | |
| 7: | use Atk4\Core\DiContainerTrait; |
| 8: | use Atk4\Data\Persistence; |
| 9: | use Doctrine\DBAL\Connection as DbalConnection; |
| 10: | use Doctrine\DBAL\Exception as DbalException; |
| 11: | use Doctrine\DBAL\ParameterType; |
| 12: | use Doctrine\DBAL\Platforms\OraclePlatform; |
| 13: | use Doctrine\DBAL\Platforms\PostgreSQLPlatform; |
| 14: | use Doctrine\DBAL\Platforms\SQLitePlatform; |
| 15: | use Doctrine\DBAL\Platforms\SQLServerPlatform; |
| 16: | use Doctrine\DBAL\Result as DbalResult; |
| 17: | use Doctrine\DBAL\Statement; |
| 18: | |
| 19: | |
| 20: | |
| 21: | |
| 22: | abstract class Expression implements Expressionable, \ArrayAccess |
| 23: | { |
| 24: | use DiContainerTrait; |
| 25: | |
| 26: | |
| 27: | protected const ESCAPE_PARAM = 'param'; |
| 28: | |
| 29: | protected const ESCAPE_IDENTIFIER = 'identifier'; |
| 30: | |
| 31: | protected const ESCAPE_IDENTIFIER_SOFT = 'identifier-soft'; |
| 32: | |
| 33: | protected const ESCAPE_NONE = 'none'; |
| 34: | |
| 35: | public const QUOTED_TOKEN_REGEX = <<<'EOF' |
| 36: | (?:(?sx) |
| 37: | '(?:[^'\\]+|\\.|'')*+' |
| 38: | |"(?:[^"\\]+|\\.|"")*+" |
| 39: | |`(?:[^`\\]+|\\.|``)*+` |
| 40: | |\[(?:[^\]\\]+|\\.|\]\])*+\] |
| 41: | |(?:--|\#)[^\r\n]*+ |
| 42: | |/\*(?:[^*]+|\*(?!/))*+\*/ |
| 43: | ) |
| 44: | EOF; |
| 45: | |
| 46: | protected ?string $template = null; |
| 47: | |
| 48: | |
| 49: | |
| 50: | |
| 51: | |
| 52: | |
| 53: | |
| 54: | |
| 55: | |
| 56: | |
| 57: | |
| 58: | public array $args = ['custom' => []]; |
| 59: | |
| 60: | |
| 61: | protected string $paramBase = 'a'; |
| 62: | |
| 63: | |
| 64: | protected string $identifierEscapeChar; |
| 65: | |
| 66: | private ?string $renderParamBase = null; |
| 67: | |
| 68: | private ?array $renderParams = null; |
| 69: | |
| 70: | public Connection $connection; |
| 71: | |
| 72: | |
| 73: | public bool $wrapInParentheses = false; |
| 74: | |
| 75: | |
| 76: | |
| 77: | |
| 78: | |
| 79: | |
| 80: | |
| 81: | |
| 82: | public function __construct($template = [], array $arguments = []) |
| 83: | { |
| 84: | if (is_string($template)) { |
| 85: | $template = ['template' => $template]; |
| 86: | } |
| 87: | |
| 88: | $this->setDefaults($template); |
| 89: | |
| 90: | $this->args['custom'] = $arguments; |
| 91: | } |
| 92: | |
| 93: | |
| 94: | |
| 95: | |
| 96: | #[\Override] |
| 97: | public function getDsqlExpression(self $expression): self |
| 98: | { |
| 99: | return $this; |
| 100: | } |
| 101: | |
| 102: | #[\Override] |
| 103: | public function offsetExists($offset): bool |
| 104: | { |
| 105: | return array_key_exists($offset, $this->args['custom']); |
| 106: | } |
| 107: | |
| 108: | #[\Override] |
| 109: | #[\ReturnTypeWillChange] |
| 110: | public function offsetGet($offset) |
| 111: | { |
| 112: | return $this->args['custom'][$offset]; |
| 113: | } |
| 114: | |
| 115: | #[\Override] |
| 116: | public function offsetSet($offset, $value): void |
| 117: | { |
| 118: | if ($offset === null) { |
| 119: | $this->args['custom'][] = $value; |
| 120: | } else { |
| 121: | $this->args['custom'][$offset] = $value; |
| 122: | } |
| 123: | } |
| 124: | |
| 125: | #[\Override] |
| 126: | public function offsetUnset($offset): void |
| 127: | { |
| 128: | unset($this->args['custom'][$offset]); |
| 129: | } |
| 130: | |
| 131: | |
| 132: | |
| 133: | |
| 134: | |
| 135: | |
| 136: | |
| 137: | public function expr($template = [], array $arguments = []): self |
| 138: | { |
| 139: | return $this->connection->expr($template, $arguments); |
| 140: | } |
| 141: | |
| 142: | |
| 143: | |
| 144: | |
| 145: | |
| 146: | |
| 147: | public function reset(string $tag = null) |
| 148: | { |
| 149: | |
| 150: | if ($tag === null) { |
| 151: | $this->args = ['custom' => []]; |
| 152: | |
| 153: | return $this; |
| 154: | } |
| 155: | |
| 156: | |
| 157: | if ($this->offsetExists($tag)) { |
| 158: | $this->offsetUnset($tag); |
| 159: | } elseif (isset($this->args[$tag])) { |
| 160: | unset($this->args[$tag]); |
| 161: | } |
| 162: | |
| 163: | return $this; |
| 164: | } |
| 165: | |
| 166: | |
| 167: | |
| 168: | |
| 169: | |
| 170: | |
| 171: | |
| 172: | |
| 173: | |
| 174: | protected function consume($expr, string $escapeMode) |
| 175: | { |
| 176: | if (!is_object($expr)) { |
| 177: | switch ($escapeMode) { |
| 178: | case self::ESCAPE_PARAM: |
| 179: | return $this->escapeParam($expr); |
| 180: | case self::ESCAPE_IDENTIFIER: |
| 181: | return $this->escapeIdentifier($expr); |
| 182: | case self::ESCAPE_IDENTIFIER_SOFT: |
| 183: | return $this->escapeIdentifierSoft($expr); |
| 184: | case self::ESCAPE_NONE: |
| 185: | return $expr; |
| 186: | } |
| 187: | |
| 188: | throw (new Exception('Unexpected escape mode')) |
| 189: | ->addMoreInfo('escapeMode', $escapeMode); |
| 190: | } |
| 191: | |
| 192: | $expr = $expr->getDsqlExpression($this); |
| 193: | |
| 194: | |
| 195: | $expressionParamBaseBackup = $expr->paramBase; |
| 196: | try { |
| 197: | $expr->paramBase = $this->renderParamBase; |
| 198: | [$sql, $params] = $expr->wrapInParentheses |
| 199: | ? $expr->renderNested() |
| 200: | : $expr->render(); |
| 201: | foreach ($params as $k => $v) { |
| 202: | $this->renderParams[$k] = $v; |
| 203: | } |
| 204: | |
| 205: | if (count($params) > 0) { |
| 206: | $kWithoutColon = substr(array_key_last($params), 1); |
| 207: | while ($this->renderParamBase !== $kWithoutColon) { |
| 208: | ++$this->renderParamBase; |
| 209: | } |
| 210: | ++$this->renderParamBase; |
| 211: | } |
| 212: | } finally { |
| 213: | $expr->paramBase = $expressionParamBaseBackup; |
| 214: | } |
| 215: | |
| 216: | return $sql; |
| 217: | } |
| 218: | |
| 219: | |
| 220: | |
| 221: | |
| 222: | |
| 223: | |
| 224: | |
| 225: | |
| 226: | |
| 227: | |
| 228: | protected function escapeParam($value): string |
| 229: | { |
| 230: | $name = ':' . $this->renderParamBase; |
| 231: | ++$this->renderParamBase; |
| 232: | $this->renderParams[$name] = $value; |
| 233: | |
| 234: | return $name; |
| 235: | } |
| 236: | |
| 237: | |
| 238: | |
| 239: | |
| 240: | protected function escapeStringLiteral(string $value): string |
| 241: | { |
| 242: | $platform = $this->connection->getDatabasePlatform(); |
| 243: | if ($platform instanceof PostgreSQLPlatform || $platform instanceof SQLServerPlatform) { |
| 244: | $dummyPersistence = new Persistence\Sql($this->connection); |
| 245: | if (\Closure::bind(static fn () => $dummyPersistence->binaryTypeValueIsEncoded($value), null, Persistence\Sql::class)()) { |
| 246: | $value = \Closure::bind(static fn () => $dummyPersistence->binaryTypeValueDecode($value), null, Persistence\Sql::class)(); |
| 247: | |
| 248: | if ($platform instanceof PostgreSQLPlatform) { |
| 249: | return 'decode(\'' . bin2hex($value) . '\', \'hex\')'; |
| 250: | } |
| 251: | |
| 252: | return 'CONVERT(VARBINARY(MAX), \'' . bin2hex($value) . '\', 2)'; |
| 253: | } |
| 254: | } |
| 255: | |
| 256: | $parts = []; |
| 257: | foreach (explode("\0", $value) as $i => $v) { |
| 258: | if ($i > 0) { |
| 259: | if ($platform instanceof PostgreSQLPlatform) { |
| 260: | |
| 261: | $parts[] = 'convert_from(decode(\'00\', \'hex\'), \'UTF8\')'; |
| 262: | } elseif ($platform instanceof SQLServerPlatform) { |
| 263: | $parts[] = 'NCHAR(0)'; |
| 264: | } elseif ($platform instanceof OraclePlatform) { |
| 265: | $parts[] = 'CHR(0)'; |
| 266: | } else { |
| 267: | $parts[] = 'x\'00\''; |
| 268: | } |
| 269: | } |
| 270: | |
| 271: | if ($v !== '') { |
| 272: | $parts[] = '\'' . str_replace('\'', '\'\'', $v) . '\''; |
| 273: | } |
| 274: | } |
| 275: | if ($parts === []) { |
| 276: | $parts = ['\'\'']; |
| 277: | } |
| 278: | |
| 279: | $buildConcatSqlFx = static function (array $parts) use (&$buildConcatSqlFx, $platform): string { |
| 280: | if (count($parts) > 1) { |
| 281: | $partsLeft = array_slice($parts, 0, intdiv(count($parts), 2)); |
| 282: | $partsRight = array_slice($parts, count($partsLeft)); |
| 283: | |
| 284: | $sqlLeft = $buildConcatSqlFx($partsLeft); |
| 285: | if ($platform instanceof SQLServerPlatform && count($partsLeft) === 1) { |
| 286: | $sqlLeft = 'CAST(' . $sqlLeft . ' AS NVARCHAR(MAX))'; |
| 287: | } |
| 288: | |
| 289: | return ($platform instanceof SQLitePlatform ? '(' : 'CONCAT(') |
| 290: | . $sqlLeft |
| 291: | . ($platform instanceof SQLitePlatform ? ' || ' : ', ') |
| 292: | . $buildConcatSqlFx($partsRight) |
| 293: | . ')'; |
| 294: | } |
| 295: | |
| 296: | return reset($parts); |
| 297: | }; |
| 298: | |
| 299: | return $buildConcatSqlFx($parts); |
| 300: | } |
| 301: | |
| 302: | |
| 303: | |
| 304: | |
| 305: | |
| 306: | |
| 307: | |
| 308: | protected function escapeIdentifier(string $value): string |
| 309: | { |
| 310: | $char = $this->identifierEscapeChar; |
| 311: | |
| 312: | return ($char === ']' ? '[' : $char) |
| 313: | . str_replace($char, $char . $char, $value) |
| 314: | . $char; |
| 315: | } |
| 316: | |
| 317: | |
| 318: | |
| 319: | |
| 320: | |
| 321: | |
| 322: | |
| 323: | |
| 324: | |
| 325: | protected function escapeIdentifierSoft(string $value): string |
| 326: | { |
| 327: | if ($this->isUnescapableIdentifier($value)) { |
| 328: | return $value; |
| 329: | } |
| 330: | |
| 331: | if (str_contains($value, '.')) { |
| 332: | return implode('.', array_map(fn ($v) => $this->escapeIdentifierSoft($v), explode('.', $value))); |
| 333: | } |
| 334: | |
| 335: | return $this->escapeIdentifier($value); |
| 336: | } |
| 337: | |
| 338: | |
| 339: | |
| 340: | |
| 341: | |
| 342: | protected function isUnescapableIdentifier(string $value): bool |
| 343: | { |
| 344: | return $value === '*' |
| 345: | || str_contains($value, '(') |
| 346: | || str_contains($value, $this->identifierEscapeChar); |
| 347: | } |
| 348: | |
| 349: | |
| 350: | |
| 351: | |
| 352: | private function _render(): array |
| 353: | { |
| 354: | |
| 355: | |
| 356: | |
| 357: | $namelessCount = 0; |
| 358: | $res = preg_replace_callback( |
| 359: | '~(?!\[\w*\])' . self::QUOTED_TOKEN_REGEX . '\K|\[\w*\]|\{\w*\}|\{\{\w*\}\}~', |
| 360: | function ($matches) use (&$namelessCount) { |
| 361: | if ($matches[0] === '') { |
| 362: | return ''; |
| 363: | } |
| 364: | |
| 365: | $identifier = substr($matches[0], 1, -1); |
| 366: | |
| 367: | $escapeMode = null; |
| 368: | if (substr($matches[0], 0, 1) === '[') { |
| 369: | $escapeMode = self::ESCAPE_PARAM; |
| 370: | } elseif (substr($matches[0], 0, 1) === '{') { |
| 371: | if (substr($matches[0], 1, 1) === '{') { |
| 372: | $escapeMode = self::ESCAPE_IDENTIFIER_SOFT; |
| 373: | $identifier = substr($identifier, 1, -1); |
| 374: | } else { |
| 375: | $escapeMode = self::ESCAPE_IDENTIFIER; |
| 376: | } |
| 377: | } |
| 378: | |
| 379: | |
| 380: | if ($identifier === '') { |
| 381: | $identifier = $namelessCount++; |
| 382: | |
| 383: | |
| 384: | } |
| 385: | |
| 386: | if (array_key_exists($identifier, $this->args['custom'])) { |
| 387: | $value = $this->consume($this->args['custom'][$identifier], $escapeMode); |
| 388: | } else { |
| 389: | $renderMethodName = !is_int($identifier) ? '_render' . ucfirst($identifier) : null; |
| 390: | if ($renderMethodName !== null |
| 391: | && method_exists($this, $renderMethodName) |
| 392: | && (new \ReflectionMethod($this, $renderMethodName))->getName() === $renderMethodName |
| 393: | ) { |
| 394: | $value = $this->{$renderMethodName}(); |
| 395: | } else { |
| 396: | throw (new Exception('Expression could not render tag')) |
| 397: | ->addMoreInfo('tag', $identifier); |
| 398: | } |
| 399: | } |
| 400: | |
| 401: | return $value; |
| 402: | }, |
| 403: | $this->template |
| 404: | ); |
| 405: | |
| 406: | return [trim($res), $this->renderParams]; |
| 407: | } |
| 408: | |
| 409: | |
| 410: | |
| 411: | |
| 412: | |
| 413: | |
| 414: | public function render(): array |
| 415: | { |
| 416: | if ($this->template === null) { |
| 417: | throw new Exception('Template is not defined for Expression'); |
| 418: | } |
| 419: | |
| 420: | try { |
| 421: | $this->renderParamBase = $this->paramBase; |
| 422: | $this->renderParams = []; |
| 423: | |
| 424: | return $this->_render(); |
| 425: | } finally { |
| 426: | $this->renderParamBase = null; |
| 427: | $this->renderParams = null; |
| 428: | } |
| 429: | } |
| 430: | |
| 431: | |
| 432: | |
| 433: | |
| 434: | protected function renderNested(): array |
| 435: | { |
| 436: | [$sql, $params] = $this->render(); |
| 437: | |
| 438: | return ['(' . $sql . ')', $params]; |
| 439: | } |
| 440: | |
| 441: | |
| 442: | |
| 443: | |
| 444: | public function getDebugQuery(): string |
| 445: | { |
| 446: | [$sql, $params] = $this->render(); |
| 447: | |
| 448: | $i = 0; |
| 449: | $sql = preg_replace_callback( |
| 450: | '~' . self::QUOTED_TOKEN_REGEX . '\K|(?:\?|:\w+)~', |
| 451: | static function ($matches) use ($params, &$i) { |
| 452: | if ($matches[0] === '') { |
| 453: | return ''; |
| 454: | } |
| 455: | |
| 456: | $k = $matches[0] === '?' ? ++$i : $matches[0]; |
| 457: | if (!array_key_exists($k, $params)) { |
| 458: | return $matches[0]; |
| 459: | } |
| 460: | |
| 461: | $v = $params[$k]; |
| 462: | |
| 463: | if ($v === null) { |
| 464: | return 'NULL'; |
| 465: | } elseif (is_bool($v)) { |
| 466: | return $v ? 'true' : 'false'; |
| 467: | } elseif (is_int($v)) { |
| 468: | return (string) $v; |
| 469: | } elseif (is_float($v)) { |
| 470: | return self::castFloatToString($v); |
| 471: | } elseif (strlen($v) > 4096) { |
| 472: | return '*long string* (length: ' . strlen($v) . ' bytes, sha256: ' . hash('sha256', $v) . ')'; |
| 473: | } |
| 474: | |
| 475: | return '\'' . str_replace('\'', '\'\'', $v) . '\''; |
| 476: | }, |
| 477: | $sql |
| 478: | ); |
| 479: | |
| 480: | if (class_exists(\SqlFormatter::class)) { |
| 481: | \Closure::bind(static function () { |
| 482: | |
| 483: | if (end(\SqlFormatter::$reserved_toplevel) === 'INTERSECT') { |
| 484: | \SqlFormatter::$reserved_toplevel[] = 'OFFSET'; |
| 485: | \SqlFormatter::$reserved_toplevel[] = 'FETCH'; |
| 486: | } |
| 487: | }, null, \SqlFormatter::class)(); |
| 488: | |
| 489: | $sql = preg_replace('~' . self::QUOTED_TOKEN_REGEX . '\K| +(?=\n)|(?<=:) (?=\w)~', '', \SqlFormatter::format($sql, false)); |
| 490: | } |
| 491: | |
| 492: | return $sql; |
| 493: | } |
| 494: | |
| 495: | |
| 496: | |
| 497: | |
| 498: | public function __debugInfo(): array |
| 499: | { |
| 500: | $arr = [ |
| 501: | 'R' => 'n/a', |
| 502: | 'R_params' => 'n/a', |
| 503: | 'template' => $this->template, |
| 504: | 'templateArgs' => $this->args, |
| 505: | ]; |
| 506: | |
| 507: | try { |
| 508: | $arr['R'] = $this->getDebugQuery(); |
| 509: | $arr['R_params'] = $this->render()[1]; |
| 510: | } catch (\Exception $e) { |
| 511: | $arr['R'] = get_class($e) . ': ' . $e->getMessage(); |
| 512: | } |
| 513: | |
| 514: | return $arr; |
| 515: | } |
| 516: | |
| 517: | protected function hasNativeNamedParamSupport(): bool |
| 518: | { |
| 519: | return true; |
| 520: | } |
| 521: | |
| 522: | |
| 523: | |
| 524: | |
| 525: | |
| 526: | |
| 527: | |
| 528: | |
| 529: | protected function updateRenderBeforeExecute(array $render): array |
| 530: | { |
| 531: | [$sql, $params] = $render; |
| 532: | |
| 533: | if (!$this->hasNativeNamedParamSupport()) { |
| 534: | $numParams = []; |
| 535: | $i = 0; |
| 536: | $j = 0; |
| 537: | $sql = preg_replace_callback( |
| 538: | '~' . self::QUOTED_TOKEN_REGEX . '\K|(?:\?|:\w+)~', |
| 539: | static function ($matches) use ($params, &$numParams, &$i, &$j) { |
| 540: | if ($matches[0] === '') { |
| 541: | return ''; |
| 542: | } |
| 543: | |
| 544: | $numParams[++$i] = $params[$matches[0] === '?' ? ++$j : $matches[0]]; |
| 545: | |
| 546: | return '?'; |
| 547: | }, |
| 548: | $sql |
| 549: | ); |
| 550: | $params = $numParams; |
| 551: | } |
| 552: | |
| 553: | return [$sql, $params]; |
| 554: | } |
| 555: | |
| 556: | |
| 557: | |
| 558: | |
| 559: | |
| 560: | |
| 561: | protected function _executeStatement(Statement $statement, bool $fromExecuteStatement) |
| 562: | { |
| 563: | if ($fromExecuteStatement) { |
| 564: | $result = $statement->executeStatement(); |
| 565: | } else { |
| 566: | $result = $statement->executeQuery(); |
| 567: | } |
| 568: | |
| 569: | return $result; |
| 570: | } |
| 571: | |
| 572: | |
| 573: | |
| 574: | |
| 575: | |
| 576: | |
| 577: | protected function _execute(?object $connection, bool $fromExecuteStatement) |
| 578: | { |
| 579: | if ($connection === null) { |
| 580: | $connection = $this->connection; |
| 581: | } |
| 582: | |
| 583: | if (!$connection instanceof DbalConnection) { |
| 584: | if ($fromExecuteStatement) { |
| 585: | return $connection->executeStatement($this); |
| 586: | } |
| 587: | |
| 588: | return $connection->executeQuery($this); |
| 589: | } |
| 590: | |
| 591: | [$sql, $params] = $this->updateRenderBeforeExecute($this->render()); |
| 592: | |
| 593: | $platform = $this->connection->getDatabasePlatform(); |
| 594: | try { |
| 595: | $statement = $connection->prepare($sql); |
| 596: | |
| 597: | foreach ($params as $key => $val) { |
| 598: | if ($val === null) { |
| 599: | $type = ParameterType::NULL; |
| 600: | } elseif (is_bool($val)) { |
| 601: | $type = ParameterType::BOOLEAN; |
| 602: | if ($platform instanceof OraclePlatform) { |
| 603: | $val = $val ? '1' : '0'; |
| 604: | } |
| 605: | } elseif (is_int($val)) { |
| 606: | $type = ParameterType::INTEGER; |
| 607: | } elseif (is_float($val)) { |
| 608: | $val = self::castFloatToString($val); |
| 609: | $type = ParameterType::STRING; |
| 610: | } elseif (is_string($val)) { |
| 611: | $type = ParameterType::STRING; |
| 612: | |
| 613: | if ($platform instanceof PostgreSQLPlatform || $platform instanceof SQLServerPlatform) { |
| 614: | $dummyPersistence = new Persistence\Sql($this->connection); |
| 615: | if (\Closure::bind(static fn () => $dummyPersistence->binaryTypeValueIsEncoded($val), null, Persistence\Sql::class)()) { |
| 616: | $val = \Closure::bind(static fn () => $dummyPersistence->binaryTypeValueDecode($val), null, Persistence\Sql::class)(); |
| 617: | $type = ParameterType::BINARY; |
| 618: | } |
| 619: | } |
| 620: | } elseif (is_resource($val)) { |
| 621: | throw new Exception('Resource type is not supported, set value as string instead'); |
| 622: | } else { |
| 623: | throw (new Exception('Unsupported param type')) |
| 624: | ->addMoreInfo('key', $key) |
| 625: | ->addMoreInfo('value', $val) |
| 626: | ->addMoreInfo('type', gettype($val)); |
| 627: | } |
| 628: | |
| 629: | $bindResult = $statement->bindValue($key, $val, $type); |
| 630: | if (!$bindResult) { |
| 631: | throw (new Exception('Unable to bind parameter')) |
| 632: | ->addMoreInfo('param', $key) |
| 633: | ->addMoreInfo('value', $val) |
| 634: | ->addMoreInfo('type', $type); |
| 635: | } |
| 636: | } |
| 637: | |
| 638: | return $this->_executeStatement($statement, $fromExecuteStatement); |
| 639: | } catch (DbalException $e) { |
| 640: | $firstException = $e; |
| 641: | while ($firstException->getPrevious() !== null) { |
| 642: | $firstException = $firstException->getPrevious(); |
| 643: | } |
| 644: | $errorInfo = $firstException instanceof \PDOException ? $firstException->errorInfo : null; |
| 645: | |
| 646: | $eNew = (new ExecuteException('Dsql execute error', $errorInfo[1] ?? $e->getCode(), $e)); |
| 647: | if ($errorInfo !== null && $errorInfo !== []) { |
| 648: | $eNew->addMoreInfo('error', $errorInfo[2] ?? 'n/a (' . $errorInfo[0] . ')'); |
| 649: | } |
| 650: | $eNew->addMoreInfo('query', $this->getDebugQuery()); |
| 651: | |
| 652: | throw $eNew; |
| 653: | } |
| 654: | } |
| 655: | |
| 656: | |
| 657: | |
| 658: | |
| 659: | public function executeQuery(object $connection = null): DbalResult |
| 660: | { |
| 661: | return $this->_execute($connection, false); |
| 662: | } |
| 663: | |
| 664: | |
| 665: | |
| 666: | |
| 667: | |
| 668: | |
| 669: | public function executeStatement(object $connection = null): int |
| 670: | { |
| 671: | return $this->_execute($connection, true); |
| 672: | } |
| 673: | |
| 674: | |
| 675: | |
| 676: | |
| 677: | |
| 678: | |
| 679: | final public static function castFloatToString(float $value): string |
| 680: | { |
| 681: | $precisionBackup = ini_get('precision'); |
| 682: | ini_set('precision', '-1'); |
| 683: | try { |
| 684: | $valueStr = (string) $value; |
| 685: | |
| 686: | return is_finite($value) && str_contains($valueStr, '.') === false |
| 687: | ? $valueStr . '.0' |
| 688: | : $valueStr; |
| 689: | } finally { |
| 690: | ini_set('precision', $precisionBackup); |
| 691: | } |
| 692: | } |
| 693: | |
| 694: | |
| 695: | |
| 696: | |
| 697: | private function castGetValue($v): ?string |
| 698: | { |
| 699: | if (is_bool($v)) { |
| 700: | return $v ? '1' : '0'; |
| 701: | } elseif (is_int($v)) { |
| 702: | return (string) $v; |
| 703: | } elseif (is_float($v)) { |
| 704: | $res = self::castFloatToString($v); |
| 705: | |
| 706: | if (str_ends_with($res, '.0')) { |
| 707: | $res = substr($res, 0, -2); |
| 708: | } |
| 709: | |
| 710: | return $res; |
| 711: | } |
| 712: | |
| 713: | |
| 714: | if (is_resource($v) && get_resource_type($v) === 'stream') { |
| 715: | $platform = $this->connection->getDatabasePlatform(); |
| 716: | if ($platform instanceof PostgreSQLPlatform || $platform instanceof OraclePlatform) { |
| 717: | $v = stream_get_contents($v); |
| 718: | } |
| 719: | } |
| 720: | |
| 721: | return $v; |
| 722: | } |
| 723: | |
| 724: | |
| 725: | |
| 726: | |
| 727: | public function getRowsIterator(): \Traversable |
| 728: | { |
| 729: | $result = $this->executeQuery(); |
| 730: | if ($this->connection->getDatabasePlatform() instanceof SQLServerPlatform) { |
| 731: | |
| 732: | $iterator = $result->fetchAllAssociative(); |
| 733: | } else { |
| 734: | $iterator = $result->iterateAssociative(); |
| 735: | } |
| 736: | |
| 737: | foreach ($iterator as $row) { |
| 738: | yield array_map(function ($v) { |
| 739: | return $this->castGetValue($v); |
| 740: | }, $row); |
| 741: | } |
| 742: | } |
| 743: | |
| 744: | |
| 745: | |
| 746: | |
| 747: | |
| 748: | |
| 749: | public function getRows(): array |
| 750: | { |
| 751: | $result = $this->executeQuery(); |
| 752: | |
| 753: | if ($this->connection->getDatabasePlatform() instanceof OraclePlatform) { |
| 754: | |
| 755: | |
| 756: | |
| 757: | $res = []; |
| 758: | while (($row = $result->fetchAssociative()) !== false) { |
| 759: | $res[] = array_map(function ($v) { |
| 760: | return $this->castGetValue($v); |
| 761: | }, $row); |
| 762: | } |
| 763: | |
| 764: | return $res; |
| 765: | } |
| 766: | |
| 767: | $rows = $result->fetchAllAssociative(); |
| 768: | |
| 769: | return array_map(function ($row) { |
| 770: | return array_map(function ($v) { |
| 771: | return $this->castGetValue($v); |
| 772: | }, $row); |
| 773: | }, $rows); |
| 774: | } |
| 775: | |
| 776: | |
| 777: | |
| 778: | |
| 779: | |
| 780: | |
| 781: | public function getRow(): ?array |
| 782: | { |
| 783: | $row = $this->executeQuery()->fetchAssociative(); |
| 784: | |
| 785: | if ($row === false) { |
| 786: | return null; |
| 787: | } |
| 788: | |
| 789: | return array_map(function ($v) { |
| 790: | return $this->castGetValue($v); |
| 791: | }, $row); |
| 792: | } |
| 793: | |
| 794: | |
| 795: | |
| 796: | |
| 797: | public function getOne(): ?string |
| 798: | { |
| 799: | $row = $this->executeQuery()->fetchAssociative(); |
| 800: | |
| 801: | if ($row === false || count($row) === 0) { |
| 802: | throw (new Exception('Unable to fetch single cell of data')) |
| 803: | ->addMoreInfo('result', $row) |
| 804: | ->addMoreInfo('query', $this->getDebugQuery()); |
| 805: | } |
| 806: | |
| 807: | return $this->castGetValue(reset($row)); |
| 808: | } |
| 809: | |
| 810: | |
| 811: | } |
| 812: | |