Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/Database/Adapter/Postgres.php
Original file line number Diff line number Diff line change
Expand Up @@ -2110,6 +2110,11 @@ public function getSupportForUpsertOnUniqueIndex(): bool
return false;
}

public function getSupportForInsertReturning(): bool
{
return true;
}

/**
* Is vector type supported?
*
Expand Down
37 changes: 37 additions & 0 deletions src/Database/Adapter/SQL.php
Original file line number Diff line number Diff line change
Expand Up @@ -1075,6 +1075,16 @@ public function getSupportForCaching(): bool
return true;
}

/**
* Can INSERT return the generated sequences (INSERT ... RETURNING)?
*
* @return bool
*/
public function getSupportForInsertReturning(): bool
{
return false;
}

/**
* Is hostname supported?
*
Expand Down Expand Up @@ -2527,10 +2537,21 @@ public function createDocuments(Document $collection, array $documents): array

$batchKeys = \implode(', ', $batchKeys);

// Read generated sequences from the insert itself, saving the getSequences() lookup
$returnSequences = !$hasSequence && $this->getSupportForInsertReturning();
$returning = '';
if ($returnSequences) {
$returning = 'RETURNING ' . $this->quote('_uid') . ', ' . $this->quote('_id');
if ($this->sharedTables) {
$returning .= ', ' . $this->quote('_tenant');
}
}

$stmt = $this->getPDO()->prepare("
{$this->getInsertKeyword()} {$this->getSQLTable($name)} {$columns}
VALUES {$batchKeys}
{$this->getInsertSuffix($name)}
{$returning}
");

foreach ($bindValues as $key => $value) {
Expand All @@ -2539,6 +2560,22 @@ public function createDocuments(Document $collection, array $documents): array

$this->execute($stmt);

if ($returnSequences) {
// Map by tenant and _uid, skipped duplicates are not returned and keep an empty sequence
$sequences = [];
foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
$sequences[(string)($row['_tenant'] ?? '')][$row['_uid']] = $row['_id'];
}
$stmt->closeCursor();

foreach ($documents as $document) {
$tenant = $this->sharedTables ? (string)$document->getTenant() : '';
if (isset($sequences[$tenant][$document->getId()])) {
$document['$sequence'] = $sequences[$tenant][$document->getId()];
}
}
}

if (!empty($permissions)) {
$tenantColumn = $this->sharedTables ? ', _tenant' : '';
$permissions = \implode(', ', $permissions);
Expand Down
Loading