-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathSQLite.php
More file actions
3394 lines (2950 loc) · 117 KB
/
SQLite.php
File metadata and controls
3394 lines (2950 loc) · 117 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
namespace Utopia\Database\Adapter;
use Exception;
use PDO;
use PDOException;
use Swoole\Database\PDOStatementProxy;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Exception as DatabaseException;
use Utopia\Database\Exception\Duplicate as DuplicateException;
use Utopia\Database\Exception\Limit as LimitException;
use Utopia\Database\Exception\NotFound as NotFoundException;
use Utopia\Database\Exception\Operator as OperatorException;
use Utopia\Database\Exception\Timeout as TimeoutException;
use Utopia\Database\Exception\Transaction as TransactionException;
use Utopia\Database\Exception\Truncate as TruncateException;
use Utopia\Database\Helpers\ID;
use Utopia\Database\Operator;
use Utopia\Database\Query;
/**
* Main differences from MariaDB and MySQL:
*
* 1. No concept of a schema. All tables are in the same schema.
* 2. AUTO_INCREMENT is AUTOINCREAMENT.
* 3. Can't create indexes in the same statement as creating a table.
* 4. Can't use SET to bind values on INSERT
* 5. last_insert_id is last_insert_rowid
* 6. Can only drop one table at a time
* 7. no index length support?
* 8. DELETE doesn't support ORDER BY or LIMIT
* 9. MODIFY COLUMN is not supported
* 10. Can't rename an index directly
*/
class SQLite extends MariaDB
{
/**
* MariaDB byte ceilings for TEXT-family types, mirrored so PRAGMA-based
* introspection produces the same characterMaximumLength values that
* INFORMATION_SCHEMA.COLUMNS would on MariaDB.
*/
private const MARIADB_TEXT_BYTES = '65535';
private const MARIADB_MEDIUMTEXT_BYTES = '16777215';
private const MARIADB_LONGTEXT_BYTES = '4294967295';
/** Suffix appended to every FTS5 virtual table name created by this adapter. */
private const FTS_TABLE_SUFFIX = '_fts';
/** AFTER INSERT trigger suffix on the parent collection. */
private const FTS_TRIGGER_INSERT = 'ai';
/** AFTER DELETE trigger suffix on the parent collection. */
private const FTS_TRIGGER_DELETE = 'ad';
/** AFTER UPDATE trigger suffix on the parent collection. */
private const FTS_TRIGGER_UPDATE = 'au';
/**
* Per-collection attribute → FTS5 table memo. Populated in one pass
* so multi-attribute SEARCH batches don't issue PRAGMA per attribute.
*
* @var array<string, array<string, ?string>>
*/
private array $ftsTableCache = [];
/**
* When enabled, the adapter reports MariaDB-shaped column metadata,
* advertises MariaDB-only capabilities (upserts, attribute resizing,
* PCRE regex via the registered UDF), and declares schema-internal
* columns (e.g. `_tenant`) using MariaDB-style types so callers that
* inspect INFORMATION_SCHEMA-style results behave identically across
* both adapters. Off by default — vanilla SQLite stays vanilla.
*/
protected bool $emulateMySQL = false;
/**
* Whether the REGEXP UDF actually wired up. Pool/proxy PDOs may not
* expose sqliteCreateFunction.
*/
private bool $pcreRegistered = false;
public function __construct(mixed $pdo)
{
parent::__construct($pdo);
$this->registerUserFunctions();
}
/**
* Toggle MariaDB/MySQL emulation. See $emulateMySQL for what this
* actually changes.
*/
public function setEmulateMySQL(bool $emulate): static
{
$this->emulateMySQL = $emulate;
return $this;
}
public function getEmulateMySQL(): bool
{
return $this->emulateMySQL;
}
public function setTenant(int|string|null $tenant): bool
{
$changed = $this->tenant !== $tenant;
$result = parent::setTenant($tenant);
if ($changed) {
// Invalidate after the parent setter so a validation failure
// doesn't leave us with a cleared cache against the prior tenant.
$this->ftsTableCache = [];
}
return $result;
}
public function setNamespace(string $namespace): static
{
// Invalidate after the parent setter so a thrown validation
// doesn't leave a cleared cache against the prior namespace.
parent::setNamespace($namespace);
$this->ftsTableCache = [];
return $this;
}
public function setSharedTables(bool $sharedTables): bool
{
$changed = $this->sharedTables !== $sharedTables;
$result = parent::setSharedTables($sharedTables);
if ($changed) {
$this->ftsTableCache = [];
}
return $result;
}
/**
* Reject patterns over this size to bound ReDoS exposure — the UDF runs
* once per candidate row, so a pathological pattern is amplified by
* table cardinality.
*/
private const REGEXP_MAX_PATTERN_LENGTH = 512;
/**
* Cap on cached delimited patterns. Long-lived adapters processing many
* distinct user patterns would otherwise grow this map without bound.
*/
private const REGEXP_PATTERN_CACHE_LIMIT = 256;
/**
* Register a preg_match-backed REGEXP UDF so the inherited REGEXP
* path resolves. Best-effort — non-SQLite PDOs simply skip it.
*/
private function registerUserFunctions(): void
{
// SQLite invokes the UDF once per candidate row, so cache the
// delimited pattern across rows. FIFO-evict at REGEXP_PATTERN_CACHE_LIMIT
// entries so distinct user patterns can't grow this without bound.
$delimitedCache = [];
$pcre = static function (?string $pattern, ?string $value) use (&$delimitedCache): int {
if ($pattern === null || $value === null) {
return 0;
}
if (\strlen($pattern) > self::REGEXP_MAX_PATTERN_LENGTH) {
return 0;
}
if (!isset($delimitedCache[$pattern])) {
if (\count($delimitedCache) >= self::REGEXP_PATTERN_CACHE_LIMIT) {
\array_shift($delimitedCache);
}
// Use a delimiter unlikely to appear in user input (chr(1))
// so we don't have to escape forward-slashes the user wrote
// intentionally and risk double-escaping backslashes.
$delimitedCache[$pattern] = "\x01" . $pattern . "\x01u";
}
$delimited = $delimitedCache[$pattern];
// preg_match returns false on bad pattern / runtime error
// (e.g. PREG_BACKTRACK_LIMIT_ERROR). Silently treat those as
// no-match — REGEXP is a query predicate, not a validator.
$result = @\preg_match($delimited, $value);
return $result === 1 ? 1 : 0;
};
try {
$this->getPDO()->sqliteCreateFunction('REGEXP', $pcre, 2);
$this->pcreRegistered = true;
} catch (\Throwable) {
}
}
/**
* @inheritDoc
*
* SQLite serialises writers through a single file lock. PDO's default
* `BEGIN` is `DEFERRED`, which acquires the writer lock lazily on the
* first write — if two transactions both started as readers and try to
* promote to writer at the same time, one fails immediately with
* SQLITE_BUSY without any busy_timeout retry (a real deadlock case).
* `BEGIN IMMEDIATE` reserves the writer slot up-front so concurrent
* writers queue behind it under busy_timeout instead.
*/
public function startTransaction(): bool
{
try {
if ($this->inTransaction === 0) {
if ($this->getPDO()->inTransaction()) {
$this->getPDO()
->prepare('ROLLBACK')
->execute();
}
$result = $this->getPDO()
->prepare('BEGIN IMMEDIATE')
->execute();
} else {
$result = $this->getPDO()
->prepare('SAVEPOINT transaction' . $this->inTransaction)
->execute();
}
} catch (PDOException $e) {
throw new TransactionException('Failed to start transaction: ' . $e->getMessage(), $e->getCode(), $e);
}
if (!$result) {
throw new TransactionException('Failed to start transaction');
}
$this->inTransaction++;
return $result;
}
/**
* @inheritDoc
*
* Overrides the inherited PDO-driven commit because startTransaction
* issues a raw `BEGIN IMMEDIATE` (rather than PDO::beginTransaction),
* so PDO's internal in-transaction flag is never set and PDO::commit()
* would throw "no active transaction". Mirrors that with a raw COMMIT
* and SAVEPOINT release for nested levels.
*/
public function commitTransaction(): bool
{
if ($this->inTransaction === 0) {
return false;
}
try {
if ($this->inTransaction > 1) {
$result = $this->getPDO()
->prepare('RELEASE SAVEPOINT transaction' . ($this->inTransaction - 1))
->execute();
$this->inTransaction--;
return $result;
}
$result = $this->getPDO()
->prepare('COMMIT')
->execute();
$this->inTransaction = 0;
} catch (PDOException $e) {
throw new TransactionException('Failed to commit transaction: ' . $e->getMessage(), $e->getCode(), $e);
}
return $result;
}
/**
* @inheritDoc
*
* Counterpart to commitTransaction — uses a raw ROLLBACK for the same
* reason (raw BEGIN IMMEDIATE bypasses PDO's transaction tracking).
*/
public function rollbackTransaction(): bool
{
if ($this->inTransaction === 0) {
return false;
}
try {
if ($this->inTransaction > 1) {
$this->getPDO()
->prepare('ROLLBACK TO transaction' . ($this->inTransaction - 1))
->execute();
$this->inTransaction--;
} else {
$this->getPDO()
->prepare('ROLLBACK')
->execute();
$this->inTransaction = 0;
}
} catch (PDOException $e) {
$this->inTransaction = 0;
throw new DatabaseException('Failed to rollback transaction: ' . $e->getMessage(), $e->getCode(), $e);
}
return true;
}
/**
* Check if Database exists
* Optionally check if collection exists in Database
*
* @param string $database
* @param string|null $collection
* @return bool
* @throws DatabaseException
*/
public function exists(string $database, ?string $collection = null): bool
{
$database = $this->filter($database);
if (\is_null($collection)) {
return false;
}
$collection = $this->filter($collection);
$sql = "
SELECT name FROM sqlite_master
WHERE type='table' AND name = :table
";
$sql = $this->trigger(Database::EVENT_DATABASE_CREATE, $sql);
$stmt = $this->getPDO()->prepare($sql);
$stmt->bindValue(':table', "{$this->getNamespace()}_{$collection}", PDO::PARAM_STR);
$stmt->execute();
$document = $stmt->fetchAll();
$stmt->closeCursor();
if (!empty($document)) {
$document = $document[0];
}
return (($document['name'] ?? '') === "{$this->getNamespace()}_{$collection}");
}
/**
* Create Database
*
* @param string $name
* @return bool
* @throws Exception
* @throws PDOException
*/
public function create(string $name): bool
{
return true;
}
/**
* Delete Database
*
* @param string $name
* @return bool
* @throws Exception
* @throws PDOException
*/
public function delete(string $name): bool
{
return true;
}
/**
* Create Collection
*
* @param string $name
* @param array<Document> $attributes
* @param array<Document> $indexes
* @return bool
* @throws Exception
* @throws PDOException
*/
public function createCollection(string $name, array $attributes = [], array $indexes = []): bool
{
$id = $this->filter($name);
/** @var array<string> $attributeStrings */
$attributeStrings = [];
foreach ($attributes as $key => $attribute) {
$attrId = $this->filter($attribute->getId());
$attrType = $this->getSQLType(
$attribute->getAttribute('type'),
$attribute->getAttribute('size', 0),
$attribute->getAttribute('signed', true),
$attribute->getAttribute('array', false),
$attribute->getAttribute('required', false)
);
$attributeStrings[$key] = "`{$attrId}` {$attrType}, ";
}
// SQLite stores integers regardless of declared type, but
// testSchemaAttributes asserts the columnType reads back as
// `int(11) unsigned` to match MariaDB. Quote the declaration so
// PRAGMA table_info echoes the exact string under emulation;
// otherwise use INTEGER, the affinity-correct vanilla form.
$tenantType = $this->emulateMySQL ? '"INT(11) UNSIGNED"' : 'INTEGER';
$tenantQuery = $this->sharedTables ? "`_tenant` {$tenantType} DEFAULT NULL," : '';
$collection = "
CREATE TABLE {$this->getSQLTable($id)} (
`_id` INTEGER PRIMARY KEY AUTOINCREMENT,
`_uid` VARCHAR(36) NOT NULL,
{$tenantQuery}
`_createdAt` DATETIME(3) DEFAULT NULL,
`_updatedAt` DATETIME(3) DEFAULT NULL,
`_permissions` MEDIUMTEXT DEFAULT NULL".(!empty($attributes) ? ',' : '')."
" . \substr(\implode(' ', $attributeStrings), 0, -2) . "
)
";
$collection = $this->trigger(Database::EVENT_COLLECTION_CREATE, $collection);
$permissions = "
CREATE TABLE {$this->getSQLTable($id . '_perms')} (
`_id` INTEGER PRIMARY KEY AUTOINCREMENT,
{$tenantQuery}
`_type` VARCHAR(12) NOT NULL,
`_permission` VARCHAR(255) NOT NULL,
`_document` VARCHAR(255) NOT NULL
)
";
$permissions = $this->trigger(Database::EVENT_COLLECTION_CREATE, $permissions);
try {
$this->getPDO()
->prepare($collection)
->execute();
$this->getPDO()
->prepare($permissions)
->execute();
$this->createIndex($id, '_index1', Database::INDEX_UNIQUE, ['_uid'], [], []);
$this->createIndex($id, '_created_at', Database::INDEX_KEY, [ '_createdAt'], [], []);
$this->createIndex($id, '_updated_at', Database::INDEX_KEY, [ '_updatedAt'], [], []);
$this->createIndex("{$id}_perms", '_index_1', Database::INDEX_UNIQUE, ['_document', '_type', '_permission'], [], []);
$this->createIndex("{$id}_perms", '_index_2', Database::INDEX_KEY, ['_permission', '_type'], [], []);
if ($this->sharedTables) {
$this->createIndex($id, '_tenant_id', Database::INDEX_KEY, [ '_id'], [], []);
}
foreach ($indexes as $index) {
$indexId = $this->filter($index->getId());
$indexType = $index->getAttribute('type');
$indexAttributes = $index->getAttribute('attributes', []);
$indexLengths = $index->getAttribute('lengths', []);
$indexOrders = $index->getAttribute('orders', []);
$indexTtl = $index->getAttribute('ttl', 0);
$this->createIndex($id, $indexId, $indexType, $indexAttributes, $indexLengths, $indexOrders, [], [], $indexTtl);
}
} catch (PDOException $e) {
throw $this->processException($e);
}
return true;
}
/**
* Get Collection Size of raw data
* @param string $collection
* @return int
* @throws DatabaseException
*
*/
public function getSizeOfCollection(string $collection): int
{
$collection = $this->filter($collection);
$namespace = $this->getNamespace();
$name = $namespace . '_' . $collection;
$permissions = $namespace . '_' . $collection . '_perms';
$ftsPrefix = $this->getFulltextTablePrefix($collection);
// FTS5 storage lives in `<vtable>_data|_idx|_docsize|_config`
// shadow tables; sum (pgsize - unused) over all of them.
$ftsPattern = $this->escapeLikePattern($ftsPrefix) . '%' . $this->escapeLikePattern(self::FTS_TABLE_SUFFIX) . '%';
$stmt = $this->getPDO()->prepare("
SELECT COALESCE(SUM(\"pgsize\" - \"unused\"), 0)
FROM \"dbstat\"
WHERE name = :name OR name = :perms OR name LIKE :fts_pattern ESCAPE '\\';
");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':perms', $permissions);
$stmt->bindParam(':fts_pattern', $ftsPattern);
try {
$stmt->execute();
$size = (int) $stmt->fetchColumn();
$stmt->closeCursor();
} catch (PDOException $e) {
throw new DatabaseException('Failed to get collection size: ' . $e->getMessage());
}
return $size;
}
/**
* Get Collection Size on disk
* @param string $collection
* @return int
* @throws DatabaseException
*/
public function getSizeOfCollectionOnDisk(string $collection): int
{
return $this->getSizeOfCollection($collection);
}
/**
* Delete Collection
* @param string $id
* @return bool
* @throws Exception
* @throws PDOException
*/
public function deleteCollection(string $id): bool
{
$id = $this->filter($id);
// FTS5 shadow tables don't drop with the parent.
foreach ($this->findFulltextTables($id) as $ftsTable) {
$sql = "DROP TABLE IF EXISTS `{$ftsTable}`";
$sql = $this->trigger(Database::EVENT_COLLECTION_DELETE, $sql);
$this->getPDO()->prepare($sql)->execute();
}
$sql = "DROP TABLE IF EXISTS {$this->getSQLTable($id)}";
$sql = $this->trigger(Database::EVENT_COLLECTION_DELETE, $sql);
$this->getPDO()
->prepare($sql)
->execute();
$sql = "DROP TABLE IF EXISTS {$this->getSQLTable($id . '_perms')}";
$sql = $this->trigger(Database::EVENT_COLLECTION_DELETE, $sql);
$this->getPDO()
->prepare($sql)
->execute();
unset($this->ftsTableCache[$id]);
return true;
}
/**
* Analyze a collection updating it's metadata on the database engine
*
* @param string $collection
* @return bool
*/
public function analyzeCollection(string $collection): bool
{
return false;
}
/**
* Update Attribute
*
* @param string $collection
* @param string $id
* @param string $type
* @param int $size
* @param bool $signed
* @param bool $array
* @param string|null $newKey
* @param bool $required
* @return bool
* @throws Exception
* @throws PDOException
*/
public function updateAttribute(string $collection, string $id, string $type, int $size, bool $signed = true, bool $array = false, ?string $newKey = null, bool $required = false): bool
{
if (!empty($newKey) && $newKey !== $id) {
return $this->renameAttribute($collection, $id, $newKey);
}
// SQLite is dynamically typed — `ALTER TABLE ... MODIFY COLUMN` is
// not supported and a smaller declared size silently accepts
// larger values. Under MySQL emulation, scan the column and
// raise the same TruncateException MariaDB throws. Off-
// emulation the declared size is metadata-only, so skip the
// scan and let the rename branch (if any) handle the rest.
if ($this->emulateMySQL && $type === Database::VAR_STRING && $size > 0 && !$array) {
$name = $this->filter($collection);
$column = $this->filter($id);
// Under shared tables the underlying table is shared across
// tenants; scoping the scan by `_tenant` keeps tenant A's
// resize from being blocked (and tenant A's metadata from
// leaking) by an oversized value owned by tenant B.
$tenantClause = $this->sharedTables ? ' AND `_tenant` = :_tenant' : '';
$sql = "SELECT 1 FROM {$this->getSQLTable($name)} WHERE LENGTH(`{$column}`) > :max{$tenantClause} LIMIT 1";
$stmt = $this->getPDO()->prepare($sql);
$stmt->bindValue(':max', $size, PDO::PARAM_INT);
if ($this->sharedTables) {
$stmt->bindValue(':_tenant', $this->tenant, \is_int($this->tenant) ? PDO::PARAM_INT : PDO::PARAM_STR);
}
try {
$stmt->execute();
$exceeds = $stmt->fetchColumn() !== false;
} finally {
$stmt->closeCursor();
}
if ($exceeds) {
throw new TruncateException("Attribute '{$id}' has values exceeding new size {$size}");
}
}
return true;
}
/**
* Delete Attribute
*
* @param string $collection
* @param string $id
* @param bool $array
* @return bool
* @throws Exception
* @throws PDOException
*/
public function deleteAttribute(string $collection, string $id, bool $array = false): bool
{
$name = $this->filter($collection);
$id = $this->filter($id);
$metadataCollection = new Document(['$id' => Database::METADATA]);
$collection = $this->getDocument($metadataCollection, $name);
if ($collection->isEmpty()) {
throw new NotFoundException('Collection not found');
}
$indexes = $collection->getAttribute('indexes', []);
if (\is_string($indexes)) {
$indexes = \json_decode($indexes, true) ?? [];
}
foreach ($indexes as $index) {
$attributes = $index['attributes'];
if ($attributes === [$id]) {
$this->deleteIndex($name, $index['$id']);
} elseif (\in_array($id, $attributes)) {
$this->deleteIndex($name, $index['$id']);
$this->createIndex($name, $index['$id'], $index['type'], \array_diff($attributes, [$id]), $index['lengths'], $index['orders']);
}
}
$sql = "ALTER TABLE {$this->getSQLTable($name)} DROP COLUMN `{$id}`";
$sql = $this->trigger(Database::EVENT_COLLECTION_DELETE, $sql);
try {
return $this->getPDO()
->prepare($sql)
->execute();
} catch (PDOException $e) {
if (str_contains($e->getMessage(), 'no such column')) {
return true;
}
throw $e;
}
}
/**
* Rename Index
*
* @param string $collection
* @param string $old
* @param string $new
* @return bool
* @throws Exception
* @throws PDOException
*/
public function renameIndex(string $collection, string $old, string $new): bool
{
$metadataCollection = new Document(['$id' => Database::METADATA]);
$collection = $this->getDocument($metadataCollection, $collection);
if ($collection->isEmpty()) {
throw new NotFoundException('Collection not found');
}
$old = $this->filter($old);
$new = $this->filter($new);
$indexes = $collection->getAttribute('indexes', []);
if (\is_string($indexes)) {
$indexes = \json_decode($indexes, true) ?? [];
}
$index = null;
foreach ($indexes as $node) {
if ($node['key'] === $old) {
$index = $node;
break;
}
}
if ($index
&& $this->deleteIndex($collection->getId(), $old)
&& $this->createIndex(
$collection->getId(),
$new,
$index['type'],
$index['attributes'],
$index['lengths'],
$index['orders'],
)) {
return true;
}
return false;
}
/**
* Create Index
*
* @param string $collection
* @param string $id
* @param string $type
* @param array<string> $attributes
* @param array<int> $lengths
* @param array<string> $orders
* @param array<string,string> $indexAttributeTypes
* @return bool
* @throws Exception
* @throws PDOException
*/
public function createIndex(string $collection, string $id, string $type, array $attributes, array $lengths, array $orders, array $indexAttributeTypes = [], array $collation = [], int $ttl = 1): bool
{
$name = $this->filter($collection);
$id = $this->filter($id);
if ($type === Database::INDEX_FULLTEXT) {
return $this->createFulltextIndex($name, $id, $attributes);
}
// Workaround for no support for CREATE INDEX IF NOT EXISTS
$stmt = $this->getPDO()->prepare("
SELECT name
FROM sqlite_master
WHERE type='index' AND name=:_index;
");
$stmt->bindValue(':_index', "{$this->getNamespace()}_{$this->getTenantSegment()}_{$name}_{$id}");
$stmt->execute();
$index = $stmt->fetch();
if (!empty($index)) {
return true;
}
$sql = $this->getSQLIndex($name, $id, $type, $attributes);
$sql = $this->trigger(Database::EVENT_INDEX_CREATE, $sql);
return $this->getPDO()
->prepare($sql)
->execute();
}
/**
* Create an FTS5 virtual table mirroring `$attributes` and the triggers
* that keep it in sync with the parent collection.
*
* @param array<string> $attributes
* @throws PDOException
*/
protected function createFulltextIndex(string $collection, string $id, array $attributes): bool
{
if (empty($attributes)) {
throw new DatabaseException('Fulltext index requires at least one attribute');
}
$attributes = \array_map(fn (string $a) => $this->getInternalKeyForAttribute($a), $attributes);
$ftsTable = $this->getFulltextTableName($collection, $attributes);
$parentTable = "{$this->getNamespace()}_{$collection}";
$stmt = $this->getPDO()->prepare("
SELECT name
FROM sqlite_master
WHERE type='table' AND name=:_table;
");
$stmt->bindValue(':_table', $ftsTable);
$stmt->execute();
$exists = !empty($stmt->fetch());
$stmt->closeCursor();
if ($exists) {
return true;
}
$columns = \array_map(fn (string $attr) => $this->filter($attr), $attributes);
$ftsColumnList = \implode(', ', $columns);
$columnList = \implode(', ', \array_map(fn (string $c) => "`{$c}`", $columns));
$newColumnList = \implode(', ', \array_map(fn (string $c) => "NEW.`{$c}`", $columns));
$oldColumnList = \implode(', ', \array_map(fn (string $c) => "OLD.`{$c}`", $columns));
// Under shared tables every tenant has a distinct FTS vtable but the
// parent table is shared, so triggers must filter by `_tenant`
// literal — otherwise tenant A's vtable accumulates tenant B's
// tokenized content. The same applies to the initial backfill.
$tenantLiteral = $this->sharedTables ? $this->getTenantSqlLiteral() : null;
$insertWhen = $tenantLiteral !== null ? " WHEN NEW.`_tenant` IS {$tenantLiteral}" : '';
$deleteWhen = $tenantLiteral !== null ? " WHEN OLD.`_tenant` IS {$tenantLiteral}" : '';
$updateWhen = $tenantLiteral !== null
? " WHEN OLD.`_tenant` IS {$tenantLiteral} OR NEW.`_tenant` IS {$tenantLiteral}"
: '';
$backfillWhere = $tenantLiteral !== null ? " WHERE `_tenant` IS {$tenantLiteral}" : '';
$this->startTransaction();
try {
$createSql = "CREATE VIRTUAL TABLE `{$ftsTable}` USING fts5({$ftsColumnList}, content=\"{$parentTable}\", content_rowid=\"_id\")";
$createSql = $this->trigger(Database::EVENT_INDEX_CREATE, $createSql);
$this->getPDO()->prepare($createSql)->execute();
$insertSuffix = self::FTS_TRIGGER_INSERT;
$insertTrigger = "
CREATE TRIGGER `{$ftsTable}_{$insertSuffix}` AFTER INSERT ON `{$parentTable}`{$insertWhen} BEGIN
INSERT INTO `{$ftsTable}` (rowid, {$columnList}) VALUES (NEW.`_id`, {$newColumnList});
END
";
$this->getPDO()->prepare($insertTrigger)->execute();
$deleteSuffix = self::FTS_TRIGGER_DELETE;
$deleteTrigger = "
CREATE TRIGGER `{$ftsTable}_{$deleteSuffix}` AFTER DELETE ON `{$parentTable}`{$deleteWhen} BEGIN
INSERT INTO `{$ftsTable}` (`{$ftsTable}`, rowid, {$columnList}) VALUES ('delete', OLD.`_id`, {$oldColumnList});
END
";
$this->getPDO()->prepare($deleteTrigger)->execute();
$updateSuffix = self::FTS_TRIGGER_UPDATE;
// OF <cols>: skip re-tokenise when only timestamps/permissions change.
$updateTrigger = "
CREATE TRIGGER `{$ftsTable}_{$updateSuffix}` AFTER UPDATE OF {$columnList} ON `{$parentTable}`{$updateWhen} BEGIN
INSERT INTO `{$ftsTable}` (`{$ftsTable}`, rowid, {$columnList}) VALUES ('delete', OLD.`_id`, {$oldColumnList});
INSERT INTO `{$ftsTable}` (rowid, {$columnList}) VALUES (NEW.`_id`, {$newColumnList});
END
";
$this->getPDO()->prepare($updateTrigger)->execute();
$backfill = "INSERT INTO `{$ftsTable}` (rowid, {$columnList}) SELECT `_id`, {$columnList} FROM `{$parentTable}`{$backfillWhere}";
$this->getPDO()->prepare($backfill)->execute();
$this->commitTransaction();
} catch (\Throwable $e) {
// Swallow rollback failures so the original cause keeps its
// place at the top of the stack — a "Failed to rollback"
// wrapper hides what actually went wrong.
try {
$this->rollbackTransaction();
} catch (\Throwable) {
}
throw $e;
}
unset($this->ftsTableCache[$collection]);
return true;
}
/**
* FTS5 table name keyed off the sorted attribute set. Hashed because
* `_`-joining `['ab', 'cd_ef']` collides with `['ab_cd', 'ef']`.
*
* @param array<string>|string $attributes
*/
protected function getFulltextTableName(string $collection, array|string $attributes): string
{
$attrs = \is_array($attributes) ? $attributes : [$attributes];
$attrs = \array_map(fn (string $attr) => $this->filter($attr), $attrs);
\sort($attrs);
$key = \substr(\hash('sha1', \implode("\0", $attrs)), 0, 16);
return $this->getFulltextTablePrefix($collection) . $key . self::FTS_TABLE_SUFFIX;
}
/**
* Common LIKE prefix for FTS5 tables on `$collection`. Tenant-scoped
* under sharedTables so per-tenant drops don't tear down a shared vtable.
*/
protected function getFulltextTablePrefix(string $collection): string
{
if ($this->sharedTables) {
return "{$this->getNamespace()}_{$this->getTenantSegment()}_{$this->filter($collection)}_";
}
return "{$this->getNamespace()}_{$this->filter($collection)}_";
}
/**
* Filtered tenant for identifier interpolation (the base property is
* `int|string|null`).
*/
private function getTenantSegment(): string
{
return $this->filter((string) ($this->tenant ?? ''));
}
/**
* Tenant rendered as a SQL literal for embedding in trigger bodies and
* other places where parameter binding isn't available.
*/
private function getTenantSqlLiteral(): string
{
if ($this->tenant === null) {
return 'NULL';
}
if (\is_int($this->tenant)) {
return (string) $this->tenant;
}
return $this->getPDO()->quote((string) $this->tenant);
}
/**
* Delete Index
*
* @param string $collection
* @param string $id
* @return bool
* @throws Exception
* @throws PDOException
*/
public function deleteIndex(string $collection, string $id): bool
{
$name = $this->filter($collection);
$id = $this->filter($id);
// If a regular SQLite index with this id exists, take the normal
// DROP INDEX path. Otherwise the index is either an FTS5 virtual
// table (whose name is keyed off attributes, not the id) or
// already absent — try the FTS5 path before erroring.
$regularIndex = "{$this->getNamespace()}_{$this->getTenantSegment()}_{$name}_{$id}";
$stmt = $this->getPDO()->prepare("
SELECT name FROM sqlite_master WHERE type='index' AND name=:_index
");
$stmt->bindValue(':_index', $regularIndex);
$stmt->execute();
$hasRegular = $stmt->fetchColumn() !== false;
// Free the read cursor before issuing DDL — SQLite holds a SHARED
// lock on the database while a statement has unfetched rows, and
// any subsequent DROP INDEX / ALTER TABLE under emulated prepares
// will trip "database table is locked".
$stmt->closeCursor();
if (!$hasRegular && $this->dropFulltextIndexById($name, $id)) {
return true;
}
$sql = "DROP INDEX `{$regularIndex}`";
$sql = $this->trigger(Database::EVENT_INDEX_DELETE, $sql);
try {
return $this->getPDO()
->prepare($sql)
->execute();
} catch (PDOException $e) {
if (str_contains($e->getMessage(), 'no such index')) {
return true;
}
throw $e;
}
}
/**
* Drop the FTS5 vtable backing index `$id` on `$collection`. Returns
* false when no FTS5 table exists; throws when ambiguous.
*/
protected function dropFulltextIndexById(string $collection, string $id): bool
{
$tables = $this->findFulltextTables($collection);
if (empty($tables)) {
return false;
}
// Resolve via metadata since the table name is hashed off the
// attribute set, not the index id.