Repository navigation
Expand file tree
/
Copy pathSQL.php
More file actions
6931 lines (6033 loc) · 245 KB
/
Copy pathSQL.php
File metadata and controls
6931 lines (6033 loc) · 245 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 Closure;
use Exception;
use PDO;
use PDOException;
use PDOStatement;
use Swoole\Database\PDOProxy;
use Swoole\Database\PDOStatementProxy;
use Throwable;
use Utopia\Console;
use Utopia\Database\Adapter;
use Utopia\Database\Adapter\SQL\BoundedPage;
use Utopia\Database\Adapter\SQL\Expression;
use Utopia\Database\Adapter\SQL\Hook\Join;
use Utopia\Database\Adapter\SQL\Hook\Permission;
use Utopia\Database\Adapter\SQL\Hook\Tenant;
use Utopia\Database\Adapter\SQL\Hook\WriteContext;
use Utopia\Database\Adapter\SQL\JoinAlias;
use Utopia\Database\Adapter\SQL\Scope\Filter as FilterScope;
use Utopia\Database\Adapter\SQL\Scope\Raw as RawScope;
use Utopia\Database\Attribute;
use Utopia\Database\Builder\Filtering;
use Utopia\Database\Builder\Scope;
use Utopia\Database\Builder\Scoping;
use Utopia\Database\Capability;
use Utopia\Database\Change;
use Utopia\Database\Database;
use Utopia\Database\DateTime;
use Utopia\Database\Document;
use Utopia\Database\Event;
use Utopia\Database\Exception as DatabaseException;
use Utopia\Database\Exception\Contention as ContentionException;
use Utopia\Database\Exception\Duplicate as DuplicateException;
use Utopia\Database\Exception\NotFound as NotFoundException;
use Utopia\Database\Exception\Query as QueryException;
use Utopia\Database\Exception\Timeout as TimeoutException;
use Utopia\Database\Exception\Transaction as TransactionException;
use Utopia\Database\Hook\Tenancy;
use Utopia\Database\Operator;
use Utopia\Database\OperatorType;
use Utopia\Database\PDO as DatabasePDO;
use Utopia\Database\PDOStatement as DatabasePDOStatement;
use Utopia\Database\PermissionType;
use Utopia\Database\Query;
use Utopia\Database\Relationship;
use Utopia\Database\RelationshipSide;
use Utopia\Database\RelationshipType;
use Utopia\Database\RelationshipUpdate;
use Utopia\Database\Storage;
use Utopia\Database\Validator\BigInt;
use Utopia\Database\Validator\Query\Join as JoinValidator;
use Utopia\Query\Builder\Condition;
use Utopia\Query\Builder\Feature\FullOuterJoins as FullOuterJoinsFeature;
use Utopia\Query\Builder\Feature\InsertOrIgnore as InsertOrIgnoreFeature;
use Utopia\Query\Builder\Feature\MariaDB\Returning as MariaDBReturning;
use Utopia\Query\Builder\Feature\Upsert as UpsertFeature;
use Utopia\Query\Builder\JoinType;
use Utopia\Query\Builder\SQL as SQLBuilder;
use Utopia\Query\Builder\Statement;
use Utopia\Query\CursorDirection;
use Utopia\Query\Exception\UnsupportedException;
use Utopia\Query\Exception\ValidationException;
use Utopia\Query\Hook\Attribute\Map as AttributeMap;
use Utopia\Query\Method;
use Utopia\Query\OrderDirection;
use Utopia\Query\Query as BaseQuery;
use Utopia\Query\Schema;
use Utopia\Query\Schema\Column;
use Utopia\Query\Schema\ColumnType;
use Utopia\Query\Schema\MySQL as MySQLSchema;
use Utopia\Query\Schema\PostgreSQL as PostgresSchema;
use Utopia\Query\Schema\Table;
use Utopia\Query\Schema\Table\PostgreSQL as PostgresTable;
abstract class SQL extends Adapter implements Feature\Connection, Feature\RawQuery, Feature\QueryBuilder, Feature\Relationships, Feature\Upserts
{
/**
* remapRow() drops every column with this prefix from every row it reads. filter() strips `$` from
* every column name and a join alias cannot hold one, so only the columns an emulated full outer
* join is ordered by carry it.
*/
private const string FOJ_ORDER_ALIAS_PREFIX = '$foj_ord_';
private const string FOJ_ROWS_ALIAS = 'foj_rows';
protected const string MIN_DATETIME = '1000-01-01 00:00:00';
/**
* The internal attributes `alias.*` returns next to the joined `$id`: those a direct read of the joined
* collection returns, but `$tenant`, which is the read's own tenant on every joined row.
*/
private const array JOINED_ROW_INTERNALS = [
Document::SEQUENCE,
Document::CREATED_AT,
Document::UPDATED_AT,
Document::PERMISSIONS,
];
/**
* MariaDB, MySQL and SQLite accept OFFSET only after a LIMIT; this one bounds nothing on any engine.
*/
private const int UNBOUNDED_LIMIT = PHP_INT_MAX;
/**
* No aggregate alias can start with `$`, so a projected column never shares a result name with an
* aggregate.
*/
private const string FOJ_COLUMN_PREFIX = '$foj_col_';
/**
* Where the rows of an emulated full outer join come from: a main-side row it paired with no
* joined row, a main-side row paired with a joined row, a joined row it paired with no main-side
* row. Every right join after the full outer join adds a bit of its own for its unmatched rows.
*/
private const int UNPAIRED_MAIN_ROWS = 1;
private const int PAIRED_ROWS = 2;
private const int UNPAIRED_JOINED_ROWS = 4;
protected object $pdo;
/**
* Controls how many fractional digits are used when binding float parameters.
*/
protected int $floatPrecision = 17;
/**
* Lazily constructed AttributeMap shared by every builder's scope.
* AttributeMap is a readonly stateless config object, so it can safely
* be reused across queries on the same adapter.
*/
private ?AttributeMap $attributeMap = null;
/**
* @var \WeakMap<object, Event>|null
*/
private ?\WeakMap $statementEvents = null;
/**
* The metadata the comments ahead of every statement were last written for, when every value is
* scalar or null, so the same metadata yields the same comments.
*
* @var array<string, mixed>|null
*/
private ?array $commentedMetadata = null;
private string $comments = '';
/**
* @var \WeakMap<object, array<mixed>>|null
*/
private ?\WeakMap $statementBindings = null;
/**
* @var \WeakMap<object, string>|null
*/
private ?\WeakMap $statementCollections = null;
/**
* Accepts Utopia\Database\PDO, a PDO-compatible proxy, or a native PDO.
*/
public function __construct(object $pdo)
{
$this->pdo = $pdo;
}
/**
* @return array<Capability>
*/
#[\Override]
public function capabilities(): array
{
return array_merge(parent::capabilities(), [
Capability::Schemas,
Capability::Caching,
Capability::IndexFulltext,
Capability::IndexFulltextMultiple,
Capability::UpdateLock,
Capability::TransactionRetries,
Capability::TransactionNested,
Capability::Operators,
Capability::OrderRandom,
Capability::IndexIdentical,
Capability::AttributeResizing,
Capability::DefinedAttributes,
Capability::Joins,
Capability::Aggregations,
]);
}
/**
* @return DatabasePDO|PDOProxy|PDO
*/
#[\Override]
public function getDriver(): object
{
if ($this->pdo instanceof DatabasePDO || $this->pdo instanceof PDOProxy || $this->pdo instanceof PDO) {
return $this->pdo;
}
throw new DatabaseException('SQL adapter requires Utopia\\Database\\PDO, Swoole\\Database\\PDOProxy, or PDO');
}
/**
* Helper to format a float value according to configured precision for binding/logging.
*/
protected function getFloatPrecision(float $value): string
{
return sprintf('%.'.$this->floatPrecision.'F', $value);
}
#[\Override]
public function hostname(): string
{
try {
if ($this->pdo instanceof DatabasePDO) {
return $this->pdo->getHostname();
}
return $this->hostname;
} catch (Throwable) {
return '';
}
}
protected function getLockType(): string
{
if ($this->supports(Capability::AlterLock) && $this->locks) {
return ',LOCK=SHARED';
}
return '';
}
/**
* @throws Exception
* @throws PDOException
*/
#[\Override]
public function ping(): bool
{
$result = $this->dialectBuilder()->fromNone()->selectRaw('1')->build();
return $this->prepareStatement($result->query)->execute();
}
#[\Override]
public function reconnect(): void
{
$pdo = $this->getDriver();
if ($pdo instanceof DatabasePDO) {
$pdo->reconnect();
}
$this->inTransaction = 0;
}
#[\Override]
public function startTransaction(): bool
{
try {
if ($this->inTransaction === 0) {
try {
if ($this->getDriver()->inTransaction()) {
$this->getDriver()->rollBack();
}
} catch (PDOException) {
// A pooled connection can report a transaction it no longer
// holds after a reconnect (e.g. Swoole PDOProxy keeps its own
// counter), making this cleanup rollback throw. It is best
// effort; swallow it and begin a fresh transaction below.
}
$result = $this->getDriver()->beginTransaction();
} else {
$this->getDriver()->exec('SAVEPOINT transaction'.$this->inTransaction);
$result = true;
}
} catch (PDOException $e) {
throw new TransactionException('Failed to start transaction: '.$e->getMessage(), $e->getCode(), $e);
}
if ($result !== true) {
throw new TransactionException('Failed to start transaction');
}
$this->inTransaction++;
return true;
}
#[\Override]
public function commitTransaction(): bool
{
if ($this->inTransaction === 0) {
return false;
}
if (! $this->getDriver()->inTransaction()) {
$this->inTransaction = 0;
throw new TransactionException('Failed to commit transaction: the connection no longer holds the transaction');
}
if ($this->inTransaction > 1) {
$this->inTransaction--;
return true;
}
try {
$result = $this->getDriver()->commit();
$this->inTransaction = 0;
} catch (PDOException $e) {
throw new TransactionException('Failed to commit transaction: '.$e->getMessage(), $e->getCode(), $e);
}
if (! $result) {
throw new TransactionException('Failed to commit transaction');
}
return $result;
}
#[\Override]
public function rollbackTransaction(): bool
{
if ($this->inTransaction === 0) {
return false;
}
try {
if ($this->inTransaction > 1) {
$this->getDriver()->exec('ROLLBACK TO transaction'.($this->inTransaction - 1));
$this->inTransaction--;
$result = true;
} else {
$result = $this->getDriver()->rollBack();
$this->inTransaction = 0;
}
} catch (PDOException $e) {
$this->inTransaction = 0;
throw new DatabaseException('Failed to rollback transaction: '.$e->getMessage(), $e->getCode(), $e);
}
if ($result !== true) {
throw new TransactionException('Failed to rollback transaction');
}
return true;
}
#[\Override]
protected function abandonTransaction(): void
{
$pdo = $this->getDriver();
if (! $pdo->inTransaction()) {
return;
}
try {
$pdo->rollBack();
} catch (PDOException) {
// A connection that only reports a transaction it no longer holds has nothing left to end.
}
}
/**
* @throws DatabaseException
*/
#[\Override]
public function exists(string $database): bool
{
$result = $this->dialectBuilder()
->fromTable('INFORMATION_SCHEMA.SCHEMATA')
->selectRaw('SCHEMA_NAME')
->filter([BaseQuery::equal('SCHEMA_NAME', [$this->filter($database)])])
->build();
return $this->returnsRows($this->executeResult($result, Event::DatabaseList));
}
/**
* @throws DatabaseException
*/
#[\Override]
public function collectionExists(string $database, string $collection): bool
{
$result = $this->dialectBuilder()
->fromTable('INFORMATION_SCHEMA.TABLES')
->selectRaw('TABLE_NAME')
->filter([
BaseQuery::equal('TABLE_SCHEMA', [$this->filter($database)]),
BaseQuery::equal('TABLE_NAME', ["{$this->getNamespace()}_{$this->filter($collection)}"]),
])
->build();
return $this->returnsRows($this->executeResult($result, Event::CollectionRead));
}
/**
* @param PDOStatement|DatabasePDOStatement|PDOStatementProxy $statement
*
* @throws DatabaseException
*/
private function returnsRows(object $statement): bool
{
try {
$this->execute($statement);
$rows = $statement->fetchAll();
$statement->closeCursor();
} catch (PDOException $error) {
$error = $this->processException($error);
if ($error instanceof NotFoundException) {
return false;
}
throw $error;
}
return ! empty($rows);
}
/**
* @return array<Document>
*/
#[\Override]
public function list(): array
{
return [];
}
/**
* @throws Exception
* @throws PDOException
*/
#[\Override]
public function createAttribute(string $collection, Attribute $attribute): bool
{
return $this->createAttributeWithEvent($collection, $attribute, Event::AttributeCreate);
}
protected function createAttributeWithEvent(string $collection, Attribute $attribute, Event $event): bool
{
$schema = $this->schema();
$table = $schema->table($this->getTableRaw($collection));
$this->addAttributeColumn($table, $attribute);
$result = $table->alter();
$sql = $result->query;
$lockType = $this->getLockType();
if (! empty($lockType)) {
$sql = rtrim($sql, ';').' '.$lockType;
}
try {
return $this->executeStatement($sql, $event);
} catch (PDOException $error) {
throw $this->processException($error);
}
}
/**
* @param list<Attribute> $attributes
*
* @throws DatabaseException
*/
#[\Override]
public function createAttributes(string $collection, array $attributes): bool
{
$schema = $this->schema();
$table = $schema->table($this->getTableRaw($collection));
foreach ($attributes as $attribute) {
$this->addAttributeColumn($table, $attribute);
}
$result = $table->alter();
$sql = $result->query;
$lockType = $this->getLockType();
if (! empty($lockType)) {
$sql = rtrim($sql, ';').' '.$lockType;
}
try {
return $this->executeStatement($sql, Event::AttributesCreate);
} catch (PDOException $error) {
throw $this->processException($error);
}
}
/**
* @throws Exception
* @throws PDOException
*/
#[\Override]
public function deleteAttribute(string $collection, string $key): bool
{
$schema = $this->schema();
$table = $schema->table($this->getTableRaw($collection));
$table->dropColumn($this->filter($key));
$result = $table->alter();
$sql = $result->query;
try {
return $this->executeStatement($sql, Event::AttributeDelete);
} catch (PDOException $e) {
throw $this->processException($e);
}
}
/**
* @throws Exception
* @throws PDOException
*/
#[\Override]
public function renameAttribute(string $collection, string $old, string $new): bool
{
if ($this->isRenamed($collection, $old, $new)) {
return true;
}
$schema = $this->schema();
$table = $schema->table($this->getTableRaw($collection));
$table->renameColumn($this->filter($old), $this->filter($new));
$result = $table->alter();
$sql = $result->query;
try {
return $this->executeStatement($sql, Event::AttributeUpdate);
} catch (PDOException $e) {
throw $this->processException($e);
}
}
/**
* Whether an earlier rename already moved the column: under shared tables every tenant
* of a collection id renames the one physical column, so only the first rename runs.
*
* @throws DatabaseException
*/
protected function isRenamed(string $collection, string $old, string $new): bool
{
$old = $this->filter($old);
$new = $this->filter($new);
if ($old === $new) {
return false;
}
$columns = $this->getColumnNames($collection);
return ! \in_array($old, $columns, true) && \in_array($new, $columns, true);
}
/**
* The physical column names of a collection's table, empty when the table does not exist.
*
* @return array<string>
*
* @throws DatabaseException
*/
abstract protected function getColumnNames(string $collection): array;
/**
* @param Query[] $queries
*
* @throws DatabaseException
*/
#[\Override]
public function getDocument(Document $collection, string $id, array $queries = [], bool $forUpdate = false): Document
{
$collectionDoc = $collection;
$collection = $collection->getId();
$name = $this->filter($collection);
$selections = $this->getAttributeSelections($queries);
$alias = Query::DEFAULT_ALIAS;
// Fast path: single-row lookup by primary key with no projection and
// no joins. This is by far the most common shape (metadata fetch,
// primary cache miss, the locked read of every update); skip the
// builder pipeline and go directly to a parameterised SELECT, filtered
// by tenant and locked the way the builder's Tenant\Filter and lock
// clause do it.
if (
empty($selections)
&& ! $this->queriesHaveJoins($queries)
) {
$tableExpr = $this->getTable($name);
$aliasQuoted = $this->quote($alias);
$uidQuoted = $this->quote(Storage::UID);
$sql = "SELECT * FROM {$tableExpr} AS {$aliasQuoted} WHERE {$this->collateDocumentId($uidQuoted)} = " . ':'.Storage::UID;
$bindings = [':'.Storage::UID => $id];
if ($this->sharedTables) {
$tenantColumn = $aliasQuoted.'.'.Storage::TENANT;
$sql .= $name === Database::METADATA || $name === Storage::permissionsTable(Database::METADATA)
? " AND ({$tenantColumn} IN (:".Storage::TENANT.") OR {$tenantColumn} IS NULL)"
: " AND {$tenantColumn} IN (:".Storage::TENANT.')';
$bindings[':'.Storage::TENANT] = $this->currentTenant();
}
if ($forUpdate && $this->supports(Capability::UpdateLock)) {
$sql .= ' FOR UPDATE';
}
$statement = null;
$row = false;
$exception = null;
try {
$statement = $this->prepareStatement($sql, Event::DocumentRead);
foreach ($bindings as $parameter => $value) {
$statement->bindValue($parameter, $value, $this->getPdoType($value));
}
$this->describeStatement($statement, $bindings, $name);
$this->execute($statement);
/** @var array<string, mixed>|false $row */
$row = $statement->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
$exception = $e;
} finally {
if ($statement !== null) {
try {
$statement->closeCursor();
} catch (PDOException $e) {
$exception ??= $e;
}
}
}
if ($exception !== null) {
throw $this->processException($exception);
}
if (! is_array($row) || empty($row)) {
return new Document([]);
}
$this->remapRow($row);
return Document::fromRow($row);
}
if ($this->queriesHaveJoins($queries)) {
if ($forUpdate) {
throw new QueryException('Cannot lock a document for update when join queries are present');
}
$roles = $this->authorization->getRoles();
$queries = \array_map(static fn ($query) => clone $query, $queries);
$joinTablePrefixes = $this->remapJoinQueries($queries);
$queries = $this->rewriteFullOuterJoins($queries, Method::LeftJoin);
$builder = $this->newBuilder($name, $alias, $this->keepsUnmatchedRows($queries), unindexed: $this->unindexedJoins($collectionDoc, $queries, $joinTablePrefixes));
$this->configureFindBuilder(
$builder,
$collectionDoc,
$queries,
$joinTablePrefixes,
false,
false,
[],
$name,
$alias,
$roles,
PermissionType::Read,
);
$builder->filter([BaseQuery::equal($alias.'.'.Storage::UID, [$id])]);
$joinAliases = \array_column($joinTablePrefixes, 'alias');
foreach ($joinAliases as $joinAlias) {
$builder->sortAsc($this->qualifyOrderAttribute($joinAlias.'.'.Document::SEQUENCE, $joinAliases));
}
$builder->limit(1);
} else {
$builder = $this->newBuilder($name, $alias);
if (! \in_array('*', $selections)) {
$builder->select($this->mapSelectionsToColumns($selections, joinAliases: []));
}
$builder->filter([BaseQuery::equal(Storage::UID, [$id])]);
if ($forUpdate && $this->supports(Capability::UpdateLock)) {
$builder->forUpdate();
}
}
$rows = $this->executeSelect($builder, Event::DocumentRead, $name);
if (empty($rows)) {
return new Document([]);
}
/** @var array<string, mixed> $document */
$document = $rows[0];
$this->remapRow($document);
return Document::fromRow($document);
}
/**
* Under ignoreDuplicates() only the documents written are returned and handed to the write
* hooks, so a skipped document writes no permission rows for a stored one.
*
* @param array<Document> $documents
* @return array<Document>
*
* @throws DuplicateException
* @throws Throwable
*/
#[\Override]
public function createDocuments(Document $collection, array $documents): array
{
if (empty($documents)) {
return $documents;
}
$this->syncWriteHooks();
$spatialAttributes = $this->getSpatialAttributes($collection);
$collection = $collection->getId();
try {
$name = $this->filter($collection);
$hasSequence = $this->batchHasSequence($documents);
if ($this->isIgnoringDuplicates()) {
$documents = $this->firstCopies($documents);
$documents = $this->supportsInsertReturning()
? $this->insertReturning($name, $documents, $spatialAttributes, $hasSequence)
: $this->insertThenReadBack($name, $documents, $spatialAttributes, $hasSequence);
} else {
$insert = $this->buildDocumentsInsert($name, $documents, $spatialAttributes, $hasSequence)->insert();
$this->execute($this->executeResult($insert, Event::DocumentsCreate));
}
if (! empty($documents)) {
$context = $this->writeContext();
$this->runWriteHooks(fn ($hook) => $hook->afterDocumentCreate($name, $documents, $context));
}
} catch (PDOException $e) {
throw $this->processException($e);
}
return $documents;
}
protected function supportsInsertReturning(): bool
{
return true;
}
/**
* MariaDB, MySQL and SQLite cannot name the index to ignore, so they skip any unique collision.
*
* @throws DatabaseException
*/
protected function insertOrIgnore(SQLBuilder $builder): Statement
{
if (! $builder instanceof InsertOrIgnoreFeature) {
throw new DatabaseException('Insert-or-ignore is not supported on this dialect');
}
return $builder->insertOrIgnore();
}
/**
* @return list<string>
*/
protected function documentKeyColumns(): array
{
return $this->sharedTables ? [Storage::UID, Storage::TENANT] : [Storage::UID];
}
/**
* @param array<Document> $documents
*
* @throws DatabaseException
*/
private function batchHasSequence(array $documents): bool
{
$hasSequence = null;
foreach ($documents as $document) {
if ($hasSequence === null) {
$hasSequence = ! empty($document->getSequence());
} elseif ($hasSequence == empty($document->getSequence())) {
throw new DatabaseException('All documents must have an sequence if one is set');
}
}
return $hasSequence ?? false;
}
/**
* A single statement writes at most one copy of an id, and a later copy may be written when
* the first is skipped for another unique value; keeping only the first copy leaves no row
* whose grants could be taken from another copy.
*
* @param array<Document> $documents
* @return list<Document>
*/
private function firstCopies(array $documents): array
{
$seen = [];
$firstCopies = [];
foreach ($documents as $document) {
[$tenant, $id] = $this->documentKey($document);
if (isset($seen[$tenant][$id])) {
continue;
}
$seen[$tenant][$id] = true;
$firstCopies[] = $document;
}
return $firstCopies;
}
/**
* @param array<Document> $documents
* @param list<string> $spatialAttributes
*
* @throws DatabaseException
*/
private function buildDocumentsInsert(string $name, array $documents, array $spatialAttributes, bool $hasSequence): SQLBuilder
{
$attributeKeySet = [];
foreach (Database::INTERNAL_ATTRIBUTE_KEYS as $key) {
$attributeKeySet[$key] = true;
}
foreach ($documents as $document) {
foreach ($document->getAttributes() as $key => $value) {
$attributeKeySet[$key] = true;
}
}
$attributeKeys = \array_keys($attributeKeySet);
if ($hasSequence) {
$attributeKeys[] = Storage::SEQUENCE;
}
$builder = $this->dialectBuilder()->into($this->getTableRaw($name));
$spatialMap = \array_fill_keys($spatialAttributes, true);
foreach ($spatialAttributes as $spatialColumn) {
$builder->insertColumnExpression($spatialColumn, $this->getSpatialGeometryFromText('?'));
}
$intBools = $this->supports(Capability::IntegerBooleans);
foreach ($documents as $document) {
$row = $this->buildDocumentRow($document, $attributeKeys, $spatialMap, $intBools);
$row = $this->decorateRow($row, $document);
$builder->set($row);
}
return $builder;
}
/**
* @param list<Document> $documents
* @param list<string> $spatialAttributes
* @return list<Document>
*
* @throws DatabaseException
*/
private function insertReturning(string $name, array $documents, array $spatialAttributes, bool $hasSequence): array
{
$builder = $this->buildDocumentsInsert($name, $documents, $spatialAttributes, $hasSequence);
$columns = $this->documentKeyColumns();
if ($builder instanceof MariaDBReturning) {
$insert = $this->insertOrIgnore($builder->returning($columns));
} else {
$insert = $this->insertOrIgnore($builder);
$quoted = \array_map($this->quote(...), $columns);
$insert = new Statement($insert->query.' RETURNING '.\implode(', ', $quoted), $insert->bindings);
}
$statement = $this->executeResult($insert, Event::DocumentsCreate);
$this->execute($statement);
/** @var list<list<mixed>> $rows */
$rows = $statement->fetchAll(PDO::FETCH_NUM);
$statement->closeCursor();
$written = $this->rowKeys($rows);
return \array_values(\array_filter(
$documents,
fn (Document $document): bool => $this->hasKey($written, $document),
));
}
/**
* Without RETURNING the ids are read before the insert, which keeps a stored id out of it,
* and read back when the insert wrote fewer rows than it was sent. A row read back is taken
* as written only when it carries the document's own permissions: a row another writer
* stored meanwhile under the same id then gains no grant it does not already state.
*
* @param list<Document> $documents
* @param list<string> $spatialAttributes
* @return list<Document>
*
* @throws DatabaseException
*/
private function insertThenReadBack(string $name, array $documents, array $spatialAttributes, bool $hasSequence): array
{
$stored = $this->rowKeys($this->readRows($name, $documents, $this->documentKeyColumns()));
$candidates = \array_values(\array_filter(
$documents,
fn (Document $document): bool => ! $this->hasKey($stored, $document),
));
if (empty($candidates)) {
return [];
}
$statement = $this->executeResult(
$this->insertOrIgnore($this->buildDocumentsInsert($name, $candidates, $spatialAttributes, $hasSequence)),
Event::DocumentsCreate,
);
$this->execute($statement);
$written = $statement->rowCount();
$statement->closeCursor();
if ($written === \count($candidates)) {
return $candidates;
}
$permissions = [];
foreach ($this->readRows($name, $candidates, [...$this->documentKeyColumns(), Storage::PERMISSIONS]) as $row) {
$rowPermissions = \end($row);
$permissions[$this->rowTenant($row)][$this->rowId($row)] = \is_string($rowPermissions) ? \json_decode($rowPermissions, true) : null;
}
return \array_values(\array_filter(
$candidates,
function (Document $document) use ($permissions): bool {
[$tenant, $id] = $this->documentKey($document);
return \array_key_exists($id, $permissions[$tenant] ?? [])
&& $permissions[$tenant][$id] === $document->getPermissions();
},
));
}
/**
* @param list<Document> $documents
* @param list<string> $columns
* @return list<list<mixed>>
*
* @throws DatabaseException
*/
private function readRows(string $name, array $documents, array $columns): array
{
$ids = [];
$tenants = [];
foreach ($documents as $document) {
$ids[] = $document->getId();
$tenant = $this->documentTenant($document);
if ($this->sharedTables && $this->tenantPerDocument && ! \in_array($tenant, $tenants, true)) {
$tenants[] = $tenant;
}
}
$builder = $this->newBuilder($name, tenants: $tenants);
$builder->select($columns);
$builder->filter([BaseQuery::equal(Storage::UID, \array_values(\array_unique($ids)))]);
$statement = $this->executeResult($builder->build(), Event::DocumentRead);
$this->execute($statement);
/** @var list<list<mixed>> $rows */
$rows = $statement->fetchAll(PDO::FETCH_NUM);
$statement->closeCursor();
return $rows;
}
/**
* @param list<list<mixed>> $rows each starting with `_uid`, then `_tenant` under shared tables
* @return array<string, array<string, true>>
*/
private function rowKeys(array $rows): array
{
$keys = [];
foreach ($rows as $row) {
$keys[$this->rowTenant($row)][$this->rowId($row)] = true;
}
return $keys;
}