-
Notifications
You must be signed in to change notification settings - Fork 893
/
Copy pathSQLiteAdapter.php
2004 lines (1732 loc) · 67.9 KB
/
SQLiteAdapter.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
declare(strict_types=1);
/**
* MIT License
* For full license information, please view the LICENSE file that was distributed with this source code.
*/
namespace Phinx\Db\Adapter;
use BadMethodCallException;
use Cake\Database\Connection;
use Cake\Database\Driver\Sqlite as SqliteDriver;
use InvalidArgumentException;
use PDO;
use PDOException;
use Phinx\Db\Table\Column;
use Phinx\Db\Table\ForeignKey;
use Phinx\Db\Table\Index;
use Phinx\Db\Table\Table;
use Phinx\Db\Util\AlterInstructions;
use Phinx\Util\Expression;
use Phinx\Util\Literal;
use RuntimeException;
use const FILTER_VALIDATE_BOOLEAN;
/**
* Phinx SQLite Adapter.
*/
class SQLiteAdapter extends PdoAdapter
{
public const MEMORY = ':memory:';
public const DEFAULT_SUFFIX = '.sqlite3';
/**
* List of supported Phinx column types with their SQL equivalents
* some types have an affinity appended to ensure they do not receive NUMERIC affinity
*
* @var string[]
*/
protected static array $supportedColumnTypes = [
self::PHINX_TYPE_BIG_INTEGER => 'biginteger',
self::PHINX_TYPE_BINARY => 'binary_blob',
self::PHINX_TYPE_BINARYUUID => 'uuid_blob',
self::PHINX_TYPE_BLOB => 'blob',
self::PHINX_TYPE_BOOLEAN => 'boolean_integer',
self::PHINX_TYPE_CHAR => 'char',
self::PHINX_TYPE_DATE => 'date_text',
self::PHINX_TYPE_DATETIME => 'datetime_text',
self::PHINX_TYPE_DECIMAL => 'decimal',
self::PHINX_TYPE_DOUBLE => 'double',
self::PHINX_TYPE_FLOAT => 'float',
self::PHINX_TYPE_INTEGER => 'integer',
self::PHINX_TYPE_JSON => 'json_text',
self::PHINX_TYPE_JSONB => 'jsonb_text',
self::PHINX_TYPE_SMALL_INTEGER => 'smallinteger',
self::PHINX_TYPE_STRING => 'varchar',
self::PHINX_TYPE_TEXT => 'text',
self::PHINX_TYPE_TIME => 'time_text',
self::PHINX_TYPE_TIMESTAMP => 'timestamp_text',
self::PHINX_TYPE_TINY_INTEGER => 'tinyinteger',
self::PHINX_TYPE_UUID => 'uuid_text',
self::PHINX_TYPE_VARBINARY => 'varbinary_blob',
];
/**
* List of aliases of supported column types
*
* @var string[]
*/
protected static array $supportedColumnTypeAliases = [
'varchar' => self::PHINX_TYPE_STRING,
'tinyint' => self::PHINX_TYPE_TINY_INTEGER,
'tinyinteger' => self::PHINX_TYPE_TINY_INTEGER,
'smallint' => self::PHINX_TYPE_SMALL_INTEGER,
'int' => self::PHINX_TYPE_INTEGER,
'mediumint' => self::PHINX_TYPE_INTEGER,
'mediuminteger' => self::PHINX_TYPE_INTEGER,
'bigint' => self::PHINX_TYPE_BIG_INTEGER,
'tinytext' => self::PHINX_TYPE_TEXT,
'mediumtext' => self::PHINX_TYPE_TEXT,
'longtext' => self::PHINX_TYPE_TEXT,
'tinyblob' => self::PHINX_TYPE_BLOB,
'mediumblob' => self::PHINX_TYPE_BLOB,
'longblob' => self::PHINX_TYPE_BLOB,
'real' => self::PHINX_TYPE_FLOAT,
];
/**
* List of known but unsupported Phinx column types
*
* @var string[]
*/
protected static array $unsupportedColumnTypes = [
self::PHINX_TYPE_BIT,
self::PHINX_TYPE_CIDR,
self::PHINX_TYPE_ENUM,
self::PHINX_TYPE_FILESTREAM,
self::PHINX_TYPE_GEOMETRY,
self::PHINX_TYPE_INET,
self::PHINX_TYPE_INTERVAL,
self::PHINX_TYPE_LINESTRING,
self::PHINX_TYPE_MACADDR,
self::PHINX_TYPE_POINT,
self::PHINX_TYPE_POLYGON,
self::PHINX_TYPE_SET,
];
/**
* @var string[]
*/
protected array $definitionsWithLimits = [
'CHAR',
'CHARACTER',
'VARCHAR',
'VARYING CHARACTER',
'NCHAR',
'NATIVE CHARACTER',
'NVARCHAR',
];
/**
* @var string
*/
protected string $suffix = self::DEFAULT_SUFFIX;
/**
* Indicates whether the database library version is at least the specified version
*
* @param string $ver The version to check against e.g. '3.28.0'
* @return bool
*/
public function databaseVersionAtLeast(string $ver): bool
{
$actual = $this->query('SELECT sqlite_version()')->fetchColumn();
return version_compare($actual, $ver, '>=');
}
/**
* {@inheritDoc}
*
* @throws \RuntimeException
* @throws \InvalidArgumentException
* @return void
*/
public function connect(): void
{
if ($this->connection === null) {
if (!class_exists('PDO') || !in_array('sqlite', PDO::getAvailableDrivers(), true)) {
// @codeCoverageIgnoreStart
throw new RuntimeException('You need to enable the PDO_SQLITE extension for Phinx to run properly.');
// @codeCoverageIgnoreEnd
}
$options = $this->getOptions();
if (PHP_VERSION_ID < 80100 && (!empty($options['mode']) || !empty($options['cache']))) {
throw new RuntimeException('SQLite URI support requires PHP 8.1.');
} elseif ((!empty($options['mode']) || !empty($options['cache'])) && !empty($options['memory'])) {
throw new RuntimeException('Memory must not be set when cache or mode are.');
} elseif (PHP_VERSION_ID >= 80100 && (!empty($options['mode']) || !empty($options['cache']))) {
$params = [];
if (!empty($options['cache'])) {
$params[] = 'cache=' . $options['cache'];
}
if (!empty($options['mode'])) {
$params[] = 'mode=' . $options['mode'];
}
$dsn = 'sqlite:file:' . ($options['name'] ?? '') . '?' . implode('&', $params);
} else {
// use a memory database if the option was specified
if (!empty($options['memory']) || $options['name'] === static::MEMORY) {
$dsn = 'sqlite:' . static::MEMORY;
} else {
$dsn = 'sqlite:' . $options['name'] . $this->suffix;
}
}
$driverOptions = [];
// use custom data fetch mode
if (!empty($options['fetch_mode'])) {
$driverOptions[PDO::ATTR_DEFAULT_FETCH_MODE] = constant('\PDO::FETCH_' . strtoupper($options['fetch_mode']));
}
// pass \PDO::ATTR_PERSISTENT to driver options instead of useless setting it after instantiation
if (isset($options['attr_persistent'])) {
$driverOptions[PDO::ATTR_PERSISTENT] = $options['attr_persistent'];
}
$db = $this->createPdoConnection($dsn, null, null, $driverOptions);
$this->setConnection($db);
}
}
/**
* Get the suffix to use for the SQLite database file.
*
* @param array $options Environment options
* @return string
*/
public static function getSuffix(array $options): string
{
if ($options['name'] === self::MEMORY) {
return '';
}
$suffix = self::DEFAULT_SUFFIX;
if (isset($options['suffix'])) {
$suffix = $options['suffix'];
}
//don't "fix" the file extension if it is blank, some people
//might want a SQLITE db file with absolutely no extension.
if ($suffix !== '' && strpos($suffix, '.') !== 0) {
$suffix = '.' . $suffix;
}
return $suffix;
}
/**
* @inheritDoc
*/
public function setOptions(array $options): AdapterInterface
{
parent::setOptions($options);
$this->suffix = self::getSuffix($options);
return $this;
}
/**
* @inheritDoc
*/
public function disconnect(): void
{
$this->connection = null;
}
/**
* @inheritDoc
*/
public function hasTransactions(): bool
{
return true;
}
/**
* @inheritDoc
*/
public function beginTransaction(): void
{
$this->getConnection()->beginTransaction();
}
/**
* @inheritDoc
*/
public function commitTransaction(): void
{
$this->getConnection()->commit();
}
/**
* @inheritDoc
*/
public function rollbackTransaction(): void
{
$this->getConnection()->rollBack();
}
/**
* @inheritDoc
*/
public function quoteTableName($tableName): string
{
return str_replace('.', '`.`', $this->quoteColumnName($tableName));
}
/**
* @inheritDoc
*/
public function quoteColumnName($columnName): string
{
return '`' . str_replace('`', '``', $columnName) . '`';
}
/**
* Generates a regular expression to match identifiers that may or
* may not be quoted with any of the supported quotes.
*
* @param string $identifier The identifier to match.
* @param bool $spacedNoQuotes Whether the non-quoted identifier requires to be surrounded by whitespace.
* @return string
*/
protected function possiblyQuotedIdentifierRegex(string $identifier, bool $spacedNoQuotes = true): string
{
$identifiers = [];
$identifier = preg_quote($identifier, '/');
$hasTick = str_contains($identifier, '`');
$hasDoubleQuote = str_contains($identifier, '"');
$hasSingleQuote = str_contains($identifier, "'");
$identifiers[] = '\[' . $identifier . '\]';
$identifiers[] = '`' . ($hasTick ? str_replace('`', '``', $identifier) : $identifier) . '`';
$identifiers[] = '"' . ($hasDoubleQuote ? str_replace('"', '""', $identifier) : $identifier) . '"';
$identifiers[] = "'" . ($hasSingleQuote ? str_replace("'", "''", $identifier) : $identifier) . "'";
if (!$hasTick && !$hasDoubleQuote && !$hasSingleQuote) {
if ($spacedNoQuotes) {
$identifiers[] = "\s+$identifier\s+";
} else {
$identifiers[] = $identifier;
}
}
return '(' . implode('|', $identifiers) . ')';
}
/**
* @param string $tableName Table name
* @param bool $quoted Whether to return the schema name and table name escaped and quoted. If quoted, the schema (if any) will also be appended with a dot
* @return array
*/
protected function getSchemaName(string $tableName, bool $quoted = false): array
{
if (preg_match("/.\.([^\.]+)$/", $tableName, $match)) {
$table = $match[1];
$schema = substr($tableName, 0, strlen($tableName) - strlen($match[0]) + 1);
$result = ['schema' => $schema, 'table' => $table];
} else {
$result = ['schema' => '', 'table' => $tableName];
}
if ($quoted) {
$result['schema'] = $result['schema'] !== '' ? $this->quoteColumnName($result['schema']) . '.' : '';
$result['table'] = $this->quoteColumnName($result['table']);
}
return $result;
}
/**
* Retrieves information about a given table from one of the SQLite pragmas
*
* @param string $tableName The table to query
* @param string $pragma The pragma to query
* @return array
*/
protected function getTableInfo(string $tableName, string $pragma = 'table_info'): array
{
$info = $this->getSchemaName($tableName, true);
return $this->fetchAll(sprintf('PRAGMA %s%s(%s)', $info['schema'], $pragma, $info['table']));
}
/**
* Searches through all available schemata to find a table and returns an array
* containing the bare schema name and whether the table exists at all.
* If no schema was specified and the table does not exist the "main" schema is returned
*
* @param string $tableName The name of the table to find
* @return array
*/
protected function resolveTable(string $tableName): array
{
$info = $this->getSchemaName($tableName);
if ($info['schema'] === '') {
// if no schema is specified we search all schemata
$rows = $this->fetchAll('PRAGMA database_list;');
// the temp schema is always first to be searched
$schemata = ['temp'];
foreach ($rows as $row) {
if (strtolower($row['name']) !== 'temp') {
$schemata[] = $row['name'];
}
}
$defaultSchema = 'main';
} else {
// otherwise we search just the specified schema
$schemata = (array)$info['schema'];
$defaultSchema = $info['schema'];
}
$table = strtolower($info['table']);
foreach ($schemata as $schema) {
if (strtolower($schema) === 'temp') {
$master = 'sqlite_temp_master';
} else {
$master = sprintf('%s.%s', $this->quoteColumnName($schema), 'sqlite_master');
}
try {
$rows = $this->fetchAll(sprintf("SELECT name FROM %s WHERE type='table' AND lower(name) = %s", $master, $this->quoteString($table)));
} catch (PDOException $e) {
// an exception can occur if the schema part of the table refers to a database which is not attached
break;
}
// this somewhat pedantic check with strtolower is performed because the SQL lower function may be redefined,
// and can act on all Unicode characters if the ICU extension is loaded, while SQL identifiers are only case-insensitive for ASCII
foreach ($rows as $row) {
if (strtolower($row['name']) === $table) {
return ['schema' => $schema, 'table' => $row['name'], 'exists' => true];
}
}
}
return ['schema' => $defaultSchema, 'table' => $info['table'], 'exists' => false];
}
/**
* @inheritDoc
*/
public function hasTable(string $tableName): bool
{
return $this->hasCreatedTable($tableName) || $this->resolveTable($tableName)['exists'];
}
/**
* @inheritDoc
*/
public function createTable(Table $table, array $columns = [], array $indexes = []): void
{
// Add the default primary key
$options = $table->getOptions();
if (!isset($options['id']) || (isset($options['id']) && $options['id'] === true)) {
$options['id'] = 'id';
}
if (isset($options['id']) && is_string($options['id'])) {
// Handle id => "field_name" to support AUTO_INCREMENT
$column = new Column();
$column->setName($options['id'])
->setType('integer')
->setOptions(['identity' => true]);
array_unshift($columns, $column);
}
$sql = 'CREATE TABLE ';
$sql .= $this->quoteTableName($table->getName()) . ' (';
if (isset($options['primary_key'])) {
$options['primary_key'] = (array)$options['primary_key'];
}
foreach ($columns as $column) {
$sql .= $this->quoteColumnName($column->getName()) . ' ' . $this->getColumnSqlDefinition($column) . ', ';
if (isset($options['primary_key']) && $column->getIdentity()) {
//remove column from the primary key array as it is already defined as an autoincrement
//primary id
$identityColumnIndex = array_search($column->getName(), $options['primary_key'], true);
if ($identityColumnIndex !== false) {
unset($options['primary_key'][$identityColumnIndex]);
if (empty($options['primary_key'])) {
//The last primary key has been removed
unset($options['primary_key']);
}
}
}
}
// set the primary key(s)
if (isset($options['primary_key'])) {
$sql = rtrim($sql);
$sql .= ' PRIMARY KEY (';
if (is_array($options['primary_key'])) { // handle primary_key => array('tag_id', 'resource_id')
$sql .= implode(',', array_map([$this, 'quoteColumnName'], $options['primary_key']));
}
$sql .= ')';
} else {
$sql = substr(rtrim($sql), 0, -1); // no primary keys
}
$sql = rtrim($sql) . ');';
// execute the sql
$this->execute($sql);
foreach ($indexes as $index) {
$this->addIndex($table, $index);
}
$this->addCreatedTable($table->getName());
}
/**
* {@inheritDoc}
*
* @throws \InvalidArgumentException
*/
protected function getChangePrimaryKeyInstructions(Table $table, $newColumns): AlterInstructions
{
$instructions = new AlterInstructions();
// Drop the existing primary key
$primaryKey = $this->getPrimaryKey($table->getName());
if (!empty($primaryKey)) {
$instructions->merge(
// FIXME: array access is a hack to make this incomplete implementation work with a correct getPrimaryKey implementation
$this->getDropPrimaryKeyInstructions($table, $primaryKey[0])
);
}
// Add the primary key(s)
if (!empty($newColumns)) {
if (!is_string($newColumns)) {
throw new InvalidArgumentException(sprintf(
'Invalid value for primary key: %s',
json_encode($newColumns)
));
}
$instructions->merge(
$this->getAddPrimaryKeyInstructions($table, $newColumns)
);
}
return $instructions;
}
/**
* {@inheritDoc}
*
* SQLiteAdapter does not implement this functionality, and so will always throw an exception if used.
*
* @throws \BadMethodCallException
*/
protected function getChangeCommentInstructions(Table $table, $newComment): AlterInstructions
{
throw new BadMethodCallException('SQLite does not have table comments');
}
/**
* @inheritDoc
*/
protected function getRenameTableInstructions(string $tableName, string $newTableName): AlterInstructions
{
$this->updateCreatedTableName($tableName, $newTableName);
$sql = sprintf(
'ALTER TABLE %s RENAME TO %s',
$this->quoteTableName($tableName),
$this->quoteTableName($newTableName)
);
return new AlterInstructions([], [$sql]);
}
/**
* @inheritDoc
*/
protected function getDropTableInstructions(string $tableName): AlterInstructions
{
$this->removeCreatedTable($tableName);
$sql = sprintf('DROP TABLE %s', $this->quoteTableName($tableName));
return new AlterInstructions([], [$sql]);
}
/**
* @inheritDoc
*/
public function truncateTable(string $tableName): void
{
$info = $this->resolveTable($tableName);
// first try deleting the rows
$this->execute(sprintf(
'DELETE FROM %s.%s',
$this->quoteColumnName($info['schema']),
$this->quoteColumnName($info['table'])
));
// assuming no error occurred, reset the autoincrement (if any)
if ($this->hasTable($info['schema'] . '.sqlite_sequence')) {
$this->execute(sprintf(
'DELETE FROM %s.%s where name = %s',
$this->quoteColumnName($info['schema']),
'sqlite_sequence',
$this->quoteString($info['table'])
));
}
}
/**
* Parses a default-value expression to yield either a Literal representing
* a string value, a string representing an expression, or some other scalar
*
* @param mixed $default The default-value expression to interpret
* @param string $columnType The Phinx type of the column
* @return mixed
*/
protected function parseDefaultValue(mixed $default, string $columnType): mixed
{
if ($default === null) {
return null;
}
// split the input into tokens
$trimChars = " \t\n\r\0\x0B";
$pattern = <<<PCRE_PATTERN
/
'(?:[^']|'')*'| # String literal
"(?:[^"]|"")*"| # Standard identifier
`(?:[^`]|``)*`| # MySQL identifier
\[[^\]]*\]| # SQL Server identifier
--[^\r\n]*| # Single-line comment
\/\*(?:\*(?!\/)|[^\*])*\*\/| # Multi-line comment
[^\/\-]+| # Non-special characters
. # Any other single character
/sx
PCRE_PATTERN;
preg_match_all($pattern, $default, $matches);
// strip out any comment tokens
$matches = array_map(function ($v) {
return preg_match('/^(?:\/\*|--)/', $v) ? ' ' : $v;
}, $matches[0]);
// reconstitute the string, trimming whitespace as well as parentheses
$defaultClean = trim(implode('', $matches));
$defaultBare = rtrim(ltrim($defaultClean, $trimChars . '('), $trimChars . ')');
// match the string against one of several patterns
if (preg_match('/^CURRENT_(?:DATE|TIME|TIMESTAMP)$/i', $defaultBare)) {
// magic date or time
return strtoupper($defaultBare);
} elseif (preg_match('/^\'(?:[^\']|\'\')*\'$/i', $defaultBare)) {
// string literal
$str = str_replace("''", "'", substr($defaultBare, 1, strlen($defaultBare) - 2));
return Literal::from($str);
} elseif (preg_match('/^[+-]?\d+$/i', $defaultBare)) {
$int = (int)$defaultBare;
// integer literal
if ($columnType === self::PHINX_TYPE_BOOLEAN && ($int === 0 || $int === 1)) {
return (bool)$int;
} else {
return $int;
}
} elseif (preg_match('/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i', $defaultBare)) {
// float literal
return (float)$defaultBare;
} elseif (preg_match('/^0x[0-9a-f]+$/i', $defaultBare)) {
// hexadecimal literal
return hexdec(substr($defaultBare, 2));
} elseif (preg_match('/^null$/i', $defaultBare)) {
// null literal
return null;
} elseif (preg_match('/^true|false$/i', $defaultBare)) {
// boolean literal
return filter_var($defaultClean, FILTER_VALIDATE_BOOLEAN);
} else {
// any other expression: return the expression with parentheses, but without comments
return Expression::from($defaultClean);
}
}
/**
* Returns the name of the specified table's identity column, or null if the table has no identity
*
* The process of finding an identity column is somewhat convoluted as SQLite has no direct way of querying whether a given column is an alias for the table's row ID
*
* @param string $tableName The name of the table
* @return string|null
*/
protected function resolveIdentity(string $tableName): ?string
{
$result = null;
// make sure the table has only one primary key column which is of type integer
foreach ($this->getTableInfo($tableName) as $col) {
$type = strtolower($col['type']);
if ($col['pk'] > 1) {
// the table has a composite primary key
return null;
} elseif ($col['pk'] == 0) {
// the column is not a primary key column and is thus not relevant
continue;
} elseif ($type !== 'integer') {
// if the primary key's type is not exactly INTEGER, it cannot be a row ID alias
return null;
} else {
// the column is a candidate for a row ID alias
$result = $col['name'];
}
}
// if there is no suitable PK column, stop now
if ($result === null) {
return null;
}
// make sure the table does not have a PK-origin autoindex
// such an autoindex would indicate either that the primary key was specified as descending, or that this is a WITHOUT ROWID table
foreach ($this->getTableInfo($tableName, 'index_list') as $idx) {
if ($idx['origin'] === 'pk') {
return null;
}
}
return $result;
}
/**
* @inheritDoc
*/
public function getColumns(string $tableName): array
{
$columns = [];
$rows = $this->getTableInfo($tableName);
$identity = $this->resolveIdentity($tableName);
foreach ($rows as $columnInfo) {
$column = new Column();
$type = $this->getPhinxType($columnInfo['type']);
$default = $this->parseDefaultValue($columnInfo['dflt_value'], $type['name']);
$column->setName($columnInfo['name'])
// SQLite on PHP 8.1 returns int for notnull, older versions return a string
->setNull((int)$columnInfo['notnull'] !== 1)
->setDefault($default)
->setType($type['name'])
->setLimit($type['limit'])
->setScale($type['scale'])
->setIdentity($columnInfo['name'] === $identity);
$columns[] = $column;
}
return $columns;
}
/**
* @inheritDoc
*/
public function hasColumn(string $tableName, string $columnName): bool
{
$rows = $this->getTableInfo($tableName);
foreach ($rows as $column) {
if (strcasecmp($column['name'], $columnName) === 0) {
return true;
}
}
return false;
}
/**
* @inheritDoc
*/
protected function getAddColumnInstructions(Table $table, Column $column): AlterInstructions
{
$tableName = $table->getName();
$instructions = $this->beginAlterByCopyTable($tableName);
$instructions->addPostStep(function ($state) use ($tableName, $column) {
// we use the final column to anchor our regex to insert the new column,
// as the alternative is unwinding all possible table constraints which
// gets messy quickly with CHECK constraints.
$columns = $this->getColumns($tableName);
if (!$columns) {
return $state;
}
$finalColumnName = end($columns)->getName();
$sql = preg_replace(
sprintf(
"/(%s(?:\/\*.*?\*\/|\([^)]+\)|'[^']*?'|[^,])+)([,)])/",
$this->quoteColumnName($finalColumnName)
),
sprintf(
'$1, %s %s$2',
$this->quoteColumnName($column->getName()),
$this->getColumnSqlDefinition($column)
),
$state['createSQL'],
1
);
$this->execute($sql);
return $state;
});
$instructions->addPostStep(function ($state) use ($tableName) {
$newState = $this->calculateNewTableColumns($tableName, false, false);
return $newState + $state;
});
return $this->endAlterByCopyTable($instructions, $tableName);
}
/**
* Returns the original CREATE statement for the give table
*
* @param string $tableName The table name to get the create statement for
* @return string
*/
protected function getDeclaringSql(string $tableName): string
{
$rows = $this->fetchAll("SELECT * FROM sqlite_master WHERE `type` = 'table'");
$sql = '';
foreach ($rows as $table) {
if ($table['tbl_name'] === $tableName) {
$sql = $table['sql'];
}
}
$columnsInfo = $this->getTableInfo($tableName);
foreach ($columnsInfo as $column) {
$columnName = preg_quote($column['name'], '#');
$columnNamePattern = "\"$columnName\"|`$columnName`|\\[$columnName\\]|$columnName";
$columnNamePattern = "#([\(,]+\\s*)($columnNamePattern)(\\s)#iU";
$sql = preg_replace($columnNamePattern, "$1`{$column['name']}`$3", $sql);
}
$tableNamePattern = "\"$tableName\"|`$tableName`|\\[$tableName\\]|$tableName";
$tableNamePattern = "#^(CREATE TABLE)\s*($tableNamePattern)\s*(\()#Ui";
$sql = preg_replace($tableNamePattern, "$1 `$tableName` $3", $sql, 1);
return $sql;
}
/**
* Returns the original CREATE statement for the give index
*
* @param string $tableName The table name to get the create statement for
* @param string $indexName The table index
* @return string
*/
protected function getDeclaringIndexSql(string $tableName, string $indexName): string
{
$rows = $this->fetchAll("SELECT * FROM sqlite_master WHERE `type` = 'index'");
$sql = '';
foreach ($rows as $table) {
if ($table['tbl_name'] === $tableName && $table['name'] === $indexName) {
$sql = $table['sql'] . '; ';
}
}
return $sql;
}
/**
* Obtains index and trigger information for a table.
*
* They will be stored in the state as arrays under the `indices` and `triggers`
* keys accordingly.
*
* Index columns defined as expressions, as for example in `ON (ABS(id), other)`,
* will appear as `null`, so for the given example the columns for the index would
* look like `[null, 'other']`.
*
* @param \Phinx\Db\Util\AlterInstructions $instructions The instructions to modify
* @param string $tableName The name of table being processed
* @return \Phinx\Db\Util\AlterInstructions
*/
protected function bufferIndicesAndTriggers(AlterInstructions $instructions, string $tableName): AlterInstructions
{
$instructions->addPostStep(function (array $state) use ($tableName): array {
$state['indices'] = [];
$state['triggers'] = [];
$rows = $this->fetchAll(
sprintf(
"
SELECT *
FROM sqlite_master
WHERE
(`type` = 'index' OR `type` = 'trigger')
AND tbl_name = %s
AND sql IS NOT NULL
",
$this->quoteValue($tableName)
)
);
$schema = $this->getSchemaName($tableName, true)['schema'];
foreach ($rows as $row) {
switch ($row['type']) {
case 'index':
$info = $this->fetchAll(
sprintf('PRAGMA %sindex_info(%s)', $schema, $this->quoteValue($row['name']))
);
$columns = array_map(
function ($column) {
if ($column === null) {
return null;
}
return strtolower($column);
},
array_column($info, 'name')
);
$hasExpressions = in_array(null, $columns, true);
$index = [
'columns' => $columns,
'hasExpressions' => $hasExpressions,
];
$state['indices'][] = $index + $row;
break;
case 'trigger':
$state['triggers'][] = $row;
break;
}
}
return $state;
});
return $instructions;
}
/**
* Filters out indices that reference a removed column.
*
* @param \Phinx\Db\Util\AlterInstructions $instructions The instructions to modify
* @param string $columnName The name of the removed column
* @return \Phinx\Db\Util\AlterInstructions
*/
protected function filterIndicesForRemovedColumn(
AlterInstructions $instructions,
string $columnName
): AlterInstructions {
$instructions->addPostStep(function (array $state) use ($columnName): array {
foreach ($state['indices'] as $key => $index) {
if (
!$index['hasExpressions'] &&
in_array(strtolower($columnName), $index['columns'], true)
) {
unset($state['indices'][$key]);
}
}
return $state;
});
return $instructions;
}
/**
* Updates indices that reference a renamed column.
*
* @param \Phinx\Db\Util\AlterInstructions $instructions The instructions to modify
* @param string $oldColumnName The old column name
* @param string $newColumnName The new column name
* @return \Phinx\Db\Util\AlterInstructions
*/
protected function updateIndicesForRenamedColumn(
AlterInstructions $instructions,
string $oldColumnName,
string $newColumnName
): AlterInstructions {
$instructions->addPostStep(function (array $state) use ($oldColumnName, $newColumnName): array {
foreach ($state['indices'] as $key => $index) {
if (
!$index['hasExpressions'] &&
in_array(strtolower($oldColumnName), $index['columns'], true)
) {
$pattern = '
/
(INDEX.+?ON\s.+?)
(\(\s*|,\s*) # opening parenthesis or comma
(?:`|"|\[)? # optional opening quote
(%s) # column name
(?:`|"|\])? # optional closing quote
(\s+COLLATE\s+.+?)? # optional collation
(\s+(?:ASC|DESC))? # optional order
(\s*,|\s*\)) # comma or closing parenthesis
/isx';
$newColumnName = $this->quoteColumnName($newColumnName);
$state['indices'][$key]['sql'] = preg_replace(
sprintf($pattern, preg_quote($oldColumnName, '/')),
"\\1\\2$newColumnName\\4\\5\\6",
$index['sql']
);
}
}
return $state;
});
return $instructions;
}
/**
* Recreates indices and triggers.
*
* @param \Phinx\Db\Util\AlterInstructions $instructions The instructions to process