PageRenderTime 40ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/kohana_core/system/libraries/drivers/Database/Pdosqlite.php

https://gitlab.com/vince.omega/mcb-nov-build
PHP | 486 lines | 421 code | 36 blank | 29 comment | 27 complexity | 861a4ece0d179f0f9924443438d91af6 MD5 | raw file
  1. <?php defined('SYSPATH') OR die('No direct access allowed.');
  2. /*
  3. * Class: Database_PdoSqlite_Driver
  4. * Provides specific database items for Sqlite.
  5. *
  6. * Connection string should be, eg: "pdosqlite://path/to/database.db"
  7. *
  8. * Version 1.0 alpha
  9. * author - Doutu, updated by gregmac
  10. * copyright - (c) BSD
  11. * license - <no>
  12. */
  13. class Database_Pdosqlite_Driver extends Database_Driver {
  14. // Database connection link
  15. protected $link;
  16. protected $db_config;
  17. /*
  18. * Constructor: __construct
  19. * Sets up the config for the class.
  20. *
  21. * Parameters:
  22. * config - database configuration
  23. *
  24. */
  25. public function __construct($config)
  26. {
  27. $this->db_config = $config;
  28. Kohana::log('debug', 'PDO:Sqlite Database Driver Initialized');
  29. }
  30. public function connect()
  31. {
  32. // Import the connect variables
  33. extract($this->db_config['connection']);
  34. try
  35. {
  36. $this->link = new PDO('sqlite:'.$socket.$database, $user, $pass,
  37. array(PDO::ATTR_PERSISTENT => $this->db_config['persistent']));
  38. $this->link->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
  39. //$this->link->query('PRAGMA count_changes=1;');
  40. if ($charset = $this->db_config['character_set'])
  41. {
  42. $this->set_charset($charset);
  43. }
  44. }
  45. catch (PDOException $e)
  46. {
  47. throw new Kohana_Database_Exception('database.error', $e->getMessage());
  48. }
  49. // Clear password after successful connect
  50. $this->db_config['connection']['pass'] = NULL;
  51. return $this->link;
  52. }
  53. public function query($sql)
  54. {
  55. try
  56. {
  57. $sth = $this->link->prepare($sql);
  58. }
  59. catch (PDOException $e)
  60. {
  61. throw new Kohana_Database_Exception('database.error', $e->getMessage());
  62. }
  63. return new Pdosqlite_Result($sth, $this->link, $this->db_config['object'], $sql);
  64. }
  65. public function set_charset($charset)
  66. {
  67. $this->link->query('PRAGMA encoding = '.$this->escape_str($charset));
  68. }
  69. public function escape_table($table)
  70. {
  71. if ( ! $this->db_config['escape'])
  72. return $table;
  73. return '`'.str_replace('.', '`.`', $table).'`';
  74. }
  75. public function escape_column($column)
  76. {
  77. if ( ! $this->db_config['escape'])
  78. return $column;
  79. if ($column == '*')
  80. return $column;
  81. // This matches any functions we support to SELECT.
  82. if ( preg_match('/(avg|count|sum|max|min)\(\s*(.*)\s*\)(\s*as\s*(.+)?)?/i', $column, $matches))
  83. {
  84. if ( count($matches) == 3)
  85. {
  86. return $matches[1].'('.$this->escape_column($matches[2]).')';
  87. }
  88. else if ( count($matches) == 5)
  89. {
  90. return $matches[1].'('.$this->escape_column($matches[2]).') AS '.$this->escape_column($matches[2]);
  91. }
  92. }
  93. // This matches any modifiers we support to SELECT.
  94. if ( ! preg_match('/\b(?:rand|all|distinct(?:row)?|high_priority|sql_(?:small_result|b(?:ig_result|uffer_result)|no_cache|ca(?:che|lc_found_rows)))\s/i', $column))
  95. {
  96. if (stripos($column, ' AS ') !== FALSE)
  97. {
  98. // Force 'AS' to uppercase
  99. $column = str_ireplace(' AS ', ' AS ', $column);
  100. // Runs escape_column on both sides of an AS statement
  101. $column = array_map(array($this, __FUNCTION__), explode(' AS ', $column));
  102. // Re-create the AS statement
  103. return implode(' AS ', $column);
  104. }
  105. return preg_replace('/[^.*]+/', '`$0`', $column);
  106. }
  107. $parts = explode(' ', $column);
  108. $column = '';
  109. for ($i = 0, $c = count($parts); $i < $c; $i++)
  110. {
  111. // The column is always last
  112. if ($i == ($c - 1))
  113. {
  114. $column .= preg_replace('/[^.*]+/', '`$0`', $parts[$i]);
  115. }
  116. else // otherwise, it's a modifier
  117. {
  118. $column .= $parts[$i].' ';
  119. }
  120. }
  121. return $column;
  122. }
  123. public function limit($limit, $offset = 0)
  124. {
  125. return 'LIMIT '.$offset.', '.$limit;
  126. }
  127. public function compile_select($database)
  128. {
  129. $sql = ($database['distinct'] == TRUE) ? 'SELECT DISTINCT ' : 'SELECT ';
  130. $sql .= (count($database['select']) > 0) ? implode(', ', $database['select']) : '*';
  131. if (count($database['from']) > 0)
  132. {
  133. $sql .= "\nFROM ";
  134. $sql .= implode(', ', $database['from']);
  135. }
  136. if (count($database['join']) > 0)
  137. {
  138. foreach($database['join'] AS $join)
  139. {
  140. $sql .= "\n".$join['type'].'JOIN '.implode(', ', $join['tables']).' ON '.$join['conditions'];
  141. }
  142. }
  143. if (count($database['where']) > 0)
  144. {
  145. $sql .= "\nWHERE ";
  146. }
  147. $sql .= implode("\n", $database['where']);
  148. if (count($database['groupby']) > 0)
  149. {
  150. $sql .= "\nGROUP BY ";
  151. $sql .= implode(', ', $database['groupby']);
  152. }
  153. if (count($database['having']) > 0)
  154. {
  155. $sql .= "\nHAVING ";
  156. $sql .= implode("\n", $database['having']);
  157. }
  158. if (count($database['orderby']) > 0)
  159. {
  160. $sql .= "\nORDER BY ";
  161. $sql .= implode(', ', $database['orderby']);
  162. }
  163. if (is_numeric($database['limit']))
  164. {
  165. $sql .= "\n";
  166. $sql .= $this->limit($database['limit'], $database['offset']);
  167. }
  168. return $sql;
  169. }
  170. public function escape_str($str)
  171. {
  172. if ( ! $this->db_config['escape'])
  173. return $str;
  174. if (function_exists('sqlite_escape_string'))
  175. {
  176. $res = sqlite_escape_string($str);
  177. }
  178. else
  179. {
  180. $res = str_replace("'", "''", $str);
  181. }
  182. return $res;
  183. }
  184. public function list_tables()
  185. {
  186. $sql = "SELECT `name` FROM `sqlite_master` WHERE `type`='table' ORDER BY `name`;";
  187. try
  188. {
  189. $result = $this->query($sql)->result(FALSE, PDO::FETCH_ASSOC);
  190. $tables = array();
  191. foreach ($result as $row)
  192. {
  193. $tables[] = current($row);
  194. }
  195. }
  196. catch (PDOException $e)
  197. {
  198. throw new Kohana_Database_Exception('database.error', $e->getMessage());
  199. }
  200. return $tables;
  201. }
  202. public function show_error()
  203. {
  204. $err = $this->link->errorInfo();
  205. return isset($err[2]) ? $err[2] : 'Unknown error!';
  206. }
  207. public function list_fields($table, $query = FALSE)
  208. {
  209. static $tables;
  210. if (is_object($query))
  211. {
  212. if (empty($tables[$table]))
  213. {
  214. $tables[$table] = array();
  215. foreach ($query->result() as $row)
  216. {
  217. $tables[$table][] = $row->name;
  218. }
  219. }
  220. return $tables[$table];
  221. }
  222. else
  223. {
  224. $result = $this->link->query( 'PRAGMA table_info('.$this->escape_table($table).')' );
  225. foreach ($result as $row)
  226. {
  227. $tables[$table][$row['name']] = $this->sql_type($row['type']);
  228. }
  229. return $tables[$table];
  230. }
  231. }
  232. public function field_data($table)
  233. {
  234. Kohana::log('error', 'This method is under developing');
  235. }
  236. /**
  237. * Version number query string
  238. *
  239. * @access public
  240. * @return string
  241. */
  242. function version()
  243. {
  244. return $this->link->getAttribute(constant("PDO::ATTR_SERVER_VERSION"));
  245. }
  246. } // End Database_PdoSqlite_Driver Class
  247. /*
  248. * PDO-sqlite Result
  249. */
  250. class Pdosqlite_Result extends Database_Result {
  251. // Data fetching types
  252. protected $fetch_type = PDO::FETCH_OBJ;
  253. protected $return_type = PDO::FETCH_ASSOC;
  254. /**
  255. * Sets up the result variables.
  256. *
  257. * @param resource query result
  258. * @param resource database link
  259. * @param boolean return objects or arrays
  260. * @param string SQL query that was run
  261. */
  262. public function __construct($result, $link, $object = TRUE, $sql)
  263. {
  264. if (is_object($result) OR $result = $link->prepare($sql))
  265. {
  266. // run the query. Return true if success, false otherwise
  267. if( ! $result->execute())
  268. {
  269. // Throw Kohana Exception with error message. See PDOStatement errorInfo() method
  270. $arr_infos = $result->errorInfo();
  271. throw new Kohana_Database_Exception('database.error', $arr_infos[2]);
  272. }
  273. if (preg_match('/^SELECT|PRAGMA|EXPLAIN/i', $sql))
  274. {
  275. $this->result = $result;
  276. $this->current_row = 0;
  277. $this->total_rows = $this->sqlite_row_count();
  278. $this->fetch_type = ($object === TRUE) ? PDO::FETCH_OBJ : PDO::FETCH_ASSOC;
  279. }
  280. elseif (preg_match('/^DELETE|INSERT|UPDATE/i', $sql))
  281. {
  282. $this->insert_id = $link->lastInsertId();
  283. $this->total_rows = $result->rowCount();
  284. }
  285. }
  286. else
  287. {
  288. // SQL error
  289. throw new Kohana_Database_Exception('database.error', $link->errorInfo().' - '.$sql);
  290. }
  291. // Set result type
  292. $this->result($object);
  293. // Store the SQL
  294. $this->sql = $sql;
  295. }
  296. private function sqlite_row_count()
  297. {
  298. $count = 0;
  299. while ($this->result->fetch())
  300. {
  301. $count++;
  302. }
  303. // The query must be re-fetched now.
  304. $this->result->execute();
  305. return $count;
  306. }
  307. /*
  308. * Destructor: __destruct
  309. * Magic __destruct function, frees the result.
  310. */
  311. public function __destruct()
  312. {
  313. if (is_object($this->result))
  314. {
  315. $this->result->closeCursor();
  316. $this->result = NULL;
  317. }
  318. }
  319. public function result($object = TRUE, $type = PDO::FETCH_BOTH)
  320. {
  321. $this->fetch_type = (bool) $object ? PDO::FETCH_OBJ : PDO::FETCH_BOTH;
  322. if ($this->fetch_type == PDO::FETCH_OBJ)
  323. {
  324. $this->return_type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass';
  325. }
  326. else
  327. {
  328. $this->return_type = $type;
  329. }
  330. return $this;
  331. }
  332. public function as_array($object = NULL, $type = PDO::FETCH_ASSOC)
  333. {
  334. return $this->result_array($object, $type);
  335. }
  336. public function result_array($object = NULL, $type = PDO::FETCH_ASSOC)
  337. {
  338. $rows = array();
  339. if (is_string($object))
  340. {
  341. $fetch = $object;
  342. }
  343. elseif (is_bool($object))
  344. {
  345. if ($object === TRUE)
  346. {
  347. $fetch = PDO::FETCH_OBJ;
  348. // NOTE - The class set by $type must be defined before fetching the result,
  349. // autoloading is disabled to save a lot of stupid overhead.
  350. $type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass';
  351. }
  352. else
  353. {
  354. $fetch = PDO::FETCH_OBJ;
  355. }
  356. }
  357. else
  358. {
  359. // Use the default config values
  360. $fetch = $this->fetch_type;
  361. if ($fetch == PDO::FETCH_OBJ)
  362. {
  363. $type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass';
  364. }
  365. }
  366. try
  367. {
  368. while ($row = $this->result->fetch($fetch))
  369. {
  370. $rows[] = $row;
  371. }
  372. }
  373. catch(PDOException $e)
  374. {
  375. throw new Kohana_Database_Exception('database.error', $e->getMessage());
  376. return FALSE;
  377. }
  378. return $rows;
  379. }
  380. public function list_fields()
  381. {
  382. $field_names = array();
  383. for ($i = 0, $max = $this->result->columnCount(); $i < $max; $i++)
  384. {
  385. $info = $this->result->getColumnMeta($i);
  386. $field_names[] = $info['name'];
  387. }
  388. return $field_names;
  389. }
  390. public function seek($offset)
  391. {
  392. // To request a scrollable cursor for your PDOStatement object, you must
  393. // set the PDO::ATTR_CURSOR attribute to PDO::CURSOR_SCROLL when you
  394. // prepare the statement.
  395. Kohana::log('error', get_class($this).' does not support scrollable cursors, '.__FUNCTION__.' call ignored');
  396. return FALSE;
  397. }
  398. public function offsetGet($offset)
  399. {
  400. try
  401. {
  402. return $this->result->fetch($this->fetch_type, PDO::FETCH_ORI_ABS, $offset);
  403. }
  404. catch(PDOException $e)
  405. {
  406. throw new Kohana_Database_Exception('database.error', $e->getMessage());
  407. }
  408. }
  409. public function rewind()
  410. {
  411. // Same problem that seek() has, see above.
  412. return $this->seek(0);
  413. }
  414. } // End PdoSqlite_Result Class