[005c96]: adminer / drivers / sqlite.inc.php Maximize Restore History

Download this file

sqlite.inc.php    690 lines (594 with data), 20.2 kB

  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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
<?php
$drivers["sqlite"] = "SQLite 3";
$drivers["sqlite2"] = "SQLite 2";
if (isset($_GET["sqlite"]) || isset($_GET["sqlite2"])) {
$possible_drivers = array((isset($_GET["sqlite"]) ? "SQLite3" : "SQLite"), "PDO_SQLite");
define("DRIVER", (isset($_GET["sqlite"]) ? "sqlite" : "sqlite2"));
if (class_exists(isset($_GET["sqlite"]) ? "SQLite3" : "SQLiteDatabase")) {
if (isset($_GET["sqlite"])) {
class Min_SQLite {
var $extension = "SQLite3", $server_info, $affected_rows, $errno, $error, $_link;
function Min_SQLite($filename) {
$this->_link = new SQLite3($filename);
$version = $this->_link->version();
$this->server_info = $version["versionString"];
}
function query($query) {
$result = @$this->_link->query($query);
$this->error = "";
if (!$result) {
$this->errno = $this->_link->lastErrorCode();
$this->error = $this->_link->lastErrorMsg();
return false;
} elseif ($result->numColumns()) {
return new Min_Result($result);
}
$this->affected_rows = $this->_link->changes();
return true;
}
function quote($string) {
return (is_utf8($string)
? "'" . $this->_link->escapeString($string) . "'"
: "x'" . reset(unpack('H*', $string)) . "'"
);
}
function store_result() {
return $this->_result;
}
function result($query, $field = 0) {
$result = $this->query($query);
if (!is_object($result)) {
return false;
}
$row = $result->_result->fetchArray();
return $row[$field];
}
}
class Min_Result {
var $_result, $_offset = 0, $num_rows;
function Min_Result($result) {
$this->_result = $result;
}
function fetch_assoc() {
return $this->_result->fetchArray(SQLITE3_ASSOC);
}
function fetch_row() {
return $this->_result->fetchArray(SQLITE3_NUM);
}
function fetch_field() {
$column = $this->_offset++;
$type = $this->_result->columnType($column);
return (object) array(
"name" => $this->_result->columnName($column),
"type" => $type,
"charsetnr" => ($type == SQLITE3_BLOB ? 63 : 0), // 63 - binary
);
}
function __desctruct() {
return $this->_result->finalize();
}
}
} else {
class Min_SQLite {
var $extension = "SQLite", $server_info, $affected_rows, $error, $_link;
function Min_SQLite($filename) {
$this->server_info = sqlite_libversion();
$this->_link = new SQLiteDatabase($filename);
}
function query($query, $unbuffered = false) {
$method = ($unbuffered ? "unbufferedQuery" : "query");
$result = @$this->_link->$method($query, SQLITE_BOTH, $error);
$this->error = "";
if (!$result) {
$this->error = $error;
return false;
} elseif ($result === true) {
$this->affected_rows = $this->changes();
return true;
}
return new Min_Result($result);
}
function quote($string) {
return "'" . sqlite_escape_string($string) . "'";
}
function store_result() {
return $this->_result;
}
function result($query, $field = 0) {
$result = $this->query($query);
if (!is_object($result)) {
return false;
}
$row = $result->_result->fetch();
return $row[$field];
}
}
class Min_Result {
var $_result, $_offset = 0, $num_rows;
function Min_Result($result) {
$this->_result = $result;
if (method_exists($result, 'numRows')) { // not available in unbuffered query
$this->num_rows = $result->numRows();
}
}
function fetch_assoc() {
$row = $this->_result->fetch(SQLITE_ASSOC);
if (!$row) {
return false;
}
$return = array();
foreach ($row as $key => $val) {
$return[($key[0] == '"' ? idf_unescape($key) : $key)] = $val;
}
return $return;
}
function fetch_row() {
return $this->_result->fetch(SQLITE_NUM);
}
function fetch_field() {
$name = $this->_result->fieldName($this->_offset++);
$pattern = '(\\[.*]|"(?:[^"]|"")*"|(.+))';
if (preg_match("~^($pattern\\.)?$pattern\$~", $name, $match)) {
$table = ($match[3] != "" ? $match[3] : idf_unescape($match[2]));
$name = ($match[5] != "" ? $match[5] : idf_unescape($match[4]));
}
return (object) array(
"name" => $name,
"orgname" => $name,
"orgtable" => $table,
);
}
}
}
} elseif (extension_loaded("pdo_sqlite")) {
class Min_SQLite extends Min_PDO {
var $extension = "PDO_SQLite";
function Min_SQLite($filename) {
$this->dsn(DRIVER . ":$filename", "", "");
}
}
}
if (class_exists("Min_SQLite")) {
class Min_DB extends Min_SQLite {
function Min_DB() {
$this->Min_SQLite(":memory:");
}
function select_db($filename) {
if (is_readable($filename) && $this->query("ATTACH " . $this->quote(ereg("(^[/\\\\]|:)", $filename) ? $filename : dirname($_SERVER["SCRIPT_FILENAME"]) . "/$filename") . " AS a")) { // is_readable - SQLite 3
$this->Min_SQLite($filename);
return true;
}
return false;
}
function multi_query($query) {
return $this->_result = $this->query($query);
}
function next_result() {
return false;
}
}
}
function idf_escape($idf) {
return '"' . str_replace('"', '""', $idf) . '"';
}
function table($idf) {
return idf_escape($idf);
}
function connect() {
return new Min_DB;
}
function get_databases() {
return array();
}
function limit($query, $where, $limit, $offset = 0, $separator = " ") {
return " $query$where" . ($limit !== null ? $separator . "LIMIT $limit" . ($offset ? " OFFSET $offset" : "") : "");
}
function limit1($query, $where) {
global $connection;
return ($connection->result("SELECT sqlite_compileoption_used('ENABLE_UPDATE_DELETE_LIMIT')") ? limit($query, $where, 1) : " $query$where");
}
function db_collation($db, $collations) {
global $connection;
return $connection->result("PRAGMA encoding"); // there is no database list so $db == DB
}
function engines() {
return array();
}
function logged_user() {
return get_current_user(); // should return effective user
}
function tables_list() {
return get_key_vals("SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') ORDER BY (name = 'sqlite_sequence'), name", 1);
}
function count_tables($databases) {
return array();
}
function table_status($name = "") {
global $connection;
$return = array();
foreach (get_rows("SELECT name AS Name, type AS Engine FROM sqlite_master WHERE type IN ('table', 'view')" . ($name != "" ? " AND name = " . q($name) : "")) as $row) {
$row["Oid"] = 1;
$row["Auto_increment"] = "";
$row["Rows"] = $connection->result("SELECT COUNT(*) FROM " . idf_escape($row["Name"]));
$return[$row["Name"]] = $row;
}
foreach (get_rows("SELECT * FROM sqlite_sequence", null, "") as $row) {
$return[$row["name"]]["Auto_increment"] = $row["seq"];
}
return ($name != "" ? $return[$name] : $return);
}
function is_view($table_status) {
return $table_status["Engine"] == "view";
}
function fk_support($table_status) {
global $connection;
return !$connection->result("SELECT sqlite_compileoption_used('OMIT_FOREIGN_KEY')");
}
function fields($table) {
$return = array();
foreach (get_rows("PRAGMA table_info(" . table($table) . ")") as $row) {
$type = strtolower($row["type"]);
$default = $row["dflt_value"];
$return[$row["name"]] = array(
"field" => $row["name"],
"type" => (eregi("int", $type) ? "integer" : (eregi("char|clob|text", $type) ? "text" : (eregi("blob", $type) ? "blob" : (eregi("real|floa|doub", $type) ? "real" : "numeric")))),
"full_type" => $type,
"default" => (ereg("'(.*)'", $default, $match) ? str_replace("''", "'", $match[1]) : ($default == "NULL" ? null : $default)),
"null" => !$row["notnull"],
"auto_increment" => eregi('^integer$', $type) && $row["pk"], //! possible false positive
"privileges" => array("select" => 1, "insert" => 1, "update" => 1),
"primary" => $row["pk"],
);
}
return $return;
}
function indexes($table, $connection2 = null) {
$return = array();
$primary = array();
foreach (fields($table) as $field) {
if ($field["primary"]) {
$primary[] = $field["field"];
}
}
if ($primary) {
$return[""] = array("type" => "PRIMARY", "columns" => $primary, "lengths" => array());
}
foreach (get_rows("PRAGMA index_list(" . table($table) . ")") as $row) {
if (!ereg("^sqlite_", $row["name"])) {
$return[$row["name"]]["type"] = ($row["unique"] ? "UNIQUE" : "INDEX");
$return[$row["name"]]["lengths"] = array();
foreach (get_rows("PRAGMA index_info(" . idf_escape($row["name"]) . ")") as $row1) {
$return[$row["name"]]["columns"][] = $row1["name"];
}
}
}
return $return;
}
function foreign_keys($table) {
$return = array();
foreach (get_rows("PRAGMA foreign_key_list(" . table($table) . ")") as $row) {
$foreign_key = &$return[$row["id"]];
//! idf_unescape in SQLite2
if (!$foreign_key) {
$foreign_key = $row;
}
$foreign_key["source"][] = $row["from"];
$foreign_key["target"][] = $row["to"];
}
return $return;
}
function view($name) {
global $connection;
return array("select" => preg_replace('~^(?:[^`"[]+|`[^`]*`|"[^"]*")* AS\\s+~iU', '', $connection->result("SELECT sql FROM sqlite_master WHERE name = " . q($name)))); //! identifiers may be inside []
}
function collations() {
return (isset($_GET["create"]) ? get_vals("PRAGMA collation_list", 1) : array());
}
function information_schema($db) {
return false;
}
function error() {
global $connection;
return h($connection->error);
}
function exact_value($val) {
return q($val);
}
function check_sqlite_name($name) {
// avoid creating PHP files on unsecured servers
global $connection;
$extensions = "db|sdb|sqlite";
if (!preg_match("~^[^\\0]*\\.($extensions)\$~", $name)) {
$connection->error = lang('Please use one of the extensions %s.', str_replace("|", ", ", $extensions));
return false;
}
return true;
}
function create_database($db, $collation) {
global $connection;
if (file_exists($db)) {
$connection->error = lang('File exists.');
return false;
}
if (!check_sqlite_name($db)) {
return false;
}
$link = new Min_SQLite($db); //! exception handler
$link->query('PRAGMA encoding = "UTF-8"');
$link->query('CREATE TABLE adminer (i)'); // otherwise creates empty file
$link->query('DROP TABLE adminer');
return true;
}
function drop_databases($databases) {
global $connection;
$connection->Min_SQLite(":memory:"); // to unlock file, doesn't work in PDO on Windows
foreach ($databases as $db) {
if (!@unlink($db)) {
$connection->error = lang('File exists.');
return false;
}
}
return true;
}
function rename_database($name, $collation) {
global $connection;
if (!check_sqlite_name($name)) {
return false;
}
$connection->Min_SQLite(":memory:");
$connection->error = lang('File exists.');
return @rename(DB, $name);
}
function auto_increment() {
return " PRIMARY KEY" . (DRIVER == "sqlite" ? " AUTOINCREMENT" : "");
}
function alter_table($table, $name, $fields, $foreign, $comment, $engine, $collation, $auto_increment, $partitioning) {
$use_all_fields = ($table == "" || $foreign);
foreach ($fields as $field) {
if ($field[0] != "" || !$field[1] || $field[2]) {
$use_all_fields = true;
break;
}
}
$alter = array();
$originals = array();
$primary_key = false;
foreach ($fields as $field) {
if ($field[1]) {
if ($field[1][6]) {
$primary_key = true;
}
$alter[] = ($use_all_fields ? " " : "ADD ") . implode($field[1]);
if ($field[0] != "") {
$originals[$field[0]] = $field[1][0];
}
}
}
if ($use_all_fields) {
if ($table != "") {
queries("BEGIN");
foreach (foreign_keys($table) as $foreign_key) {
$columns = array();
foreach ($foreign_key["source"] as $column) {
if (!$originals[$column]) {
continue 2;
}
$columns[] = $originals[$column];
}
$foreign[] = " FOREIGN KEY (" . implode(", ", $columns) . ") REFERENCES "
. table($foreign_key["table"])
. " (" . implode(", ", array_map('idf_escape', $foreign_key["target"]))
. ") ON DELETE $foreign_key[on_delete] ON UPDATE $foreign_key[on_update]"
;
}
$indexes = array();
foreach (indexes($table) as $key_name => $index) {
$columns = array();
foreach ($index["columns"] as $column) {
if (!$originals[$column]) {
continue 2;
}
$columns[] = $originals[$column];
}
$columns = "(" . implode(", ", $columns) . ")";
if ($index["type"] != "PRIMARY") {
$indexes[] = array($index["type"], $key_name, $columns);
} elseif (!$primary_key) {
$foreign[] = " PRIMARY KEY $columns";
}
}
}
$alter = array_merge($alter, $foreign);
if (!queries("CREATE TABLE " . table($table != "" ? "adminer_$name" : $name) . " (\n" . implode(",\n", $alter) . "\n)")) {
// implicit ROLLBACK to not overwrite $connection->error
return false;
}
if ($table != "") {
if ($originals && !queries("INSERT INTO " . table("adminer_$name") . " (" . implode(", ", $originals) . ") SELECT " . implode(", ", array_map('idf_escape', array_keys($originals))) . " FROM " . table($table))) {
return false;
}
$triggers = array();
foreach (triggers($table) as $trigger_name => $timing_event) {
$trigger = trigger($trigger_name);
$triggers[] = "CREATE TRIGGER " . idf_escape($trigger_name) . " " . implode(" ", $timing_event) . " ON " . table($name) . "\n$trigger[Statement]";
}
if (!queries("DROP TABLE " . table($table))) { // drop before creating indexes and triggers to allow using old names
return false;
}
queries("ALTER TABLE " . table("adminer_$name") . " RENAME TO " . table($name));
if (!alter_indexes($name, $indexes)) {
return false;
}
foreach ($triggers as $trigger) {
if (!queries($trigger)) {
return false;
}
}
queries("COMMIT");
}
} else {
foreach ($alter as $val) {
if (!queries("ALTER TABLE " . table($table) . " $val")) {
return false;
}
}
if ($table != $name && !queries("ALTER TABLE " . table($table) . " RENAME TO " . table($name))) {
return false;
}
}
if ($auto_increment) {
queries("UPDATE sqlite_sequence SET seq = $auto_increment WHERE name = " . q($name)); // ignores error
}
return true;
}
function index_sql($table, $type, $name, $columns) {
return "CREATE $type " . ($type != "INDEX" ? "INDEX " : "")
. idf_escape($name != "" ? $name : uniqid($table . "_"))
. " ON " . table($table)
. " $columns"
;
}
function alter_indexes($table, $alter) {
foreach ($alter as $val) {
if (!queries($val[2] == "DROP"
? "DROP INDEX " . idf_escape($val[1])
: index_sql($table, $val[0], $val[1], $val[2])
)) {
return false;
}
}
return true;
}
function truncate_tables($tables) {
return apply_queries("DELETE FROM", $tables);
}
function drop_views($views) {
return apply_queries("DROP VIEW", $views);
}
function drop_tables($tables) {
return apply_queries("DROP TABLE", $tables);
}
function move_tables($tables, $views, $target) {
return false;
}
function trigger($name) {
global $connection;
if ($name == "") {
return array("Statement" => "BEGIN\n\t;\nEND");
}
preg_match('~^CREATE\\s+TRIGGER\\s*(?:[^`"\\s]+|`[^`]*`|"[^"]*")+\\s*([a-z]+)\\s+([a-z]+)\\s+ON\\s*(?:[^`"\\s]+|`[^`]*`|"[^"]*")+\\s*(?:FOR\\s*EACH\\s*ROW\\s)?(.*)~is', $connection->result("SELECT sql FROM sqlite_master WHERE name = " . q($name)), $match);
return array("Timing" => strtoupper($match[1]), "Event" => strtoupper($match[2]), "Trigger" => $name, "Statement" => $match[3]);
}
function triggers($table) {
$return = array();
foreach (get_rows("SELECT * FROM sqlite_master WHERE type = 'trigger' AND tbl_name = " . q($table)) as $row) {
preg_match('~^CREATE\\s+TRIGGER\\s*(?:[^`"\\s]+|`[^`]*`|"[^"]*")+\\s*([a-z]+)\\s*([a-z]+)~i', $row["sql"], $match);
$return[$row["name"]] = array($match[1], $match[2]);
}
return $return;
}
function trigger_options() {
return array(
"Timing" => array("BEFORE", "AFTER", "INSTEAD OF"),
"Type" => array("FOR EACH ROW"),
);
}
function routine($name, $type) {
// not supported by SQLite
}
function routines() {
// not supported by SQLite
}
function routine_languages() {
// not supported by SQLite
}
function begin() {
return queries("BEGIN");
}
function insert_into($table, $set) {
return queries("INSERT INTO " . table($table) . ($set ? " (" . implode(", ", array_keys($set)) . ")\nVALUES (" . implode(", ", $set) . ")" : "DEFAULT VALUES"));
}
function insert_update($table, $set, $primary) {
return queries("REPLACE INTO " . table($table) . " (" . implode(", ", array_keys($set)) . ") VALUES (" . implode(", ", $set) . ")");
}
function last_id() {
global $connection;
return $connection->result("SELECT LAST_INSERT_ROWID()");
}
function explain($connection, $query) {
return $connection->query("EXPLAIN $query");
}
function found_rows($table_status, $where) {
}
function types() {
return array();
}
function schemas() {
return array();
}
function get_schema() {
return "";
}
function set_schema($scheme) {
return true;
}
function create_sql($table, $auto_increment) {
global $connection;
$return = $connection->result("SELECT sql FROM sqlite_master WHERE type IN ('table', 'view') AND name = " . q($table));
foreach (indexes($table) as $name => $index) {
if ($name == '') {
continue;
}
$return .= ";\n\n" . index_sql($table, $index['type'], $name, "(" . implode(", ", array_map('idf_escape', $index['columns'])) . ")");
}
return $return;
}
function truncate_sql($table) {
return "DELETE FROM " . table($table);
}
function use_sql($database) {
}
function trigger_sql($table, $style) {
return implode(get_vals("SELECT sql || ';;\n' FROM sqlite_master WHERE type = 'trigger' AND tbl_name = " . q($table)));
}
function show_variables() {
global $connection;
$return = array();
foreach (array("auto_vacuum", "cache_size", "count_changes", "default_cache_size", "empty_result_callbacks", "encoding", "foreign_keys", "full_column_names", "fullfsync", "journal_mode", "journal_size_limit", "legacy_file_format", "locking_mode", "page_size", "max_page_count", "read_uncommitted", "recursive_triggers", "reverse_unordered_selects", "secure_delete", "short_column_names", "synchronous", "temp_store", "temp_store_directory", "schema_version", "integrity_check", "quick_check") as $key) {
$return[$key] = $connection->result("PRAGMA $key");
}
return $return;
}
function show_status() {
$return = array();
foreach (get_vals("PRAGMA compile_options") as $option) {
list($key, $val) = explode("=", $option, 2);
$return[$key] = $val;
}
return $return;
}
function convert_field($field) {
}
function unconvert_field($field, $return) {
return $return;
}
function support($feature) {
return ereg('^(view|trigger|variables|status|dump|move_col|drop_col)$', $feature);
}
$jush = "sqlite";
$types = array("integer" => 0, "real" => 0, "numeric" => 0, "text" => 0, "blob" => 0);
$structured_types = array_keys($types);
$unsigned = array();
$operators = array("=", "<", ">", "<=", ">=", "!=", "LIKE", "LIKE %%", "IN", "IS NULL", "NOT LIKE", "NOT IN", "IS NOT NULL", "SQL"); // REGEXP can be user defined function
$functions = array("hex", "length", "lower", "round", "unixepoch", "upper");
$grouping = array("avg", "count", "count distinct", "group_concat", "max", "min", "sum");
$edit_functions = array(
array(
// "text" => "date('now')/time('now')/datetime('now')",
), array(
"integer|real|numeric" => "+/-",
// "text" => "date/time/datetime",
"text" => "||",
)
);
}