prefetch.inc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. <?php
  2. /**
  3. * @file
  4. * Database interface code for engines that need complete control over their
  5. * result sets. For example, SQLite will prefix some column names by the name
  6. * of the table. We post-process the data, by renaming the column names
  7. * using the same convention as MySQL and PostgreSQL.
  8. */
  9. /**
  10. * @addtogroup database
  11. * @{
  12. */
  13. /**
  14. * An implementation of DatabaseStatementInterface that prefetches all data.
  15. *
  16. * This class behaves very similar to a PDOStatement but as it always fetches
  17. * every row it is possible to manipulate those results.
  18. */
  19. class DatabaseStatementPrefetch implements Iterator, DatabaseStatementInterface {
  20. /**
  21. * The query string.
  22. *
  23. * @var string
  24. */
  25. protected $queryString;
  26. /**
  27. * Driver-specific options. Can be used by child classes.
  28. *
  29. * @var Array
  30. */
  31. protected $driverOptions;
  32. /**
  33. * Reference to the database connection object for this statement.
  34. *
  35. * The name $dbh is inherited from PDOStatement.
  36. *
  37. * @var DatabaseConnection
  38. */
  39. public $dbh;
  40. /**
  41. * Main data store.
  42. *
  43. * @var Array
  44. */
  45. protected $data = array();
  46. /**
  47. * The current row, retrieved in PDO::FETCH_ASSOC format.
  48. *
  49. * @var Array
  50. */
  51. protected $currentRow = NULL;
  52. /**
  53. * The key of the current row.
  54. *
  55. * @var int
  56. */
  57. protected $currentKey = NULL;
  58. /**
  59. * The list of column names in this result set.
  60. *
  61. * @var Array
  62. */
  63. protected $columnNames = NULL;
  64. /**
  65. * The number of rows affected by the last query.
  66. *
  67. * @var int
  68. */
  69. protected $rowCount = NULL;
  70. /**
  71. * The number of rows in this result set.
  72. *
  73. * @var int
  74. */
  75. protected $resultRowCount = 0;
  76. /**
  77. * Holds the current fetch style (which will be used by the next fetch).
  78. * @see PDOStatement::fetch()
  79. *
  80. * @var int
  81. */
  82. protected $fetchStyle = PDO::FETCH_OBJ;
  83. /**
  84. * Holds supplementary current fetch options (which will be used by the next fetch).
  85. *
  86. * @var Array
  87. */
  88. protected $fetchOptions = array(
  89. 'class' => 'stdClass',
  90. 'constructor_args' => array(),
  91. 'object' => NULL,
  92. 'column' => 0,
  93. );
  94. /**
  95. * Holds the default fetch style.
  96. *
  97. * @var int
  98. */
  99. protected $defaultFetchStyle = PDO::FETCH_OBJ;
  100. /**
  101. * Holds supplementary default fetch options.
  102. *
  103. * @var Array
  104. */
  105. protected $defaultFetchOptions = array(
  106. 'class' => 'stdClass',
  107. 'constructor_args' => array(),
  108. 'object' => NULL,
  109. 'column' => 0,
  110. );
  111. public function __construct(DatabaseConnection $connection, $query, array $driver_options = array()) {
  112. $this->dbh = $connection;
  113. $this->queryString = $query;
  114. $this->driverOptions = $driver_options;
  115. }
  116. /**
  117. * Executes a prepared statement.
  118. *
  119. * @param $args
  120. * An array of values with as many elements as there are bound parameters in the SQL statement being executed.
  121. * @param $options
  122. * An array of options for this query.
  123. * @return
  124. * TRUE on success, or FALSE on failure.
  125. */
  126. public function execute($args = array(), $options = array()) {
  127. if (isset($options['fetch'])) {
  128. if (is_string($options['fetch'])) {
  129. // Default to an object. Note: db fields will be added to the object
  130. // before the constructor is run. If you need to assign fields after
  131. // the constructor is run, see http://drupal.org/node/315092.
  132. $this->setFetchMode(PDO::FETCH_CLASS, $options['fetch']);
  133. }
  134. else {
  135. $this->setFetchMode($options['fetch']);
  136. }
  137. }
  138. $logger = $this->dbh->getLogger();
  139. if (!empty($logger)) {
  140. $query_start = microtime(TRUE);
  141. }
  142. // Prepare the query.
  143. $statement = $this->getStatement($this->queryString, $args);
  144. if (!$statement) {
  145. $this->throwPDOException();
  146. }
  147. $return = $statement->execute($args);
  148. if (!$return) {
  149. $this->throwPDOException();
  150. }
  151. // Fetch all the data from the reply, in order to release any lock
  152. // as soon as possible.
  153. $this->rowCount = $statement->rowCount();
  154. $this->data = $statement->fetchAll(PDO::FETCH_ASSOC);
  155. // Destroy the statement as soon as possible. See
  156. // DatabaseConnection_sqlite::PDOPrepare() for explanation.
  157. unset($statement);
  158. $this->resultRowCount = count($this->data);
  159. if ($this->resultRowCount) {
  160. $this->columnNames = array_keys($this->data[0]);
  161. }
  162. else {
  163. $this->columnNames = array();
  164. }
  165. if (!empty($logger)) {
  166. $query_end = microtime(TRUE);
  167. $logger->log($this, $args, $query_end - $query_start);
  168. }
  169. // Initialize the first row in $this->currentRow.
  170. $this->next();
  171. return $return;
  172. }
  173. /**
  174. * Throw a PDO Exception based on the last PDO error.
  175. */
  176. protected function throwPDOException() {
  177. $error_info = $this->dbh->errorInfo();
  178. // We rebuild a message formatted in the same way as PDO.
  179. $exception = new PDOException("SQLSTATE[" . $error_info[0] . "]: General error " . $error_info[1] . ": " . $error_info[2]);
  180. $exception->errorInfo = $error_info;
  181. throw $exception;
  182. }
  183. /**
  184. * Grab a PDOStatement object from a given query and its arguments.
  185. *
  186. * Some drivers (including SQLite) will need to perform some preparation
  187. * themselves to get the statement right.
  188. *
  189. * @param $query
  190. * The query.
  191. * @param array $args
  192. * An array of arguments.
  193. * @return PDOStatement
  194. * A PDOStatement object.
  195. */
  196. protected function getStatement($query, &$args = array()) {
  197. return $this->dbh->prepare($query);
  198. }
  199. /**
  200. * Return the object's SQL query string.
  201. */
  202. public function getQueryString() {
  203. return $this->queryString;
  204. }
  205. /**
  206. * @see PDOStatement::setFetchMode()
  207. */
  208. public function setFetchMode($fetchStyle, $a2 = NULL, $a3 = NULL) {
  209. $this->defaultFetchStyle = $fetchStyle;
  210. switch ($fetchStyle) {
  211. case PDO::FETCH_CLASS:
  212. $this->defaultFetchOptions['class'] = $a2;
  213. if ($a3) {
  214. $this->defaultFetchOptions['constructor_args'] = $a3;
  215. }
  216. break;
  217. case PDO::FETCH_COLUMN:
  218. $this->defaultFetchOptions['column'] = $a2;
  219. break;
  220. case PDO::FETCH_INTO:
  221. $this->defaultFetchOptions['object'] = $a2;
  222. break;
  223. }
  224. // Set the values for the next fetch.
  225. $this->fetchStyle = $this->defaultFetchStyle;
  226. $this->fetchOptions = $this->defaultFetchOptions;
  227. }
  228. /**
  229. * Return the current row formatted according to the current fetch style.
  230. *
  231. * This is the core method of this class. It grabs the value at the current
  232. * array position in $this->data and format it according to $this->fetchStyle
  233. * and $this->fetchMode.
  234. *
  235. * @return
  236. * The current row formatted as requested.
  237. */
  238. #[\ReturnTypeWillChange]
  239. public function current() {
  240. if (isset($this->currentRow)) {
  241. switch ($this->fetchStyle) {
  242. case PDO::FETCH_ASSOC:
  243. return $this->currentRow;
  244. case PDO::FETCH_BOTH:
  245. // PDO::FETCH_BOTH returns an array indexed by both the column name
  246. // and the column number.
  247. return $this->currentRow + array_values($this->currentRow);
  248. case PDO::FETCH_NUM:
  249. return array_values($this->currentRow);
  250. case PDO::FETCH_LAZY:
  251. // We do not do lazy as everything is fetched already. Fallback to
  252. // PDO::FETCH_OBJ.
  253. case PDO::FETCH_OBJ:
  254. return (object) $this->currentRow;
  255. case PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE:
  256. $class_name = array_shift($this->currentRow);
  257. // Deliberate no break.
  258. case PDO::FETCH_CLASS:
  259. if (!isset($class_name)) {
  260. $class_name = $this->fetchOptions['class'];
  261. }
  262. if (count($this->fetchOptions['constructor_args'])) {
  263. $reflector = new ReflectionClass($class_name);
  264. $result = $reflector->newInstanceArgs($this->fetchOptions['constructor_args']);
  265. }
  266. else {
  267. $result = new $class_name();
  268. }
  269. foreach ($this->currentRow as $k => $v) {
  270. $result->$k = $v;
  271. }
  272. return $result;
  273. case PDO::FETCH_INTO:
  274. foreach ($this->currentRow as $k => $v) {
  275. $this->fetchOptions['object']->$k = $v;
  276. }
  277. return $this->fetchOptions['object'];
  278. case PDO::FETCH_COLUMN:
  279. if (isset($this->columnNames[$this->fetchOptions['column']])) {
  280. return $this->currentRow[$k][$this->columnNames[$this->fetchOptions['column']]];
  281. }
  282. else {
  283. return;
  284. }
  285. }
  286. }
  287. }
  288. /* Implementations of Iterator. */
  289. #[\ReturnTypeWillChange]
  290. public function key() {
  291. return $this->currentKey;
  292. }
  293. #[\ReturnTypeWillChange]
  294. public function rewind() {
  295. // Nothing to do: our DatabaseStatement can't be rewound.
  296. }
  297. #[\ReturnTypeWillChange]
  298. public function next() {
  299. if (!empty($this->data)) {
  300. $this->currentRow = reset($this->data);
  301. $this->currentKey = key($this->data);
  302. unset($this->data[$this->currentKey]);
  303. }
  304. else {
  305. $this->currentRow = NULL;
  306. }
  307. }
  308. #[\ReturnTypeWillChange]
  309. public function valid() {
  310. return isset($this->currentRow);
  311. }
  312. /* Implementations of DatabaseStatementInterface. */
  313. public function rowCount() {
  314. return $this->rowCount;
  315. }
  316. public function fetch($fetch_style = NULL, $cursor_orientation = PDO::FETCH_ORI_NEXT, $cursor_offset = NULL) {
  317. if (isset($this->currentRow)) {
  318. // Set the fetch parameter.
  319. $this->fetchStyle = isset($fetch_style) ? $fetch_style : $this->defaultFetchStyle;
  320. $this->fetchOptions = $this->defaultFetchOptions;
  321. // Grab the row in the format specified above.
  322. $return = $this->current();
  323. // Advance the cursor.
  324. $this->next();
  325. // Reset the fetch parameters to the value stored using setFetchMode().
  326. $this->fetchStyle = $this->defaultFetchStyle;
  327. $this->fetchOptions = $this->defaultFetchOptions;
  328. return $return;
  329. }
  330. else {
  331. return FALSE;
  332. }
  333. }
  334. public function fetchColumn($index = 0) {
  335. if (isset($this->currentRow) && isset($this->columnNames[$index])) {
  336. // We grab the value directly from $this->data, and format it.
  337. $return = $this->currentRow[$this->columnNames[$index]];
  338. $this->next();
  339. return $return;
  340. }
  341. else {
  342. return FALSE;
  343. }
  344. }
  345. public function fetchField($index = 0) {
  346. return $this->fetchColumn($index);
  347. }
  348. public function fetchObject($class_name = NULL, $constructor_args = array()) {
  349. if (isset($this->currentRow)) {
  350. if (!isset($class_name)) {
  351. // Directly cast to an object to avoid a function call.
  352. $result = (object) $this->currentRow;
  353. }
  354. else {
  355. $this->fetchStyle = PDO::FETCH_CLASS;
  356. $this->fetchOptions = array('constructor_args' => $constructor_args);
  357. // Grab the row in the format specified above.
  358. $result = $this->current();
  359. // Reset the fetch parameters to the value stored using setFetchMode().
  360. $this->fetchStyle = $this->defaultFetchStyle;
  361. $this->fetchOptions = $this->defaultFetchOptions;
  362. }
  363. $this->next();
  364. return $result;
  365. }
  366. else {
  367. return FALSE;
  368. }
  369. }
  370. public function fetchAssoc() {
  371. if (isset($this->currentRow)) {
  372. $result = $this->currentRow;
  373. $this->next();
  374. return $result;
  375. }
  376. else {
  377. return FALSE;
  378. }
  379. }
  380. public function fetchAll($fetch_style = NULL, $fetch_column = NULL, $constructor_args = NULL) {
  381. $this->fetchStyle = isset($fetch_style) ? $fetch_style : $this->defaultFetchStyle;
  382. $this->fetchOptions = $this->defaultFetchOptions;
  383. if (isset($fetch_column)) {
  384. $this->fetchOptions['column'] = $fetch_column;
  385. }
  386. if (isset($constructor_args)) {
  387. $this->fetchOptions['constructor_args'] = $constructor_args;
  388. }
  389. $result = array();
  390. // Traverse the array as PHP would have done.
  391. while (isset($this->currentRow)) {
  392. // Grab the row in the format specified above.
  393. $result[] = $this->current();
  394. $this->next();
  395. }
  396. // Reset the fetch parameters to the value stored using setFetchMode().
  397. $this->fetchStyle = $this->defaultFetchStyle;
  398. $this->fetchOptions = $this->defaultFetchOptions;
  399. return $result;
  400. }
  401. public function fetchCol($index = 0) {
  402. if (isset($this->columnNames[$index])) {
  403. $column = $this->columnNames[$index];
  404. $result = array();
  405. // Traverse the array as PHP would have done.
  406. while (isset($this->currentRow)) {
  407. $result[] = $this->currentRow[$this->columnNames[$index]];
  408. $this->next();
  409. }
  410. return $result;
  411. }
  412. else {
  413. return array();
  414. }
  415. }
  416. public function fetchAllKeyed($key_index = 0, $value_index = 1) {
  417. if (!isset($this->columnNames[$key_index]) || !isset($this->columnNames[$value_index]))
  418. return array();
  419. $key = $this->columnNames[$key_index];
  420. $value = $this->columnNames[$value_index];
  421. $result = array();
  422. // Traverse the array as PHP would have done.
  423. while (isset($this->currentRow)) {
  424. $result[$this->currentRow[$key]] = $this->currentRow[$value];
  425. $this->next();
  426. }
  427. return $result;
  428. }
  429. public function fetchAllAssoc($key, $fetch_style = NULL) {
  430. $this->fetchStyle = isset($fetch_style) ? $fetch_style : $this->defaultFetchStyle;
  431. $this->fetchOptions = $this->defaultFetchOptions;
  432. $result = array();
  433. // Traverse the array as PHP would have done.
  434. while (isset($this->currentRow)) {
  435. // Grab the row in its raw PDO::FETCH_ASSOC format.
  436. $row = $this->currentRow;
  437. // Grab the row in the format specified above.
  438. $result_row = $this->current();
  439. $result[$this->currentRow[$key]] = $result_row;
  440. $this->next();
  441. }
  442. // Reset the fetch parameters to the value stored using setFetchMode().
  443. $this->fetchStyle = $this->defaultFetchStyle;
  444. $this->fetchOptions = $this->defaultFetchOptions;
  445. return $result;
  446. }
  447. }
  448. /**
  449. * @} End of "addtogroup database".
  450. */