PageRenderTime 69ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/extlib/DB/QueryTool/Query.php

https://bitbucket.org/stk2k/charcoalphp2.1
PHP | 2631 lines | 1121 code | 236 blank | 1274 comment | 172 complexity | 31bec428033d8bd022344b499a2f978d MD5 | raw file
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. /**
  4. * Contains the DB_QueryTool_Query class
  5. *
  6. * PHP versions 4 and 5
  7. *
  8. * LICENSE: This source file is subject to version 3.0 of the PHP license
  9. * that is available through the world-wide-web at the following URI:
  10. * http://www.php.net/license/3_0.txt. If you did not receive a copy of
  11. * the PHP License and are unable to obtain it through the web, please
  12. * send a note to license@php.net so we can mail you a copy immediately.
  13. *
  14. * @category Database
  15. * @package DB_QueryTool
  16. * @author Wolfram Kriesing <wk@visionp.de>
  17. * @author Paolo Panto <wk@visionp.de>
  18. * @author Lorenzo Alberton <l dot alberton at quipo dot it>
  19. * @copyright 2003-2007 Wolfram Kriesing, Paolo Panto, Lorenzo Alberton
  20. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  21. * @version CVS: $Id: Query.php,v 1.71 2007/01/10 17:49:47 quipo Exp $
  22. * @link http://pear.php.net/package/DB_QueryTool
  23. */
  24. /**
  25. * require the PEAR and DB classes
  26. */
  27. require_once 'PEAR.php';
  28. require_once 'DB.php';
  29. /**
  30. * DB_QueryTool_Query class
  31. *
  32. * This class should be extended
  33. *
  34. * @category Database
  35. * @package DB_QueryTool
  36. * @author Wolfram Kriesing <wk@visionp.de>
  37. * @author Paolo Panto <wk@visionp.de>
  38. * @author Lorenzo Alberton <l dot alberton at quipo dot it>
  39. * @copyright 2003-2007 Wolfram Kriesing, Paolo Panto, Lorenzo Alberton
  40. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  41. * @link http://pear.php.net/package/DB_QueryTool
  42. */
  43. class DB_QueryTool_Query
  44. {
  45. // {{{ class vars
  46. /**
  47. * @var string the name of the primary column
  48. */
  49. var $primaryCol = 'id';
  50. /**
  51. * @var string the current table the class works on
  52. */
  53. var $table = '';
  54. /**
  55. * @var string the name of the sequence for this table
  56. */
  57. var $sequenceName = null;
  58. /**
  59. * @var object the db-object, a PEAR::DB instance
  60. */
  61. var $db = null;
  62. /**
  63. * @var string the where condition
  64. * @access private
  65. */
  66. var $_where = '';
  67. /**
  68. * @var string the order condition
  69. * @access private
  70. */
  71. var $_order = '';
  72. /**
  73. * @var string the having definition
  74. * @access private
  75. */
  76. var $_having = '';
  77. /**
  78. * @var array contains the join content
  79. * the key is the join type, for now we have 'default' and 'left'
  80. * inside each key 'table' contains the table
  81. * key 'where' contains the where clause for the join
  82. * @access private
  83. */
  84. var $_join = array();
  85. /**
  86. * @var string which column to index the result by
  87. * @access private
  88. */
  89. var $_index = null;
  90. /**
  91. * @var string the group-by clause
  92. * @access private
  93. */
  94. var $_group = '';
  95. /**
  96. * @var array the limit
  97. * @access private
  98. */
  99. var $_limit = array();
  100. /**
  101. * @var string type of result to return
  102. * @access private
  103. */
  104. var $_resultType = 'none';
  105. /**
  106. * @var array the metadata temporary saved
  107. * @access private
  108. */
  109. var $_metadata = array();
  110. /**
  111. * @var string
  112. * @access private
  113. */
  114. var $_lastQuery = null;
  115. /**
  116. * @var string the rows that shall be selected
  117. * @access private
  118. */
  119. var $_select = '*';
  120. /**
  121. * @var string the rows that shall not be selected
  122. * @access private
  123. */
  124. var $_dontSelect = '';
  125. /**
  126. * @var array this array saves different modes in which this class works
  127. * i.e. 'raw' means no quoting before saving/updating data
  128. * @access private
  129. */
  130. var $options = array(
  131. 'raw' => false,
  132. 'verbose' => true, // set this to false in a productive environment
  133. // it will produce error-logs if set to true
  134. 'useCache' => false,
  135. 'logFile' => false,
  136. );
  137. /**
  138. * this array contains information about the tables
  139. * those are
  140. * - 'name' => the real table name
  141. * - 'shortName' => the short name used, so that when moving the table i.e.
  142. * onto a provider's db and u have to rename the tables to
  143. * longer names this name will be relevant, i.e. when
  144. * autoJoining, i.e. a table name on your local machine is:
  145. * 'user' but online it has to be 'applName_user' then the
  146. * shortName will be used to determine if a column refers to
  147. * another table, if the colName is 'user_id', it knows the
  148. * shortName 'user' refers to the table 'applName_user'
  149. */
  150. var $tableSpec = array();
  151. /**
  152. * this is the regular expression that shall be used to find a table's shortName
  153. * in a column name, the string found by using this regular expression will be removed
  154. * from the column name and it will be checked if it is a table name
  155. * i.e. the default '/_id$/' would find the table name 'user' from the column name 'user_id'
  156. *
  157. * @access private
  158. */
  159. var $_tableNameToShortNamePreg = '/^.*_/';
  160. /**
  161. * @var array this array caches queries that have already been built once
  162. * to reduce the execution time
  163. * @access private
  164. */
  165. var $_queryCache = array();
  166. /**
  167. * The object that contains the log-instance
  168. * @access private
  169. */
  170. var $_logObject = null;
  171. /**
  172. * Some internal data the logging needs
  173. * @access private
  174. */
  175. var $_logData = array();
  176. // }}}
  177. // {{{ __construct()
  178. /**
  179. * this is the constructor, as it will be implemented in ZE2 (php5)
  180. *
  181. * @version 2002/04/02
  182. * @author Wolfram Kriesing <wk@visionp.de>
  183. * @param object db-object
  184. * @param array options array
  185. * @access public
  186. */
  187. /*
  188. function __construct($dsn=false, $options=array())
  189. {
  190. if (!isset($options['autoConnect'])) {
  191. $autoConnect = true;
  192. } else {
  193. $autoConnect = $options['autoConnect'];
  194. }
  195. if (isset($options['errorCallback'])) {
  196. $this->setErrorCallback($options['errorCallback']);
  197. }
  198. if (isset($options['errorSetCallback'])) {
  199. $this->setErrorSetCallback($options['errorSetCallback']);
  200. }
  201. if (isset($options['errorLogCallback'])) {
  202. $this->setErrorLogCallback($options['errorLogCallback']);
  203. }
  204. if ($autoConnect && $dsn) {
  205. $this->connect($dsn, $options);
  206. }
  207. //we would need to parse the dsn first ... i dont feel like now :-)
  208. // oracle has all column names in upper case
  209. //FIXXXME make the class work only with upper case when we work with oracle
  210. //if ($this->db->phptype=='oci8' && !$this->primaryCol) {
  211. // $this->primaryCol = 'ID';
  212. //}
  213. if (is_null($this->sequenceName)) {
  214. $this->sequenceName = $this->table;
  215. }
  216. }
  217. */
  218. // }}}
  219. // {{{ DB_QueryTool_Query()
  220. /**
  221. * @version 2002/04/02
  222. * @author Wolfram Kriesing <wk@visionp.de>
  223. * @param mixed $dsn DSN string, DSN array or DB object
  224. * @param array $options
  225. * @access public
  226. */
  227. function DB_QueryTool_Query($dsn=false, $options=array())
  228. {
  229. //$this->__construct($dsn, $options);
  230. if (!isset($options['autoConnect'])) {
  231. $autoConnect = true;
  232. } else {
  233. $autoConnect = $options['autoConnect'];
  234. unset($options['autoConnect']);
  235. }
  236. if (isset($options['errorCallback'])) {
  237. $this->setErrorCallback($options['errorCallback']);
  238. unset($options['errorCallback']);
  239. }
  240. if (isset($options['errorSetCallback'])) {
  241. $this->setErrorSetCallback($options['errorSetCallback']);
  242. unset($options['errorSetCallback']);
  243. }
  244. if (isset($options['errorLogCallback'])) {
  245. $this->setErrorLogCallback($options['errorLogCallback']);
  246. unset($options['errorLogCallback']);
  247. }
  248. if ($autoConnect && $dsn) {
  249. $this->connect($dsn, $options);
  250. }
  251. if (is_null($this->sequenceName)) {
  252. $this->sequenceName = $this->table;
  253. }
  254. }
  255. // }}}
  256. // {{{ connect()
  257. /**
  258. * use this method if you want to connect manually
  259. * @param mixed $dsn DSN string, DSN array or DB object
  260. * @param array $options
  261. */
  262. function connect($dsn, $options=array())
  263. {
  264. if (is_object($dsn)) {
  265. $res = $this->db =& $dsn;
  266. } else {
  267. $res = $this->db = DB::connect($dsn, $options);
  268. }
  269. if (PEAR::isError($res)) {
  270. // FIXXME what shall we do here?
  271. $this->_errorLog($res->getUserInfo());
  272. } else {
  273. $this->db->setFetchMode(DB_FETCHMODE_ASSOC);
  274. }
  275. }
  276. // }}}
  277. // {{{ getDbInstance()
  278. /**
  279. * @return reference to current DB instance
  280. */
  281. function &getDbInstance()
  282. {
  283. return $this->db;
  284. }
  285. // }}}
  286. // {{{ setDbInstance()
  287. /**
  288. * Setup using an existing connection.
  289. * this also sets the DB_FETCHMODE_ASSOC since this class
  290. * needs this to be set!
  291. *
  292. * @param object a reference to an existing DB-object
  293. * @return void
  294. */
  295. function setDbInstance(&$dbh)
  296. {
  297. $this->db =& $dbh;
  298. $this->db->setFetchMode(DB_FETCHMODE_ASSOC);
  299. }
  300. // }}}
  301. // {{{ get()
  302. /**
  303. * get the data of a single entry
  304. * if the second parameter is only one column the result will be returned
  305. * directly not as an array!
  306. *
  307. * @version 2002/03/05
  308. * @author Wolfram Kriesing <wk@visionp.de>
  309. * @param integer the id of the element to retrieve
  310. * @param string if this is given only one row shall be returned,
  311. * directly, not an array
  312. * @return mixed (1) an array of the retrieved data
  313. * (2) if the second parameter is given and its only one column,
  314. * only this column's data will be returned
  315. * (3) false in case of failure
  316. * @access public
  317. */
  318. function get($id, $column='')
  319. {
  320. if (is_string($id)) {
  321. $id = trim($id);
  322. }
  323. $column = trim($column);
  324. $table = $this->table;
  325. $getMethod = 'getRow';
  326. if ($column && !strpos($column, ',')) { // if only one column shall be selected
  327. $getMethod = 'getOne';
  328. }
  329. // we dont use 'setSelect' here, since this changes the setup of the class, we
  330. // build the query directly
  331. // if $column is '' then _buildSelect selects '*' anyway, so that's the same behaviour as before
  332. $query['select'] = $this->_buildSelect($column);
  333. $query['where'] = $this->_buildWhere(
  334. $this->_quoteIdentifier($this->table).'.'.$this->_quoteIdentifier($this->primaryCol) .'='. $this->_quote($id));
  335. $queryString = $this->_buildSelectQuery($query);
  336. return $this->returnResult($this->execute($queryString, $getMethod));
  337. }
  338. // }}}
  339. // {{{ getMultiple()
  340. /**
  341. * gets the data of the given ids
  342. *
  343. * @version 2002/04/23
  344. * @author Wolfram Kriesing <wk@visionp.de>
  345. * @param array this is an array of ids to retrieve
  346. * @param string the column to search in for
  347. * @return mixed an array of the retrieved data, or false in case of failure
  348. * when failing an error is set in $this->_error
  349. * @access public
  350. */
  351. function getMultiple($ids, $column='')
  352. {
  353. $col = $this->primaryCol;
  354. if ($column) {
  355. $col = $column;
  356. }
  357. // FIXXME if $ids has no table.col syntax and we are using joins, the table better be put in front!!!
  358. $ids = $this->_quoteArray($ids);
  359. $query['where'] = $this->_buildWhere($col.' IN ('.implode(',', $ids).')');
  360. $queryString = $this->_buildSelectQuery($query);
  361. return $this->returnResult($this->execute($queryString));
  362. }
  363. // }}}
  364. // {{{ getOne()
  365. /**
  366. * get the first value of the first row
  367. *
  368. * @access public
  369. * @return mixed (1) a scalar value in case of success
  370. * (2) false in case of failure
  371. */
  372. function getOne()
  373. {
  374. $queryString = $this->getQueryString();
  375. return $this->execute($queryString, 'getOne');
  376. }
  377. // }}}
  378. // {{{ getAll()
  379. /**
  380. * get all entries from the DB
  381. * for sorting use setOrder!!!, the last 2 parameters are deprecated
  382. *
  383. * @version 2002/03/05
  384. * @author Wolfram Kriesing <wk@visionp.de>
  385. * @param int to start from
  386. * @param int the number of rows to show
  387. * @param string the DB-method to use, i dont know if we should leave this param here ...
  388. * @return mixed an array of the retrieved data, or false in case of failure
  389. * when failing an error is set in $this->_error
  390. * @access public
  391. */
  392. function getAll($from = 0, $count = 0, $method = 'getAll')
  393. {
  394. $query = array();
  395. if ($count) {
  396. $query = array('limit' => array($from, $count));
  397. //echo '<br/>'.$this->_buildSelectQuery($query).'<br/>';
  398. }
  399. return $this->returnResult($this->execute($this->_buildSelectQuery($query), $method));
  400. }
  401. // }}}
  402. // {{{ getCol()
  403. /**
  404. * this method only returns one column, so the result will be a one dimensional array
  405. * this does also mean that using setSelect() should be set to *one* column, the one you want to
  406. * have returned a most common use case for this could be:
  407. * $table->setSelect('id');
  408. * $ids = $table->getCol();
  409. * OR
  410. * $ids = $table->getCol('id');
  411. * so ids will be an array with all the id's
  412. *
  413. * @version 2003/02/25
  414. * @author Wolfram Kriesing <wk@visionp.de>
  415. * @param string the column that shall be retrieved
  416. * @param int to start from
  417. * @param int the number of rows to show
  418. * @return mixed an array of the retrieved data, or false in case of failure
  419. * when failing an error is set in $this->_error
  420. * @access public
  421. */
  422. function getCol($column=null, $from=0, $count=0)
  423. {
  424. $query = array();
  425. if (!is_null($column)) {
  426. // by using _buildSelect() I can be sure that the table name will not be ambiguous
  427. // i.e. in a join, where all the joined tables have a col 'id'
  428. // _buildSelect() will put the proper table name in front in case there is none
  429. $query['select'] = $this->_buildSelect(trim($column));
  430. }
  431. if ($count) {
  432. $query['limit'] = array($from,$count);
  433. }
  434. $res = $this->returnResult($this->execute($this->_buildSelectQuery($query), 'getCol'));
  435. return ($res === false) ? array() : $res;
  436. }
  437. // }}}
  438. // {{{ getCount()
  439. /**
  440. * get the number of entries
  441. *
  442. * @version 2002/04/02
  443. * @author Wolfram Kriesing <wk@visionp.de>
  444. * @return mixed an array of the retrieved data, or false in case of failure
  445. * when failing an error is set in $this->_error
  446. * @access public
  447. */
  448. function getCount()
  449. {
  450. /* the following query works on mysql
  451. SELECT count(DISTINCT image.id) FROM image2tree
  452. RIGHT JOIN image ON image.id = image2tree.image_id
  453. the reason why this is needed - i just wanted to get the number of rows that do exist if the result is grouped by image.id
  454. the following query is what i tried first, but that returns the number of rows that have been grouped together
  455. for each image.id
  456. SELECT count(*) FROM image2tree
  457. RIGHT JOIN image ON image.id = image2tree.image_id GROUP BY image.id
  458. so that's why we do the following, i am not sure if that is standard SQL and absolutley correct!!!
  459. */
  460. //FIXXME see comment above if this is absolutely correct!!!
  461. if ($group = $this->_buildGroup()) {
  462. $query['select'] = 'COUNT(DISTINCT '.$group.')';
  463. $query['group'] = '';
  464. } else {
  465. $query['select'] = 'COUNT(*)';
  466. }
  467. $query['order'] = ''; // order is not of importance and might freak up the special group-handling up there, since the order-col is not be known
  468. /*# FIXXME use the following line, but watch out, then it has to be used in every method, or this
  469. # value will be used always, simply try calling getCount and getAll afterwards, getAll will return the count :-)
  470. # if getAll doesn't use setSelect!!!
  471. */
  472. //$this->setSelect('count(*)');
  473. $queryString = $this->_buildSelectQuery($query, true);
  474. return ($res = $this->execute($queryString, 'getOne')) ? $res : 0;
  475. }
  476. // }}}
  477. // {{{ getDefaultValues()
  478. /**
  479. * return an empty element where all the array elements do already exist
  480. * corresponding to the columns in the DB
  481. *
  482. * @version 2002/04/05
  483. * @author Wolfram Kriesing <wk@visionp.de>
  484. * @return array an empty, or pre-initialized element
  485. * @access public
  486. */
  487. function getDefaultValues()
  488. {
  489. $ret = array();
  490. // here we read all the columns from the DB and initialize them
  491. // with '' to prevent PHP-warnings in case we use error_reporting=E_ALL
  492. foreach ($this->metadata() as $aCol=>$x) {
  493. $ret[$aCol] = '';
  494. }
  495. return $ret;
  496. }
  497. // }}}
  498. // {{{ getEmptyElement()
  499. /**
  500. * this is just for BC
  501. * @deprecated
  502. */
  503. function getEmptyElement()
  504. {
  505. $this->getDefaultValues();
  506. }
  507. // }}}
  508. // {{{ getQueryString()
  509. /**
  510. * Render the current query and return it as a string.
  511. *
  512. * @return string the current query
  513. */
  514. function getQueryString()
  515. {
  516. $ret = $this->_buildSelectQuery();
  517. if (is_string($ret)) {
  518. $ret = trim($ret);
  519. }
  520. return $ret;
  521. }
  522. // }}}
  523. // {{{ _floatToStringNoLocale()
  524. /**
  525. * If a double number was "localized", restore its decimal separator to "."
  526. * @see http://pear.php.net/bugs/bug.php?id=3021
  527. * @param float
  528. * @access private
  529. */
  530. function _floatToStringNoLocale($float)
  531. {
  532. $precision = strlen($float) - strlen(intval($float));
  533. if ($precision) {
  534. --$precision; // don't count decimal seperator
  535. }
  536. return number_format($float, $precision, '.', '');
  537. }
  538. // }}}
  539. // {{{ _localeSafeImplode()
  540. /**
  541. * New "implode()" implementation to bypass float locale formatting:
  542. * the SQL decimal separator is and must be ".". Always.
  543. * @param Charcoal_String $glue
  544. * @param array $array
  545. * @access private
  546. */
  547. function _localeSafeImplode($glue, $array)
  548. {
  549. $str = '';
  550. foreach ($array as $value) {
  551. if (!empty($str)) {
  552. $str .= $glue;
  553. }
  554. $str .= is_double($value) ? $this->_floatToStringNoLocale($value) : $value;
  555. }
  556. return $str;
  557. }
  558. // }}}
  559. // {{{ save()
  560. /**
  561. * save data, calls either update or add
  562. * if the primaryCol is given in the data this method knows that the
  563. * data passed to it are meant to be updated (call 'update'), otherwise it will
  564. * call the method 'add'.
  565. * If you dont like this behaviour simply stick with the methods 'add'
  566. * and 'update' and ignore this one here.
  567. * This method is very useful when you have validation checks that have to
  568. * be done for both adding and updating, then you can simply overwrite this
  569. * method and do the checks in here, and both cases will be validated first.
  570. *
  571. * @version 2002/03/11
  572. * @author Wolfram Kriesing <wk@visionp.de>
  573. * @param array contains the new data that shall be saved in the DB
  574. * @return mixed the data returned by either add or update-method
  575. * @access public
  576. */
  577. function save($data)
  578. {
  579. if (isset($data[$this->primaryCol]) && $data[$this->primaryCol]) {
  580. return $this->update($data);
  581. }
  582. return $this->add($data);
  583. }
  584. // }}}
  585. // {{{ update()
  586. /**
  587. * update the member data of a data set
  588. *
  589. * @version 2002/03/06
  590. * @author Wolfram Kriesing <wk@visionp.de>
  591. * @param array contains the new data that shall be saved in the DB
  592. * the id has to be given in the field with the key 'ID'
  593. * @return mixed true on success, or false otherwise
  594. * @access public
  595. */
  596. function update($newData)
  597. {
  598. $query = array();
  599. $raw = $this->getOption('raw');
  600. // do only set the 'where' part in $query, if a primary column is given
  601. // if not the default 'where' clause is used
  602. if (isset($newData[$this->primaryCol])) {
  603. $query['where'] = $this->_quoteIdentifier($this->primaryCol) . '=' . $this->_quote($newData[$this->primaryCol]);
  604. }
  605. $newData = $this->_checkColumns($newData, 'update');
  606. $values = array();
  607. foreach ($newData as $key => $aData) { // quote the data
  608. //$values[] = "{$this->table}.$key=". $this->_quote($aData);
  609. $values[] = $this->_quoteIdentifier($key) . '=' . $this->_quote($aData);
  610. }
  611. $query['set'] = $this->_localeSafeImplode(',', $values);
  612. //FIXXXME _buildUpdateQuery() seems to take joins into account, whcih is bullshit here
  613. $updateString = $this->_buildUpdateQuery($query);
  614. //print '$updateString = '.$updateString;
  615. return $this->execute($updateString, 'query') ? true : false;
  616. }
  617. // }}}
  618. // {{{ add()
  619. /**
  620. * add a new member in the DB
  621. *
  622. * @version 2002/04/02
  623. * @author Wolfram Kriesing <wk@visionp.de>
  624. * @param array contains the new data that shall be saved in the DB
  625. * @return mixed the inserted id on success, or false otherwise
  626. * @access public
  627. */
  628. function add($newData)
  629. {
  630. // if no primary col is given, get next sequence value
  631. if (empty($newData[$this->primaryCol])) {
  632. if ($this->primaryCol) {
  633. // do only use the sequence if a primary column is given
  634. // otherwise the data are written as given
  635. $id = $this->db->nextId($this->sequenceName);
  636. $newData[$this->primaryCol] = (int)$id;
  637. } else {
  638. // if no primary col is given return true on success
  639. $id = true;
  640. }
  641. } else {
  642. $id = $newData[$this->primaryCol];
  643. }
  644. //unset($newData[$this->primaryCol]);
  645. $newData = $this->_checkColumns($newData, 'add');
  646. $newData = $this->_quoteArray($newData);
  647. //quoting the columns
  648. $tmpData = array();
  649. foreach ($newData as $key=>$val) {
  650. $tmpData[$this->_quoteIdentifier($key)] = $val;
  651. }
  652. $newData = $tmpData;
  653. unset($tmpData);
  654. $query = sprintf(
  655. 'INSERT INTO %s (%s) VALUES (%s)',
  656. $this->table,
  657. implode(', ', array_keys($newData)),
  658. $this->_localeSafeImplode(', ', $newData)
  659. );
  660. //echo $query;
  661. return $this->execute($query, 'query') ? $id : false;
  662. }
  663. // }}}
  664. // {{{ addMultiple()
  665. /**
  666. * adds multiple new members in the DB
  667. *
  668. * @version 2002/07/17
  669. * @author Wolfram Kriesing <wk@visionp.de>
  670. * @param array contains an array of new data that shall be saved in the DB
  671. * the key-value pairs have to be the same for all the data!!!
  672. * @return mixed the inserted ids on success, or false otherwise
  673. * @access public
  674. */
  675. function addMultiple($data)
  676. {
  677. if (!sizeof($data)) {
  678. return false;
  679. }
  680. $ret = true;
  681. // the inserted ids which will be returned or if no primaryCol is given
  682. // we return true by default
  683. $retIds = $this->primaryCol ? array() : true;
  684. $dbtype = $this->db->phptype;
  685. if ($dbtype == 'mysql') { //Optimise for MySQL
  686. $allData = array(); // each row that will be inserted
  687. foreach ($data as $key => $aData) {
  688. $aData = $this->_checkColumns($aData, 'add');
  689. $aData = $this->_quoteArray($aData);
  690. if (empty($aData[$this->primaryCol])) {
  691. if ($this->primaryCol) {
  692. // do only use the sequence if a primary column is given
  693. // otherwise the data are written as given
  694. $retIds[] = $id = (int)$this->db->nextId($this->sequenceName);
  695. $aData[$this->primaryCol] = $id;
  696. }
  697. } else {
  698. $retIds[] = $aData[$this->primaryCol];
  699. }
  700. $allData[] = '('.$this->_localeSafeImplode(', ', $aData).')';
  701. }
  702. //quoting the columns
  703. $tmpData = array();
  704. foreach ($aData as $key=>$val) {
  705. $tmpData[$this->_quoteIdentifier($key)] = $val;
  706. }
  707. $newData = $tmpData;
  708. unset($tmpData);
  709. $query = sprintf(
  710. 'INSERT INTO %s (%s) VALUES %s',
  711. $this->table ,
  712. implode(', ', array_keys($aData)) ,
  713. $this->_localeSafeImplode(', ', $allData)
  714. );
  715. return $this->execute($query, 'query') ? $retIds : false;
  716. }
  717. //Executing for every entry the add method
  718. foreach ($data as $entity) {
  719. if ($ret) {
  720. $res = $this->add($entity);
  721. if (!$res) {
  722. $ret = false;
  723. } else {
  724. $retIds[] = $res;
  725. }
  726. }
  727. }
  728. //Setting the return value to the array with ids
  729. if ($ret) {
  730. $ret = $retIds;
  731. }
  732. return $ret;
  733. }
  734. // }}}
  735. // {{{ remove()
  736. /**
  737. * removes a member from the DB
  738. *
  739. * @version 2002/04/08
  740. * @author Wolfram Kriesing <wk@visionp.de>
  741. * @param mixed integer/string - the value of the column that shall be removed
  742. * array - multiple columns that shall be matched, the second parameter will be ignored
  743. * @param string the column to match the data against, only if $data is not an array
  744. * @return boolean
  745. * @access public
  746. */
  747. function remove($data, $whereCol='')
  748. {
  749. $raw = $this->getOption('raw');
  750. if (is_array($data)) {
  751. //FIXXME check $data if it only contains columns that really exist in the table
  752. $wheres = array();
  753. foreach ($data as $key => $val) {
  754. if (is_null($val)) {
  755. $wheres[] = $this->_quoteIdentifier($key) .' IS NULL';
  756. } else {
  757. $wheres[] = $this->_quoteIdentifier($key) .'='. $this->_quote($val);
  758. }
  759. }
  760. $whereClause = implode(' AND ', $wheres);
  761. } else {
  762. if (empty($whereCol)) {
  763. $whereCol = $this->primaryCol;
  764. }
  765. $whereClause = $this->_quoteIdentifier($whereCol) .'='. $this->_quote($data);
  766. }
  767. $query = 'DELETE FROM '. $this->table .' WHERE '. $whereClause;
  768. return $this->execute($query, 'query') ? true : false;
  769. // i think this method should return the ID's that it removed, this way we could simply use the result
  770. // for further actions that depend on those id ... or? make stuff easier, see ignaz::imail::remove
  771. }
  772. // }}}
  773. // {{{ removeAll()
  774. /**
  775. * empty a table
  776. *
  777. * @version 2002/06/17
  778. * @author Wolfram Kriesing <wk@visionp.de>
  779. * @return resultSet or false on error [execute() result]
  780. * @access public
  781. */
  782. function removeAll()
  783. {
  784. $query = 'DELETE FROM '.$this->table;
  785. return $this->execute($query, 'query') ? true : false;
  786. }
  787. // }}}
  788. // {{{ removeMultiple()
  789. /**
  790. * remove the datasets with the given ids
  791. *
  792. * @version 2002/04/24
  793. * @author Wolfram Kriesing <wk@visionp.de>
  794. * @param array the ids to remove
  795. * @return resultSet or false on error [execute() result]
  796. * @access public
  797. */
  798. function removeMultiple($ids, $colName='')
  799. {
  800. if (empty($colName)) {
  801. $colName = $this->primaryCol;
  802. }
  803. $ids = $this->_quoteArray($ids);
  804. $query = sprintf(
  805. 'DELETE FROM %s WHERE %s IN (%s)',
  806. $this->table,
  807. $colName,
  808. $this->_localeSafeImplode(',', $ids)
  809. );
  810. return $this->execute($query, 'query') ? true : false;
  811. }
  812. // }}}
  813. // {{{ removePrimary()
  814. /**
  815. * removes a member from the DB and calls the remove methods of the given objects
  816. * so all rows in another table that refer to this table are erased too
  817. *
  818. * @version 2002/04/08
  819. * @author Wolfram Kriesing <wk@visionp.de>
  820. * @param integer the value of the primary key
  821. * @param string the column name of the tables with the foreign keys
  822. * @param object just for convinience, so nobody forgets to call this method
  823. * with at least one object as a parameter
  824. * @return boolean
  825. * @access public
  826. */
  827. function removePrimary($id, $colName, $atLeastOneObject)
  828. {
  829. $argCounter = 2; // we have 2 parameters that need to be given at least
  830. // func_get_arg returns false and a warning if there are no more parameters, so
  831. // we suppress the warning and check for false
  832. while ($object = @func_get_arg($argCounter++)) {
  833. //FIXXXME let $object also simply be a table name
  834. if (!$object->remove($id, $colName)) {
  835. //FIXXXME do this better
  836. $this->_errorSet("Error removing '$colName=$id' from table {$object->table}.");
  837. return false;
  838. }
  839. }
  840. return ($this->remove($id) ? true : false);
  841. }
  842. // }}}
  843. // {{{ setLimit()
  844. /**
  845. * sets query limits
  846. *
  847. * @param Charcoal_Integer $from start index
  848. * @param Charcoal_Integer $count number of results
  849. * @access public
  850. */
  851. function setLimit($from=0, $count=0)
  852. {
  853. if ($from==0 && $count==0) {
  854. $this->_limit = array();
  855. } else {
  856. $this->_limit = array($from, $count);
  857. }
  858. }
  859. // }}}
  860. // {{{ getLimit()
  861. /**
  862. * gets query limits
  863. *
  864. * @return array (start index, number of results)
  865. * @access public
  866. */
  867. function getLimit()
  868. {
  869. return $this->_limit;
  870. }
  871. // }}}
  872. // {{{ setWhere()
  873. /**
  874. * sets the where condition which is used for the current instance
  875. *
  876. * @version 2002/04/16
  877. * @author Wolfram Kriesing <wk@visionp.de>
  878. * @param string the where condition, this can be complete like 'X=7 AND Y=8'
  879. * @access public
  880. */
  881. function setWhere($whereCondition='')
  882. {
  883. $this->_where = $whereCondition;
  884. //FIXXME parse the where condition and replace ambigious column names, such as "name='Deutschland'" with "country.name='Deutschland'"
  885. // then the users dont have to write that explicitly and can use the same name as in the setOrder i.e. setOrder('name,_net_name,_netPrefix_prefix');
  886. }
  887. // }}}
  888. // {{{ getWhere()
  889. /**
  890. * gets the where condition which is used for the current instance
  891. *
  892. * @version 2002/04/22
  893. * @author Wolfram Kriesing <wk@visionp.de>
  894. * @return string the where condition, this can be complete like 'X=7 AND Y=8'
  895. * @access public
  896. */
  897. function getWhere()
  898. {
  899. return $this->_where;
  900. }
  901. // }}}
  902. // {{{ addWhere()
  903. /**
  904. * only adds a string to the where clause
  905. *
  906. * @version 2002/07/22
  907. * @author Wolfram Kriesing <wk@visionp.de>
  908. * @param string the where clause to add to the existing one
  909. * @param string the condition for how to concatenate the new where clause
  910. * to the existing one
  911. * @access public
  912. */
  913. function addWhere($where, $condition='AND')
  914. {
  915. if ($this->getWhere()) {
  916. $where = $this->getWhere().' '.$condition.' '.$where;
  917. }
  918. $this->setWhere($where);
  919. }
  920. // }}}
  921. // {{{ addWhereSearch()
  922. /**
  923. * add a where-like clause which works like a search for the given string
  924. * i.e. calling it like this:
  925. * $this->addWhereSearch('name', 'otto hans')
  926. * produces a where clause like this one
  927. * LOWER(name) LIKE "%otto%hans%"
  928. * so the search finds the given string
  929. *
  930. * @version 2002/08/14
  931. * @author Wolfram Kriesing <wk@visionp.de>
  932. * @param string the column to search in for
  933. * @param string the string to search for
  934. * @param string the condition
  935. * @access public
  936. */
  937. function addWhereSearch($column, $string, $condition='AND')
  938. {
  939. // if the column doesn't contain a tablename use the current table name
  940. // in case it is a defined column to prevent ambiguous rows
  941. if (strpos($column, '.') === false) {
  942. $meta = $this->metadata();
  943. if (isset($meta[$column])) {
  944. $column = $this->table .'.'. trim($column);
  945. }
  946. }
  947. $string = $this->db->quoteSmart('%'.str_replace(' ', '%', strtolower($string)).'%');
  948. $this->addWhere("LOWER($column) LIKE $string", $condition);
  949. }
  950. // }}}
  951. // {{{ setOrder()
  952. /**
  953. * sets the order condition which is used for the current instance
  954. *
  955. * @version 2002/05/16
  956. * @author Wolfram Kriesing <wk@visionp.de>
  957. * @param string the where condition, this can be complete like 'X=7 AND Y=8'
  958. * @param boolean sorting order (TRUE => ASC, FALSE => DESC)
  959. * @access public
  960. */
  961. function setOrder($orderCondition='', $desc=false)
  962. {
  963. $this->_order = $orderCondition .($desc ? ' DESC' : '');
  964. }
  965. // }}}
  966. // {{{ addOrder()
  967. /**
  968. * Add a order parameter to the query.
  969. *
  970. * @version 2003/05/28
  971. * @author Wolfram Kriesing <wk@visionp.de>
  972. * @param string the where condition, this can be complete like 'X=7 AND Y=8'
  973. * @param boolean sorting order (TRUE => ASC, FALSE => DESC)
  974. * @access public
  975. */
  976. function addOrder($orderCondition='', $desc=false)
  977. {
  978. $order = $orderCondition .($desc ? ' DESC' : '');
  979. if ($this->_order) {
  980. $this->_order = $this->_order.','.$order;
  981. } else {
  982. $this->_order = $order;
  983. }
  984. }
  985. // }}}
  986. // {{{ getOrder()
  987. /**
  988. * gets the order condition which is used for the current instance
  989. *
  990. * @version 2002/05/16
  991. * @author Wolfram Kriesing <wk@visionp.de>
  992. * @return string the order condition, this can be complete like 'ID,TIMESTAMP DESC'
  993. * @access public
  994. */
  995. function getOrder()
  996. {
  997. return $this->_order;
  998. }
  999. // }}}
  1000. // {{{ setHaving()
  1001. /**
  1002. * sets the having definition
  1003. *
  1004. * @version 2003/06/05
  1005. * @author Johannes Schaefer <johnschaefer@gmx.de>
  1006. * @param string the having definition
  1007. * @access public
  1008. */
  1009. function setHaving($having='')
  1010. {
  1011. $this->_having = $having;
  1012. }
  1013. // }}}
  1014. // {{{ getHaving()
  1015. /**
  1016. * gets the having definition which is used for the current instance
  1017. *
  1018. * @version 2003/06/05
  1019. * @author Johannes Schaefer <johnschaefer@gmx.de>
  1020. * @return string the having definition
  1021. * @access public
  1022. */
  1023. function getHaving()
  1024. {
  1025. return $this->_having;
  1026. }
  1027. // }}}
  1028. // {{{ addHaving()
  1029. /**
  1030. * Extend the current having clause. This is very useful, when you are building
  1031. * this clause from different places and don't want to overwrite the currently
  1032. * set having clause, but extend it.
  1033. *
  1034. * @param string this is a having clause, i.e. 'column' or 'table.column' or 'MAX(column)'
  1035. * @param string the connection string, which usually stays the default, which is ',' (a comma)
  1036. * @access public
  1037. */
  1038. function addHaving($what='*', $connectString=' AND ')
  1039. {
  1040. if ($this->_having) {
  1041. $this->_having = $this->_having.$connectString.$what;
  1042. } else {
  1043. $this->_having = $what;
  1044. }
  1045. }
  1046. // }}}
  1047. // {{{ setJoin()
  1048. /**
  1049. * sets a join-condition
  1050. *
  1051. * @version 2002/06/10
  1052. * @author Wolfram Kriesing <wk@visionp.de>
  1053. * @param mixed either a string or an array that contains
  1054. * the table(s) to join on the current table
  1055. * @param string the where clause for the join
  1056. * @access public
  1057. */
  1058. function setJoin($table=null, $where=null, $joinType='default')
  1059. {
  1060. //FIXXME make it possible to pass a table name as a string like this too 'user u'
  1061. // where u is the string that can be used to refer to this table in a where/order
  1062. // or whatever condition
  1063. // this way it will be possible to join tables with itself, like setJoin(array('user u','user u1'))
  1064. // this wouldnt work yet, but for doing so we would need to change the _build methods too!!!
  1065. // because they use getJoin('tables') and this simply returns all the tables in use
  1066. // but don't take care of the mentioned syntax
  1067. if (is_null($table) || is_null($where)) { // remove the join if not sufficient parameters are given
  1068. $this->_join[$joinType] = array();
  1069. return;
  1070. }
  1071. /* this causes problems if we use the order-by, since it doenst know the name to order it by ... :-)
  1072. // replace the table names with the internal name used for the join
  1073. // this way we can also join one table multiple times if it will be implemented one day
  1074. $this->_join[$table] = preg_replace('/'.$table.'/','j1',$where);
  1075. */
  1076. $this->_join[$joinType][$table] = $where;
  1077. }
  1078. // }}}
  1079. // {{{ setLeftJoin()
  1080. /**
  1081. * if you do a left join on $this->table you will get all entries
  1082. * from $this->table, also if there are no entries for them in the joined table
  1083. * if both parameters are not given the left-join will be removed
  1084. * NOTE: be sure to only use either a right or a left join
  1085. *
  1086. * @version 2002/07/22
  1087. * @author Wolfram Kriesing <wk@visionp.de>
  1088. * @param string the table(s) to be left-joined
  1089. * @param string the where clause for the join
  1090. * @access public
  1091. */
  1092. function setLeftJoin($table=null, $where=null)
  1093. {
  1094. $this->setJoin($table, $where, 'left');
  1095. }
  1096. // }}}
  1097. // {{{ addLeftJoin()
  1098. /**
  1099. *
  1100. * @param string the table(s) to be left-joined
  1101. * @param string the where clause for the join
  1102. * @param string join type
  1103. * @access public
  1104. */
  1105. function addLeftJoin($table, $where, $type='left')
  1106. {
  1107. // init value, to prevent E_ALL-warning
  1108. if (!isset($this->_join[$type]) || !$this->_join[$type]) {
  1109. $this->_join[$type] = array();
  1110. }
  1111. $this->_join[$type][$table] = $where;
  1112. }
  1113. // }}}
  1114. // {{{ setRightJoin()
  1115. /**
  1116. * see setLeftJoin for further explaination on what a left/right join is
  1117. * NOTE: be sure to only use either a right or a left join
  1118. //FIXXME check if the above sentence is necessary and if sql doesnt allow the use of both
  1119. *
  1120. * @version 2002/09/04
  1121. * @author Wolfram Kriesing <wk@visionp.de>
  1122. * @param string the table(s) to be right-joined
  1123. * @param string the where clause for the join
  1124. * @see setLeftJoin()
  1125. * @access public
  1126. */
  1127. function setRightJoin($table=null, $where=null)
  1128. {
  1129. $this->setJoin($table, $where, 'right');
  1130. }
  1131. // }}}
  1132. // {{{ getJoin()
  1133. /**
  1134. * gets the join-condition
  1135. *
  1136. * @access public
  1137. * @param string [null|''|'table'|'tables'|'right'|'left'|'inner']
  1138. * @return array gets the join parameters
  1139. */
  1140. function getJoin($what=null)
  1141. {
  1142. // if the user requests all the join data or if the join is empty, return it
  1143. if (is_null($what) || empty($this->_join)) {
  1144. return $this->_join;
  1145. }
  1146. $ret = array();
  1147. switch (strtolower($what)) {
  1148. case 'table':
  1149. case 'tables':
  1150. foreach ($this->_join as $aJoin) {
  1151. if (count($aJoin)) {
  1152. $ret = array_merge($ret, array_keys($aJoin));
  1153. }
  1154. }
  1155. break;
  1156. case 'inner': // return inner-join data only
  1157. case 'right': // return right-join data only
  1158. case 'left': // return left join data only
  1159. default:
  1160. if (isset($this->_join[$what]) && count($this->_join[$what])) {
  1161. $ret = array_merge($ret, $this->_join[$what]);
  1162. }
  1163. break;
  1164. }
  1165. return $ret;
  1166. }
  1167. // }}}
  1168. // {{{ addJoin()
  1169. /**
  1170. * adds a table and a where clause that shall be used for the join
  1171. * instead of calling
  1172. * setJoin(array(table1,table2),'<where clause1> AND <where clause2>')
  1173. * you can also call
  1174. * setJoin(table1,'<where clause1>')
  1175. * addJoin(table2,'<where clause2>')
  1176. * or where it makes more sense is to build a query which is made out of a
  1177. * left join and a standard join
  1178. * setLeftJoin(table1,'<where clause1>')
  1179. * // results in ... FROM $this->table LEFT JOIN table ON <where clause1>
  1180. * addJoin(table2,'<where clause2>')
  1181. * // results in ... FROM $this->table,table2 LEFT JOIN table ON <where clause1> WHERE <where clause2>
  1182. *
  1183. * @param string the table to be joined
  1184. * @param string the where clause for the join
  1185. * @param string the join type
  1186. * @access public
  1187. */
  1188. function addJoin($table, $where, $type='default')
  1189. {
  1190. if ($table == $this->table) {
  1191. return; //skip. Self joins are not supported.
  1192. }
  1193. // init value, to prevent E_ALL-warning
  1194. if (!array_key_exists($type, $this->_join)) {
  1195. $this->_join[$type] = array();
  1196. }
  1197. $this->_join[$type][$table] = $where;
  1198. }
  1199. // }}}
  1200. // {{{ setTable()
  1201. /**
  1202. * sets the table this class is currently working on
  1203. *
  1204. * @version 2002/07/11
  1205. * @author Wolfram Kriesing <wk@visionp.de>
  1206. * @param string the table name
  1207. * @access public
  1208. */
  1209. function setTable($table)
  1210. {
  1211. $this->table = $table;
  1212. }
  1213. // }}}
  1214. // {{{ getTable()
  1215. /**
  1216. * gets the table this class is currently working on
  1217. *
  1218. * @version 2002/07/11
  1219. * @author Wolfram Kriesing <wk@visionp.de>
  1220. * @return string the table name
  1221. * @access public
  1222. */
  1223. function getTable()
  1224. {
  1225. return $this->table;
  1226. }
  1227. // }}}
  1228. // {{{ setGroup()
  1229. /**
  1230. * sets the group-by condition
  1231. *
  1232. * @version 2002/07/22
  1233. * @author Wolfram Kriesing <wk@visionp.de>
  1234. * @param string the group condition
  1235. * @access public
  1236. */
  1237. function setGroup($group='')
  1238. {
  1239. $this->_group = $group;
  1240. //FIXXME parse the condition and replace ambiguous column names, such as "name='Deutschland'" with "country.name='Deutschland'"
  1241. // then the users don't have to write that explicitly and can use the same name as in the setOrder i.e. setOrder('name,_net_name,_netPrefix_prefix');
  1242. }
  1243. // }}}
  1244. // {{{ getGroup()
  1245. /**
  1246. * gets the group condition which is used for the current instance
  1247. *
  1248. * @version 2002/07/22
  1249. * @author Wolfram Kriesing <wk@visionp.de>
  1250. * @return string the group condition
  1251. * @access public
  1252. */
  1253. function getGroup()
  1254. {
  1255. return $this->_group;
  1256. }
  1257. // }}}
  1258. // {{{ setSelect()
  1259. /**
  1260. * limit the result to return only the columns given in $what
  1261. * @param string fields that shall be selected
  1262. * @access public
  1263. */
  1264. function setSelect($what='*')
  1265. {
  1266. $this->_select = $what;
  1267. }
  1268. // }}}
  1269. // {{{ addSelect()
  1270. /**
  1271. * add a string to the select part of the query
  1272. *
  1273. * add a string to the select-part of the query and connects it to an existing
  1274. * string using the $connectString, which by default is a comma.
  1275. * (SELECT xxx FROM - xxx is the select-part of a query)
  1276. *
  1277. * @version 2003/01/08
  1278. * @author Wolfram Kriesing <wk@visionp.de>
  1279. * @param string the string that shall be added to the select-part
  1280. * @param string the string to connect the new string with the existing one
  1281. * @access public
  1282. */
  1283. function addSelect($what='*', $connectString=',')
  1284. {
  1285. // if the select string is not empty add the string, otherwise simply set it
  1286. if ($this->_select) {
  1287. $this->_select = $this->_select.$connectString.$what;
  1288. } else {
  1289. $this->_select = $what;
  1290. }
  1291. }
  1292. // }}}
  1293. // {{{ getSelect()
  1294. /**
  1295. * @return string
  1296. * @access public
  1297. */
  1298. function getSelect()
  1299. {
  1300. return $this->_select;
  1301. }
  1302. // }}}
  1303. // {{{ setDontSelect()
  1304. /**
  1305. * @param string
  1306. * @access public
  1307. */
  1308. function setDontSelect($what='')
  1309. {
  1310. $this->_dontSelect = $what;
  1311. }
  1312. // }}}
  1313. // {{{ getDontSelect()
  1314. /**
  1315. * @return string
  1316. * @access public
  1317. */
  1318. function getDontSelect()
  1319. {
  1320. return $this->_dontSelect;
  1321. }
  1322. // }}}
  1323. // {{{ reset()
  1324. /**
  1325. * reset all the set* settings; with no parameter given, it resets them all.
  1326. *
  1327. * @version 2002/09/16
  1328. * @author Wolfram Kriesing <wk@visionp.de>
  1329. * @param array $what
  1330. * @access public
  1331. */
  1332. function reset($what=array())
  1333. {
  1334. if (!sizeof($what)) {
  1335. $what = array(
  1336. 'select',
  1337. 'dontSelect',
  1338. 'group',
  1339. 'having',
  1340. 'limit',
  1341. 'where',
  1342. 'index',
  1343. 'order',
  1344. 'join',
  1345. 'leftJoin',
  1346. 'rightJoin'
  1347. );
  1348. }
  1349. foreach ($what as $aReset) {
  1350. $this->{'set'.ucfirst($aReset)}();
  1351. }
  1352. }
  1353. // }}}
  1354. // {{{ setOption()
  1355. /**
  1356. * set mode the class shall work in
  1357. * currently we have the modes:
  1358. * 'raw' does not quote the data before building the query
  1359. *
  1360. * @version 2002/09/17
  1361. * @author Wolfram Kriesing <wk@visionp.de>
  1362. * @param string the mode to be set
  1363. * @param mixed the value of the mode
  1364. * @access public
  1365. */
  1366. function setOption($option, $value)
  1367. {
  1368. $this->options[strtolower($option)] = $value;
  1369. }
  1370. // }}}
  1371. // {{{ getOption()
  1372. /**
  1373. * @param string name of the option to retrieve
  1374. * @return string value of the option
  1375. * @access public
  1376. */
  1377. function getOption($option)
  1378. {
  1379. return $this->options[strtolower($option)];
  1380. }
  1381. // }}}
  1382. // {{{ _quoteIdentifier()
  1383. /**
  1384. * Quotes an identifier (table or field name). This wrapper is needed to
  1385. * comply with the $raw parameter and to override DB_ibase::quoteIdentifier().
  1386. *
  1387. * @param Charcoal_String $var
  1388. * @return string quoted identifier
  1389. * @access private
  1390. */
  1391. function _quoteIdentifier($var)
  1392. {
  1393. if (!$this->getOption('raw') && $this->db->phptype != 'ibase') {
  1394. return $this->db->quoteIdentifier($var);
  1395. }
  1396. return $var;
  1397. }
  1398. // }}}
  1399. // {{{ _quoteArray()
  1400. /**
  1401. * quotes all the data in this array if we are not in raw mode!
  1402. * @param array $data
  1403. * @return array
  1404. * @access private
  1405. */
  1406. function _quoteArray($data)
  1407. {
  1408. if (!$this->getOption('raw')) {
  1409. foreach ($data as $key => $val) {
  1410. $data[$key] = $this->db->quoteSmart($val);
  1411. }
  1412. }
  1413. return $data;
  1414. }
  1415. // }}}
  1416. // {{{ _quote()
  1417. /**
  1418. * quotes all the data in this array|string if we are not in raw mode!
  1419. * @param mixed $data
  1420. * @return mixed
  1421. * @access private
  1422. */
  1423. function _quote($data)
  1424. {
  1425. if ($this->getOption('raw')) {
  1426. return $data;
  1427. }
  1428. switch (gettype($data)) {
  1429. case 'array':
  1430. return $this->_quoteArray($data);
  1431. default:
  1432. return $this->db->quoteSmart($data);
  1433. }
  1434. }
  1435. // }}}
  1436. // {{{ _checkColumns()
  1437. /**
  1438. * checks if the columns which are given as the array's indexes really exist
  1439. * if not it will be unset anyway
  1440. *
  1441. * @version 2002/04/16
  1442. * @author Wolfram Kriesing <wk@visionp.de>
  1443. * @param string the actual message, first word should always be the method name,
  1444. * to build the message like this: className::methodname
  1445. * @param integer the line number
  1446. * @access public
  1447. */
  1448. function _checkColumns($newData, $method='unknown')
  1449. {
  1450. if (!$meta = $this->metadata()) {
  1451. // if no metadata available, return data as given
  1452. return $newData;
  1453. }
  1454. foreach ($newData as $colName => $x) {
  1455. if (!isset($meta[$colName])) {
  1456. $this->_errorLog("$method, column {$this->table}.$colName doesn't exist, value was removed before '$method'",__LINE__);
  1457. unset($newData[$colName]);
  1458. } else {
  1459. // if the current column exists, check the length too, not to write content that is too long
  1460. // prevent DB-errors here
  1461. // do only check the data length if this field is given
  1462. if (isset($meta[$colName]['len']) && ($meta[$colName]['len'] != -1)
  1463. && (($oldLength=strlen($newData[$colName])) > $meta[$colName]['len'])
  1464. && !is_numeric($newData[$colName])
  1465. ) {
  1466. $this->_errorLog("_checkColumns, had to trim column '$colName' from $oldLength to ".
  1467. $meta[$colName]['DATA_LENGTH'].' characters.', __LINE__);
  1468. $newData[$colName] = substr($newData[$colName], 0, $meta[$colName]['len']);
  1469. }
  1470. }
  1471. }
  1472. return $newData;
  1473. }
  1474. // }}}
  1475. // {{{ debug()
  1476. /**
  1477. * overwrite this method and i.e. print the query $string
  1478. * to see the final query
  1479. *
  1480. * @param string the query mostly
  1481. * @access public
  1482. */
  1483. function debug($string) {}
  1484. //
  1485. //
  1486. // ONLY ORACLE SPECIFIC, not very nice since it is DB dependent, but we need it!!!
  1487. //
  1488. //
  1489. // }}}
  1490. // {{{ metadata()
  1491. /**
  1492. * !!!! query COPIED FROM db_oci8.inc - from PHPLIB !!!!
  1493. *
  1494. * @version 2001/09
  1495. * @see db_oci8.inc - PHPLIB
  1496. * @param Charcoal_String $table
  1497. * @return resultSet or false on error
  1498. * @access public
  1499. */
  1500. function metadata($table='')
  1501. {
  1502. // is there an alias in the table name, then we have something like this: 'user ua'
  1503. // cut of the alias and return the table name
  1504. if (strpos($table, ' ') !== false) {
  1505. $split = explode(' ', trim($table));
  1506. $table = $split[0];
  1507. }
  1508. $full = false;
  1509. if (empty($table)) {
  1510. $table = $this->table;
  1511. }
  1512. // to prevent multiple selects for the same metadata
  1513. if (isset($this->_metadata[$table])) {
  1514. return $this->_metadata[$table];
  1515. }
  1516. // FIXXXME use oci8 implementation of newer PEAR::DB-version
  1517. if ($this->db->phptype == 'oci8') {
  1518. $count = 0;
  1519. $id = 0;
  1520. $res = array();
  1521. //# This is a RIGHT OUTER JOIN: "(+)", if you want to see, what
  1522. //# this query results try the following:
  1523. //// $table = new Table; $this->db = new my_DB_Sql; // you have to make
  1524. //// // your own class
  1525. //// $table->show_results($this->db->query(see query vvvvvv))
  1526. ////
  1527. $res = $this->db->getAll("SELECT T.column_name,T.table_name,T.data_type,".
  1528. "T.data_length,T.data_precision,T.data_scale,T.nullable,".
  1529. "T.char_col_decl_length,I.index_name".
  1530. " FROM ALL_TAB_COLUMNS T,ALL_IND_COLUMNS I".
  1531. " WHERE T.column_name=I.column_name (+)".
  1532. " AND T.table_name=I.table_name (+)".
  1533. " AND T.table_name=UPPER('$table') ORDER BY T.column_id");
  1534. if (PEAR::isError($res)) {
  1535. //$this->_errorSet($res->getMessage());
  1536. // i think we only need to log here, since this method is never used
  1537. // directly for the user's functionality, which means if it fails it
  1538. // is most probably an appl error
  1539. $this->_errorLog($res->getUserInfo());
  1540. return false;
  1541. }
  1542. foreach ($res as $key => $val) {
  1543. $res[$key]['name'] = $val['COLUMN_NAME'];
  1544. }
  1545. } else {
  1546. if (!is_object($this->db)) {
  1547. return false;
  1548. }
  1549. $res = $this->db->tableinfo($table);
  1550. if (PEAR::isError($res)) {
  1551. //var_dump($res);
  1552. //echo '<div style="border:1px solid red; background: yellow">'.$res->getUserInfo().'<br/><pre>'; print_r(debug_backtrace()); echo '</pre></div>';
  1553. $this->_errorSet($res->getUserInfo());
  1554. return false;
  1555. }
  1556. }
  1557. $ret = array();
  1558. foreach ($res as $key => $val) {
  1559. $ret[$val['name']] = $val;
  1560. }
  1561. $this->_metadata[$table] = $ret;
  1562. return $ret;
  1563. }
  1564. // }}}
  1565. //
  1566. // methods for building the query
  1567. //
  1568. // {{{ _prependTableName()
  1569. /**
  1570. * replace 'column' by 'table.column' if the column is defined for the table
  1571. *
  1572. * @param Charcoal_String $fieldlist
  1573. * @param Charcoal_String $table table name
  1574. * @return Charcoal_String $fieldlist
  1575. * @see http://pear.php.net/bugs/bug.php?id=9734
  1576. * @access private
  1577. */
  1578. function _prependTableName($fieldlist, $table) {
  1579. if (!$meta = $this->metadata($table)) {
  1580. return $fieldlist;
  1581. }
  1582. $fields = explode(',', $fieldlist);
  1583. foreach (array_keys($meta) as $column) {
  1584. //$fieldlist = preg_replace('/(^\s*|\s+|,)'.$column.'\s*(,)?/U', "$1{$table}.$column$2", $fieldlist);
  1585. $pattern = '/^'.$column.'\b.*/U';
  1586. foreach (array_keys($fields) as $k) {
  1587. $fields[$k] = trim($fields[$k]);
  1588. if (!strpos($fields[$k], '.') && preg_match($pattern, $fields[$k])) {
  1589. $fields[$k] = $this->_quoteIdentifier($table).'.'.$this->_quoteIdentifier($fields[$k]);
  1590. }
  1591. }
  1592. }
  1593. return implode(',', $fields);
  1594. }
  1595. // }}}
  1596. // {{{ _buildFrom()
  1597. /**
  1598. * build the from string
  1599. *
  1600. * @return string the string added after FROM
  1601. * @access private
  1602. */
  1603. function _buildFrom()
  1604. {
  1605. $this_table = $from = $this->_quoteIdentifier($this->table);
  1606. $join = $this->getJoin();
  1607. if (!$join) { // no join set
  1608. return $from;
  1609. }
  1610. // handle the standard join thingy
  1611. if (isset($join['default']) && count($join['default'])) {
  1612. foreach (array_keys($join['default']) as $joined_tbl) {
  1613. $from .= ','.$this->_quoteIdentifier($joined_tbl);
  1614. }
  1615. }
  1616. // handle left/right/inner joins
  1617. foreach (array('left', 'right', 'inner') as $joinType) {
  1618. if (isset($join[$joinType]) && count($join[$joinType])) {
  1619. foreach($join[$joinType] as $table => $condition) {
  1620. // replace the _TABLENAME_COLUMNNAME by TABLENAME.COLUMNNAME
  1621. // since oracle doesn't work with the _TABLENAME_COLUMNNAME which i think is strange
  1622. // FIXXME i think this should become deprecated since the setWhere should not be used like this: '_table_column' but 'table.column'
  1623. $regExp = '/_('.$table.')_([^\s]+)/';
  1624. $where = preg_replace($regExp, '$1.$2', $condition);
  1625. // add the table name before any column that has no table prefix
  1626. // since this might cause "unambiguous column" errors
  1627. if ($meta = $this->metadata()) {
  1628. foreach ($meta as $aCol => $x) {
  1629. // this covers the LIKE,IN stuff: 'name LIKE "%you%"' 'id IN (2,3,4,5)'
  1630. $condition = preg_replace('/\s'.$aCol.'\s/', " {$this_table}.$aCol ", $condition);
  1631. // replace also the column names which are behind a '='
  1632. // and do this also if the aCol is at the end of the where clause
  1633. // that's what the $ is for
  1634. $condition = preg_replace('/=\s*'.$aCol.'(\s|$)/', "={$this_table}.$aCol ", $condition);
  1635. // replace if colName is first and possibly also if at the beginning of the where-string
  1636. $condition = preg_replace('/(^\s*|\s+)'.$aCol.'\s*=/', "$1{$this_table}.$aCol=", $condition);
  1637. }
  1638. }
  1639. $from .= ' '.strtoupper($joinType).' JOIN '.$this->_quoteIdentifier($table).' ON '.$condition;
  1640. }
  1641. }
  1642. }
  1643. return $from;
  1644. }
  1645. // }}}
  1646. // {{{ getTableShortName()
  1647. /**
  1648. * Gets the short name for a table
  1649. *
  1650. * get the short name for a table, this is needed to properly build the
  1651. * 'AS' parts in the select query
  1652. * @param string the real table name
  1653. * @return string the table's short name
  1654. * @access public
  1655. */
  1656. function getTableShortName($table)
  1657. {
  1658. $tableSpec = $this->getTableSpec(false);
  1659. if (isset($tableSpec[$table]['shortName']) && $tableSpec[$table]['shortName']) {
  1660. //print "$table ... ".$tableSpec[$table]['shortName'].'<br />';
  1661. return $tableSpec[$table]['shortName'];
  1662. }
  1663. $possibleTableShortName = preg_replace($this->_tableNameToShortNamePreg, '', $table);
  1664. //print "$table ... $possibleTableShortName<br />";
  1665. return $possibleTableShortName;
  1666. }
  1667. // }}}
  1668. // {{{ getTableSpec()
  1669. /**
  1670. * gets the tableSpec either indexed by the short name or the name
  1671. * returns the array for the tables given as parameter or if no
  1672. * parameter given for all tables that exist in the tableSpec
  1673. *
  1674. * @param array table names (not the short names!)
  1675. * @param boolean if true the table is returned indexed by the shortName
  1676. * otherwise indexed by the name
  1677. * @return array the tableSpec indexed
  1678. * @access public
  1679. */
  1680. function getTableSpec($shortNameIndexed=true, $tables=array())
  1681. {
  1682. $newSpec = array();
  1683. foreach ($this->tableSpec as $aSpec) {
  1684. if (sizeof($tables)==0 || in_array($aSpec['name'],$tables)) {
  1685. if ($shortNameIndexed) {
  1686. $newSpec[$aSpec['shortName']] = $aSpec;
  1687. } else {
  1688. $newSpec[$aSpec['name']] = $aSpec;
  1689. }
  1690. }
  1691. }
  1692. return $newSpec;
  1693. }
  1694. // }}}
  1695. // {{{ _buildSelect()
  1696. /**
  1697. * build the 'SELECT <what> FROM ... 'for a select
  1698. *
  1699. * @version 2002/07/11
  1700. * @author Wolfram Kriesing <wk@visionp.de>
  1701. * @param string if given use this string
  1702. * @return string the what-clause
  1703. * @access private
  1704. */
  1705. function _buildSelect($what=null)
  1706. {
  1707. // what has preference, that means if what is set it is used
  1708. // this is only because the methods like 'get' pass an individually built value, which
  1709. // is supposed to be used, but usually it's generically build using the 'getSelect' values
  1710. if (empty($what) && $this->getSelect()) {
  1711. $what = $this->getSelect();
  1712. }
  1713. //
  1714. // replace all the '*' by the real column names, and take care of the dontSelect-columns!
  1715. //
  1716. $dontSelect = $this->getDontSelect();
  1717. $dontSelect = $dontSelect ? explode(',', $dontSelect) : array(); // make sure dontSelect is an array
  1718. // here we will replace all the '*' and 'table.*' by all the columns that this table
  1719. // contains. we do this so we can easily apply the 'dontSelect' values.
  1720. // and so we can also handle queries like: 'SELECT *,count() FROM ' and 'SELECT table.*,x FROM ' too
  1721. if (strpos($what, '*') !== false) {
  1722. // subpattern 1 get all the table names, that are written like this: 'table.*' including '*'
  1723. // for '*' the tablename will be ''
  1724. preg_match_all('/([^,]*)(\.)?\*\s*(,|$)/U', $what, $res);
  1725. //echo '<pre>'; print "$what ... "; print_r($res); print "</pre><hr />";
  1726. $selectAllFromTables = array_unique($res[1]); // make the table names unique, so we do it all just once for each table
  1727. //echo '<pre>'; print "$what ... "; print_r($selectAllFromTables); print "</pre><hr />";
  1728. $tables = array();
  1729. if (in_array('', $selectAllFromTables)) { // was there a '*' ?
  1730. // get all the tables that we need to process, depending on if joined or not
  1731. $tables = $this->getJoin() ?
  1732. array_merge($this->getJoin('tables'), array($this->table)) : // get the joined tables and this->table
  1733. array($this->table); // create an array with only this->table
  1734. } else {
  1735. $tables = $selectAllFromTables;
  1736. }
  1737. //echo '<br />'; print_r($tables);
  1738. $cols = array();
  1739. foreach ($tables as $aTable) { // go thru all the tables and get all columns for each, and handle 'dontSelect'
  1740. //echo '<br />$this->metadata('.$aTable.')';
  1741. //echo '<br /><pre>';var_dump($this->metadata($aTable)); echo '</pre>';
  1742. if ($meta = $this->metadata($aTable)) {
  1743. foreach ($meta as $colName => $x) {
  1744. // handle the dontSelect's
  1745. if (in_array($colName, $dontSelect) || in_array("$aTable.$colName", $dontSelect)) {
  1746. continue;
  1747. }
  1748. // build the AS clauses
  1749. // put " around them to enable use of reserved words, i.e. SELECT table.option as option FROM...
  1750. // and 'option' actually is a reserved word, at least in mysql
  1751. // but don't do this for ibase because it doesn't work!
  1752. if ($aTable == $this->table) {
  1753. $cols[$aTable][] = $this->table. '.' .$colName . ' AS '. $this->_quoteIdentifier($colName);
  1754. } else {
  1755. //with ibase, don't quote aliases, and prepend the
  1756. //joined table cols alias with "t_" because an alias
  1757. //starting with just "_" triggers an "invalid token" error
  1758. $short_alias = ($this->db->phptype == 'ibase' ? 't_' : '_') . $this->getTableShortName($aTable) .'_'. $colName;
  1759. $cols[$aTable][] = $aTable. '.' .$colName . ' AS '. $this->_quoteIdentifier($short_alias);
  1760. }
  1761. }
  1762. }
  1763. }
  1764. // put the extracted select back in the $what
  1765. // that means replace 'table.*' by the i.e. 'table.id AS _table_id'
  1766. // or if it is the table of this class replace 'table.id AS id'
  1767. if (in_array('', $selectAllFromTables)) {
  1768. $allCols = array();
  1769. foreach ($cols as $aTable) {
  1770. $allCols[] = implode(',', $aTable);
  1771. }
  1772. $what = preg_replace('/(^|,)\*($|,)/', '$1'.implode(',',$allCols).'$2', $what);
  1773. // remove all the 'table.*' since we have selected all anyway (because there was a '*' in the select)
  1774. $what = preg_replace('/[^,]*(\.)?\*\s*(,|$)/U', '', $what);
  1775. } else {
  1776. foreach ($cols as $tableName => $aTable) {
  1777. if (is_array($aTable) && sizeof($aTable)) {
  1778. // replace all the 'table.*' by their select of each column
  1779. $what = preg_replace('/(^|,)\s*'.$tableName.'\.\*\s*($|,)/', '$1'.implode(',', $aTable).'$2', $what);
  1780. }
  1781. }
  1782. }
  1783. }
  1784. if ($this->getJoin()) {
  1785. // replace all 'column' by '$this->table.column' to prevent ambiguous errors
  1786. $metadata = $this->metadata();
  1787. if (is_array($metadata)) {
  1788. foreach ($metadata as $aCol => $x) {
  1789. // handle ',id as xid,MAX(id),id' etc.
  1790. // FIXXME do this better!!!
  1791. $what = preg_replace( "/(^|,|\()(\s*)$aCol(\)|\s|,|as|$)/i",
  1792. // $2 is actually just to keep the spaces, is not really
  1793. // necessary, but this way the test works independent of this functionality here
  1794. "$1$2{$this->table}.$aCol$3",
  1795. $what);
  1796. }
  1797. }
  1798. // replace all 'joinedTable.columnName' by '_joinedTable_columnName'
  1799. // this actually only has an effect if there was no 'table.*' for 'table'
  1800. // if that was there, then it has already been done before
  1801. foreach ($this->getJoin('tables') as $aTable) {
  1802. if ($meta = $this->metadata($aTable)) {
  1803. foreach ($meta as $aCol => $x) {
  1804. // dont put the 'AS' behind it if there is already one
  1805. if (preg_match("/$aTable.$aCol\s*as/i",$what)) {
  1806. continue;
  1807. }
  1808. // this covers a ' table.colName ' surrounded by spaces, and replaces it by ' table.colName AS _table_colName'
  1809. $what = preg_replace('/\s'.$aTable.'.'.$aCol.'\s/', " $aTable.$aCol AS _".$this->getTableShortName($aTable)."_$aCol ", $what);
  1810. // replace also the column names which are behind a ','
  1811. // and do this also if the aCol is at the end that's what the $ is for
  1812. $what = preg_replace('/,\s*'.$aTable.'.'.$aCol.'(,|\s|$)/', ",$aTable.$aCol AS _".$this->getTableShortName($aTable)."_$aCol$1", $what);
  1813. // replace if colName is first and possibly also if at the beginning of the where-string
  1814. $what = preg_replace('/(^\s*|\s+)'.$aTable.'.'.$aCol.'\s*,/', "$1$aTable.$aCol AS _".$this->getTableShortName($aTable)."_$aCol,", $what);
  1815. }
  1816. }
  1817. }
  1818. }
  1819. // quotations of columns
  1820. $columns = explode(',', $what);
  1821. $identifier = substr($this->_quoteIdentifier(''), 0, 1);
  1822. for ($i=0; $i<sizeof($columns); $i++) {
  1823. $column = trim($columns[$i]);
  1824. // Uppercasing "as"
  1825. $column = str_replace(' as ', ' AS ', $column);
  1826. if (strpos($column, ' AS ') !== false) {
  1827. $column = explode(' AS ', $column);
  1828. if (strpos($column[0], '(') !== false) {
  1829. //do not quote function calls, COUNT(), etc.
  1830. } elseif (strpos($column[0], '.') !== false) {
  1831. $column[0] = explode('.', $column[0]);
  1832. $column[0][0] = $this->_quoteIdentifier($column[0][0]);
  1833. $column[0][1] = $this->_quoteIdentifier($column[0][1]);
  1834. $column[0] = implode('.', $column[0]);
  1835. } else {
  1836. $column[0] = $this->_quoteIdentifier($column[0]);
  1837. }
  1838. $column = implode(' AS ', $column);
  1839. } else {
  1840. if (strpos($column, '(') !== false) {
  1841. //do not quote function calls, COUNT(), etc.
  1842. } elseif (strpos($column, '.') !== false) {
  1843. $column = explode('.', $column);
  1844. $column[0] = $this->_quoteIdentifier($column[0]);
  1845. $column[1] = $this->_quoteIdentifier($column[1]);
  1846. $column = implode('.', $column);
  1847. } else {
  1848. $column = $this->_quoteIdentifier($column);
  1849. }
  1850. }
  1851. /*
  1852. // Clean up if a function was used in the query
  1853. if (substr($column, -2) == ')'.$identifier) {
  1854. $column = substr($column, 0, -2).$identifier.')';
  1855. // Some like spaces in the function
  1856. while (strpos($column, ' '.$identifier) !== false) {
  1857. $column = str_replace(' '.$identifier, $identifier.' ', $column);
  1858. }
  1859. }
  1860. */
  1861. $columns[$i] = $column;
  1862. }
  1863. return implode(',', $columns);
  1864. }
  1865. // }}}
  1866. // {{{ _buildWhere()
  1867. /**
  1868. * Build WHERE clause
  1869. *
  1870. * @param Charcoal_String $where WHERE clause
  1871. * @return Charcoal_String $where WHERE clause after processing
  1872. * @access private
  1873. */
  1874. function _buildWhere($where='')
  1875. {
  1876. $where = trim($where);
  1877. $originalWhere = $this->getWhere();
  1878. if ($originalWhere) {
  1879. if (!empty($where)) {
  1880. $where = $originalWhere.' AND '.$where;
  1881. } else {
  1882. $where = $originalWhere;
  1883. }
  1884. }
  1885. $where = trim($where);
  1886. if ($join = $this->getJoin()) { // is join set?
  1887. // only those where conditions in the default-join have to be added here
  1888. // left-join conditions are added behind 'ON', the '_buildJoin()' does that
  1889. if (isset($join['default']) && count($join['default'])) {
  1890. // we have to add this join-where clause here
  1891. // since at least in mysql a query like: select * from tableX JOIN tableY ON ...
  1892. // doesnt work, may be that's even SQL-standard...
  1893. if (!empty($where)) {
  1894. $where = implode(' AND ', $join['default']).' AND '.$where;
  1895. } else {
  1896. $where = implode(' AND ', $join['default']);
  1897. }
  1898. }
  1899. // replace the _TABLENAME_COLUMNNAME by TABLENAME.COLUMNNAME
  1900. // since oracle doesnt work with the _TABLENAME_COLUMNNAME which i think is strange
  1901. // FIXXME i think this should become deprecated since the setWhere should not be used like this: '_table_column' but 'table.column'
  1902. $regExp = '/_('.implode('|', $this->getJoin('tables')).')_([^\s]+)/';
  1903. $where = preg_replace($regExp, '$1.$2', $where);
  1904. // add the table name before any column that has no table prefix
  1905. // since this might cause "unambigious column" errors
  1906. if ($meta = $this->metadata()) {
  1907. foreach ($meta as $aCol => $x) {
  1908. // this covers the LIKE,IN stuff: 'name LIKE "%you%"' 'id IN (2,3,4,5)'
  1909. $where = preg_replace('/\s'.$aCol.'\s/', " {$this->table}.$aCol ", $where);
  1910. // replace also the column names which are behind a '='
  1911. // and do this also if the aCol is at the end of the where clause
  1912. // that's what the $ is for
  1913. $where = preg_replace('/([=<>])\s*'.$aCol.'(\s|$)/', "$1{$this->table}.$aCol ", $where);
  1914. // replace if colName is first and possibly also if at the beginning of the where-string
  1915. $where = preg_replace('/(^\s*|\s+)'.$aCol.'\s*([=<>])/', "$1{$this->table}.$aCol$2", $where);
  1916. }
  1917. }
  1918. }
  1919. return $where;
  1920. }
  1921. // }}}
  1922. // {{{ _buildOrder()
  1923. /**
  1924. * Build the "ORDER BY" clause, replace 'column' by 'table.column'.
  1925. *
  1926. * @version 2007/01/10
  1927. * @author Lorenzo Alberton <l.alberton@quipo.it>
  1928. * @return string the rendered "ORDER BY" clause
  1929. * @access private
  1930. */
  1931. function _buildOrder()
  1932. {
  1933. return $this->_prependTableName($this->getOrder(), $this->table);
  1934. }
  1935. // }}}
  1936. // {{{ _buildGroup()
  1937. /**
  1938. * Build the "GROUP BY" clause, replace 'column' by 'table.column'.
  1939. *
  1940. * @version 2007/01/10
  1941. * @author Lorenzo Alberton <l.alberton@quipo.it>
  1942. * @return string the rendered "GROUP BY" clause
  1943. * @access private
  1944. */
  1945. function _buildGroup()
  1946. {
  1947. return $this->_prependTableName($this->getGroup(), $this->table);
  1948. }
  1949. // }}}
  1950. // {{{ _buildHaving()
  1951. /**
  1952. * Build the "HAVING" clause, replace 'column' by 'table.column'.
  1953. *
  1954. * @version 2007/01/10
  1955. * @author Lorenzo Alberton <l.alberton@quipo.it>
  1956. * @return string the rendered "HAVING" clause
  1957. * @access private
  1958. */
  1959. function _buildHaving()
  1960. {
  1961. return $this->_prependTableName($this->getHaving(), $this->table);
  1962. }
  1963. // }}}
  1964. // {{{ _buildSelectQuery()
  1965. /**
  1966. * Build the "SELECT" query
  1967. *
  1968. * @version 2002/07/11
  1969. * @author Wolfram Kriesing <wk@visionp.de>
  1970. * @param array this array contains the elements of the query,
  1971. * indexed by their key, which are: 'select','from','where', etc.
  1972. * @param boolean whether this method is called via getCount() or not.
  1973. * @return Charcoal_String $querystring or false on error
  1974. * @access private
  1975. */
  1976. function _buildSelectQuery($query=array(), $isCalledViaGetCount = false)
  1977. {
  1978. /*FIXXXME finish this
  1979. $cacheKey = md5(serialize(????));
  1980. if (isset($this->_queryCache[$cacheKey])) {
  1981. $this->_errorLog('using cached query',__LINE__);
  1982. return $this->_queryCache[$cacheKey];
  1983. }
  1984. */
  1985. $where = isset($query['where']) ? $query['where'] : $this->_buildWhere();
  1986. if ($where) {
  1987. $where = 'WHERE '.$where;
  1988. }
  1989. $order = isset($query['order']) ? $query['order'] : $this->_buildOrder();
  1990. if ($order) {
  1991. $order = 'ORDER BY '.$order;
  1992. }
  1993. $group = isset($query['group']) ? $query['group'] : $this->_buildGroup();
  1994. if ($group) {
  1995. $group = 'GROUP BY '.$group;
  1996. }
  1997. $having = isset($query['having']) ? $query['having'] : $this->_buildHaving();
  1998. if ($having) {
  1999. $having = 'HAVING '.$having;
  2000. }
  2001. $queryString = sprintf(
  2002. 'SELECT %s FROM %s %s %s %s %s',
  2003. isset($query['select']) ? $query['select'] : $this->_buildSelect(),
  2004. isset($query['from']) ? $query['from'] : $this->_buildFrom(),
  2005. $where,
  2006. $group,
  2007. $having,
  2008. $order
  2009. );
  2010. // $query['limit'] has preference!
  2011. $limit = isset($query['limit']) ? $query['limit'] : $this->_limit;
  2012. if (!$isCalledViaGetCount && !empty($limit[1])) {
  2013. // is there a count set?
  2014. $queryString = $this->db->modifyLimitQuery($queryString, $limit[0], $limit[1]);
  2015. //echo '<pre>'; var_dump($queryString); echo '</pre>';
  2016. if (PEAR::isError($queryString)) {
  2017. $this->_errorSet('DB_QueryTool::db::modifyLimitQuery failed '.$queryString->getMessage());
  2018. $this->_errorLog($queryString->getUserInfo());
  2019. return false;
  2020. }
  2021. }
  2022. // $this->_queryCache[$cacheKey] = $queryString;
  2023. return $queryString;
  2024. }
  2025. // }}}
  2026. // {{{ _buildUpdateQuery()
  2027. /**
  2028. * this simply builds an update query.
  2029. *
  2030. * @param array the parameter array might contain the following indexes
  2031. * 'where' the where clause to be added, i.e.
  2032. * UPDATE table SET x=1 WHERE y=0
  2033. * here the 'where' part simply would be 'y=0'
  2034. * 'set' the actual data to be updated
  2035. * in the example above, that would be 'x=1'
  2036. * @return string the resulting query
  2037. * @access private
  2038. */
  2039. function _buildUpdateQuery($query=array())
  2040. {
  2041. $where = isset($query['where']) ? $query['where'] : $this->_buildWhere();
  2042. if ($where) {
  2043. $where = 'WHERE '.$where;
  2044. }
  2045. $updateString = sprintf(
  2046. 'UPDATE %s SET %s %s',
  2047. $this->table,
  2048. $query['set'],
  2049. $where
  2050. );
  2051. return $updateString;
  2052. }
  2053. // }}}
  2054. // {{{ execute()
  2055. /**
  2056. *
  2057. * @version 2002/07/11
  2058. * @author Wolfram Kriesing <wk@visionp.de>
  2059. * @param Charcoal_String $query
  2060. * @param string method
  2061. * @return resultSet or false on error
  2062. * @access public
  2063. */
  2064. function execute($query=null, $method='getAll')
  2065. {
  2066. $this->writeLog();
  2067. if (is_null($query)) {
  2068. $query = $this->_buildSelectQuery();
  2069. }
  2070. $this->writeLog('query built: '.$query);
  2071. // FIXXME on ORACLE this doesnt work, since we return joined columns as _TABLE_COLNAME and the _ in front
  2072. // doesnt work on oracle, add a letter before it!!!
  2073. $this->_lastQuery = $query;
  2074. $this->debug($query);
  2075. $this->writeLog('start query');
  2076. if (PEAR::isError($res = $this->db->$method($query))) {
  2077. $this->writeLog('end query (failed)');
  2078. if ($this->getOption('verbose')) {
  2079. $this->_errorSet($res->getMessage());
  2080. } else {
  2081. $this->_errorLog($res->getMessage());
  2082. }
  2083. $this->_errorLog($res->getUserInfo(), __LINE__);
  2084. return false;
  2085. } else {
  2086. $this->writeLog('end query');
  2087. }
  2088. $res = $this->_makeIndexed($res);
  2089. return $res;
  2090. }
  2091. // }}}
  2092. // {{{ writeLog()
  2093. /**
  2094. * Write events to the logfile.
  2095. *
  2096. * It does some additional work, like time measuring etc. to
  2097. * see some additional info
  2098. *
  2099. * @param Charcoal_String $text
  2100. * @access public
  2101. */
  2102. function writeLog($text='START')
  2103. {
  2104. //its still really a quicky.... 'refactor' (nice word) that
  2105. if (!isset($this->options['logfile'])) {
  2106. return;
  2107. }
  2108. include_once 'Log.php';
  2109. if (!class_exists('Log')) {
  2110. return;
  2111. }
  2112. if (!$this->_logObject) {
  2113. $this->_logObject =& Log::factory('file', $this->options['logfile']);
  2114. }
  2115. if ($text === 'start query' || $text === 'end query') {
  2116. $bytesSent = $this->db->getAll("SHOW STATUS like 'Bytes_sent'");
  2117. $bytesSent = $bytesSent[0]['Value'];
  2118. }
  2119. if ($text === 'START') {
  2120. $startTime = split(' ', microtime());
  2121. $this->_logData['startTime'] = $startTime[1] + $startTime[0];
  2122. }
  2123. if ($text === 'start query') {
  2124. $this->_logData['startBytesSent'] = $bytesSent;
  2125. $startTime = split(' ', microtime());
  2126. $this->_logData['startQueryTime'] = $startTime[1] + $startTime[0];
  2127. return;
  2128. }
  2129. if ($text === 'end query') {
  2130. $text .= ' result size: '.((int)$bytesSent-(int)$this->_logData['startBytesSent']).' bytes';
  2131. $endTime = split(' ', microtime());
  2132. $endTime = $endTime[1] + $endTime[0];
  2133. $text .= ', took: '.(($endTime - $this->_logData['startQueryTime'])).' seconds';
  2134. }
  2135. if (strpos($text, 'query built') === 0) {
  2136. $endTime = split(' ', microtime());
  2137. $endTime = $endTime[1] + $endTime[0];
  2138. $this->writeLog('query building took: '.(($endTime - $this->_logData['startTime'])).' seconds');
  2139. }
  2140. $this->_logObject->log($text);
  2141. if (strpos($text, 'end query') === 0) {
  2142. $endTime = split(' ', microtime());
  2143. $endTime = $endTime[1] + $endTime[0];
  2144. $text = 'time over all: '.(($endTime - $this->_logData['startTime'])).' seconds';
  2145. $this->_logObject->log($text);
  2146. }
  2147. }
  2148. // }}}
  2149. // {{{ returnResult()
  2150. /**
  2151. * Return the chosen result type
  2152. *
  2153. * @version 2004/04/28
  2154. * @param object reference
  2155. * @return mixed [boolean, array or object]
  2156. * @access public
  2157. */
  2158. function returnResult($result)
  2159. {
  2160. if ($this->_resultType == 'none') {
  2161. return $result;
  2162. }
  2163. if ($result === false) {
  2164. return false;
  2165. }
  2166. //what about allowing other (custom) result types?
  2167. switch (strtolower($this->_resultType)) {
  2168. case 'object': return new DB_QueryTool_Result_Object($result);
  2169. case 'array':
  2170. default: return new DB_QueryTool_Result($result);
  2171. }
  2172. }
  2173. // }}}
  2174. // {{{ _makeIndexed()
  2175. /**
  2176. *
  2177. * @version 2002/07/11
  2178. * @author Wolfram Kriesing <wk@visionp.de>
  2179. * @param mixed $data
  2180. * @return mixed $data or array $indexedData
  2181. * @access public
  2182. */
  2183. function &_makeIndexed(&$data)
  2184. {
  2185. // we can only return an indexed result if the result has a number of columns
  2186. if (is_array($data) && sizeof($data) && $key = $this->getIndex()) {
  2187. // build the string to evaluate which might be made up out of multiple indexes of a result-row
  2188. $evalString = '$val[\''.implode('\'].\',\'.$val[\'',explode(',',$key)).'\']'; //"
  2189. $indexedData = array();
  2190. //FIXXME actually we also need to check ONCE if $val is an array, so to say if $data is 2-dimensional
  2191. foreach ($data as $val) {
  2192. eval("\$keyValue = $evalString;"); // get the actual real (string-)key (string if multiple cols are used as index)
  2193. $indexedData[$keyValue] = $val;
  2194. }
  2195. unset($data);
  2196. return $indexedData;
  2197. }
  2198. return $data;
  2199. }
  2200. // }}}
  2201. // {{{ setIndex()
  2202. /**
  2203. * format the result to be indexed by $key
  2204. * NOTE: be careful, when using this you should be aware, that if you
  2205. * use an index which's value appears multiple times you may loose data
  2206. * since a key cant exist multiple times!!
  2207. * the result for a result to be indexed by a key(=columnName)
  2208. * (i.e. 'relationtoMe') which's values are 'brother' and 'sister'
  2209. * or alike normally returns this:
  2210. * $res['brother'] = array('name'=>'xxx')
  2211. * $res['sister'] = array('name'=>'xxx')
  2212. * but if the column 'relationtoMe' contains multiple entries for 'brother'
  2213. * then the returned dataset will only contain one brother, since the
  2214. * value from the column 'relationtoMe' is used
  2215. * and which 'brother' you get depends on a lot of things, like the sortorder,
  2216. * how the db saves the data, and whatever else
  2217. *
  2218. * you can also set indexes which depend on 2 columns, simply pass the parameters like
  2219. * 'table1.id,table2.id' it will be used as a string for indexing the result
  2220. * and the index will be built using the 2 values given, so a possible
  2221. * index might be '1,2' or '2108,29389' this way you can access data which
  2222. * have 2 primary keys. Be sure to remember that the index is a string!
  2223. *
  2224. * @version 2002/07/11
  2225. * @author Wolfram Kriesing <wk@visionp.de>
  2226. * @param Charcoal_String $key
  2227. * @access public
  2228. */
  2229. function setIndex($key=null)
  2230. {
  2231. if ($this->getJoin()) { // is join set?
  2232. // replace TABLENAME.COLUMNNAME by _TABLENAME_COLUMNNAME
  2233. // since this is only the result-keys can be used for indexing :-)
  2234. $regExp = '/('.implode('|', $this->getJoin('tables')).')\.([^\s]+)/';
  2235. $key = preg_replace($regExp, '_$1_$2', $key);
  2236. // remove the table name if it is in front of '<$this->table>.columnname'
  2237. // since the key doesnt contain it neither
  2238. if ($meta = $this->metadata()) {
  2239. foreach ($meta as $aCol => $x) {
  2240. $key = preg_replace('/'.$this->table.'\.'.$aCol.'/', $aCol, $key);
  2241. }
  2242. }
  2243. }
  2244. $this->_index = $key;
  2245. }
  2246. // }}}
  2247. // {{{ getIndex()
  2248. /**
  2249. *
  2250. * @version 2002/07/11
  2251. * @author Wolfram Kriesing <wk@visionp.de>
  2252. * @return string index
  2253. * @access public
  2254. */
  2255. function getIndex()
  2256. {
  2257. return $this->_index;
  2258. }
  2259. // }}}
  2260. // {{{ useResult()
  2261. /**
  2262. * Choose the type of the returned result
  2263. *
  2264. * @version 2004/04/28
  2265. * @access public
  2266. * @param Charcoal_String $type ['array' | 'object' | 'none']
  2267. * For BC reasons, $type=true is equal to 'array',
  2268. * $type=false is equal to 'none'
  2269. * @access public
  2270. */
  2271. function useResult($type='array')
  2272. {
  2273. if ($type === true) {
  2274. $type = 'array';
  2275. } elseif ($type === false) {
  2276. $type = 'none';
  2277. }
  2278. switch (strtolower($type)) {
  2279. case 'array':
  2280. $this->_resultType = 'array';
  2281. require_once 'DB/QueryTool/Result.php';
  2282. break;
  2283. case 'object':
  2284. $this->_resultType = 'object';
  2285. require_once 'DB/QueryTool/Result/Object.php';
  2286. break;
  2287. default:
  2288. $this->_resultType = 'none';
  2289. }
  2290. }
  2291. // }}}
  2292. // {{{ setErrorCallback()
  2293. /**
  2294. * set both callbacks
  2295. * @param string
  2296. * @access public
  2297. */
  2298. function setErrorCallback($param='')
  2299. {
  2300. $this->setErrorLogCallback($param);
  2301. $this->setErrorSetCallback($param);
  2302. }
  2303. // }}}
  2304. // {{{ setErrorLogCallback()
  2305. /**
  2306. * @param string
  2307. */
  2308. function setErrorLogCallback($param='')
  2309. {
  2310. $errorLogCallback = &PEAR::getStaticProperty('DB_QueryTool','_errorLogCallback');
  2311. $errorLogCallback = $param;
  2312. }
  2313. // }}}
  2314. // {{{ setErrorSetCallback()
  2315. /**
  2316. * @param string
  2317. */
  2318. function setErrorSetCallback($param='')
  2319. {
  2320. $errorSetCallback = &PEAR::getStaticProperty('DB_QueryTool','_errorSetCallback');
  2321. $errorSetCallback = $param;
  2322. }
  2323. // }}}
  2324. // {{{ _errorLog()
  2325. /**
  2326. * sets error log and adds additional info
  2327. *
  2328. * @version 2002/04/16
  2329. * @author Wolfram Kriesing <wk@visionp.de>
  2330. * @param string the actual message, first word should always be the method name,
  2331. * to build the message like this: className::methodname
  2332. * @param integer the line number
  2333. * @access private
  2334. */
  2335. function _errorLog($msg, $line='unknown')
  2336. {
  2337. $this->_errorHandler('log', $msg, $line);
  2338. /*
  2339. if ($this->getOption('verbose') == true) {
  2340. $this->_errorLog(get_class($this)."::$msg ($line)");
  2341. return;
  2342. }
  2343. if ($this->_errorLogCallback) {
  2344. call_user_func($this->_errorLogCallback, $msg);
  2345. }
  2346. */
  2347. }
  2348. // }}}
  2349. // {{{ _errorSet()
  2350. /**
  2351. * @param string
  2352. * @param string
  2353. */
  2354. function _errorSet($msg, $line='unknown')
  2355. {
  2356. $this->_errorHandler('set', $msg, $line);
  2357. }
  2358. // }}}
  2359. // {{{ _errorHandler()
  2360. /**
  2361. * @param
  2362. * @param string
  2363. * @param string
  2364. */
  2365. function _errorHandler($logOrSet, $msg, $line='unknown')
  2366. {
  2367. /* what did i do this for?
  2368. if ($this->getOption('verbose') == true) {
  2369. $this->_errorHandler($logOrSet, get_class($this)."::$msg ($line)");
  2370. return;
  2371. }
  2372. */
  2373. $msg = get_class($this)."::$msg ($line)";
  2374. $logOrSet = ucfirst($logOrSet);
  2375. $callback = &PEAR::getStaticProperty('DB_QueryTool','_error'.$logOrSet.'Callback');
  2376. //var_dump($callback);
  2377. //if ($callback)
  2378. // call_user_func($callback, $msg);
  2379. // else
  2380. // ?????
  2381. }
  2382. // }}}
  2383. }
  2384. ?>