-
Notifications
You must be signed in to change notification settings - Fork 44
/
class-wp-sqlite-translator.php
3710 lines (3364 loc) · 105 KB
/
class-wp-sqlite-translator.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
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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* The queries translator.
*
* @package wp-sqlite-integration
* @see https://github.com/phpmyadmin/sql-parser
*/
/**
* The queries translator class.
*/
class WP_SQLite_Translator {
const SQLITE_BUSY = 5;
const SQLITE_LOCKED = 6;
const DATA_TYPES_CACHE_TABLE = '_mysql_data_types_cache';
const CREATE_DATA_TYPES_CACHE_TABLE = 'CREATE TABLE IF NOT EXISTS _mysql_data_types_cache (
`table` TEXT NOT NULL,
`column_or_index` TEXT NOT NULL,
`mysql_type` TEXT NOT NULL,
PRIMARY KEY(`table`, `column_or_index`)
);';
/**
* We use the ASCII SUB character to escape LIKE literal _ and %
*/
const LIKE_ESCAPE_CHAR = "\x1a";
/**
* Class variable to reference to the PDO instance.
*
* @access private
*
* @var PDO object
*/
private $pdo;
/**
* The database version.
*
* This is used here to avoid PHP warnings in the health screen.
*
* @var string
*/
public $client_info = '';
/**
* How to translate field types from MySQL to SQLite.
*
* @var array
*/
private $field_types_translation = array(
'bit' => 'integer',
'bool' => 'integer',
'boolean' => 'integer',
'tinyint' => 'integer',
'smallint' => 'integer',
'mediumint' => 'integer',
'int' => 'integer',
'integer' => 'integer',
'bigint' => 'integer',
'float' => 'real',
'double' => 'real',
'decimal' => 'real',
'dec' => 'real',
'numeric' => 'real',
'fixed' => 'real',
'date' => 'text',
'datetime' => 'text',
'timestamp' => 'text',
'time' => 'text',
'year' => 'text',
'char' => 'text',
'varchar' => 'text',
'binary' => 'integer',
'varbinary' => 'blob',
'tinyblob' => 'blob',
'tinytext' => 'text',
'blob' => 'blob',
'text' => 'text',
'mediumblob' => 'blob',
'mediumtext' => 'text',
'longblob' => 'blob',
'longtext' => 'text',
'geomcollection' => 'text',
'geometrycollection' => 'text',
);
/**
* The MySQL to SQLite date formats translation.
*
* Maps MySQL formats to SQLite strftime() formats.
*
* For MySQL formats, see:
* * https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-format
*
* For SQLite formats, see:
* * https://www.sqlite.org/lang_datefunc.html
* * https://strftime.org/
*
* @var array
*/
private $mysql_date_format_to_sqlite_strftime = array(
'%a' => '%D',
'%b' => '%M',
'%c' => '%n',
'%D' => '%jS',
'%d' => '%d',
'%e' => '%j',
'%H' => '%H',
'%h' => '%h',
'%I' => '%h',
'%i' => '%M',
'%j' => '%z',
'%k' => '%G',
'%l' => '%g',
'%M' => '%F',
'%m' => '%m',
'%p' => '%A',
'%r' => '%h:%i:%s %A',
'%S' => '%s',
'%s' => '%s',
'%T' => '%H:%i:%s',
'%U' => '%W',
'%u' => '%W',
'%V' => '%W',
'%v' => '%W',
'%W' => '%l',
'%w' => '%w',
'%X' => '%Y',
'%x' => '%o',
'%Y' => '%Y',
'%y' => '%y',
);
/**
* Number of rows found by the last SELECT query.
*
* @var int
*/
private $last_select_found_rows;
/**
* Number of rows found by the last SQL_CALC_FOUND_ROW query.
*
* @var int integer
*/
private $last_sql_calc_found_rows = null;
/**
* The query rewriter.
*
* @var WP_SQLite_Query_Rewriter
*/
private $rewriter;
/**
* Last executed MySQL query.
*
* @var string
*/
public $mysql_query;
/**
* A list of executed SQLite queries.
*
* @var array
*/
public $executed_sqlite_queries = array();
/**
* The affected table name.
*
* @var array
*/
private $table_name = array();
/**
* The type of the executed query (SELECT, INSERT, etc).
*
* @var array
*/
private $query_type = array();
/**
* The columns to insert.
*
* @var array
*/
private $insert_columns = array();
/**
* Class variable to store the result of the query.
*
* @access private
*
* @var array reference to the PHP object
*/
private $results = null;
/**
* Class variable to check if there is an error.
*
* @var boolean
*/
public $is_error = false;
/**
* Class variable to store the file name and function to cause error.
*
* @access private
*
* @var array
*/
private $errors;
/**
* Class variable to store the error messages.
*
* @access private
*
* @var array
*/
private $error_messages = array();
/**
* Class variable to store the affected row id.
*
* @var int integer
* @access private
*/
private $last_insert_id;
/**
* Class variable to store the number of rows affected.
*
* @var int integer
*/
private $affected_rows;
/**
* Class variable to store the queried column info.
*
* @var array
*/
private $column_data;
/**
* Variable to emulate MySQL affected row.
*
* @var integer
*/
private $num_rows;
/**
* Return value from query().
*
* Each query has its own return value.
*
* @var mixed
*/
private $return_value;
/**
* Variable to keep track of nested transactions level.
*
* @var int
*/
private $transaction_level = 0;
/**
* Value returned by the last exec().
*
* @var mixed
*/
private $last_exec_returned;
/**
* The PDO fetch mode passed to query().
*
* @var mixed
*/
private $pdo_fetch_mode;
/**
* The last reserved keyword seen in an SQL query.
*
* @var mixed
*/
private $last_reserved_keyword;
/**
* True if a VACUUM operation should be done on shutdown,
* to handle OPTIMIZE TABLE and similar operations.
*
* @var bool
*/
private $vacuum_requested = false;
/**
* True if the present query is metadata
*
* @var bool
*/
private $is_information_schema_query = false;
/**
* True if a GROUP BY clause is detected.
*
* @var bool
*/
private $has_group_by = false;
/**
* 0 if no LIKE is in progress, otherwise counts nested parentheses.
*
* @todo A generic stack of expression would scale better. There's already a call_stack in WP_SQLite_Query_Rewriter.
* @var int
*/
private $like_expression_nesting = 0;
/**
* 0 if no LIKE is in progress, otherwise counts nested parentheses.
*
* @var int
*/
private $like_escape_count = 0;
/**
* Associative array with list of system (non-WordPress) tables.
*
* @var array [tablename => tablename]
*/
private $sqlite_system_tables = array();
/**
* The last error message from SQLite.
*
* @var string
*/
private $last_sqlite_error;
/**
* Constructor.
*
* Create PDO object, set user defined functions and initialize other settings.
* Don't use parent::__construct() because this class does not only returns
* PDO instance but many others jobs.
*
* @param PDO $pdo The PDO object.
*/
public function __construct( $pdo = null ) {
if ( ! $pdo ) {
if ( ! is_file( FQDB ) ) {
$this->prepare_directory();
}
$locked = false;
$status = 0;
$err_message = '';
do {
try {
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_STRINGIFY_FETCHES => true,
PDO::ATTR_TIMEOUT => 5,
);
$dsn = 'sqlite:' . FQDB;
$pdo = new PDO( $dsn, null, null, $options ); // phpcs:ignore WordPress.DB.RestrictedClasses
} catch ( PDOException $ex ) {
$status = $ex->getCode();
if ( self::SQLITE_BUSY === $status || self::SQLITE_LOCKED === $status ) {
$locked = true;
} else {
$err_message = $ex->getMessage();
}
}
} while ( $locked );
if ( $status > 0 ) {
$message = sprintf(
'<p>%s</p><p>%s</p><p>%s</p>',
'Database initialization error!',
"Code: $status",
"Error Message: $err_message"
);
$this->is_error = true;
$this->error_messages[] = $message;
return;
}
}
new WP_SQLite_PDO_User_Defined_Functions( $pdo );
// MySQL data comes across stringified by default.
$pdo->setAttribute( PDO::ATTR_STRINGIFY_FETCHES, true ); // phpcs:ignore WordPress.DB.RestrictedClasses.mysql__PDO
$pdo->query( WP_SQLite_Translator::CREATE_DATA_TYPES_CACHE_TABLE );
/*
* A list of system tables lets us emulate information_schema
* queries without returning extra tables.
*/
$this->sqlite_system_tables ['sqlite_sequence'] = 'sqlite_sequence';
$this->sqlite_system_tables [ self::DATA_TYPES_CACHE_TABLE ] = self::DATA_TYPES_CACHE_TABLE;
$this->pdo = $pdo;
// Fixes a warning in the site-health screen.
$this->client_info = SQLite3::version()['versionString'];
register_shutdown_function( array( $this, '__destruct' ) );
// WordPress happens to use no foreign keys.
$statement = $this->pdo->query( 'PRAGMA foreign_keys' );
// phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
if ( $statement->fetchColumn( 0 ) == '0' ) {
$this->pdo->query( 'PRAGMA foreign_keys = ON' );
}
$this->pdo->query( 'PRAGMA encoding="UTF-8";' );
}
/**
* Destructor
*
* If SQLITE_MEM_DEBUG constant is defined, append information about
* memory usage into database/mem_debug.txt.
*
* This definition is changed since version 1.7.
*/
public function __destruct() {
if ( defined( 'SQLITE_MEM_DEBUG' ) && SQLITE_MEM_DEBUG ) {
$max = ini_get( 'memory_limit' );
if ( is_null( $max ) ) {
$message = sprintf(
'[%s] Memory_limit is not set in php.ini file.',
gmdate( 'Y-m-d H:i:s', $_SERVER['REQUEST_TIME'] )
);
error_log( $message );
return;
}
if ( stripos( $max, 'M' ) !== false ) {
$max = (int) $max * MB_IN_BYTES;
}
$peak = memory_get_peak_usage( true );
$used = round( (int) $peak / (int) $max * 100, 2 );
if ( $used > 90 ) {
$message = sprintf(
"[%s] Memory peak usage warning: %s %% used. (max: %sM, now: %sM)\n",
gmdate( 'Y-m-d H:i:s', $_SERVER['REQUEST_TIME'] ),
$used,
$max,
$peak
);
error_log( $message );
}
}
}
/**
* Get the PDO object.
*
* @return PDO
*/
public function get_pdo() {
return $this->pdo;
}
/**
* Method to return inserted row id.
*/
public function get_insert_id() {
return $this->last_insert_id;
}
/**
* Method to return the number of rows affected.
*/
public function get_affected_rows() {
return $this->affected_rows;
}
/**
* This method makes database directory and .htaccess file.
*
* It is executed only once when the installation begins.
*/
private function prepare_directory() {
global $wpdb;
$u = umask( 0000 );
if ( ! is_dir( FQDBDIR ) ) {
if ( ! @mkdir( FQDBDIR, 0704, true ) ) {
umask( $u );
wp_die( 'Unable to create the required directory! Please check your server settings.', 'Error!' );
}
}
if ( ! is_writable( FQDBDIR ) ) {
umask( $u );
$message = 'Unable to create a file in the directory! Please check your server settings.';
wp_die( $message, 'Error!' );
}
if ( ! is_file( FQDBDIR . '.htaccess' ) ) {
$fh = fopen( FQDBDIR . '.htaccess', 'w' );
if ( ! $fh ) {
umask( $u );
echo 'Unable to create a file in the directory! Please check your server settings.';
return false;
}
fwrite( $fh, 'DENY FROM ALL' );
fclose( $fh );
}
if ( ! is_file( FQDBDIR . 'index.php' ) ) {
$fh = fopen( FQDBDIR . 'index.php', 'w' );
if ( ! $fh ) {
umask( $u );
echo 'Unable to create a file in the directory! Please check your server settings.';
return false;
}
fwrite( $fh, '<?php // Silence is gold. ?>' );
fclose( $fh );
}
umask( $u );
return true;
}
/**
* Method to execute query().
*
* Divide the query types into seven different ones. That is to say:
*
* 1. SELECT SQL_CALC_FOUND_ROWS
* 2. INSERT
* 3. CREATE TABLE(INDEX)
* 4. ALTER TABLE
* 5. SHOW VARIABLES
* 6. DROP INDEX
* 7. THE OTHERS
*
* #1 is just a tricky play. See the private function handle_sql_count() in query.class.php.
* From #2 through #5 call different functions respectively.
* #6 call the ALTER TABLE query.
* #7 is a normal process: sequentially call prepare_query() and execute_query().
*
* #1 process has been changed since version 1.5.1.
*
* @param string $statement Full SQL statement string.
* @param int $mode Not used.
* @param array ...$fetch_mode_args Not used.
*
* @see PDO::query()
*
* @throws Exception If the query could not run.
* @throws PDOException If the translated query could not run.
*
* @return mixed according to the query type
*/
public function query( $statement, $mode = PDO::FETCH_OBJ, ...$fetch_mode_args ) { // phpcs:ignore WordPress.DB.RestrictedClasses
$this->flush();
if ( function_exists( 'apply_filters' ) ) {
/**
* Filters queries before they are translated and run.
*
* Return a non-null value to cause query() to return early with that result.
* Use this filter to intercept queries that don't work correctly in SQLite.
*
* From within the filter you can do
* function filter_sql ($result, $translator, $statement, $mode, $fetch_mode_args) {
* if ( intercepting this query ) {
* return $translator->execute_sqlite_query( $statement );
* }
* return $result;
* }
*
* @param null|array $result Default null to continue with the query.
* @param object $translator The translator object. You can call $translator->execute_sqlite_query().
* @param string $statement The statement passed.
* @param int $mode Fetch mode: PDO::FETCH_OBJ, PDO::FETCH_CLASS, etc.
* @param array $fetch_mode_args Variable arguments passed to query.
*
* @returns null|array Null to proceed, or an array containing a resultset.
* @since 2.1.0
*/
$pre = apply_filters( 'pre_query_sqlite_db', null, $this, $statement, $mode, $fetch_mode_args );
if ( null !== $pre ) {
return $pre;
}
}
$this->pdo_fetch_mode = $mode;
$this->mysql_query = $statement;
if (
preg_match( '/^\s*START TRANSACTION/i', $statement )
|| preg_match( '/^\s*BEGIN/i', $statement )
) {
return $this->begin_transaction();
}
if ( preg_match( '/^\s*COMMIT/i', $statement ) ) {
return $this->commit();
}
if ( preg_match( '/^\s*ROLLBACK/i', $statement ) ) {
return $this->rollback();
}
try {
// Perform all the queries in a nested transaction.
$this->begin_transaction();
do {
$error = null;
try {
$this->execute_mysql_query(
$statement
);
} catch ( PDOException $error ) {
if ( $error->getCode() !== self::SQLITE_BUSY ) {
throw $error;
}
}
} while ( $error );
/**
* Notifies that a query has been translated and executed.
*
* @param string $query The executed SQL query.
* @param string $query_type The type of the SQL query (e.g. SELECT, INSERT, UPDATE, DELETE).
* @param string $table_name The name of the table affected by the SQL query.
* @param array $insert_columns The columns affected by the INSERT query (if applicable).
* @param int $last_insert_id The ID of the last inserted row (if applicable).
* @param int $affected_rows The number of affected rows (if applicable).
*
* @since 0.1.0
*/
do_action(
'sqlite_translated_query_executed',
$this->mysql_query,
$this->query_type,
$this->table_name,
$this->insert_columns,
$this->last_insert_id,
$this->affected_rows
);
// Commit the nested transaction.
$this->commit();
return $this->return_value;
} catch ( Exception $err ) {
// Rollback the nested transaction.
$this->rollback();
if ( defined( 'PDO_DEBUG' ) && PDO_DEBUG === true ) {
throw $err;
}
return $this->handle_error( $err );
}
}
/**
* Method to return the queried column names.
*
* These data are meaningless for SQLite. So they are dummy emulating
* MySQL columns data.
*
* @return array|null of the object
*/
public function get_columns() {
if ( ! empty( $this->results ) ) {
$primary_key = array(
'meta_id',
'comment_ID',
'link_ID',
'option_id',
'blog_id',
'option_name',
'ID',
'term_id',
'object_id',
'term_taxonomy_id',
'umeta_id',
'id',
);
$unique_key = array( 'term_id', 'taxonomy', 'slug' );
$data = array(
'name' => '', // Column name.
'table' => '', // Table name.
'max_length' => 0, // Max length of the column.
'not_null' => 1, // 1 if not null.
'primary_key' => 0, // 1 if column has primary key.
'unique_key' => 0, // 1 if column has unique key.
'multiple_key' => 0, // 1 if column doesn't have unique key.
'numeric' => 0, // 1 if column has numeric value.
'blob' => 0, // 1 if column is blob.
'type' => '', // Type of the column.
'int' => 0, // 1 if column is int integer.
'zerofill' => 0, // 1 if column is zero-filled.
);
$table_name = '';
$sql = '';
$query = end( $this->executed_sqlite_queries );
if ( $query ) {
$sql = $query['sql'];
}
if ( preg_match( '/\s*FROM\s*(.*)?\s*/i', $sql, $match ) ) {
$table_name = trim( $match[1] );
}
foreach ( $this->results[0] as $key => $value ) {
$data['name'] = $key;
$data['table'] = $table_name;
if ( in_array( $key, $primary_key, true ) ) {
$data['primary_key'] = 1;
} elseif ( in_array( $key, $unique_key, true ) ) {
$data['unique_key'] = 1;
} else {
$data['multiple_key'] = 1;
}
$this->column_data[] = json_decode( json_encode( $data ) );
// Reset data for next iteration.
$data['name'] = '';
$data['table'] = '';
$data['primary_key'] = 0;
$data['unique_key'] = 0;
$data['multiple_key'] = 0;
}
return $this->column_data;
}
return null;
}
/**
* Method to return the queried result data.
*
* @return mixed
*/
public function get_query_results() {
return $this->results;
}
/**
* Method to return the number of rows from the queried result.
*/
public function get_num_rows() {
return $this->num_rows;
}
/**
* Method to return the queried results according to the query types.
*
* @return mixed
*/
public function get_return_value() {
return $this->return_value;
}
/**
* Executes a MySQL query in SQLite.
*
* @param string $query The query.
*
* @throws Exception If the query is not supported.
*/
private function execute_mysql_query( $query ) {
$tokens = ( new WP_SQLite_Lexer( $query ) )->tokens;
$this->rewriter = new WP_SQLite_Query_Rewriter( $tokens );
$this->query_type = $this->rewriter->peek()->value;
switch ( $this->query_type ) {
case 'ALTER':
$this->execute_alter();
break;
case 'CREATE':
$this->execute_create();
break;
case 'SELECT':
$this->execute_select();
break;
case 'INSERT':
case 'REPLACE':
$this->execute_insert_or_replace();
break;
case 'UPDATE':
$this->execute_update();
break;
case 'DELETE':
$this->execute_delete();
break;
case 'CALL':
case 'SET':
/*
* It would be lovely to support at least SET autocommit,
* but I don't think that is even possible with SQLite.
*/
$this->results = 0;
break;
case 'TRUNCATE':
$this->execute_truncate();
break;
case 'BEGIN':
case 'START TRANSACTION':
$this->results = $this->begin_transaction();
break;
case 'COMMIT':
$this->results = $this->commit();
break;
case 'ROLLBACK':
$this->results = $this->rollback();
break;
case 'DROP':
$this->execute_drop();
break;
case 'SHOW':
$this->execute_show();
break;
case 'DESCRIBE':
$this->execute_describe();
break;
case 'CHECK':
$this->execute_check();
break;
case 'OPTIMIZE':
case 'REPAIR':
case 'ANALYZE':
$this->execute_optimize( $this->query_type );
break;
default:
throw new Exception( 'Unknown query type: ' . $this->query_type );
}
}
/**
* Executes a MySQL CREATE TABLE query in SQLite.
*
* @throws Exception If the query is not supported.
*/
private function execute_create_table() {
$table = $this->parse_create_table();
$definitions = array();
foreach ( $table->fields as $field ) {
/*
* Do not include the inline PRIMARY KEY definition
* if there is more than one primary key.
*/
if ( $field->primary_key && count( $table->primary_key ) > 1 ) {
$field->primary_key = false;
}
if ( $field->auto_increment && count( $table->primary_key ) > 1 ) {
throw new Exception( 'Cannot combine AUTOINCREMENT and multiple primary keys in SQLite' );
}
$definitions[] = $this->make_sqlite_field_definition( $field );
$this->update_data_type_cache(
$table->name,
$field->name,
$field->mysql_data_type
);
}
if ( count( $table->primary_key ) > 1 ) {
$definitions[] = 'PRIMARY KEY ("' . implode( '", "', $table->primary_key ) . '")';
}
$create_query = (
$table->create_table .
'"' . $table->name . '" (' . "\n" .
implode( ",\n", $definitions ) .
')'
);
$this->execute_sqlite_query( $create_query );
$this->results = $this->last_exec_returned;
$this->return_value = $this->results;
foreach ( $table->constraints as $constraint ) {
$index_type = $this->mysql_index_type_to_sqlite_type( $constraint->value );
$unique = '';
if ( 'UNIQUE INDEX' === $index_type ) {
$unique = 'UNIQUE ';
}
$index_name = "{$table->name}__{$constraint->name}";
$this->execute_sqlite_query(
"CREATE $unique INDEX \"$index_name\" ON \"{$table->name}\" (\"" . implode( '", "', $constraint->columns ) . '")'
);
$this->update_data_type_cache(
$table->name,
$index_name,
$constraint->value
);
}
}
/**
* Parse the CREATE TABLE query.
*
* @return stdClass Structured data.
*/
private function parse_create_table() {
$this->rewriter = clone $this->rewriter;
$result = new stdClass();
$result->create_table = null;
$result->name = null;
$result->fields = array();
$result->constraints = array();
$result->primary_key = array();
/*
* The query starts with CREATE TABLE [IF NOT EXISTS].
* Consume everything until the table name.
*/
while ( true ) {
$token = $this->rewriter->consume();
if ( ! $token ) {
break;
}
// The table name is the first non-keyword token.
if ( WP_SQLite_Token::TYPE_KEYWORD !== $token->type ) {
// Store the table name for later.
$result->name = $this->normalize_column_name( $token->value );
// Drop the table name and store the CREATE TABLE command.
$this->rewriter->drop_last();
$result->create_table = $this->rewriter->get_updated_query();
break;
}
}
/*
* Move to the opening parenthesis:
* CREATE TABLE wp_options (
* ^ here.
*/
$this->rewriter->skip(
array(
'type' => WP_SQLite_Token::TYPE_OPERATOR,
'value' => '(',
)
);
/*
* We're in the table definition now.
* Read everything until the closing parenthesis.
*/
$declarations_depth = $this->rewriter->depth;
do {
/*
* We want to capture a rewritten line of the query.
* Let's clear any data we might have captured so far.
*/
$this->rewriter->replace_all( array() );
/*
* Decide how to parse the current line. We expect either:
*
* Field definition, e.g.:
* `my_field` varchar(255) NOT NULL DEFAULT 'foo'
* Constraint definition, e.g.:
* PRIMARY KEY (`my_field`)
*
* Lexer does not seem to reliably understand whether the
* first token is a field name or a reserved keyword, so
* instead we'll check whether the second non-whitespace
* token is a data type.
*/
$second_token = $this->rewriter->peek_nth( 2 );
if ( $second_token->matches(
WP_SQLite_Token::TYPE_KEYWORD,
WP_SQLite_Token::FLAG_KEYWORD_DATA_TYPE
) ) {
$result->fields[] = $this->parse_mysql_create_table_field();
} else {
$result->constraints[] = $this->parse_mysql_create_table_constraint();
}
/*
* If we're back at the initial depth, we're done.
* Also, MySQL supports a trailing comma – if we see one,
* then we're also done.
*/
} while (
$token