Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
12345 anikendra 1
<?php
2
/**
3
 * SQLite layer for DBO
4
 *
5
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
6
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
7
 *
8
 * Licensed under The MIT License
9
 * For full copyright and license information, please see the LICENSE.txt
10
 * Redistributions of files must retain the above copyright notice.
11
 *
12
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
13
 * @link          http://cakephp.org CakePHP(tm) Project
14
 * @package       Cake.Model.Datasource.Database
15
 * @since         CakePHP(tm) v 0.9.0
16
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
17
 */
18
 
19
App::uses('DboSource', 'Model/Datasource');
20
App::uses('String', 'Utility');
21
 
22
/**
23
 * DBO implementation for the SQLite3 DBMS.
24
 *
25
 * A DboSource adapter for SQLite 3 using PDO
26
 *
27
 * @package       Cake.Model.Datasource.Database
28
 */
29
class Sqlite extends DboSource {
30
 
31
/**
32
 * Datasource Description
33
 *
34
 * @var string
35
 */
36
	public $description = "SQLite DBO Driver";
37
 
38
/**
39
 * Quote Start
40
 *
41
 * @var string
42
 */
43
	public $startQuote = '"';
44
 
45
/**
46
 * Quote End
47
 *
48
 * @var string
49
 */
50
	public $endQuote = '"';
51
 
52
/**
53
 * Base configuration settings for SQLite3 driver
54
 *
55
 * @var array
56
 */
57
	protected $_baseConfig = array(
58
		'persistent' => false,
59
		'database' => null,
60
		'flags' => array()
61
	);
62
 
63
/**
64
 * SQLite3 column definition
65
 *
66
 * @var array
67
 */
68
	public $columns = array(
69
		'primary_key' => array('name' => 'integer primary key autoincrement'),
70
		'string' => array('name' => 'varchar', 'limit' => '255'),
71
		'text' => array('name' => 'text'),
72
		'integer' => array('name' => 'integer', 'limit' => null, 'formatter' => 'intval'),
73
		'biginteger' => array('name' => 'bigint', 'limit' => 20),
74
		'float' => array('name' => 'float', 'formatter' => 'floatval'),
75
		'decimal' => array('name' => 'decimal', 'formatter' => 'floatval'),
76
		'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
77
		'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
78
		'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
79
		'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
80
		'binary' => array('name' => 'blob'),
81
		'boolean' => array('name' => 'boolean')
82
	);
83
 
84
/**
85
 * List of engine specific additional field parameters used on table creating
86
 *
87
 * @var array
88
 */
89
	public $fieldParameters = array(
90
		'collate' => array(
91
			'value' => 'COLLATE',
92
			'quote' => false,
93
			'join' => ' ',
94
			'column' => 'Collate',
95
			'position' => 'afterDefault',
96
			'options' => array(
97
				'BINARY', 'NOCASE', 'RTRIM'
98
			)
99
		),
100
	);
101
 
102
/**
103
 * Connects to the database using config['database'] as a filename.
104
 *
105
 * @return bool
106
 * @throws MissingConnectionException
107
 */
108
	public function connect() {
109
		$config = $this->config;
110
		$flags = $config['flags'] + array(
111
			PDO::ATTR_PERSISTENT => $config['persistent'],
112
			PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
113
		);
114
		try {
115
			$this->_connection = new PDO('sqlite:' . $config['database'], null, null, $flags);
116
			$this->connected = true;
117
		} catch(PDOException $e) {
118
			throw new MissingConnectionException(array(
119
				'class' => get_class($this),
120
				'message' => $e->getMessage()
121
			));
122
		}
123
		return $this->connected;
124
	}
125
 
126
/**
127
 * Check whether the SQLite extension is installed/loaded
128
 *
129
 * @return bool
130
 */
131
	public function enabled() {
132
		return in_array('sqlite', PDO::getAvailableDrivers());
133
	}
134
 
135
/**
136
 * Returns an array of tables in the database. If there are no tables, an error is raised and the application exits.
137
 *
138
 * @param mixed $data Unused.
139
 * @return array Array of table names in the database
140
 */
141
	public function listSources($data = null) {
142
		$cache = parent::listSources();
143
		if ($cache) {
144
			return $cache;
145
		}
146
 
147
		$result = $this->fetchAll("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;", false);
148
 
149
		if (!$result || empty($result)) {
150
			return array();
151
		}
152
 
153
		$tables = array();
154
		foreach ($result as $table) {
155
			$tables[] = $table[0]['name'];
156
		}
157
		parent::listSources($tables);
158
		return $tables;
159
	}
160
 
161
/**
162
 * Returns an array of the fields in given table name.
163
 *
164
 * @param Model|string $model Either the model or table name you want described.
165
 * @return array Fields in table. Keys are name and type
166
 */
167
	public function describe($model) {
168
		$table = $this->fullTableName($model, false, false);
169
		$cache = parent::describe($table);
170
		if ($cache) {
171
			return $cache;
172
		}
173
		$fields = array();
174
		$result = $this->_execute(
175
			'PRAGMA table_info(' . $this->value($table, 'string') . ')'
176
		);
177
 
178
		foreach ($result as $column) {
179
			$column = (array)$column;
180
			$default = ($column['dflt_value'] === 'NULL') ? null : trim($column['dflt_value'], "'");
181
 
182
			$fields[$column['name']] = array(
183
				'type' => $this->column($column['type']),
184
				'null' => !$column['notnull'],
185
				'default' => $default,
186
				'length' => $this->length($column['type'])
187
			);
188
			if ($column['pk'] == 1) {
189
				$fields[$column['name']]['key'] = $this->index['PRI'];
190
				$fields[$column['name']]['null'] = false;
191
				if (empty($fields[$column['name']]['length'])) {
192
					$fields[$column['name']]['length'] = 11;
193
				}
194
			}
195
		}
196
 
197
		$result->closeCursor();
198
		$this->_cacheDescription($table, $fields);
199
		return $fields;
200
	}
201
 
202
/**
203
 * Generates and executes an SQL UPDATE statement for given model, fields, and values.
204
 *
205
 * @param Model $model The model instance to update.
206
 * @param array $fields The fields to update.
207
 * @param array $values The values to set columns to.
208
 * @param mixed $conditions array of conditions to use.
209
 * @return array
210
 */
211
	public function update(Model $model, $fields = array(), $values = null, $conditions = null) {
212
		if (empty($values) && !empty($fields)) {
213
			foreach ($fields as $field => $value) {
214
				if (strpos($field, $model->alias . '.') !== false) {
215
					unset($fields[$field]);
216
					$field = str_replace($model->alias . '.', "", $field);
217
					$field = str_replace($model->alias . '.', "", $field);
218
					$fields[$field] = $value;
219
				}
220
			}
221
		}
222
		return parent::update($model, $fields, $values, $conditions);
223
	}
224
 
225
/**
226
 * Deletes all the records in a table and resets the count of the auto-incrementing
227
 * primary key, where applicable.
228
 *
229
 * @param string|Model $table A string or model class representing the table to be truncated
230
 * @return bool SQL TRUNCATE TABLE statement, false if not applicable.
231
 */
232
	public function truncate($table) {
233
		if (in_array('sqlite_sequence', $this->listSources())) {
234
			$this->_execute('DELETE FROM sqlite_sequence where name=' . $this->startQuote . $this->fullTableName($table, false, false) . $this->endQuote);
235
		}
236
		return $this->execute('DELETE FROM ' . $this->fullTableName($table));
237
	}
238
 
239
/**
240
 * Converts database-layer column types to basic types
241
 *
242
 * @param string $real Real database-layer column type (i.e. "varchar(255)")
243
 * @return string Abstract column type (i.e. "string")
244
 */
245
	public function column($real) {
246
		if (is_array($real)) {
247
			$col = $real['name'];
248
			if (isset($real['limit'])) {
249
				$col .= '(' . $real['limit'] . ')';
250
			}
251
			return $col;
252
		}
253
 
254
		$col = strtolower(str_replace(')', '', $real));
255
		if (strpos($col, '(') !== false) {
256
			list($col) = explode('(', $col);
257
		}
258
 
259
		$standard = array(
260
			'text',
261
			'integer',
262
			'float',
263
			'boolean',
264
			'timestamp',
265
			'date',
266
			'datetime',
267
			'time'
268
		);
269
		if (in_array($col, $standard)) {
270
			return $col;
271
		}
272
		if ($col === 'bigint') {
273
			return 'biginteger';
274
		}
275
		if (strpos($col, 'char') !== false) {
276
			return 'string';
277
		}
278
		if (in_array($col, array('blob', 'clob'))) {
279
			return 'binary';
280
		}
281
		if (strpos($col, 'numeric') !== false || strpos($col, 'decimal') !== false) {
282
			return 'decimal';
283
		}
284
		return 'text';
285
	}
286
 
287
/**
288
 * Generate ResultSet
289
 *
290
 * @param mixed $results The results to modify.
291
 * @return void
292
 */
293
	public function resultSet($results) {
294
		$this->results = $results;
295
		$this->map = array();
296
		$numFields = $results->columnCount();
297
		$index = 0;
298
		$j = 0;
299
 
300
		// PDO::getColumnMeta is experimental and does not work with sqlite3,
301
		// so try to figure it out based on the querystring
302
		$querystring = $results->queryString;
303
		if (stripos($querystring, 'SELECT') === 0) {
304
			$last = strripos($querystring, 'FROM');
305
			if ($last !== false) {
306
				$selectpart = substr($querystring, 7, $last - 8);
307
				$selects = String::tokenize($selectpart, ',', '(', ')');
308
			}
309
		} elseif (strpos($querystring, 'PRAGMA table_info') === 0) {
310
			$selects = array('cid', 'name', 'type', 'notnull', 'dflt_value', 'pk');
311
		} elseif (strpos($querystring, 'PRAGMA index_list') === 0) {
312
			$selects = array('seq', 'name', 'unique');
313
		} elseif (strpos($querystring, 'PRAGMA index_info') === 0) {
314
			$selects = array('seqno', 'cid', 'name');
315
		}
316
		while ($j < $numFields) {
317
			if (!isset($selects[$j])) {
318
				$j++;
319
				continue;
320
			}
321
			if (preg_match('/\bAS\s+(.*)/i', $selects[$j], $matches)) {
322
				$columnName = trim($matches[1], '"');
323
			} else {
324
				$columnName = trim(str_replace('"', '', $selects[$j]));
325
			}
326
 
327
			if (strpos($selects[$j], 'DISTINCT') === 0) {
328
				$columnName = str_ireplace('DISTINCT', '', $columnName);
329
			}
330
 
331
			$metaType = false;
332
			try {
333
				$metaData = (array)$results->getColumnMeta($j);
334
				if (!empty($metaData['sqlite:decl_type'])) {
335
					$metaType = trim($metaData['sqlite:decl_type']);
336
				}
337
			} catch (Exception $e) {
338
			}
339
 
340
			if (strpos($columnName, '.')) {
341
				$parts = explode('.', $columnName);
342
				$this->map[$index++] = array(trim($parts[0]), trim($parts[1]), $metaType);
343
			} else {
344
				$this->map[$index++] = array(0, $columnName, $metaType);
345
			}
346
			$j++;
347
		}
348
	}
349
 
350
/**
351
 * Fetches the next row from the current result set
352
 *
353
 * @return mixed array with results fetched and mapped to column names or false if there is no results left to fetch
354
 */
355
	public function fetchResult() {
356
		if ($row = $this->_result->fetch(PDO::FETCH_NUM)) {
357
			$resultRow = array();
358
			foreach ($this->map as $col => $meta) {
359
				list($table, $column, $type) = $meta;
360
				$resultRow[$table][$column] = $row[$col];
361
				if ($type === 'boolean' && $row[$col] !== null) {
362
					$resultRow[$table][$column] = $this->boolean($resultRow[$table][$column]);
363
				}
364
			}
365
			return $resultRow;
366
		}
367
		$this->_result->closeCursor();
368
		return false;
369
	}
370
 
371
/**
372
 * Returns a limit statement in the correct format for the particular database.
373
 *
374
 * @param int $limit Limit of results returned
375
 * @param int $offset Offset from which to start results
376
 * @return string SQL limit/offset statement
377
 */
378
	public function limit($limit, $offset = null) {
379
		if ($limit) {
380
			$rt = sprintf(' LIMIT %u', $limit);
381
			if ($offset) {
382
				$rt .= sprintf(' OFFSET %u', $offset);
383
			}
384
			return $rt;
385
		}
386
		return null;
387
	}
388
 
389
/**
390
 * Generate a database-native column schema string
391
 *
392
 * @param array $column An array structured like the following: array('name'=>'value', 'type'=>'value'[, options]),
393
 *    where options can be 'default', 'length', or 'key'.
394
 * @return string
395
 */
396
	public function buildColumn($column) {
397
		$name = $type = null;
398
		$column += array('null' => true);
399
		extract($column);
400
 
401
		if (empty($name) || empty($type)) {
402
			trigger_error(__d('cake_dev', 'Column name or type not defined in schema'), E_USER_WARNING);
403
			return null;
404
		}
405
 
406
		if (!isset($this->columns[$type])) {
407
			trigger_error(__d('cake_dev', 'Column type %s does not exist', $type), E_USER_WARNING);
408
			return null;
409
		}
410
 
411
		$isPrimary = (isset($column['key']) && $column['key'] === 'primary');
412
		if ($isPrimary && $type === 'integer') {
413
			return $this->name($name) . ' ' . $this->columns['primary_key']['name'];
414
		}
415
		$out = parent::buildColumn($column);
416
		if ($isPrimary && $type === 'biginteger') {
417
			$replacement = 'PRIMARY KEY';
418
			if ($column['null'] === false) {
419
				$replacement = 'NOT NULL ' . $replacement;
420
			}
421
			return str_replace($this->columns['primary_key']['name'], $replacement, $out);
422
		}
423
		return $out;
424
	}
425
 
426
/**
427
 * Sets the database encoding
428
 *
429
 * @param string $enc Database encoding
430
 * @return bool
431
 */
432
	public function setEncoding($enc) {
433
		if (!in_array($enc, array("UTF-8", "UTF-16", "UTF-16le", "UTF-16be"))) {
434
			return false;
435
		}
436
		return $this->_execute("PRAGMA encoding = \"{$enc}\"") !== false;
437
	}
438
 
439
/**
440
 * Gets the database encoding
441
 *
442
 * @return string The database encoding
443
 */
444
	public function getEncoding() {
445
		return $this->fetchRow('PRAGMA encoding');
446
	}
447
 
448
/**
449
 * Removes redundant primary key indexes, as they are handled in the column def of the key.
450
 *
451
 * @param array $indexes The indexes to build.
452
 * @param string $table The table name.
453
 * @return string The completed index.
454
 */
455
	public function buildIndex($indexes, $table = null) {
456
		$join = array();
457
 
458
		$table = str_replace('"', '', $table);
459
		list($dbname, $table) = explode('.', $table);
460
		$dbname = $this->name($dbname);
461
 
462
		foreach ($indexes as $name => $value) {
463
 
464
			if ($name === 'PRIMARY') {
465
				continue;
466
			}
467
			$out = 'CREATE ';
468
 
469
			if (!empty($value['unique'])) {
470
				$out .= 'UNIQUE ';
471
			}
472
			if (is_array($value['column'])) {
473
				$value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
474
			} else {
475
				$value['column'] = $this->name($value['column']);
476
			}
477
			$t = trim($table, '"');
478
			$indexname = $this->name($t . '_' . $name);
479
			$table = $this->name($table);
480
			$out .= "INDEX {$dbname}.{$indexname} ON {$table}({$value['column']});";
481
			$join[] = $out;
482
		}
483
		return $join;
484
	}
485
 
486
/**
487
 * Overrides DboSource::index to handle SQLite index introspection
488
 * Returns an array of the indexes in given table name.
489
 *
490
 * @param string $model Name of model to inspect
491
 * @return array Fields in table. Keys are column and unique
492
 */
493
	public function index($model) {
494
		$index = array();
495
		$table = $this->fullTableName($model, false, false);
496
		if ($table) {
497
			$indexes = $this->query('PRAGMA index_list(' . $table . ')');
498
 
499
			if (is_bool($indexes)) {
500
				return array();
501
			}
502
			foreach ($indexes as $info) {
503
				$key = array_pop($info);
504
				$keyInfo = $this->query('PRAGMA index_info("' . $key['name'] . '")');
505
				foreach ($keyInfo as $keyCol) {
506
					if (!isset($index[$key['name']])) {
507
						$col = array();
508
						if (preg_match('/autoindex/', $key['name'])) {
509
							$key['name'] = 'PRIMARY';
510
						}
511
						$index[$key['name']]['column'] = $keyCol[0]['name'];
512
						$index[$key['name']]['unique'] = intval($key['unique'] == 1);
513
					} else {
514
						if (!is_array($index[$key['name']]['column'])) {
515
							$col[] = $index[$key['name']]['column'];
516
						}
517
						$col[] = $keyCol[0]['name'];
518
						$index[$key['name']]['column'] = $col;
519
					}
520
				}
521
			}
522
		}
523
		return $index;
524
	}
525
 
526
/**
527
 * Overrides DboSource::renderStatement to handle schema generation with SQLite-style indexes
528
 *
529
 * @param string $type The type of statement being rendered.
530
 * @param array $data The data to convert to SQL.
531
 * @return string
532
 */
533
	public function renderStatement($type, $data) {
534
		switch (strtolower($type)) {
535
			case 'schema':
536
				extract($data);
537
				if (is_array($columns)) {
538
					$columns = "\t" . implode(",\n\t", array_filter($columns));
539
				}
540
				if (is_array($indexes)) {
541
					$indexes = "\t" . implode("\n\t", array_filter($indexes));
542
				}
543
				return "CREATE TABLE {$table} (\n{$columns});\n{$indexes}";
544
			default:
545
				return parent::renderStatement($type, $data);
546
		}
547
	}
548
 
549
/**
550
 * PDO deals in objects, not resources, so overload accordingly.
551
 *
552
 * @return bool
553
 */
554
	public function hasResult() {
555
		return is_object($this->_result);
556
	}
557
 
558
/**
559
 * Generate a "drop table" statement for the given table
560
 *
561
 * @param type $table Name of the table to drop
562
 * @return string Drop table SQL statement
563
 */
564
	protected function _dropTable($table) {
565
		return 'DROP TABLE IF EXISTS ' . $this->fullTableName($table) . ";";
566
	}
567
 
568
/**
569
 * Gets the schema name
570
 *
571
 * @return string The schema name
572
 */
573
	public function getSchemaName() {
574
		return "main"; // Sqlite Datasource does not support multidb
575
	}
576
 
577
/**
578
 * Check if the server support nested transactions
579
 *
580
 * @return bool
581
 */
582
	public function nestedTransactionSupported() {
583
		return $this->useNestedTransactions && version_compare($this->getVersion(), '3.6.8', '>=');
584
	}
585
 
586
}