Repository navigation
Expand file tree
/
Copy pathclass-wp-sqlite-information-schema-builder.php
More file actions
3562 lines (3277 loc) · 132 KB
/
Copy pathclass-wp-sqlite-information-schema-builder.php
File metadata and controls
3562 lines (3277 loc) · 132 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
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
/**
* SQLite information schema builder for MySQL.
*
* This class builds and maintains MySQL INFORMATION_SCHEMA tables in SQLite.
* It consumes the AST of MySQL DDL queries and records the schema information
* in SQLite tables that emulate the MySQL INFORMATION_SCHEMA.
*
* @access private
*/
class WP_SQLite_Information_Schema_Builder {
/**
* The name of the database that is saved in the information schema tables.
*
* The SQLite driver injects the configured database name dynamically,
* but we need to store some value in the information schema tables.
* This database name will also be visible in SQLite admin tools.
*
* @var string
*/
const SAVED_DATABASE_NAME = 'sqlite_database';
/**
* SQL definitions for tables that emulate MySQL "information_schema".
*
* The full MySQL information schema comprises a large number of tables:
* https://dev.mysql.com/doc/refman/8.4/en/information-schema-table-reference.html
*
* We only implement a limited subset that is necessary for a database schema
* introspection and representation, currently covering the following tables:
*
* - SCHEMATA
* - TABLES
* - COLUMNS
* - STATISTICS (indexes)
* - TABLE_CONSTRAINTS
* - CHECK_CONSTRAINTS
*
* TODO (not yet implemented):
* - VIEWS
* - TRIGGERS
*/
const INFORMATION_SCHEMA_TABLE_DEFINITIONS = array(
// INFORMATION_SCHEMA.SCHEMATA
'schemata' => "
CATALOG_NAME TEXT NOT NULL DEFAULT 'def' COLLATE NOCASE, -- always 'def'
SCHEMA_NAME TEXT NOT NULL COLLATE NOCASE, -- database name
DEFAULT_CHARACTER_SET_NAME TEXT NOT NULL COLLATE NOCASE, -- default character set
DEFAULT_COLLATION_NAME TEXT NOT NULL COLLATE NOCASE, -- default collation
SQL_PATH TEXT NULL COLLATE NOCASE, -- always NULL
DEFAULT_ENCRYPTION TEXT NOT NULL DEFAULT 'NO' COLLATE NOCASE, -- not implemented
PRIMARY KEY (SCHEMA_NAME)
",
// INFORMATION_SCHEMA.TABLES
'tables' => "
TABLE_CATALOG TEXT NOT NULL DEFAULT 'def' COLLATE NOCASE, -- always 'def'
TABLE_SCHEMA TEXT NOT NULL COLLATE NOCASE, -- database name
TABLE_NAME TEXT NOT NULL COLLATE NOCASE, -- table name
TABLE_TYPE TEXT NOT NULL COLLATE BINARY, -- 'BASE TABLE', 'VIEW', or 'SYSTEM VIEW'
ENGINE TEXT NOT NULL COLLATE NOCASE, -- storage engine
VERSION INTEGER NOT NULL DEFAULT 10, -- unused, in MySQL 8 hardcoded to 10
ROW_FORMAT TEXT NOT NULL COLLATE BINARY, -- row storage format @TODO - implement
TABLE_ROWS INTEGER NOT NULL DEFAULT 0, -- not implemented
AVG_ROW_LENGTH INTEGER NOT NULL DEFAULT 0, -- not implemented
DATA_LENGTH INTEGER NOT NULL DEFAULT 0, -- not implemented
MAX_DATA_LENGTH INTEGER NOT NULL DEFAULT 0, -- not implemented
INDEX_LENGTH INTEGER NOT NULL DEFAULT 0, -- not implemented
DATA_FREE INTEGER NOT NULL DEFAULT 0, -- not implemented
AUTO_INCREMENT INTEGER, -- not implemented
CREATE_TIME TEXT NOT NULL -- table creation timestamp
DEFAULT CURRENT_TIMESTAMP,
UPDATE_TIME TEXT, -- table update time
CHECK_TIME TEXT, -- not implemented
TABLE_COLLATION TEXT NOT NULL COLLATE NOCASE, -- table collation
CHECKSUM INTEGER, -- not implemented
CREATE_OPTIONS TEXT NOT NULL DEFAULT '' COLLATE NOCASE, -- extra CREATE TABLE options
TABLE_COMMENT TEXT NOT NULL DEFAULT '' COLLATE NOCASE, -- comment
PRIMARY KEY (TABLE_SCHEMA, TABLE_NAME)
",
// INFORMATION_SCHEMA.COLUMNS
'columns' => "
TABLE_CATALOG TEXT NOT NULL DEFAULT 'def' COLLATE NOCASE, -- always 'def'
TABLE_SCHEMA TEXT NOT NULL COLLATE NOCASE, -- database name
TABLE_NAME TEXT NOT NULL COLLATE NOCASE, -- table name
COLUMN_NAME TEXT NOT NULL COLLATE NOCASE, -- column name
ORDINAL_POSITION INTEGER NOT NULL, -- column position
COLUMN_DEFAULT TEXT COLLATE BINARY, -- default value, NULL for both NULL and none
IS_NULLABLE TEXT NOT NULL COLLATE NOCASE, -- 'YES' or 'NO'
DATA_TYPE TEXT NOT NULL COLLATE BINARY, -- data type (without length, precision, etc.)
CHARACTER_MAXIMUM_LENGTH INTEGER, -- max length for string columns in characters
CHARACTER_OCTET_LENGTH INTEGER, -- max length for string columns in bytes
NUMERIC_PRECISION INTEGER, -- number precision for numeric columns
NUMERIC_SCALE INTEGER, -- number scale for numeric columns
DATETIME_PRECISION INTEGER, -- fractional seconds precision for temporal columns
CHARACTER_SET_NAME TEXT COLLATE NOCASE, -- charset for string columns
COLLATION_NAME TEXT COLLATE NOCASE, -- collation for string columns
COLUMN_TYPE TEXT NOT NULL COLLATE BINARY, -- full data type (with length, precision, etc.)
COLUMN_KEY TEXT NOT NULL DEFAULT '' COLLATE BINARY, -- if column is indexed ('', 'PRI', 'UNI', 'MUL')
EXTRA TEXT NOT NULL DEFAULT '' COLLATE NOCASE, -- AUTO_INCREMENT, VIRTUAL, STORED, etc.
PRIVILEGES TEXT NOT NULL COLLATE NOCASE, -- not implemented
COLUMN_COMMENT TEXT NOT NULL DEFAULT '' COLLATE BINARY, -- comment
GENERATION_EXPRESSION TEXT NOT NULL DEFAULT '' COLLATE BINARY, -- expression for generated columns
SRS_ID INTEGER, -- not implemented
PRIMARY KEY (TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME)
",
// INFORMATION_SCHEMA.STATISTICS (indexes)
'statistics' => "
TABLE_CATALOG TEXT NOT NULL DEFAULT 'def' COLLATE NOCASE, -- always 'def'
TABLE_SCHEMA TEXT NOT NULL COLLATE NOCASE, -- database name
TABLE_NAME TEXT NOT NULL COLLATE NOCASE, -- table name
NON_UNIQUE INTEGER NOT NULL, -- 0 for unique indexes, 1 otherwise
INDEX_SCHEMA TEXT NOT NULL COLLATE NOCASE, -- index database name
INDEX_NAME TEXT NOT NULL COLLATE NOCASE, -- index name, for PKs always 'PRIMARY'
SEQ_IN_INDEX INTEGER NOT NULL, -- column position in index (from 1)
COLUMN_NAME TEXT COLLATE NOCASE, -- column name (NULL for functional indexes)
COLLATION TEXT COLLATE NOCASE, -- column sort in the index ('A', 'D', or NULL)
CARDINALITY INTEGER, -- not implemented
SUB_PART INTEGER, -- number of indexed chars, NULL for full column
PACKED TEXT, -- not implemented
NULLABLE TEXT NOT NULL COLLATE NOCASE, -- 'YES' if column can contain NULL, '' otherwise
INDEX_TYPE TEXT NOT NULL COLLATE BINARY, -- 'BTREE', 'FULLTEXT', 'SPATIAL'
COMMENT TEXT NOT NULL DEFAULT '' COLLATE NOCASE, -- not implemented
INDEX_COMMENT TEXT NOT NULL DEFAULT '' COLLATE BINARY, -- index comment
IS_VISIBLE TEXT NOT NULL DEFAULT 'YES' COLLATE NOCASE, -- 'NO' if column is hidden, 'YES' otherwise
EXPRESSION TEXT COLLATE BINARY, -- expression for functional indexes
PRIMARY KEY (TABLE_SCHEMA, TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX),
UNIQUE (INDEX_SCHEMA, TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX)
",
// INFORMATION_SCHEMA.TABLE_CONSTRAINTS
'table_constraints' => "
CONSTRAINT_CATALOG TEXT NOT NULL DEFAULT 'def' COLLATE NOCASE, -- always 'def'
CONSTRAINT_SCHEMA TEXT NOT NULL COLLATE NOCASE, -- constraint database name
CONSTRAINT_NAME TEXT NOT NULL COLLATE NOCASE, -- constraint name
TABLE_SCHEMA TEXT NOT NULL COLLATE NOCASE, -- table database name
TABLE_NAME TEXT NOT NULL COLLATE NOCASE, -- table name
CONSTRAINT_TYPE TEXT NOT NULL COLLATE BINARY, -- constraint type ('PRIMARY KEY', 'UNIQUE', 'FOREIGN KEY', 'CHECK')
ENFORCED TEXT NOT NULL DEFAULT 'YES' COLLATE BINARY, -- 'YES' if constraint is enforced, 'NO' otherwise
-- Constraint names are unique per type in each table.
-- A MySQL table can have a PRIMARY KEY, UNIQUE, FOREIGN KEY, and CHECK
-- constraints with the same name, but the name must be unique per type.
-- CHECK and FOREIGN KEY constraint names must also be unique per schema.
PRIMARY KEY (TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_TYPE, CONSTRAINT_NAME),
UNIQUE (CONSTRAINT_SCHEMA, TABLE_NAME, CONSTRAINT_TYPE, CONSTRAINT_NAME)
",
// INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
'referential_constraints' => "
CONSTRAINT_CATALOG TEXT NOT NULL DEFAULT 'def' COLLATE NOCASE, -- always 'def'
CONSTRAINT_SCHEMA TEXT NOT NULL COLLATE NOCASE, -- constraint database name
CONSTRAINT_NAME TEXT NOT NULL COLLATE NOCASE, -- constraint name
UNIQUE_CONSTRAINT_CATALOG TEXT NOT NULL DEFAULT 'def' COLLATE NOCASE, -- always 'def'
UNIQUE_CONSTRAINT_SCHEMA TEXT NOT NULL COLLATE NOCASE, -- referenced unique constraint database name
UNIQUE_CONSTRAINT_NAME TEXT COLLATE NOCASE, -- referenced unique constraint name or NULL
MATCH_OPTION TEXT NOT NULL COLLATE NOCASE DEFAULT 'NONE', -- always 'NONE'
UPDATE_RULE TEXT NOT NULL COLLATE NOCASE, -- 'CASCADE', 'SET NULL', 'SET DEFAULT', 'RESTRICT', 'NO ACTION'
DELETE_RULE TEXT NOT NULL COLLATE NOCASE, -- 'CASCADE', 'SET NULL', 'SET DEFAULT', 'RESTRICT', 'NO ACTION'
TABLE_NAME TEXT NOT NULL COLLATE NOCASE, -- table name
REFERENCED_TABLE_NAME TEXT NOT NULL COLLATE NOCASE, -- referenced table name
PRIMARY KEY (CONSTRAINT_SCHEMA, CONSTRAINT_NAME)
",
// INFORMATION_SCHEMA.KEY_COLUMN_USAGE
'key_column_usage' => "
CONSTRAINT_CATALOG TEXT NOT NULL DEFAULT 'def' COLLATE NOCASE, -- always 'def'
CONSTRAINT_SCHEMA TEXT NOT NULL COLLATE NOCASE, -- constraint database name
CONSTRAINT_NAME TEXT NOT NULL COLLATE NOCASE, -- constraint name
TABLE_CATALOG TEXT NOT NULL DEFAULT 'def' COLLATE NOCASE, -- always 'def'
TABLE_SCHEMA TEXT NOT NULL COLLATE NOCASE, -- table database name
TABLE_NAME TEXT NOT NULL COLLATE NOCASE, -- table name
COLUMN_NAME TEXT NOT NULL COLLATE NOCASE, -- column name
ORDINAL_POSITION INTEGER NOT NULL, -- column position
POSITION_IN_UNIQUE_CONSTRAINT INTEGER, -- column position in referenced unique constraint
REFERENCED_TABLE_SCHEMA TEXT COLLATE NOCASE, -- referenced table database name
REFERENCED_TABLE_NAME TEXT COLLATE NOCASE, -- referenced table name
REFERENCED_COLUMN_NAME TEXT COLLATE NOCASE, -- referenced column name
UNIQUE (CONSTRAINT_SCHEMA, CONSTRAINT_NAME, COLUMN_NAME, REFERENCED_TABLE_SCHEMA)
",
// INFORMATION_SCHEMA.CHECK_CONSTRAINTS
'check_constraints' => "
CONSTRAINT_CATALOG TEXT NOT NULL DEFAULT 'def' COLLATE NOCASE, -- always 'def'
CONSTRAINT_SCHEMA TEXT NOT NULL COLLATE NOCASE, -- constraint database name
CONSTRAINT_NAME TEXT NOT NULL COLLATE NOCASE, -- constraint name
CHECK_CLAUSE TEXT NOT NULL COLLATE BINARY, -- check clause
PRIMARY KEY (CONSTRAINT_SCHEMA, CONSTRAINT_NAME)
",
);
/**
* A mapping of MySQL tokens to normalized MySQL data types.
* This is used to store column data types in the information schema.
*/
const TOKEN_TO_TYPE_MAP = array(
WP_MySQL_Lexer::INT_SYMBOL => 'int',
WP_MySQL_Lexer::TINYINT_SYMBOL => 'tinyint',
WP_MySQL_Lexer::SMALLINT_SYMBOL => 'smallint',
WP_MySQL_Lexer::MEDIUMINT_SYMBOL => 'mediumint',
WP_MySQL_Lexer::BIGINT_SYMBOL => 'bigint',
WP_MySQL_Lexer::REAL_SYMBOL => 'double',
WP_MySQL_Lexer::DOUBLE_SYMBOL => 'double',
WP_MySQL_Lexer::FLOAT_SYMBOL => 'float',
WP_MySQL_Lexer::DECIMAL_SYMBOL => 'decimal',
WP_MySQL_Lexer::NUMERIC_SYMBOL => 'decimal',
WP_MySQL_Lexer::FIXED_SYMBOL => 'decimal',
WP_MySQL_Lexer::BIT_SYMBOL => 'bit',
WP_MySQL_Lexer::BOOL_SYMBOL => 'tinyint',
WP_MySQL_Lexer::BOOLEAN_SYMBOL => 'tinyint',
WP_MySQL_Lexer::BINARY_SYMBOL => 'binary',
WP_MySQL_Lexer::VARBINARY_SYMBOL => 'varbinary',
WP_MySQL_Lexer::YEAR_SYMBOL => 'year',
WP_MySQL_Lexer::DATE_SYMBOL => 'date',
WP_MySQL_Lexer::TIME_SYMBOL => 'time',
WP_MySQL_Lexer::TIMESTAMP_SYMBOL => 'timestamp',
WP_MySQL_Lexer::DATETIME_SYMBOL => 'datetime',
WP_MySQL_Lexer::TINYBLOB_SYMBOL => 'tinyblob',
WP_MySQL_Lexer::BLOB_SYMBOL => 'blob',
WP_MySQL_Lexer::MEDIUMBLOB_SYMBOL => 'mediumblob',
WP_MySQL_Lexer::LONGBLOB_SYMBOL => 'longblob',
WP_MySQL_Lexer::TINYTEXT_SYMBOL => 'tinytext',
WP_MySQL_Lexer::TEXT_SYMBOL => 'text',
WP_MySQL_Lexer::MEDIUMTEXT_SYMBOL => 'mediumtext',
WP_MySQL_Lexer::LONGTEXT_SYMBOL => 'longtext',
WP_MySQL_Lexer::ENUM_SYMBOL => 'enum',
WP_MySQL_Lexer::SET_SYMBOL => 'set',
WP_MySQL_Lexer::SERIAL_SYMBOL => 'bigint',
WP_MySQL_Lexer::GEOMETRY_SYMBOL => 'geometry',
WP_MySQL_Lexer::GEOMETRYCOLLECTION_SYMBOL => 'geomcollection',
WP_MySQL_Lexer::POINT_SYMBOL => 'point',
WP_MySQL_Lexer::MULTIPOINT_SYMBOL => 'multipoint',
WP_MySQL_Lexer::LINESTRING_SYMBOL => 'linestring',
WP_MySQL_Lexer::MULTILINESTRING_SYMBOL => 'multilinestring',
WP_MySQL_Lexer::POLYGON_SYMBOL => 'polygon',
WP_MySQL_Lexer::MULTIPOLYGON_SYMBOL => 'multipolygon',
WP_MySQL_Lexer::JSON_SYMBOL => 'json',
);
/**
* The default collation for each MySQL charset.
* This is needed as collation is not always specified in a query.
*/
const CHARSET_DEFAULT_COLLATION_MAP = array(
'armscii8' => 'armscii8_general_ci',
'ascii' => 'ascii_general_ci',
'big5' => 'big5_chinese_ci',
'binary' => 'binary',
'cp1250' => 'cp1250_general_ci',
'cp1251' => 'cp1251_general_ci',
'cp1256' => 'cp1256_general_ci',
'cp1257' => 'cp1257_general_ci',
'cp850' => 'cp850_general_ci',
'cp852' => 'cp852_general_ci',
'cp866' => 'cp866_general_ci',
'cp932' => 'cp932_japanese_ci',
'dec8' => 'dec8_swedish_ci',
'eucjpms' => 'eucjpms_japanese_ci',
'euckr' => 'euckr_korean_ci',
'gb18030' => 'gb18030_chinese_ci',
'gb2312' => 'gb2312_chinese_ci',
'gbk' => 'gbk_chinese_ci',
'geostd8' => 'geostd8_general_ci',
'greek' => 'greek_general_ci',
'hebrew' => 'hebrew_general_ci',
'hp8' => 'hp8_english_ci',
'keybcs2' => 'keybcs2_general_ci',
'koi8r' => 'koi8r_general_ci',
'koi8u' => 'koi8u_general_ci',
'latin1' => 'latin1_swedish_ci',
'latin2' => 'latin2_general_ci',
'latin5' => 'latin5_turkish_ci',
'latin7' => 'latin7_general_ci',
'macce' => 'macce_general_ci',
'macroman' => 'macroman_general_ci',
'sjis' => 'sjis_japanese_ci',
'swe7' => 'swe7_swedish_ci',
'tis620' => 'tis620_thai_ci',
'ucs2' => 'ucs2_general_ci',
'ujis' => 'ujis_japanese_ci',
'utf16' => 'utf16_general_ci',
'utf16le' => 'utf16le_general_ci',
'utf32' => 'utf32_general_ci',
'utf8' => 'utf8_general_ci',
'utf8mb4' => 'utf8mb4_0900_ai_ci', // @TODO: This should probably be version-dependent.
// Before MySQL 8, the default was different.
);
/**
* Maximum number of bytes per character for each charset.
* The map contains only multi-byte charsets.
* Charsets that are not included are single-byte.
*/
const CHARSET_MAX_BYTES_MAP = array(
'big5' => 2,
'cp932' => 2,
'eucjpms' => 3,
'euckr' => 2,
'gb18030' => 4,
'gb2312' => 2,
'gbk' => 2,
'sjis' => 2,
'ucs2' => 2,
'ujis' => 3,
'utf16' => 4,
'utf16le' => 4,
'utf32' => 4,
'utf8' => 3,
'utf8mb4' => 4,
);
/**
* Zero values of temporal data types, without fractional seconds.
*/
const TEMPORAL_ZERO_VALUE_MAP = array(
'date' => '0000-00-00',
'time' => '00:00:00',
'datetime' => '0000-00-00 00:00:00',
'timestamp' => '0000-00-00 00:00:00',
'year' => '0000',
);
/**
* A prefix for information schema table names.
*
* @var string
*/
private $table_prefix;
/**
* A prefix for information schema table names for temporary tables.
*
* This is needed because for temporary tables, we store the information
* schema tables as temporary tables as well, and temporary tables with
* the same name as regular tables would override the regular tables.
*
* @var string
*/
private $temporary_table_prefix;
/**
* Whether the information schema for temporary tables was already created.
*
* This is used to avoid trying to create a temporary information schema
* for each CREATE TEMPORARY TABLE statement during a single session.
*
* @var bool
*/
private $temporary_information_schema_exists = false;
/**
* An instance of the SQLite connection.
*
* @var WP_SQLite_Connection
*/
private $connection;
/**
* Constructor.
*
* @param string $reserved_prefix An identifier prefix for internal database objects.
* @param WP_SQLite_Connection $connection An instance of the SQLite connection.
*/
public function __construct( string $reserved_prefix, WP_SQLite_Connection $connection ) {
$this->connection = $connection;
$this->table_prefix = $reserved_prefix . 'mysql_information_schema_';
$this->temporary_table_prefix = $reserved_prefix . 'mysql_information_schema_tmp_';
}
/**
* Get SQLite table name for the given MySQL information schema table name.
*
* @param bool $table_is_temporary Whether a temporary table information schema is requested.
* @param string $information_schema_table_name The MySQL information schema table name.
* @return string The SQLite table name.
*/
public function get_table_name( bool $table_is_temporary, string $information_schema_table_name ): string {
$prefix = $table_is_temporary ? $this->temporary_table_prefix : $this->table_prefix;
return $prefix . $information_schema_table_name;
}
/**
* Check if a temporary table exists in the SQLite database.
*
* @param string $table_name The temporary table name.
* @return bool True if the temporary table exists, false otherwise.
*/
public function temporary_table_exists( string $table_name ): bool {
/*
* We could search in the "{$this->temporary_table_prefix}tables" table,
* but it may not exist yet, so using "sqlite_temp_master" is simpler.
*
* The name is matched case-insensitively, as it is in the information
* schema tables. The fetched value is not compared to a string, because
* PDO SQLite returns native types when fetches are not stringified.
*/
$stmt = $this->connection->query(
"SELECT 1 FROM sqlite_temp_master WHERE type = 'table' AND name = ? COLLATE NOCASE",
array( $table_name )
);
return false !== $stmt->fetchColumn();
}
/**
* Ensure that the information schema tables exist in the SQLite
* database. Tables that are missing will be created.
*/
public function ensure_information_schema_tables(): void {
$sqlite_version = $this->connection->get_pdo()->getAttribute( PDO::ATTR_SERVER_VERSION ); // phpcs:ignore WordPress.DB.RestrictedClasses.mysql__PDO
$supports_strict_tables = version_compare( $sqlite_version, '3.37.0', '>=' );
foreach ( self::INFORMATION_SCHEMA_TABLE_DEFINITIONS as $table_name => $table_body ) {
$this->connection->query(
sprintf(
'CREATE TABLE IF NOT EXISTS %s%s (%s)%s',
$this->table_prefix,
$table_name,
$table_body,
$supports_strict_tables ? ' STRICT' : ''
)
);
}
}
/**
* Get the definition and data of a computed information schema table.
*
* Some information schema tables can be computed on the fly when they are
* referenced in a query. This method provides their definitions and data.
*
* @param string $table_name The table name.
* @return string|null The table definition and data, or null if
* the table is not a computed table.
*/
public function get_computed_information_schema_table_definition( string $table_name ): ?string {
switch ( strtolower( $table_name ) ) {
case 'character_sets':
return "SELECT
column1 AS CHARACTER_SET_NAME,
column2 AS DEFAULT_COLLATE_NAME,
column3 AS DESCRIPTION,
column4 AS MAXLEN
FROM (
VALUES
('binary', 'binary', 'Binary pseudo charset', 1),
('utf8', 'utf8_general_ci', 'UTF-8 Unicode', 3),
('utf8mb4', 'utf8mb4_0900_ai_ci', 'UTF-8 Unicode', 4)
)";
case 'collations':
return "SELECT
column1 AS COLLATION_NAME,
column2 AS CHARACTER_SET_NAME,
column3 AS ID,
column4 AS IS_DEFAULT,
column5 AS IS_COMPILED,
column6 AS SORTLEN,
column7 AS PAD_ATTRIBUTE
FROM (
VALUES
('binary', 'binary', 63, 'Yes', 'Yes', 1, 'NO PAD'),
('utf8_bin', 'utf8', 83, '', 'Yes', 1, 'PAD SPACE'),
('utf8_general_ci', 'utf8', 33, 'Yes', 'Yes', 1, 'PAD SPACE'),
('utf8_unicode_ci', 'utf8', 192, '', 'Yes', 8, 'PAD SPACE'),
('utf8mb4_bin', 'utf8mb4', 46, '', 'Yes', 1, 'PAD SPACE'),
('utf8mb4_unicode_ci', 'utf8mb4', 224, '', 'Yes', 8, 'PAD SPACE'),
('utf8mb4_unicode_520_ci', 'utf8mb4', 246, '', 'Yes', 8, 'PAD SPACE'),
('utf8mb4_0900_ai_ci', 'utf8mb4', 255, 'Yes', 'Yes', 0, 'NO PAD')
)";
default:
return null;
}
}
/**
* Ensure that the temporary information schema tables exist in
* the SQLite database. Tables that are missing will be created.
*/
public function ensure_temporary_information_schema_tables(): void {
$sqlite_version = $this->connection->get_pdo()->getAttribute( PDO::ATTR_SERVER_VERSION ); // phpcs:ignore WordPress.DB.RestrictedClasses.mysql__PDO
$supports_strict_tables = version_compare( $sqlite_version, '3.37.0', '>=' );
foreach ( self::INFORMATION_SCHEMA_TABLE_DEFINITIONS as $table_name => $table_body ) {
// Skip the "schemata" table; MySQL doesn't support temporary databases.
if ( 'schemata' === $table_name ) {
continue;
}
$this->connection->query(
sprintf(
'CREATE TEMPORARY TABLE IF NOT EXISTS %s%s (%s)%s',
$this->temporary_table_prefix,
$table_name,
$table_body,
$supports_strict_tables ? ' STRICT' : ''
)
);
}
$this->temporary_information_schema_exists = true;
}
/**
* Analyze CREATE TABLE statement and record data in the information schema.
*
* @param WP_Parser_Node $node The "createStatement" AST node with "createTable" child.
*/
public function record_create_table( WP_Parser_Node $node ): void {
$table_name_node = $node->get_first_descendant_node( 'tableName' );
$table_name = $this->get_table_name_from_node( $table_name_node );
$table_engine = $this->get_table_engine( $node );
$table_row_format = 'MyISAM' === $table_engine ? 'Fixed' : 'Dynamic';
$table_collation = $this->get_table_collation( $node );
$table_comment = $this->get_table_comment( $node );
/*
* When creating a temporary table:
* 1. Track that we're processing a temporary table.
* 2. Ensure that the temporary information schema tables exist.
*/
$subnode = $node->get_first_child_node();
$table_is_temporary = $subnode->has_child_token( WP_MySQL_Lexer::TEMPORARY_SYMBOL );
if ( $table_is_temporary && ! $this->temporary_information_schema_exists ) {
$this->ensure_temporary_information_schema_tables();
}
// 1. Table.
$tables_table_name = $this->get_table_name( $table_is_temporary, 'tables' );
$table_data = array(
'table_schema' => self::SAVED_DATABASE_NAME,
'table_name' => $table_name,
'table_type' => 'BASE TABLE',
'engine' => $table_engine,
'row_format' => $table_row_format,
'table_collation' => $table_collation,
'table_comment' => $table_comment,
);
try {
$this->insert_values( $tables_table_name, $table_data );
} catch ( PDOException $e ) {
/*
* Even though we keep track of whether the temporary information
* schema tables already exist, there is a special case in which
* the tracked information may be incorrect.
*
* This can happen when the query is in a transaction that is later
* rolled back. In that case, let's ensure the schema, and try again.
*/
if ( $table_is_temporary && str_contains( $e->getMessage(), 'no such table' ) ) {
$this->ensure_temporary_information_schema_tables();
try {
$e = null;
$this->insert_values( $tables_table_name, $table_data );
} catch ( PDOException $retry_exception ) {
$e = $retry_exception;
}
}
if ( $e ) {
if ( '23000' === $e->getCode() ) {
throw WP_SQLite_Information_Schema_Exception::duplicate_table_name( $table_name );
} else {
throw $e;
}
}
}
// 2. Columns.
$column_position = 1;
foreach ( $node->get_descendant_nodes( 'columnDefinition' ) as $column_node ) {
$column_name = $this->get_value( $column_node->get_first_child_node( 'fieldIdentifier' ) );
// Column definition.
$column_data = $this->extract_column_data(
$table_name,
$column_name,
$column_node,
$column_position
);
try {
$this->insert_values(
$this->get_table_name( $table_is_temporary, 'columns' ),
$column_data
);
} catch ( PDOException $e ) {
if ( '23000' === $e->getCode() ) {
throw WP_SQLite_Information_Schema_Exception::duplicate_column_name( $column_name );
}
throw $e;
}
// Extract inline column constraints and indexes.
$index_data = $this->extract_column_statistics_data(
$table_name,
$column_name,
$column_node,
'YES' === $column_data['is_nullable']
);
$constraint_data = $this->extract_table_constraint_data(
$column_node,
$table_name,
$index_data['index_name'] ?? null
);
$referential_constraint_data = $this->extract_referential_constraint_data(
$column_node,
$table_name
);
$key_column_usage_data = $this->extract_key_column_usage_data(
$column_node,
$table_name,
$index_data['index_name'] ?? null
);
$check_constraint_data = $this->extract_check_constraint_data(
$column_node,
$table_name
);
// Save inline column constraints and indexes.
if ( null !== $index_data ) {
$this->insert_values(
$this->get_table_name( $table_is_temporary, 'statistics' ),
$index_data
);
}
if ( null !== $constraint_data ) {
$this->insert_values(
$this->get_table_name( $table_is_temporary, 'table_constraints' ),
$constraint_data
);
}
if ( null !== $referential_constraint_data ) {
$this->insert_values(
$this->get_table_name( $table_is_temporary, 'referential_constraints' ),
$referential_constraint_data
);
}
foreach ( $key_column_usage_data as $key_column_usage_item ) {
$this->insert_values(
$this->get_table_name( $table_is_temporary, 'key_column_usage' ),
$key_column_usage_item
);
}
if ( null !== $check_constraint_data ) {
$this->insert_values(
$this->get_table_name( $table_is_temporary, 'check_constraints' ),
$check_constraint_data
);
}
$column_position += 1;
}
// 3. Constraints and indexes.
foreach ( $node->get_descendant_nodes( 'tableConstraintDef' ) as $constraint_node ) {
$this->record_add_constraint_or_index( $table_is_temporary, $table_name, $constraint_node );
}
}
/**
* Analyze ALTER TABLE statement and record data in the information schema.
*
* @param WP_Parser_Node $node The "alterStatement" AST node with "alterTable" child.
*/
public function record_alter_table( WP_Parser_Node $node ): void {
$table_ref = $node->get_first_descendant_node( 'tableRef' );
$table_name = $this->get_table_name_from_node( $table_ref );
$actions = $node->get_descendant_nodes( 'alterListItem' );
// Check if a temporary table with the given name exists.
$table_is_temporary = $this->temporary_table_exists( $table_name );
foreach ( $actions as $action ) {
$first_token = $action->get_first_child_token();
// ADD
if ( WP_MySQL_Lexer::ADD_SYMBOL === $first_token->id ) {
// ADD [COLUMN] (...[, ...])
$table_element_list = $action->get_first_child_node( 'tableElementList' );
if ( null !== $table_element_list ) {
foreach ( $table_element_list->get_descendant_nodes( 'columnDefinition' ) as $column_definition ) {
$name = $this->get_value( $column_definition->get_first_child_node( 'fieldIdentifier' ) );
$this->record_add_column( $table_is_temporary, $table_name, $name, $column_definition );
}
foreach ( $table_element_list->get_descendant_nodes( 'tableConstraintDef' ) as $constraint ) {
$this->record_add_constraint_or_index( $table_is_temporary, $table_name, $constraint );
}
continue;
}
// ADD [COLUMN] ...
$field_definition = $action->get_first_descendant_node( 'fieldDefinition' );
if ( null !== $field_definition ) {
$name = $this->get_value( $action->get_first_child_node( 'identifier' ) );
$this->record_add_column( $table_is_temporary, $table_name, $name, $field_definition );
// @TODO: Handle FIRST/AFTER.
continue;
}
// ADD constraint or index.
$constraint = $action->get_first_descendant_node( 'tableConstraintDef' );
if ( null !== $constraint ) {
$this->record_add_constraint_or_index( $table_is_temporary, $table_name, $constraint );
continue;
}
throw new \Exception( sprintf( 'Unsupported ALTER TABLE ADD action: %s', $first_token->get_value() ) );
}
// CHANGE [COLUMN]
if ( WP_MySQL_Lexer::CHANGE_SYMBOL === $first_token->id ) {
$old_name = $this->get_value( $action->get_first_child_node( 'fieldIdentifier' ) );
$new_name = $this->get_value( $action->get_first_child_node( 'identifier' ) );
$this->record_change_column(
$table_is_temporary,
$table_name,
$old_name,
$new_name,
$action->get_first_descendant_node( 'fieldDefinition' )
);
continue;
}
// MODIFY [COLUMN]
if ( WP_MySQL_Lexer::MODIFY_SYMBOL === $first_token->id ) {
$name = $this->get_value( $action->get_first_child_node( 'fieldIdentifier' ) );
$this->record_modify_column(
$table_is_temporary,
$table_name,
$name,
$action->get_first_descendant_node( 'fieldDefinition' )
);
continue;
}
// DROP
if ( WP_MySQL_Lexer::DROP_SYMBOL === $first_token->id ) {
// DROP CONSTRAINT
if ( $action->has_child_token( WP_MySQL_Lexer::CONSTRAINT_SYMBOL ) ) {
$name = $this->get_value( $action->get_first_child_node( 'identifier' ) );
$this->record_drop_constraint( $table_is_temporary, $table_name, $name );
continue;
}
// DROP PRIMARY KEY
if ( $action->has_child_token( WP_MySQL_Lexer::PRIMARY_SYMBOL ) ) {
$this->record_drop_key( $table_is_temporary, $table_name, 'PRIMARY' );
continue;
}
// DROP FOREIGN KEY
if ( $action->has_child_token( WP_MySQL_Lexer::FOREIGN_SYMBOL ) ) {
$field_identifier = $action->get_first_child_node( 'fieldIdentifier' );
$identifiers = $field_identifier->get_descendant_nodes( 'identifier' );
$name = $this->get_value( end( $identifiers ) );
$this->record_drop_foreign_key( $table_is_temporary, $table_name, $name );
continue;
}
// DROP CHECK
if ( $action->has_child_token( WP_MySQL_Lexer::CHECK_SYMBOL ) ) {
$name = $this->get_value( $action->get_first_child_node( 'identifier' ) );
$this->record_drop_check_constraint( $table_is_temporary, $table_name, $name );
continue;
}
// DROP [COLUMN]
$column_ref = $action->get_first_child_node( 'fieldIdentifier' );
if ( null !== $column_ref ) {
$name = $this->get_value( $column_ref );
$this->record_drop_column( $table_is_temporary, $table_name, $name );
continue;
}
// DROP INDEX
if ( $action->has_child_node( 'keyOrIndex' ) ) {
$name = $this->get_value( $action->get_first_child_node( 'indexRef' ) );
$this->record_drop_index_data( $table_is_temporary, $table_name, $name );
continue;
}
}
// ALTER [COLUMN]
if ( WP_MySQL_Lexer::ALTER_SYMBOL === $first_token->id ) {
// SET DEFAULT and DROP DEFAULT
$column_ref = $action->get_first_child_node( 'fieldIdentifier' );
if ( null !== $column_ref && $action->has_child_token( WP_MySQL_Lexer::DEFAULT_SYMBOL ) ) {
$name = $this->get_value( $column_ref );
$this->record_alter_column_default( $table_is_temporary, $table_name, $name, $action );
}
}
}
}
/**
* Analyze DROP TABLE statement and record data in the information schema.
*
* @param WP_Parser_Node $node The "dropStatement" AST node with "dropTable" child.
*/
public function record_drop_table( WP_Parser_Node $node ): void {
$child_node = $node->get_first_child_node();
$has_temporary_keyword = $child_node->has_child_token( WP_MySQL_Lexer::TEMPORARY_SYMBOL );
$table_refs = $child_node->get_first_child_node( 'tableRefList' )->get_child_nodes();
foreach ( $table_refs as $table_ref ) {
$table_name = $this->get_table_name_from_node( $table_ref );
$table_is_temporary = $this->temporary_table_exists( $table_name );
/*
* DROP TEMPORARY TABLE drops only temporary tables. When there is no
* such table, there is nothing to record. The temporary information
* schema tables may not even exist yet.
*/
if ( $has_temporary_keyword && ! $table_is_temporary ) {
continue;
}
$this->delete_values(
$this->get_table_name( $table_is_temporary, 'tables' ),
array(
'table_schema' => self::SAVED_DATABASE_NAME,
'table_name' => $table_name,
)
);
$this->delete_values(
$this->get_table_name( $table_is_temporary, 'columns' ),
array(
'table_schema' => self::SAVED_DATABASE_NAME,
'table_name' => $table_name,
)
);
$this->delete_values(
$this->get_table_name( $table_is_temporary, 'statistics' ),
array(
'table_schema' => self::SAVED_DATABASE_NAME,
'table_name' => $table_name,
)
);
$this->delete_values(
$this->get_table_name( $table_is_temporary, 'table_constraints' ),
array(
'table_schema' => self::SAVED_DATABASE_NAME,
'table_name' => $table_name,
)
);
}
// @TODO: RESTRICT vs. CASCADE
}
/**
* Analyze CREATE INDEX definition and record data in the information schema.
*
* @param WP_Parser_Node $node The "createStatement" AST node with "createIndex" child.
*/
public function record_create_index( WP_Parser_Node $node ): void {
$create_index = $node->get_first_child_node( 'createIndex' );
$target = $create_index->get_first_child_node( 'createIndexTarget' );
$table_ref = $target->get_first_child_node( 'tableRef' );
$table_name = $this->get_table_name_from_node( $table_ref );
$table_is_temporary = $this->temporary_table_exists( $table_name );
$this->record_add_index( $table_is_temporary, $table_name, $create_index );
}
/**
* Analyze DROP INDEX definition and record data in the information schema.
*
* @param WP_Parser_Node $node The "dropStatement" AST node with "dropIndex" child.
*/
public function record_drop_index( WP_Parser_Node $node ): void {
$drop_index = $node->get_first_child_node( 'dropIndex' );
$table_ref = $drop_index->get_first_child_node( 'tableRef' );
$table_name = $this->get_table_name_from_node( $table_ref );
$index_name = $this->get_value( $drop_index->get_first_child_node( 'indexRef' ) );
$table_is_temporary = $this->temporary_table_exists( $table_name );
$this->record_drop_index_data( $table_is_temporary, $table_name, $index_name );
}
/**
* Get the bytes of a BINARY or VARBINARY default from a hex or bit literal.
*
* Older driver versions stored these defaults as written, so this also reads
* any other value as the bytes of a text default, for their migration.
*
* @param string $default_value A hex or bit literal, or a default stored by an older version.
* @return string The default value bytes.
*/
public static function get_binary_default_bytes( string $default_value ): string {
if ( 1 === preg_match( "/\A(?|0x([0-9a-fA-F]+)|[xX]'([0-9a-fA-F]*)')\z/", $default_value, $matches ) ) {
// MySQL pads odd-length 0x literals with a leading zero.
return hex2bin( 1 === strlen( $matches[1] ) % 2 ? '0' . $matches[1] : $matches[1] );
}
if ( 1 === preg_match( "/\A(?|0b([01]+)|[bB]'([01]*)')\z/", $default_value, $matches ) ) {
$bits = str_pad( $matches[1], (int) ceil( strlen( $matches[1] ) / 8 ) * 8, '0', STR_PAD_LEFT );
$bytes = '';
for ( $i = 0; $i < strlen( $bits ); $i += 8 ) {
$bytes .= chr( bindec( substr( $bits, $i, 8 ) ) );
}
return $bytes;
}
return $default_value;
}
/**
* Analyze ADD COLUMN definition and record data in the information schema.
*
* @param bool $table_is_temporary Whether the table is temporary.
* @param string $table_name The table name.
* @param string $column_name The column name.
* @param WP_Parser_Node $node The "columnDefinition" or "fieldDefinition" AST node.
*/
private function record_add_column(
bool $table_is_temporary,
string $table_name,
string $column_name,
WP_Parser_Node $node
): void {
$columns_table_name = $this->get_table_name( $table_is_temporary, 'columns' );
$position = $this->connection->query(
'
SELECT MAX(ordinal_position)
FROM ' . $this->connection->quote_identifier( $columns_table_name ) . '
WHERE table_schema = ?
AND table_name = ?
',
array( self::SAVED_DATABASE_NAME, $table_name )
)->fetchColumn();
$column_data = $this->extract_column_data( $table_name, $column_name, $node, (int) $position + 1 );
try {
$this->insert_values(
$this->get_table_name( $table_is_temporary, 'columns' ),
$column_data
);
} catch ( PDOException $e ) {
if ( '23000' === $e->getCode() ) {
throw WP_SQLite_Information_Schema_Exception::duplicate_column_name( $column_name );
}
throw $e;
}
$index_data = $this->extract_column_statistics_data( $table_name, $column_name, $node, true );
if ( null !== $index_data ) {
$this->insert_values(
$this->get_table_name( $table_is_temporary, 'statistics' ),
$index_data
);
}
$constraint_data = $this->extract_table_constraint_data(
$node,
$table_name,
$index_data['index_name'] ?? null
);
if ( null !== $constraint_data ) {
$this->insert_values(
$this->get_table_name( $table_is_temporary, 'table_constraints' ),
$constraint_data
);
}
}
/**
* Analyze CHANGE COLUMN definition and record data in the information schema.
*
* @param bool $table_is_temporary Whether the table is temporary.
* @param string $table_name The table name.
* @param string $column_name The column name.
* @param string $new_column_name The new column name when the column is renamed.
* @param WP_Parser_Node $node The "fieldDefinition" AST node.
*/
private function record_change_column(
bool $table_is_temporary,
string $table_name,
string $column_name,
string $new_column_name,
WP_Parser_Node $node
): void {
$column_data = $this->extract_column_data( $table_name, $new_column_name, $node, 0 );
unset( $column_data['ordinal_position'] );
$this->update_values(
$this->get_table_name( $table_is_temporary, 'columns' ),
$column_data,
array(
'table_schema' => self::SAVED_DATABASE_NAME,
'table_name' => $table_name,
'column_name' => $column_name,
)
);
// Update column name in statistics, if it has changed.
if ( $new_column_name !== $column_name ) {
$this->update_values(
$this->get_table_name( $table_is_temporary, 'statistics' ),
array(
'column_name' => $new_column_name,