OCI8Statement.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. <?php
  2. namespace Doctrine\DBAL\Driver\OCI8;
  3. use Doctrine\DBAL\Driver\FetchUtils;
  4. use Doctrine\DBAL\Driver\OCI8\Exception\NonTerminatedStringLiteral;
  5. use Doctrine\DBAL\Driver\OCI8\Exception\UnknownParameterIndex;
  6. use Doctrine\DBAL\Driver\Result;
  7. use Doctrine\DBAL\Driver\Statement as StatementInterface;
  8. use Doctrine\DBAL\Driver\StatementIterator;
  9. use Doctrine\DBAL\FetchMode;
  10. use Doctrine\DBAL\ParameterType;
  11. use InvalidArgumentException;
  12. use IteratorAggregate;
  13. use PDO;
  14. use function array_key_exists;
  15. use function assert;
  16. use function count;
  17. use function implode;
  18. use function is_int;
  19. use function is_resource;
  20. use function oci_bind_by_name;
  21. use function oci_cancel;
  22. use function oci_error;
  23. use function oci_execute;
  24. use function oci_fetch_all;
  25. use function oci_fetch_array;
  26. use function oci_fetch_object;
  27. use function oci_new_descriptor;
  28. use function oci_num_fields;
  29. use function oci_num_rows;
  30. use function oci_parse;
  31. use function preg_match;
  32. use function preg_quote;
  33. use function substr;
  34. use const OCI_ASSOC;
  35. use const OCI_B_BIN;
  36. use const OCI_B_BLOB;
  37. use const OCI_BOTH;
  38. use const OCI_D_LOB;
  39. use const OCI_FETCHSTATEMENT_BY_COLUMN;
  40. use const OCI_FETCHSTATEMENT_BY_ROW;
  41. use const OCI_NUM;
  42. use const OCI_RETURN_LOBS;
  43. use const OCI_RETURN_NULLS;
  44. use const OCI_TEMP_BLOB;
  45. use const PREG_OFFSET_CAPTURE;
  46. use const SQLT_CHR;
  47. /**
  48. * The OCI8 implementation of the Statement interface.
  49. *
  50. * @deprecated Use {@link Statement} instead
  51. */
  52. class OCI8Statement implements IteratorAggregate, StatementInterface, Result
  53. {
  54. /** @var resource */
  55. protected $_dbh;
  56. /** @var resource */
  57. protected $_sth;
  58. /** @var OCI8Connection */
  59. protected $_conn;
  60. /**
  61. * @deprecated
  62. *
  63. * @var string
  64. */
  65. protected static $_PARAM = ':param';
  66. /** @var int[] */
  67. protected static $fetchModeMap = [
  68. FetchMode::MIXED => OCI_BOTH,
  69. FetchMode::ASSOCIATIVE => OCI_ASSOC,
  70. FetchMode::NUMERIC => OCI_NUM,
  71. FetchMode::COLUMN => OCI_NUM,
  72. ];
  73. /** @var int */
  74. protected $_defaultFetchMode = FetchMode::MIXED;
  75. /** @var string[] */
  76. protected $_paramMap = [];
  77. /**
  78. * Holds references to bound parameter values.
  79. *
  80. * This is a new requirement for PHP7's oci8 extension that prevents bound values from being garbage collected.
  81. *
  82. * @var mixed[]
  83. */
  84. private $boundValues = [];
  85. /**
  86. * Indicates whether the statement is in the state when fetching results is possible
  87. *
  88. * @var bool
  89. */
  90. private $result = false;
  91. /**
  92. * Creates a new OCI8Statement that uses the given connection handle and SQL statement.
  93. *
  94. * @internal The statement can be only instantiated by its driver connection.
  95. *
  96. * @param resource $dbh The connection handle.
  97. * @param string $query The SQL query.
  98. */
  99. public function __construct($dbh, $query, OCI8Connection $conn)
  100. {
  101. [$query, $paramMap] = self::convertPositionalToNamedPlaceholders($query);
  102. $stmt = oci_parse($dbh, $query);
  103. assert(is_resource($stmt));
  104. $this->_sth = $stmt;
  105. $this->_dbh = $dbh;
  106. $this->_paramMap = $paramMap;
  107. $this->_conn = $conn;
  108. }
  109. /**
  110. * Converts positional (?) into named placeholders (:param<num>).
  111. *
  112. * Oracle does not support positional parameters, hence this method converts all
  113. * positional parameters into artificially named parameters. Note that this conversion
  114. * is not perfect. All question marks (?) in the original statement are treated as
  115. * placeholders and converted to a named parameter.
  116. *
  117. * The algorithm uses a state machine with two possible states: InLiteral and NotInLiteral.
  118. * Question marks inside literal strings are therefore handled correctly by this method.
  119. * This comes at a cost, the whole sql statement has to be looped over.
  120. *
  121. * @internal
  122. *
  123. * @param string $statement The SQL statement to convert.
  124. *
  125. * @return mixed[] [0] => the statement value (string), [1] => the paramMap value (array).
  126. *
  127. * @throws OCI8Exception
  128. *
  129. * @todo extract into utility class in Doctrine\DBAL\Util namespace
  130. * @todo review and test for lost spaces. we experienced missing spaces with oci8 in some sql statements.
  131. */
  132. public static function convertPositionalToNamedPlaceholders($statement)
  133. {
  134. $fragmentOffset = $tokenOffset = 0;
  135. $fragments = $paramMap = [];
  136. $currentLiteralDelimiter = null;
  137. do {
  138. if (! $currentLiteralDelimiter) {
  139. $result = self::findPlaceholderOrOpeningQuote(
  140. $statement,
  141. $tokenOffset,
  142. $fragmentOffset,
  143. $fragments,
  144. $currentLiteralDelimiter,
  145. $paramMap
  146. );
  147. } else {
  148. $result = self::findClosingQuote($statement, $tokenOffset, $currentLiteralDelimiter);
  149. }
  150. } while ($result);
  151. if ($currentLiteralDelimiter !== null) {
  152. throw NonTerminatedStringLiteral::new($tokenOffset - 1);
  153. }
  154. $fragments[] = substr($statement, $fragmentOffset);
  155. $statement = implode('', $fragments);
  156. return [$statement, $paramMap];
  157. }
  158. /**
  159. * Finds next placeholder or opening quote.
  160. *
  161. * @param string $statement The SQL statement to parse
  162. * @param int $tokenOffset The offset to start searching from
  163. * @param int $fragmentOffset The offset to build the next fragment from
  164. * @param string[] $fragments Fragments of the original statement
  165. * not containing placeholders
  166. * @param string|null $currentLiteralDelimiter The delimiter of the current string literal
  167. * or NULL if not currently in a literal
  168. * @param array<int, string> $paramMap Mapping of the original parameter positions
  169. * to their named replacements
  170. *
  171. * @return bool Whether the token was found
  172. */
  173. private static function findPlaceholderOrOpeningQuote(
  174. $statement,
  175. &$tokenOffset,
  176. &$fragmentOffset,
  177. &$fragments,
  178. &$currentLiteralDelimiter,
  179. &$paramMap
  180. ) {
  181. $token = self::findToken($statement, $tokenOffset, '/[?\'"]/');
  182. if (! $token) {
  183. return false;
  184. }
  185. if ($token === '?') {
  186. $position = count($paramMap) + 1;
  187. $param = ':param' . $position;
  188. $fragments[] = substr($statement, $fragmentOffset, $tokenOffset - $fragmentOffset);
  189. $fragments[] = $param;
  190. $paramMap[$position] = $param;
  191. $tokenOffset += 1;
  192. $fragmentOffset = $tokenOffset;
  193. return true;
  194. }
  195. $currentLiteralDelimiter = $token;
  196. ++$tokenOffset;
  197. return true;
  198. }
  199. /**
  200. * Finds closing quote
  201. *
  202. * @param string $statement The SQL statement to parse
  203. * @param int $tokenOffset The offset to start searching from
  204. * @param string $currentLiteralDelimiter The delimiter of the current string literal
  205. *
  206. * @return bool Whether the token was found
  207. *
  208. * @param-out string|null $currentLiteralDelimiter
  209. */
  210. private static function findClosingQuote(
  211. $statement,
  212. &$tokenOffset,
  213. &$currentLiteralDelimiter
  214. ) {
  215. $token = self::findToken(
  216. $statement,
  217. $tokenOffset,
  218. '/' . preg_quote($currentLiteralDelimiter, '/') . '/'
  219. );
  220. if (! $token) {
  221. return false;
  222. }
  223. $currentLiteralDelimiter = null;
  224. ++$tokenOffset;
  225. return true;
  226. }
  227. /**
  228. * Finds the token described by regex starting from the given offset. Updates the offset with the position
  229. * where the token was found.
  230. *
  231. * @param string $statement The SQL statement to parse
  232. * @param int $offset The offset to start searching from
  233. * @param string $regex The regex containing token pattern
  234. *
  235. * @return string|null Token or NULL if not found
  236. */
  237. private static function findToken($statement, &$offset, $regex)
  238. {
  239. if (preg_match($regex, $statement, $matches, PREG_OFFSET_CAPTURE, $offset)) {
  240. $offset = $matches[0][1];
  241. return $matches[0][0];
  242. }
  243. return null;
  244. }
  245. /**
  246. * {@inheritdoc}
  247. */
  248. public function bindValue($param, $value, $type = ParameterType::STRING)
  249. {
  250. return $this->bindParam($param, $value, $type, null);
  251. }
  252. /**
  253. * {@inheritdoc}
  254. */
  255. public function bindParam($param, &$variable, $type = ParameterType::STRING, $length = null)
  256. {
  257. if (is_int($param)) {
  258. if (! isset($this->_paramMap[$param])) {
  259. throw UnknownParameterIndex::new($param);
  260. }
  261. $param = $this->_paramMap[$param];
  262. }
  263. if ($type === ParameterType::LARGE_OBJECT) {
  264. $lob = oci_new_descriptor($this->_dbh, OCI_D_LOB);
  265. assert($lob !== false);
  266. $lob->writeTemporary($variable, OCI_TEMP_BLOB);
  267. $variable =& $lob;
  268. }
  269. $this->boundValues[$param] =& $variable;
  270. return oci_bind_by_name(
  271. $this->_sth,
  272. $param,
  273. $variable,
  274. $length ?? -1,
  275. $this->convertParameterType($type)
  276. );
  277. }
  278. /**
  279. * Converts DBAL parameter type to oci8 parameter type
  280. */
  281. private function convertParameterType(int $type): int
  282. {
  283. switch ($type) {
  284. case ParameterType::BINARY:
  285. return OCI_B_BIN;
  286. case ParameterType::LARGE_OBJECT:
  287. return OCI_B_BLOB;
  288. default:
  289. return SQLT_CHR;
  290. }
  291. }
  292. /**
  293. * {@inheritdoc}
  294. *
  295. * @deprecated Use free() instead.
  296. */
  297. public function closeCursor()
  298. {
  299. $this->free();
  300. return true;
  301. }
  302. /**
  303. * {@inheritdoc}
  304. */
  305. public function columnCount()
  306. {
  307. return oci_num_fields($this->_sth) ?: 0;
  308. }
  309. /**
  310. * {@inheritdoc}
  311. *
  312. * @deprecated The error information is available via exceptions.
  313. */
  314. public function errorCode()
  315. {
  316. $error = oci_error($this->_sth);
  317. if ($error !== false) {
  318. $error = $error['code'];
  319. }
  320. return $error;
  321. }
  322. /**
  323. * {@inheritdoc}
  324. *
  325. * @deprecated The error information is available via exceptions.
  326. */
  327. public function errorInfo()
  328. {
  329. $error = oci_error($this->_sth);
  330. if ($error === false) {
  331. return [];
  332. }
  333. return $error;
  334. }
  335. /**
  336. * {@inheritdoc}
  337. */
  338. public function execute($params = null)
  339. {
  340. if ($params) {
  341. $hasZeroIndex = array_key_exists(0, $params);
  342. foreach ($params as $key => $val) {
  343. if ($hasZeroIndex && is_int($key)) {
  344. $this->bindValue($key + 1, $val);
  345. } else {
  346. $this->bindValue($key, $val);
  347. }
  348. }
  349. }
  350. $ret = @oci_execute($this->_sth, $this->_conn->getExecuteMode());
  351. if (! $ret) {
  352. throw OCI8Exception::fromErrorInfo($this->errorInfo());
  353. }
  354. $this->result = true;
  355. return $ret;
  356. }
  357. /**
  358. * {@inheritdoc}
  359. *
  360. * @deprecated Use one of the fetch- or iterate-related methods.
  361. */
  362. public function setFetchMode($fetchMode, $arg2 = null, $arg3 = null)
  363. {
  364. $this->_defaultFetchMode = $fetchMode;
  365. return true;
  366. }
  367. /**
  368. * {@inheritdoc}
  369. *
  370. * @deprecated Use iterateNumeric(), iterateAssociative() or iterateColumn() instead.
  371. */
  372. public function getIterator()
  373. {
  374. return new StatementIterator($this);
  375. }
  376. /**
  377. * {@inheritdoc}
  378. *
  379. * @deprecated Use fetchNumeric(), fetchAssociative() or fetchOne() instead.
  380. */
  381. public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEXT, $cursorOffset = 0)
  382. {
  383. // do not try fetching from the statement if it's not expected to contain result
  384. // in order to prevent exceptional situation
  385. if (! $this->result) {
  386. return false;
  387. }
  388. $fetchMode = $fetchMode ?: $this->_defaultFetchMode;
  389. if ($fetchMode === FetchMode::COLUMN) {
  390. return $this->fetchColumn();
  391. }
  392. if ($fetchMode === FetchMode::STANDARD_OBJECT) {
  393. return oci_fetch_object($this->_sth);
  394. }
  395. if (! isset(self::$fetchModeMap[$fetchMode])) {
  396. throw new InvalidArgumentException('Invalid fetch style: ' . $fetchMode);
  397. }
  398. return oci_fetch_array(
  399. $this->_sth,
  400. self::$fetchModeMap[$fetchMode] | OCI_RETURN_NULLS | OCI_RETURN_LOBS
  401. );
  402. }
  403. /**
  404. * {@inheritdoc}
  405. *
  406. * @deprecated Use fetchAllNumeric(), fetchAllAssociative() or fetchFirstColumn() instead.
  407. */
  408. public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = null)
  409. {
  410. $fetchMode = $fetchMode ?: $this->_defaultFetchMode;
  411. $result = [];
  412. if ($fetchMode === FetchMode::STANDARD_OBJECT) {
  413. while ($row = $this->fetch($fetchMode)) {
  414. $result[] = $row;
  415. }
  416. return $result;
  417. }
  418. if (! isset(self::$fetchModeMap[$fetchMode])) {
  419. throw new InvalidArgumentException('Invalid fetch style: ' . $fetchMode);
  420. }
  421. if (self::$fetchModeMap[$fetchMode] === OCI_BOTH) {
  422. while ($row = $this->fetch($fetchMode)) {
  423. $result[] = $row;
  424. }
  425. } else {
  426. $fetchStructure = OCI_FETCHSTATEMENT_BY_ROW;
  427. if ($fetchMode === FetchMode::COLUMN) {
  428. $fetchStructure = OCI_FETCHSTATEMENT_BY_COLUMN;
  429. }
  430. // do not try fetching from the statement if it's not expected to contain result
  431. // in order to prevent exceptional situation
  432. if (! $this->result) {
  433. return [];
  434. }
  435. oci_fetch_all(
  436. $this->_sth,
  437. $result,
  438. 0,
  439. -1,
  440. self::$fetchModeMap[$fetchMode] | OCI_RETURN_NULLS | $fetchStructure | OCI_RETURN_LOBS
  441. );
  442. if ($fetchMode === FetchMode::COLUMN) {
  443. $result = $result[0];
  444. }
  445. }
  446. return $result;
  447. }
  448. /**
  449. * {@inheritdoc}
  450. *
  451. * @deprecated Use fetchOne() instead.
  452. */
  453. public function fetchColumn($columnIndex = 0)
  454. {
  455. // do not try fetching from the statement if it's not expected to contain result
  456. // in order to prevent exceptional situation
  457. if (! $this->result) {
  458. return false;
  459. }
  460. $row = oci_fetch_array($this->_sth, OCI_NUM | OCI_RETURN_NULLS | OCI_RETURN_LOBS);
  461. if ($row === false) {
  462. return false;
  463. }
  464. return $row[$columnIndex] ?? null;
  465. }
  466. /**
  467. * {@inheritdoc}
  468. */
  469. public function rowCount()
  470. {
  471. return oci_num_rows($this->_sth) ?: 0;
  472. }
  473. /**
  474. * {@inheritdoc}
  475. */
  476. public function fetchNumeric()
  477. {
  478. return $this->doFetch(OCI_NUM);
  479. }
  480. /**
  481. * {@inheritdoc}
  482. */
  483. public function fetchAssociative()
  484. {
  485. return $this->doFetch(OCI_ASSOC);
  486. }
  487. /**
  488. * {@inheritdoc}
  489. */
  490. public function fetchOne()
  491. {
  492. return FetchUtils::fetchOne($this);
  493. }
  494. /**
  495. * {@inheritdoc}
  496. */
  497. public function fetchAllNumeric(): array
  498. {
  499. return $this->doFetchAll(OCI_NUM, OCI_FETCHSTATEMENT_BY_ROW);
  500. }
  501. /**
  502. * {@inheritdoc}
  503. */
  504. public function fetchAllAssociative(): array
  505. {
  506. return $this->doFetchAll(OCI_ASSOC, OCI_FETCHSTATEMENT_BY_ROW);
  507. }
  508. /**
  509. * {@inheritdoc}
  510. */
  511. public function fetchFirstColumn(): array
  512. {
  513. return $this->doFetchAll(OCI_NUM, OCI_FETCHSTATEMENT_BY_COLUMN)[0];
  514. }
  515. public function free(): void
  516. {
  517. // not having the result means there's nothing to close
  518. if (! $this->result) {
  519. return;
  520. }
  521. oci_cancel($this->_sth);
  522. $this->result = false;
  523. }
  524. /**
  525. * @return mixed|false
  526. */
  527. private function doFetch(int $mode)
  528. {
  529. // do not try fetching from the statement if it's not expected to contain the result
  530. // in order to prevent exceptional situation
  531. if (! $this->result) {
  532. return false;
  533. }
  534. return oci_fetch_array(
  535. $this->_sth,
  536. $mode | OCI_RETURN_NULLS | OCI_RETURN_LOBS
  537. );
  538. }
  539. /**
  540. * @return array<mixed>
  541. */
  542. private function doFetchAll(int $mode, int $fetchStructure): array
  543. {
  544. // do not try fetching from the statement if it's not expected to contain the result
  545. // in order to prevent exceptional situation
  546. if (! $this->result) {
  547. return [];
  548. }
  549. oci_fetch_all(
  550. $this->_sth,
  551. $result,
  552. 0,
  553. -1,
  554. $mode | OCI_RETURN_NULLS | $fetchStructure | OCI_RETURN_LOBS
  555. );
  556. return $result;
  557. }
  558. }