OCI8Statement.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  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) {
  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. private static function findClosingQuote(
  209. $statement,
  210. &$tokenOffset,
  211. &$currentLiteralDelimiter
  212. ) {
  213. $token = self::findToken(
  214. $statement,
  215. $tokenOffset,
  216. '/' . preg_quote($currentLiteralDelimiter, '/') . '/'
  217. );
  218. if (! $token) {
  219. return false;
  220. }
  221. $currentLiteralDelimiter = false;
  222. ++$tokenOffset;
  223. return true;
  224. }
  225. /**
  226. * Finds the token described by regex starting from the given offset. Updates the offset with the position
  227. * where the token was found.
  228. *
  229. * @param string $statement The SQL statement to parse
  230. * @param int $offset The offset to start searching from
  231. * @param string $regex The regex containing token pattern
  232. *
  233. * @return string|null Token or NULL if not found
  234. */
  235. private static function findToken($statement, &$offset, $regex)
  236. {
  237. if (preg_match($regex, $statement, $matches, PREG_OFFSET_CAPTURE, $offset)) {
  238. $offset = $matches[0][1];
  239. return $matches[0][0];
  240. }
  241. return null;
  242. }
  243. /**
  244. * {@inheritdoc}
  245. */
  246. public function bindValue($param, $value, $type = ParameterType::STRING)
  247. {
  248. return $this->bindParam($param, $value, $type, null);
  249. }
  250. /**
  251. * {@inheritdoc}
  252. */
  253. public function bindParam($param, &$variable, $type = ParameterType::STRING, $length = null)
  254. {
  255. if (is_int($param)) {
  256. if (! isset($this->_paramMap[$param])) {
  257. throw UnknownParameterIndex::new($param);
  258. }
  259. $param = $this->_paramMap[$param];
  260. }
  261. if ($type === ParameterType::LARGE_OBJECT) {
  262. $lob = oci_new_descriptor($this->_dbh, OCI_D_LOB);
  263. assert($lob !== false);
  264. $lob->writeTemporary($variable, OCI_TEMP_BLOB);
  265. $variable =& $lob;
  266. }
  267. $this->boundValues[$param] =& $variable;
  268. return oci_bind_by_name(
  269. $this->_sth,
  270. $param,
  271. $variable,
  272. $length ?? -1,
  273. $this->convertParameterType($type)
  274. );
  275. }
  276. /**
  277. * Converts DBAL parameter type to oci8 parameter type
  278. */
  279. private function convertParameterType(int $type): int
  280. {
  281. switch ($type) {
  282. case ParameterType::BINARY:
  283. return OCI_B_BIN;
  284. case ParameterType::LARGE_OBJECT:
  285. return OCI_B_BLOB;
  286. default:
  287. return SQLT_CHR;
  288. }
  289. }
  290. /**
  291. * {@inheritdoc}
  292. *
  293. * @deprecated Use free() instead.
  294. */
  295. public function closeCursor()
  296. {
  297. $this->free();
  298. return true;
  299. }
  300. /**
  301. * {@inheritdoc}
  302. */
  303. public function columnCount()
  304. {
  305. return oci_num_fields($this->_sth) ?: 0;
  306. }
  307. /**
  308. * {@inheritdoc}
  309. *
  310. * @deprecated The error information is available via exceptions.
  311. */
  312. public function errorCode()
  313. {
  314. $error = oci_error($this->_sth);
  315. if ($error !== false) {
  316. $error = $error['code'];
  317. }
  318. return $error;
  319. }
  320. /**
  321. * {@inheritdoc}
  322. *
  323. * @deprecated The error information is available via exceptions.
  324. */
  325. public function errorInfo()
  326. {
  327. $error = oci_error($this->_sth);
  328. if ($error === false) {
  329. return [];
  330. }
  331. return $error;
  332. }
  333. /**
  334. * {@inheritdoc}
  335. */
  336. public function execute($params = null)
  337. {
  338. if ($params) {
  339. $hasZeroIndex = array_key_exists(0, $params);
  340. foreach ($params as $key => $val) {
  341. if ($hasZeroIndex && is_int($key)) {
  342. $this->bindValue($key + 1, $val);
  343. } else {
  344. $this->bindValue($key, $val);
  345. }
  346. }
  347. }
  348. $ret = @oci_execute($this->_sth, $this->_conn->getExecuteMode());
  349. if (! $ret) {
  350. throw OCI8Exception::fromErrorInfo($this->errorInfo());
  351. }
  352. $this->result = true;
  353. return $ret;
  354. }
  355. /**
  356. * {@inheritdoc}
  357. *
  358. * @deprecated Use one of the fetch- or iterate-related methods.
  359. */
  360. public function setFetchMode($fetchMode, $arg2 = null, $arg3 = null)
  361. {
  362. $this->_defaultFetchMode = $fetchMode;
  363. return true;
  364. }
  365. /**
  366. * {@inheritdoc}
  367. *
  368. * @deprecated Use iterateNumeric(), iterateAssociative() or iterateColumn() instead.
  369. */
  370. public function getIterator()
  371. {
  372. return new StatementIterator($this);
  373. }
  374. /**
  375. * {@inheritdoc}
  376. *
  377. * @deprecated Use fetchNumeric(), fetchAssociative() or fetchOne() instead.
  378. */
  379. public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEXT, $cursorOffset = 0)
  380. {
  381. // do not try fetching from the statement if it's not expected to contain result
  382. // in order to prevent exceptional situation
  383. if (! $this->result) {
  384. return false;
  385. }
  386. $fetchMode = $fetchMode ?: $this->_defaultFetchMode;
  387. if ($fetchMode === FetchMode::COLUMN) {
  388. return $this->fetchColumn();
  389. }
  390. if ($fetchMode === FetchMode::STANDARD_OBJECT) {
  391. return oci_fetch_object($this->_sth);
  392. }
  393. if (! isset(self::$fetchModeMap[$fetchMode])) {
  394. throw new InvalidArgumentException('Invalid fetch style: ' . $fetchMode);
  395. }
  396. return oci_fetch_array(
  397. $this->_sth,
  398. self::$fetchModeMap[$fetchMode] | OCI_RETURN_NULLS | OCI_RETURN_LOBS
  399. );
  400. }
  401. /**
  402. * {@inheritdoc}
  403. *
  404. * @deprecated Use fetchAllNumeric(), fetchAllAssociative() or fetchFirstColumn() instead.
  405. */
  406. public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = null)
  407. {
  408. $fetchMode = $fetchMode ?: $this->_defaultFetchMode;
  409. $result = [];
  410. if ($fetchMode === FetchMode::STANDARD_OBJECT) {
  411. while ($row = $this->fetch($fetchMode)) {
  412. $result[] = $row;
  413. }
  414. return $result;
  415. }
  416. if (! isset(self::$fetchModeMap[$fetchMode])) {
  417. throw new InvalidArgumentException('Invalid fetch style: ' . $fetchMode);
  418. }
  419. if (self::$fetchModeMap[$fetchMode] === OCI_BOTH) {
  420. while ($row = $this->fetch($fetchMode)) {
  421. $result[] = $row;
  422. }
  423. } else {
  424. $fetchStructure = OCI_FETCHSTATEMENT_BY_ROW;
  425. if ($fetchMode === FetchMode::COLUMN) {
  426. $fetchStructure = OCI_FETCHSTATEMENT_BY_COLUMN;
  427. }
  428. // do not try fetching from the statement if it's not expected to contain result
  429. // in order to prevent exceptional situation
  430. if (! $this->result) {
  431. return [];
  432. }
  433. oci_fetch_all(
  434. $this->_sth,
  435. $result,
  436. 0,
  437. -1,
  438. self::$fetchModeMap[$fetchMode] | OCI_RETURN_NULLS | $fetchStructure | OCI_RETURN_LOBS
  439. );
  440. if ($fetchMode === FetchMode::COLUMN) {
  441. $result = $result[0];
  442. }
  443. }
  444. return $result;
  445. }
  446. /**
  447. * {@inheritdoc}
  448. *
  449. * @deprecated Use fetchOne() instead.
  450. */
  451. public function fetchColumn($columnIndex = 0)
  452. {
  453. // do not try fetching from the statement if it's not expected to contain result
  454. // in order to prevent exceptional situation
  455. if (! $this->result) {
  456. return false;
  457. }
  458. $row = oci_fetch_array($this->_sth, OCI_NUM | OCI_RETURN_NULLS | OCI_RETURN_LOBS);
  459. if ($row === false) {
  460. return false;
  461. }
  462. return $row[$columnIndex] ?? null;
  463. }
  464. /**
  465. * {@inheritdoc}
  466. */
  467. public function rowCount()
  468. {
  469. return oci_num_rows($this->_sth) ?: 0;
  470. }
  471. /**
  472. * {@inheritdoc}
  473. */
  474. public function fetchNumeric()
  475. {
  476. return $this->doFetch(OCI_NUM);
  477. }
  478. /**
  479. * {@inheritdoc}
  480. */
  481. public function fetchAssociative()
  482. {
  483. return $this->doFetch(OCI_ASSOC);
  484. }
  485. /**
  486. * {@inheritdoc}
  487. */
  488. public function fetchOne()
  489. {
  490. return FetchUtils::fetchOne($this);
  491. }
  492. /**
  493. * {@inheritdoc}
  494. */
  495. public function fetchAllNumeric(): array
  496. {
  497. return $this->doFetchAll(OCI_NUM, OCI_FETCHSTATEMENT_BY_ROW);
  498. }
  499. /**
  500. * {@inheritdoc}
  501. */
  502. public function fetchAllAssociative(): array
  503. {
  504. return $this->doFetchAll(OCI_ASSOC, OCI_FETCHSTATEMENT_BY_ROW);
  505. }
  506. /**
  507. * {@inheritdoc}
  508. */
  509. public function fetchFirstColumn(): array
  510. {
  511. return $this->doFetchAll(OCI_NUM, OCI_FETCHSTATEMENT_BY_COLUMN)[0];
  512. }
  513. public function free(): void
  514. {
  515. // not having the result means there's nothing to close
  516. if (! $this->result) {
  517. return;
  518. }
  519. oci_cancel($this->_sth);
  520. $this->result = false;
  521. }
  522. /**
  523. * @return mixed|false
  524. */
  525. private function doFetch(int $mode)
  526. {
  527. // do not try fetching from the statement if it's not expected to contain the result
  528. // in order to prevent exceptional situation
  529. if (! $this->result) {
  530. return false;
  531. }
  532. return oci_fetch_array(
  533. $this->_sth,
  534. $mode | OCI_RETURN_NULLS | OCI_RETURN_LOBS
  535. );
  536. }
  537. /**
  538. * @return array<mixed>
  539. */
  540. private function doFetchAll(int $mode, int $fetchStructure): array
  541. {
  542. // do not try fetching from the statement if it's not expected to contain the result
  543. // in order to prevent exceptional situation
  544. if (! $this->result) {
  545. return [];
  546. }
  547. oci_fetch_all(
  548. $this->_sth,
  549. $result,
  550. 0,
  551. -1,
  552. $mode | OCI_RETURN_NULLS | $fetchStructure | OCI_RETURN_LOBS
  553. );
  554. return $result;
  555. }
  556. }