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
|
<?php defined('SYSPATH') OR die('No direct access allowed.');
/*
* Class: Database_PdoSqlite_Driver
* Provides specific database items for Sqlite.
*
* Connection string should be, eg: "pdosqlite://path/to/database.db"
*
* Version 1.0 alpha
* author - Doutu, updated by gregmac
* copyright - (c) BSD
* license - <no>
*/
class Database_Pdosqlite_Driver extends Database_Driver {
// Database connection link
protected $link;
protected $db_config;
/*
* Constructor: __construct
* Sets up the config for the class.
*
* Parameters:
* config - database configuration
*
*/
public function __construct($config)
{
$this->db_config = $config;
Kohana::log('debug', 'PDO:Sqlite Database Driver Initialized');
}
public function connect()
{
// Import the connect variables
extract($this->db_config['connection']);
try
{
$this->link = new PDO('sqlite:'.$socket.$database, $user, $pass,
array(PDO::ATTR_PERSISTENT => $this->db_config['persistent']));
$this->link->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
//$this->link->query('PRAGMA count_changes=1;');
if ($charset = $this->db_config['character_set'])
{
$this->set_charset($charset);
}
}
catch (PDOException $e)
{
throw new Kohana_Database_Exception('database.error', $e->getMessage());
}
// Clear password after successful connect
$this->db_config['connection']['pass'] = NULL;
return $this->link;
}
public function query($sql)
{
try
{
$sth = $this->link->prepare($sql);
}
catch (PDOException $e)
{
throw new Kohana_Database_Exception('database.error', $e->getMessage());
}
return new Pdosqlite_Result($sth, $this->link, $this->db_config['object'], $sql);
}
public function set_charset($charset)
{
$this->link->query('PRAGMA encoding = '.$this->escape_str($charset));
}
public function escape_table($table)
{
if ( ! $this->db_config['escape'])
return $table;
return '`'.str_replace('.', '`.`', $table).'`';
}
public function escape_column($column)
{
if ( ! $this->db_config['escape'])
return $column;
if ($column == '*')
return $column;
// This matches any functions we support to SELECT.
if ( preg_match('/(avg|count|sum|max|min)\(\s*(.*)\s*\)(\s*as\s*(.+)?)?/i', $column, $matches))
{
if ( count($matches) == 3)
{
return $matches[1].'('.$this->escape_column($matches[2]).')';
}
else if ( count($matches) == 5)
{
return $matches[1].'('.$this->escape_column($matches[2]).') AS '.$this->escape_column($matches[2]);
}
}
// This matches any modifiers we support to SELECT.
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))
{
if (stripos($column, ' AS ') !== FALSE)
{
// Force 'AS' to uppercase
$column = str_ireplace(' AS ', ' AS ', $column);
// Runs escape_column on both sides of an AS statement
$column = array_map(array($this, __FUNCTION__), explode(' AS ', $column));
// Re-create the AS statement
return implode(' AS ', $column);
}
return preg_replace('/[^.*]+/', '`$0`', $column);
}
$parts = explode(' ', $column);
$column = '';
for ($i = 0, $c = count($parts); $i < $c; $i++)
{
// The column is always last
if ($i == ($c - 1))
{
$column .= preg_replace('/[^.*]+/', '`$0`', $parts[$i]);
}
else // otherwise, it's a modifier
{
$column .= $parts[$i].' ';
}
}
return $column;
}
public function limit($limit, $offset = 0)
{
return 'LIMIT '.$offset.', '.$limit;
}
public function compile_select($database)
{
$sql = ($database['distinct'] == TRUE) ? 'SELECT DISTINCT ' : 'SELECT ';
$sql .= (count($database['select']) > 0) ? implode(', ', $database['select']) : '*';
if (count($database['from']) > 0)
{
$sql .= "\nFROM ";
$sql .= implode(', ', $database['from']);
}
if (count($database['join']) > 0)
{
foreach($database['join'] AS $join)
{
$sql .= "\n".$join['type'].'JOIN '.implode(', ', $join['tables']).' ON '.$join['conditions'];
}
}
if (count($database['where']) > 0)
{
$sql .= "\nWHERE ";
}
$sql .= implode("\n", $database['where']);
if (count($database['groupby']) > 0)
{
$sql .= "\nGROUP BY ";
$sql .= implode(', ', $database['groupby']);
}
if (count($database['having']) > 0)
{
$sql .= "\nHAVING ";
$sql .= implode("\n", $database['having']);
}
if (count($database['orderby']) > 0)
{
$sql .= "\nORDER BY ";
$sql .= implode(', ', $database['orderby']);
}
if (is_numeric($database['limit']))
{
$sql .= "\n";
$sql .= $this->limit($database['limit'], $database['offset']);
}
return $sql;
}
public function escape_str($str)
{
if ( ! $this->db_config['escape'])
return $str;
if (function_exists('sqlite_escape_string'))
{
$res = sqlite_escape_string($str);
}
else
{
$res = str_replace("'", "''", $str);
}
return $res;
}
public function list_tables()
{
$sql = "SELECT `name` FROM `sqlite_master` WHERE `type`='table' ORDER BY `name`;";
try
{
$result = $this->query($sql)->result(FALSE, PDO::FETCH_ASSOC);
$tables = array();
foreach ($result as $row)
{
$tables[] = current($row);
}
}
catch (PDOException $e)
{
throw new Kohana_Database_Exception('database.error', $e->getMessage());
}
return $tables;
}
public function show_error()
{
$err = $this->link->errorInfo();
return isset($err[2]) ? $err[2] : 'Unknown error!';
}
public function list_fields($table, $query = FALSE)
{
static $tables;
if (is_object($query))
{
if (empty($tables[$table]))
{
$tables[$table] = array();
foreach ($query->result() as $row)
{
$tables[$table][] = $row->name;
}
}
return $tables[$table];
}
else
{
$result = $this->link->query( 'PRAGMA table_info('.$this->escape_table($table).')' );
foreach ($result as $row)
{
$tables[$table][$row['name']] = $this->sql_type($row['type']);
}
return $tables[$table];
}
}
public function field_data($table)
{
Kohana::log('error', 'This method is under developing');
}
/**
* Version number query string
*
* @access public
* @return string
*/
function version()
{
return $this->link->getAttribute(constant("PDO::ATTR_SERVER_VERSION"));
}
} // End Database_PdoSqlite_Driver Class
/*
* PDO-sqlite Result
*/
class Pdosqlite_Result extends Database_Result {
// Data fetching types
protected $fetch_type = PDO::FETCH_OBJ;
protected $return_type = PDO::FETCH_ASSOC;
/**
* Sets up the result variables.
*
* @param resource query result
* @param resource database link
* @param boolean return objects or arrays
* @param string SQL query that was run
*/
public function __construct($result, $link, $object = TRUE, $sql)
{
if (is_object($result) OR $result = $link->prepare($sql))
{
// run the query. Return true if success, false otherwise
if( ! $result->execute())
{
// Throw Kohana Exception with error message. See PDOStatement errorInfo() method
$arr_infos = $result->errorInfo();
throw new Kohana_Database_Exception('database.error', $arr_infos[2]);
}
if (preg_match('/^SELECT|PRAGMA|EXPLAIN/i', $sql))
{
$this->result = $result;
$this->current_row = 0;
$this->total_rows = $this->sqlite_row_count();
$this->fetch_type = ($object === TRUE) ? PDO::FETCH_OBJ : PDO::FETCH_ASSOC;
}
elseif (preg_match('/^DELETE|INSERT|UPDATE/i', $sql))
{
$this->insert_id = $link->lastInsertId();
$this->total_rows = $result->rowCount();
}
}
else
{
// SQL error
throw new Kohana_Database_Exception('database.error', $link->errorInfo().' - '.$sql);
}
// Set result type
$this->result($object);
// Store the SQL
$this->sql = $sql;
}
private function sqlite_row_count()
{
$count = 0;
while ($this->result->fetch())
{
$count++;
}
// The query must be re-fetched now.
$this->result->execute();
return $count;
}
/*
* Destructor: __destruct
* Magic __destruct function, frees the result.
*/
public function __destruct()
{
if (is_object($this->result))
{
$this->result->closeCursor();
$this->result = NULL;
}
}
public function result($object = TRUE, $type = PDO::FETCH_BOTH)
{
$this->fetch_type = (bool) $object ? PDO::FETCH_OBJ : PDO::FETCH_BOTH;
if ($this->fetch_type == PDO::FETCH_OBJ)
{
$this->return_type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass';
}
else
{
$this->return_type = $type;
}
return $this;
}
public function as_array($object = NULL, $type = PDO::FETCH_ASSOC)
{
return $this->result_array($object, $type);
}
public function result_array($object = NULL, $type = PDO::FETCH_ASSOC)
{
$rows = array();
if (is_string($object))
{
$fetch = $object;
}
elseif (is_bool($object))
{
if ($object === TRUE)
{
$fetch = PDO::FETCH_OBJ;
// NOTE - The class set by $type must be defined before fetching the result,
// autoloading is disabled to save a lot of stupid overhead.
$type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass';
}
else
{
$fetch = PDO::FETCH_OBJ;
}
}
else
{
// Use the default config values
$fetch = $this->fetch_type;
if ($fetch == PDO::FETCH_OBJ)
{
$type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass';
}
}
try
{
while ($row = $this->result->fetch($fetch))
{
$rows[] = $row;
}
}
catch(PDOException $e)
{
throw new Kohana_Database_Exception('database.error', $e->getMessage());
return FALSE;
}
return $rows;
}
public function list_fields()
{
$field_names = array();
for ($i = 0, $max = $this->result->columnCount(); $i < $max; $i++)
{
$info = $this->result->getColumnMeta($i);
$field_names[] = $info['name'];
}
return $field_names;
}
public function seek($offset)
{
// To request a scrollable cursor for your PDOStatement object, you must
// set the PDO::ATTR_CURSOR attribute to PDO::CURSOR_SCROLL when you
// prepare the statement.
Kohana::log('error', get_class($this).' does not support scrollable cursors, '.__FUNCTION__.' call ignored');
return FALSE;
}
public function offsetGet($offset)
{
try
{
return $this->result->fetch($this->fetch_type, PDO::FETCH_ORI_ABS, $offset);
}
catch(PDOException $e)
{
throw new Kohana_Database_Exception('database.error', $e->getMessage());
}
}
public function rewind()
{
// Same problem that seek() has, see above.
return $this->seek(0);
}
} // End PdoSqlite_Result Class
|