-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdbo_sqlite3.php
608 lines (578 loc) · 18.7 KB
/
dbo_sqlite3.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
<?php
/* SVN FILE: $Id$ */
/**
* SQLite3 layer for DBO
*
* Long description for file
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework <http://www.cakephp.org/>
* Copyright 2005-2008, Cake Software Foundation, Inc.
* 1785 E. Sahara Avenue, Suite 490-204
* Las Vegas, Nevada 89104
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc.
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
* @package cake
* @subpackage cake.cake.libs.model.datasources.dbo
* @since CakePHP(tm) v 0.9.0
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
/**
* DBO implementation for the SQLite3 DBMS.
*
* Long description for class
*
* @package cake
* @subpackage cake.cake.libs.model.datasources.dbo
*/
class DboSqlite3 extends DboSource {
/**
* Enter description here...
*
* @var string
*/
var $description = "SQLite3 DBO Driver";
/**
* Opening quote for quoted identifiers
*
* @var string
*/
var $startQuote = '';
/**
* Closing quote for quoted identifiers
*
* @var string
*/
var $endQuote = '';
/**
* Base configuration settings for SQLite3 driver
*
* @var array
*/
var $_baseConfig = array(
'persistent' => false,
'database' => null,
'connect' => 'sqlite' //sqlite3 in pdo_sqlite is sqlite. sqlite2 is sqlite2
);
/**
* SQLite3 column definition
*
* @var array
*/
var $columns = array(
'primary_key' => array('name' => 'integer primary key autoincrement'),
'string' => array('name' => 'varchar', 'limit' => '255'),
'text' => array('name' => 'text'),
'integer' => array('name' => 'integer', 'limit' => null, 'formatter' => 'intval'),
'float' => array('name' => 'float', 'formatter' => 'floatval'),
'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
'binary' => array('name' => 'blob'),
'boolean' => array('name' => 'boolean')
);
var $last_error = NULL;
var $pdo_statement = NULL;
var $rows = NULL;
var $row_count = NULL;
/**
* Connects to the database using config['database'] as a filename.
*
* @param array $config Configuration array for connecting
* @return mixed
*/
function connect() {
//echo "runs connect\n";
$this->last_error = null;
$config = $this->config;
//$this->connection = $config['connect']($config['database']);
try {
$this->connection = new PDO($config['connect'].':'.$config['database']);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$this->connected = is_resource($this->connection);
$this->connected = is_object($this->connection);
}
catch(PDOException $e) {
$this->last_error = array('Error connecting to database.',$e->getMessage());
}
return $this->connected;
}
/**
* Disconnects from database.
*
* @return boolean True if the database could be disconnected, else false
*/
function disconnect() {
$this->connection = NULL;
$this->connected = false;
return $this->connected;
}
/**
* Executes given SQL statement.
*
* @param string $sql SQL statement
* @return resource Result resource identifier
*/
function _execute($sql) {
for ($i = 0; $i < 2; $i++) {
try {
$this->last_error = NULL;
$this->pdo_statement = $this->connection->query($sql);
if (is_object($this->pdo_statement)) {
$this->rows = $this->pdo_statement->fetchAll(PDO::FETCH_NUM);
$this->row_count = count($this->rows);
return $this->pdo_statement;
}
}
catch(PDOException $e) {
// Schema change; re-run query
if ($e->errorInfo[1] === 17) continue;
$this->last_error = $e->getMessage();
}
}
return false;
}
/**
* Returns an array of tables in the database. If there are no tables, an error is raised and the application exits.
*
* @return array Array of tablenames in the database
*/
function listSources() {
$db = $this->config['database'];
$this->config['database'] = basename($this->config['database']);
$cache = parent::listSources();
if ($cache != null) {
return $cache;
}
$result = $this->fetchAll("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;", false);
if (!$result || empty($result)) {
return array();
} else {
$tables = array();
foreach ($result as $table) {
$tables[] = $table[0]['name'];
}
parent::listSources($tables);
$this->config['database'] = $db;
return $tables;
}
$this->config['database'] = $db;
return array();
}
/**
* Returns an array of the fields in given table name.
*
* @param string $tableName Name of database table to inspect
* @return array Fields in table. Keys are name and type
*/
function describe(&$model) {
$cache = parent::describe($model);
if ($cache != null) {
return $cache;
}
$fields = array();
$result = $this->fetchAll('PRAGMA table_info(' . $model->tablePrefix . $model->table . ')');
foreach ($result as $column) {
$fields[$column[0]['name']] = array(
'type' => $this->column($column[0]['type']),
'null' => !$column[0]['notnull'],
'default' => $column[0]['dflt_value'],
'length' => $this->length($column[0]['type'])
);
if($column[0]['pk'] == 1) {
$fields[$column[0]['name']] = array(
'type' => $fields[$column[0]['name']]['type'],
'null' => false,
'default' => $column[0]['dflt_value'],
'key' => $this->index['PRI'],
'length' => 11
);
}
}
$this->__cacheDescription($model->tablePrefix . $model->table, $fields);
return $fields;
}
/**
* Returns a quoted and escaped string of $data for use in an SQL statement.
*
* @param string $data String to be prepared for use in an SQL statement
* @return string Quoted and escaped
*/
function value ($data, $column = null, $safe = false) {
$parent = parent::value($data, $column, $safe);
if ($parent != null) {
return $parent;
}
if ($data === null) {
return 'NULL';
}
if ($data === '') {
return "''";
}
switch ($column) {
case 'boolean':
$data = $this->boolean((bool)$data);
break;
default:
$data = $this->connection->quote($data);
return $data;
break;
}
return "'" . $data . "'";
}
/**
* Generates and executes an SQL UPDATE statement for given model, fields, and values.
*
* @param Model $model
* @param array $fields
* @param array $values
* @param mixed $conditions
* @return array
*/
function update(&$model, $fields = array(), $values = null, $conditions = null) {
if (empty($values) && !empty($fields)) {
foreach ($fields as $field => $value) {
if (strpos($field, $model->alias . '.') !== false) {
unset($fields[$field]);
$field = str_replace($model->alias . '.', "", $field);
$field = str_replace($model->alias . '.', "", $field);
$fields[$field] = $value;
}
}
}
return parent::update($model, $fields, $values, $conditions);
}
/**
* Begin a transaction
*
* @param Model $model
* @return boolean True on success, false on fail
* (i.e. if the database/model does not support transactions).
*/
function begin (&$model) {
if (!$this->_transactionStarted) {
if ($this->connection->beginTransaction()) {
$this->_transactionStarted = true;
return true;
}
}
return false;
}
/**
* Commit a transaction
*
* @param Model $model
* @return boolean True on success, false on fail
* (i.e. if the database/model does not support transactions,
* or a transaction has not started).
*/
function commit (&$model) {
if ($this->_transactionStarted) {
$this->_transactionStarted = false;
return $this->connection->commit();
}
return false;
}
/**
* Rollback a transaction
*
* @param Model $model
* @return boolean True on success, false on fail
* (i.e. if the database/model does not support transactions,
* or a transaction has not started).
*/
function rollback (&$model) {
if ($this->_transactionStarted) {
$this->_transactionStarted = false;
return $this->connection->rollBack();
}
return false;
}
/**
* Deletes all the records in a table and resets the count of the auto-incrementing
* primary key, where applicable.
*
* @param mixed $table A string or model class representing the table to be truncated
* @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
* @access public
*/
function truncate($table) {
return $this->execute('DELETE From ' . $this->fullTableName($table));
}
/**
* Returns a formatted error message from previous database operation.
*
* @return string Error message
*/
function lastError() {
return $this->last_error;
}
/**
* Returns number of affected rows in previous database operation. If no previous operation exists, this returns false.
*
* @return integer Number of affected rows
*/
function lastAffected() {
if ($this->_result) {
return $this->pdo_statement->rowCount();
}
return false;
}
/**
* Returns number of rows in previous resultset. If no previous resultset exists,
* this returns false.
*
* @return integer Number of rows in resultset
*/
function lastNumRows() {
if ($this->pdo_statement) {
// pdo_statement->rowCount() doesn't work for this case
return $this->row_count;
}
return false;
}
/**
* Returns the ID generated from the previous INSERT operation.
*
* @return int
*/
function lastInsertId() {
return $this->connection->lastInsertId();
}
/**
* Converts database-layer column types to basic types
*
* @param string $real Real database-layer column type (i.e. "varchar(255)")
* @return string Abstract column type (i.e. "string")
*/
function column($real) {
if (is_array($real)) {
$col = $real['name'];
if (isset($real['limit'])) {
$col .= '('.$real['limit'].')';
}
return $col;
}
$col = strtolower(str_replace(')', '', $real));
$limit = null;
@list($col, $limit) = explode('(', $col);
if (in_array($col, array('text', 'integer', 'float', 'boolean', 'timestamp', 'date', 'datetime', 'time'))) {
return $col;
}
if (strpos($col, 'char') !== false) {
return 'string';
}
if (in_array($col, array('blob', 'clob'))) {
return 'binary';
}
if (strpos($col, 'numeric') !== false) {
return 'float';
}
return 'text';
}
/**
* Enter description here...
*
* @param unknown_type $results
*/
function resultSet(&$results) {
$this->results =& $results;
$this->map = array();
$num_fields = $results->columnCount();
$index = $j = 0;
//PDO::getColumnMeta is experimental and does not work with sqlite3,
//so try to figure it out based on the querystring
$querystring = $results->queryString;
if (strpos($querystring,"SELECT") === 0)
{
$last = strpos($querystring,"FROM");
if ($last !== false)
{
$selectpart = substr($querystring,7,$last-8);
$selects = explode(",",$selectpart);
}
}
elseif (strpos($querystring,"PRAGMA table_info") === 0)
{
$selects = array("cid","name","type","notnull","dflt_value","pk");
}
while ($j < $num_fields) {
if (stripos($selects[$j], ' AS ')) {
$matches = array_map('trim', spliti(' AS ', $selects[$j]));
$columnName = $matches[1];
} else {
$columnName = trim(str_replace('"', '', $selects[$j]));
}
if (strpos($columnName, '.')) {
$parts = explode('.', $columnName);
$this->map[$index++] = array(trim($parts[0]), trim($parts[1]));
} else {
$this->map[$index++] = array(0, $columnName);
}
$j++;
}
}
/**
* Fetches the next row from the current result set
*
* @return unknown
*/
function fetchResult() {
if (count($this->rows)) {
$row = array_shift($this->rows);
$resultRow = array();
$i = 0;
foreach ($row as $index => $field) {
if (isset($this->map[$index]) and $this->map[$index] != "") {
list($table, $column) = $this->map[$index];
$resultRow[$table][$column] = $row[$index];
} else {
$resultRow[0][str_replace('"', '', $index)] = $row[$index];
}
$i++;
}
return $resultRow;
} else {
return false;
}
}
/**
* Returns a limit statement in the correct format for the particular database.
*
* @param integer $limit Limit of results returned
* @param integer $offset Offset from which to start results
* @return string SQL limit/offset statement
*/
function limit ($limit, $offset = null) {
if ($limit) {
$rt = '';
if (!strpos(strtolower($limit), 'limit') || strpos(strtolower($limit), 'limit') === 0) {
$rt = ' LIMIT';
}
$rt .= ' ' . $limit;
if ($offset) {
$rt .= ' OFFSET ' . $offset;
}
return $rt;
}
return null;
}
/**
* Generate a database-native column schema string
*
* @param array $column An array structured like the following: array('name'=>'value', 'type'=>'value'[, options]),
* where options can be 'default', 'length', or 'key'.
* @return string
*/
function buildColumn($column) {
$name = $type = null;
$column = array_merge(array('null' => true), $column);
extract($column);
if (empty($name) || empty($type)) {
trigger_error('Column name or type not defined in schema', E_USER_WARNING);
return null;
}
if (!isset($this->columns[$type])) {
trigger_error("Column type {$type} does not exist", E_USER_WARNING);
return null;
}
$real = $this->columns[$type];
if (isset($column['key']) && $column['key'] == 'primary') {
$out = $this->name($name) . ' ' . $this->columns['primary_key']['name'];
} else {
$out = $this->name($name) . ' ' . $real['name'];
if (isset($real['limit']) || isset($real['length']) || isset($column['limit']) || isset($column['length'])) {
if (isset($column['length'])) {
$length = $column['length'];
} elseif (isset($column['limit'])) {
$length = $column['limit'];
} elseif (isset($real['length'])) {
$length = $real['length'];
} else {
$length = $real['limit'];
}
$out .= '(' . $length . ')';
}
if (isset($column['key']) && $column['key'] == 'primary') {
$out .= ' NOT NULL';
} elseif (isset($column['default']) && isset($column['null']) && $column['null'] == false) {
$out .= ' DEFAULT ' . $this->value($column['default'], $type) . ' NOT NULL';
} elseif (isset($column['default'])) {
$out .= ' DEFAULT ' . $this->value($column['default'], $type);
} elseif (isset($column['null']) && $column['null'] == true) {
$out .= ' DEFAULT NULL';
} elseif (isset($column['null']) && $column['null'] == false) {
$out .= ' NOT NULL';
}
}
return $out;
}
/**
* Removes redundant primary key indexes, as they are handled in the column def of the key.
*
* @param array $indexes
* @param string $table
* @return string
*/
function buildIndex($indexes, $table = null) {
$join = array();
foreach ($indexes as $name => $value) {
if ($name == 'PRIMARY') {
continue;
} else {
$out = 'CREATE ';
if (!empty($value['unique'])) {
$out .= 'UNIQUE ';
}
if (is_array($value['column'])) {
$value['column'] = join(', ', array_map(array(&$this, 'name'), $value['column']));
} else {
$value['column'] = $this->name($value['column']);
}
$out .= "INDEX {$name} ON {$table}({$value['column']});";
}
$join[] = $out;
}
return $join;
}
/**
* Overrides DboSource::renderStatement to handle schema generation with SQLite3-style indexes
*
* @param string $type
* @param array $data
* @return string
*/
function renderStatement($type, $data) {
switch (strtolower($type)) {
case 'schema':
extract($data);
foreach (array('columns', 'indexes') as $var) {
if (is_array(${$var})) {
${$var} = "\t" . join(",\n\t", array_filter(${$var}));
}
}
return "CREATE TABLE {$table} (\n{$columns});\n{$indexes}";
break;
default:
return parent::renderStatement($type, $data);
break;
}
}
/**
* PDO deals in objects, not resources, so overload accordingly.
*/
function hasResult() {
return is_object($this->_result);
}
}
?>