Skip to content
Closed
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
46 changes: 42 additions & 4 deletions src/Database/Database.php
Original file line number Diff line number Diff line change
Expand Up @@ -1041,7 +1041,10 @@ public function createCollection(string $id, array $attributes = [], array $inde
$collection = $this->silent(fn () => $this->getCollection($id));

if (!$collection->isEmpty() && $id !== self::METADATA) {
throw new DuplicateException('Collection ' . $id . ' already exists');
// HACK: Metadata should still be updated, can be removed when null tenant collections are supported.
if (!$this->adapter->getSharedTables()) {
throw new DuplicateException('Collection ' . $id . ' already exists');
}
}

$collection = new Document([
Expand Down Expand Up @@ -1093,7 +1096,12 @@ public function createCollection(string $id, array $attributes = [], array $inde
}
}

$createdCollection = $this->silent(fn () => $this->createDocument(self::METADATA, $collection));
$createdCollection = new Document();
try {
$createdCollection = $this->silent(fn () => $this->createDocument(self::METADATA, $collection));
} catch(DuplicateException) {
$createdCollection = $this->silent(fn () => $this->updateDocument(self::METADATA, $collection->getId(), $collection));
}

$this->trigger(self::EVENT_COLLECTION_CREATE, $createdCollection);

Expand Down Expand Up @@ -1390,7 +1398,22 @@ public function createAttribute(string $collection, string $id, string $type, in
'filters' => $filters,
]);

$collection->setAttribute('attributes', $attribute, Document::SET_TYPE_APPEND);
$existingAttributes = [];
$exists = false;
foreach ($collection->getAttribute('attributes', []) as $existingAttribute) {
if($existingAttribute->getId() === $attribute->getId()) {
$existingAttributes[] = $attribute;
$exists = true;
} else {
$existingAttributes[] = $existingAttribute;
}
}

if($exists) {
$collection->setAttribute('attributes', $existingAttributes);
} else {
$collection->setAttribute('attributes', $attribute, Document::SET_TYPE_APPEND);
}

if (
$this->adapter->getDocumentSizeLimit() > 0 &&
Expand Down Expand Up @@ -2674,7 +2697,22 @@ public function createIndex(string $collection, string $id, string $type, array
'orders' => $orders,
]);

$collection->setAttribute('indexes', $index, Document::SET_TYPE_APPEND);
$existingIndexes = [];
$exists = false;
foreach ($collection->getAttribute('indexes', []) as $existingIndex) {
if($existingIndex->getId() === $index->getId()) {
$existingIndexes[] = $index;
$exists = true;
} else {
$existingIndexes[] = $existingIndex;
}
}

if($exists) {
$collection->setAttribute('indexes', $existingIndexes);
} else {
$collection->setAttribute('indexes', $index, Document::SET_TYPE_APPEND);
}

if ($this->validate) {
$validator = new IndexValidator(
Expand Down