Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Feat txn#10023

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
abnegate wants to merge19 commits into1.8.x
base:1.8.x
Choose a base branch
Loading
fromfeat-txn
Open

Feat txn#10023

abnegate wants to merge19 commits into1.8.xfromfeat-txn

Conversation

abnegate
Copy link
Member

What does this PR do?

(Provide a description of what this PR does and why it's needed.)

Test Plan

(Write your test plan here. If you changed any code, please provide us with clear instructions on how you verified your changes work. Screenshots may also be helpful.)

Related PRs and Issues

  • (Related PR or issue)

Checklist

  • Have you read theContributing Guidelines on issues?
  • If the PR includes a change to an API's metadata (desc, label, params, etc.), does it also include updated API specs and example docs?

@coderabbitaicoderabbitai
Copy link

coderabbitaibot commentedJun 18, 2025
edited
Loading

📝 Walkthrough

Walkthrough

This change introduces a new transaction system for database operations. It adds two new collections (transactions andtransactionLogs) to the metadata schema, as well as new API endpoints for creating, listing, updating (commit/rollback), and deleting transactions. Document-related endpoints now support staging operations within a transaction using atransactionId parameter. The transaction system enforces TTL constraints and operation limits, and includes new error codes and messages for transaction-related scenarios. Role and scope configurations are updated to include transaction permissions. New validators, models, and tests are added to support and verify transactional behavior.

Suggested reviewers

  • eldadfux
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat withCodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag@coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag@coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on oursupport page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings togenerate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add@coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add@coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add@coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit ourDocumentation for detailed information on how to use CodeRabbit.
  • Join ourDiscord Community to get help, request features, and share feedback.
  • Follow us onX/Twitter for updates and announcements.

@github-actionsGitHub Actions
Copy link

Security Scan Results for PR

Docker Image Scan Results

PackageVersionVulnerabilitySeverity
binutils2.42-r0CVE-2025-0840HIGH
libexpat2.6.4-r0CVE-2024-8176HIGH
libxml22.12.7-r0CVE-2024-56171HIGH
libxml22.12.7-r0CVE-2025-24928HIGH
libxml22.12.7-r0CVE-2025-27113HIGH
libxml22.12.7-r0CVE-2025-32414HIGH
libxml22.12.7-r0CVE-2025-32415HIGH
pyc3.12.9-r0CVE-2024-12718HIGH
pyc3.12.9-r0CVE-2025-4138HIGH
pyc3.12.9-r0CVE-2025-4517HIGH
python33.12.9-r0CVE-2024-12718HIGH
python33.12.9-r0CVE-2025-4138HIGH
python33.12.9-r0CVE-2025-4517HIGH
python3-pyc3.12.9-r0CVE-2024-12718HIGH
python3-pyc3.12.9-r0CVE-2025-4138HIGH
python3-pyc3.12.9-r0CVE-2025-4517HIGH
python3-pycache-pyc03.12.9-r0CVE-2024-12718HIGH
python3-pycache-pyc03.12.9-r0CVE-2025-4138HIGH
python3-pycache-pyc03.12.9-r0CVE-2025-4517HIGH
sqlite-libs3.45.3-r1CVE-2025-29087HIGH
xz5.6.2-r0CVE-2025-31115HIGH
xz-libs5.6.2-r0CVE-2025-31115HIGH
golang.org/x/cryptov0.31.0CVE-2025-22869HIGH

Source Code Scan Results

🎉 No vulnerabilities found!

Copy link

@coderabbitaicoderabbitaibot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Actionable comments posted: 13

♻️ Duplicate comments (4)
app/controllers/api/databases.php (4)

4598-4623:Same counter / limit hole forupdateDocument staging

updateDocument writes a log entry (action =update) but likewise forgets to bumptransactions.operations, leaving the transaction inconsistent and limits unenforced.


5256-5263:Bulk-update staging also forgets to bumpoperations

ThebulkUpdate path logs the action but never adjuststransactions.operations, compounding the inconsistency noted above.


5355-5376:Bulk-upsert staging: same missing counter update

Identical issue – please ensure the transaction document is patched alongside the logs.


5482-5488:Delete-within-transaction not counted

ThedeleteDocument staging block writes the log but omits the counter update.

🧹 Nitpick comments (7)
app/init/constants.php (1)

55-57:Constants fine, but add unit in the name or php-doc for clarity

All three TTL constants are seconds, while many other timeout constants are suffixed with_MILLISECONDS.
Consider either renaming (…_SECONDS) or adding a short php-doc to avoid confusion when the values are consumed next to the millisecond ones.

src/Appwrite/Utopia/Database/Validator/Operation.php (2)

57-64:Type validation runs before presence validation fordata.

Becausedata isn’t guaranteed to exist (see above), theis_array($value['data']) call will still emit a notice even if you add it to$required but leave this block here.
Move thedata-presence check to the loop above or guard witharray_key_exists.


65-69:Inefficientin_array call in a hot path.

$this->actions is static – convert it to aconst array + useisset($map[$action]) for O(1) lookup if performance on large payloads matters.

src/Appwrite/Utopia/Response/Model/Transaction.php (2)

31-36:status field lacks server-side enforcement of allowed values.

Add theallowed key to the rule so malformed responses can be caught early.

-            ->addRule('status', [-                'type' => self::TYPE_STRING,-                'description' => 'Current status of the transaction. One of: pending, committing, committed, rolled_back, failed.',-                'default' => 'pending',-                'example' => 'pending',-            ])+            ->addRule('status', [+                'type'     => self::TYPE_STRING,+                'allowed'  => ['pending', 'committing', 'committed', 'rolled_back', 'failed'],+                'description' => 'Current status of the transaction.',+                'default' => 'pending',+                'example' => 'pending',+            ])

12-18:Model is missing theoperations counter present in the collection.

Exposing it would let clients display progress and enforce limits without extra calls.

app/config/collections/projects.php (1)

2515-2567:Consider adding an automatic TTL index onexpiresAt.

A regular KEY index won’t clean up rows automatically.
If you rely on MySQL you’ll need a scheduled job; in Mongo-like stores you can switch to a TTL index to avoid manual sweeps.

tests/e2e/Services/Databases/DatabasesBase.php (1)

4110-4110:Fix grammatical issue in comment

-                '$updatedAt' => '2022-08-01 13:09:23.050' // system will update it not api+                '$updatedAt' => '2022-08-01 13:09:23.050' // system will update it, not API
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and betweend841511 and910f270.

📒 Files selected for processing (13)
  • app/config/collections/projects.php (1 hunks)
  • app/config/errors.php (1 hunks)
  • app/config/roles.php (1 hunks)
  • app/config/scopes.php (1 hunks)
  • app/controllers/api/databases.php (31 hunks)
  • app/init/constants.php (1 hunks)
  • src/Appwrite/Extend/Exception.php (1 hunks)
  • src/Appwrite/SDK/Response.php (1 hunks)
  • src/Appwrite/Utopia/Database/Validator/Operation.php (1 hunks)
  • src/Appwrite/Utopia/Database/Validator/Queries/Transactions.php (1 hunks)
  • src/Appwrite/Utopia/Response.php (4 hunks)
  • src/Appwrite/Utopia/Response/Model/Transaction.php (1 hunks)
  • tests/e2e/Services/Databases/DatabasesBase.php (7 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Setup & Build Appwrite Image
  • GitHub Check: Setup & Build Appwrite Image
  • GitHub Check: scan
🔇 Additional comments (16)
src/Appwrite/SDK/Response.php (1)

5-5:readonly requires PHP 8.2 – confirm your minimum runtime

Declaring the whole class asreadonly is great for immutability, but this syntax is supported only from PHP 8.2 upward.
If the project still targets 8.1 or earlier it will fatal-error at load‐time.
Please double-check thecomposer.json / CI matrix and bump the platform requirement if necessary.

app/config/scopes.php (1)

43-48:Scope names added correctly – remember to wire them into roles & docs

No functional issues spotted with the newtransactions.* scopes.
Just ensure they are:

  1. Added to the relevant roles inapp/config/roles.php.
  2. Reflected in the public API docs / SDK generation matrix.
app/config/errors.php (1)

813-848:Comprehensive error set – keep codes unique

The new transaction error definitions look consistent and follow existing naming & HTTP-code conventions. ✔️
Double-check that no other constant shares the numeric 410/409/400 slots for the same domain to avoid ambiguity in clients.

src/Appwrite/Utopia/Database/Validator/Operation.php (1)

80-83:getType() advertises an object whileisArray() returns true.

Down-stream consumers might treat TYPE_OBJECT as a map of named properties, not a numerically-indexed array. Verify this aligns with Utopia’s expectations, otherwise returnTYPE_ARRAY.

src/Appwrite/Extend/Exception.php (1)

232-240:Constants addition LGTM.

Names follow existing style and are unique; no further issues spotted.

app/config/collections/projects.php (1)

2570-2649:Schema and validator drift (action enum).

transactionLogs.action comment listsincrement | decrement, but these are not accepted byOperation validator (see earlier comment).
Align both sides to prevent runtime rejects.

src/Appwrite/Utopia/Response.php (5)

108-108:Transaction model import added – looks good

The newTransaction model is correctly imported and used later in the constructor.


169-170:Constants registered for transactions

MODEL_TRANSACTION andMODEL_TRANSACTION_LIST are consistent with the existing naming scheme and ensure the new entities can be referenced everywhere.


420-420:List registration for transactions

BaseList('Transaction List', … 'transactions', …) wires the collection path and the item model properly. No issues spotted.


519-519:Entity model registration

->setModel(new Transaction()) finalises the response-layer support. All good.


375-375: Let’s inspect the surrounding routes to confirm the intended URL segment for Auth Providers:

#!/bin/bashsed -n'350,430p' src/Appwrite/Utopia/Response.php
app/config/roles.php (2)

7-9:Verify that newly added scopes are defined

Scopes such asassistant.read,avatars.read,graphql,home, andrules.read have been added formember roles. Make sure they are present inapp/config/scopes.php; otherwise authentication will reject these tokens.

Also applies to: 12-19, 22-30


80-82:Transactions scopes – double-check consistency

transactions.read /transactions.write are now assigned to admins. Confirm that:

  1. They are defined inscopes.php.
  2. All new API routes are protected by the corresponding scope middleware.

If either point is missing, admins might receive 401/403 responses.

tests/e2e/Services/Databases/DatabasesBase.php (3)

5582-5627:Well-structured transaction creation tests

The test properly covers both success and failure scenarios for transaction creation, including TTL validation boundaries.


5778-5860:Comprehensive transaction commit test

The test properly validates the transaction commit flow, including attribute creation wait time and document verification after commit.


3894-3989:Potential data integrity issue in test

The test creates documents withreleaseYear andactors fields, but these attributes are never defined in the collection schema. Only thetitle attribute is created. This could lead to unexpected behavior or test failures if the system enforces strict schema validation.

#!/bin/bash# Check if there are other tests in the codebase that create documents with undefined attributesrg -A 10 -B 5"releaseYear|actors" tests/e2e/Services/Databases/| grep -E"(createAttribute|documents.*data)"| head -20

Comment on lines +7 to +10
public const array ALLOWED_ATTRIBUTES = [
'status',
'expiresAt',
];

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

⚠️ Potential issue

Typed class constant will not parse before PHP 8.3

public const array ALLOWED_ATTRIBUTES … relies on the typed-const RFC that landed in 8.3.
Unless the codebase has already moved to 8.3-minimum this will be a parse error.

-    public const array ALLOWED_ATTRIBUTES = [+    /** @var string[] */+    public const ALLOWED_ATTRIBUTES = [
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
publicconstarrayALLOWED_ATTRIBUTES = [
'status',
'expiresAt',
];
/** @var string[] */
publicconstALLOWED_ATTRIBUTES = [
'status',
'expiresAt',
];
🤖 Prompt for AI Agents
In src/Appwrite/Utopia/Database/Validator/Queries/Transactions.php around lines7 to 10, the class constant ALLOWED_ATTRIBUTES is declared with a typed array,which is only supported in PHP 8.3 and above. To fix this, remove the typedeclaration "array" from the constant definition so it is compatible withearlier PHP versions. Just declare it as "public const ALLOWED_ATTRIBUTES =[...]" without the type.

Comment on lines +12 to +15
public function __construct()
{
parent::__construct('functions', self::ALLOWED_ATTRIBUTES);
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

⚠️ Potential issue

Wrong collection key passed to parent constructor

parent::__construct('functions', …) should reference thetransactions collection so that query validation works on the right attribute set.

-        parent::__construct('functions', self::ALLOWED_ATTRIBUTES);+        parent::__construct('transactions', self::ALLOWED_ATTRIBUTES);
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
publicfunction __construct()
{
parent::__construct('functions',self::ALLOWED_ATTRIBUTES);
}
publicfunction __construct()
{
parent::__construct('transactions',self::ALLOWED_ATTRIBUTES);
}
🤖 Prompt for AI Agents
In src/Appwrite/Utopia/Database/Validator/Queries/Transactions.php lines 12 to15, the constructor incorrectly passes 'functions' as the collection key to theparent constructor. Change the first argument from 'functions' to 'transactions'to ensure the query validation uses the correct collection and attribute set.

Comment on lines +19 to +26
private array $actions = [
'create',
'update',
'upsert',
'delete',
'bulkUpdate',
'bulkDelete',
];

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

🛠️ Refactor suggestion

Allowed-action list is incomplete and already diverges fromtransactionLogs schema.

increment anddecrement appear in the newtransactionLogs collection (size comment at line 2617) but are not accepted here. This validator will therefore reject valid log entries produced by the backend.
Add the missing actions (or, better, keep the list in a shared constant).

-    private array $actions = [-        'create',-        'update',-        'upsert',-        'delete',-        'bulkUpdate',-        'bulkDelete',-    ];+    private array $actions = [+        'create',+        'update',+        'upsert',+        'delete',+        'increment',+        'decrement',+        'bulkUpdate',+        'bulkDelete',+    ];
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private array$actions = [
'create',
'update',
'upsert',
'delete',
'bulkUpdate',
'bulkDelete',
];
private array$actions = [
'create',
'update',
'upsert',
'delete',
'increment',
'decrement',
'bulkUpdate',
'bulkDelete',
];
🤖 Prompt for AI Agents
In src/Appwrite/Utopia/Database/Validator/Operation.php between lines 19 and 26,the $actions array is missing 'increment' and 'decrement' which are validactions according to the transactionLogs schema. To fix this, add 'increment'and 'decrement' to the $actions array. For better maintainability, considerdefining this list as a shared constant used both here and in thetransactionLogs schema to avoid divergence.

Comment on lines +50 to +56
foreach ($this->required as $key) {
if (!\array_key_exists($key, $value)) {
$this->description = "Missing required key: {$key}";
return false;
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

⚠️ Potential issue

data key is accessed later but not declared as required → undefined-index warnings.

You access$value['data'] unconditionally at line 72.
Either add'data' to$required or wrap the later access witharray_key_exists().

-    private array $required = [-        'databaseId',-        'collectionId',-        'action',-    ];+    private array $required = [+        'databaseId',+        'collectionId',+        'action',+        'data',+    ];
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
foreach ($this->requiredas$key) {
if (!\array_key_exists($key,$value)) {
$this->description ="Missing required key:{$key}";
returnfalse;
}
}
private array$required= [
'databaseId',
'collectionId',
'action',
'data',
];
🤖 Prompt for AI Agents
In src/Appwrite/Utopia/Database/Validator/Operation.php around lines 50 to 56,the code checks for required keys but does not include 'data' as a required key,yet $value['data'] is accessed later unconditionally at line 72, causingundefined-index warnings. To fix this, add 'data' to the $required array toensure it is always present or modify the later access to check witharray_key_exists('data', $value) before using $value['data'].

Comment on lines 4086 to 4089
'releaseYear' => 2000
]
]);

$this->assertEquals($document['body']['title'], 'Creation Date Test');

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

⚠️ Potential issue

Undefined attribute in document creation

Similar to the previous test, this creates a document withreleaseYear field that was never defined as an attribute in the collection schema.

🤖 Prompt for AI Agents
In tests/e2e/Services/Databases/DatabasesBase.php around lines 4086 to 4089, thetest creates a document with a 'releaseYear' field that is not defined in thecollection schema attributes. To fix this, update the collection schema toinclude 'releaseYear' as a valid attribute before creating the document, orremove the 'releaseYear' field from the document creation to match the existingschema.

Comment on lines +5939 to +5943
$documents = $this->client->call(Client::METHOD_GET, "/databases/$databaseId/collections/$collectionId/documents", [
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getHeaders());

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

⚠️ Potential issue

Fix incorrect parameter order in API call

ThegetHeaders() method result should be merged with the headers array, not passed as a separate parameter.

         $documents = $this->client->call(Client::METHOD_GET, "/databases/$databaseId/collections/$collectionId/documents", [             'content-type' => 'application/json',             'x-appwrite-project' => $this->getProject()['$id'],-        ], $this->getHeaders());+        ] + $this->getHeaders());
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$documents =$this->client->call(Client::METHOD_GET,"/databases/$databaseId/collections/$collectionId/documents", [
'content-type' =>'application/json',
'x-appwrite-project' =>$this->getProject()['$id'],
],$this->getHeaders());
$documents =$this->client->call(
Client::METHOD_GET,
"/databases/$databaseId/collections/$collectionId/documents",
[
'content-type' =>'application/json',
'x-appwrite-project' =>$this->getProject()['$id'],
] +$this->getHeaders()
);
🤖 Prompt for AI Agents
In tests/e2e/Services/Databases/DatabasesBase.php around lines 5939 to 5943, thecall to the client's method incorrectly passes the headers array and the resultof getHeaders() as separate parameters. To fix this, merge the array returned bygetHeaders() into the existing headers array so that all headers are combinedinto a single array parameter before passing it to the call method.

Comment on lines +1772 to +1776
$dbForProject->withTransaction(function () use ($dbForProject, $transactionId, $transaction, $requestTimestamp) {
$dbForProject->updateDocument('transactions', $transactionId, new Document([
'status' => 'committing',
]));

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

⚠️ Potential issue

Possible fatal error when spreading$operation['data']

$operation['data'] is stored as-is intransactionLogs and can be aDocument instance.
Using the spread operator (...$operation['data']) expects an array and will throw aTypeError for objects.

Coerce to array first:

$data =$operation['data']instanceof Document ?$operation['data']->getArrayCopy() :$operation['data'];...newDocument(['$id' =>$documentId, ...$data]);
🤖 Prompt for AI Agents
In app/controllers/api/databases.php around lines 1772 to 1776, the code usesthe spread operator on $operation['data'], which can be a Document object,causing a TypeError. To fix this, check if $operation['data'] is an instance ofDocument and convert it to an array using getArrayCopy() before spreading it.Replace the spread usage with a variable $data that holds the coerced array,then spread $data inside the new Document constructor.

Comment on lines +1639 to +1648
$dbForProject->withTransaction(function () use ($dbForProject, $transactionId, $staged, $existing, $operations) {
$dbForProject->createDocuments('transactionLogs', $staged);
$dbForProject->updateDocument('transactions', $transactionId, new Document([
'operations' => $existing + \count($operations),
]));
});

$response
->setStatusCode(Response::STATUS_CODE_CREATED)
->dynamic($transaction, Response::MODEL_TRANSACTION);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

🛠️ Refactor suggestion

Response shows staleoperations counter

createOperations updates the counter inside the DB, but the$transaction object returned to the client is the pre-update instance – it still shows the oldoperations value.

Fetch the updated document (or mutate the local$transaction) before calling$response->dynamic(...).

🤖 Prompt for AI Agents
In app/controllers/api/databases.php around lines 1639 to 1648, the responsereturns the $transaction object before the operations counter is updated in thedatabase, causing stale data to be sent to the client. To fix this, after thetransaction update inside the withTransaction callback, fetch the updatedtransaction document from the database or update the local $transaction variableto reflect the new operations count before passing it to$response->dynamic(...).

Comment on lines +1788 to +1816
switch ($operation['action']) {
case 'create':
$creates[$databaseInternalId][$collectionInternalId][] = new Document([
'$id' => $documentId ?? ID::unique(),
...$operation['data']
]);
break;
case 'update':
case 'upsert':
$updates[$databaseInternalId][$collectionInternalId][] = new Document([
'$id' => $documentId,
...$operation['data'],
]);
break;
case 'delete':
$deletes[$databaseInternalId][$collectionInternalId][] = $documentId;
break;
case 'bulkUpdate':
$bulkUpdates[$databaseInternalId][$collectionInternalId][] = [
'data' => $operation['data'] ?? null,
'queries' => $operation['queries'] ?? [],
];
break;
case 'bulkDelete':
$bulkDeletes[$databaseInternalId][$collectionInternalId][] = [
'queries' => $operation['queries'] ?? [],
];
break;
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

⚠️ Potential issue

increment /decrement actions are silently dropped on commit

updateTransaction’s commit loop never handles theincrement anddecrement actions that are being written totransactionLogs by the respective endpoints.
As a result, those staged mutations are lost – the transaction is markedcommitted while the underlying data never changes.

Add explicit branches (or reuseincreaseDocumentAttribute /decreaseDocumentAttribute) before setting the transaction status tocommitted.

🤖 Prompt for AI Agents
In app/controllers/api/databases.php around lines 1788 to 1816, the switchstatement handling transaction commit actions does not process 'increment' and'decrement' actions, causing those mutations to be lost. To fix this, addexplicit cases for 'increment' and 'decrement' in the switch, and call theappropriate functions like increaseDocumentAttribute anddecreaseDocumentAttribute to apply these changes before marking the transactionas committed.

Comment on lines +3896 to +3935
if (!empty($transactionId)) {
$operations = [];
foreach ($documents as $document) {
$operations[] = new Document([
'databaseInternalId' => $database->getSequence(),
'collectionInternalId' => $collection->getSequence(),
'transactionInternalId' => $transaction->getSequence(),
'documentId' => $document->getId(),
'action' => 'create',
'data' => $document->getArrayCopy(),
]);
}

$queueForEvents
->setParam('databaseId', $databaseId)
->setParam('collectionId', $collection->getId())
->setContext('collection', $collection)
->setContext('database', $database);
try {
$dbForProject->createDocuments('transactionLogs', $operations);
} catch (DuplicateException) {
throw new Exception(Exception::DOCUMENT_ALREADY_EXISTS);
} catch (NotFoundException) {
throw new Exception(Exception::COLLECTION_NOT_FOUND);
} catch (RelationshipException $e) {
throw new Exception(Exception::RELATIONSHIP_VALUE_INVALID, $e->getMessage());
} catch (StructureException $e) {
throw new Exception(Exception::DOCUMENT_INVALID_STRUCTURE, $e->getMessage());
}
} else {
try {
$dbForProject->createDocuments(
'database_' . $database->getSequence() . '_collection_' . $collection->getSequence(),
$documents
);
} catch (DuplicateException) {
throw new Exception(Exception::DOCUMENT_ALREADY_EXISTS);
} catch (NotFoundException) {
throw new Exception(Exception::COLLECTION_NOT_FOUND);
} catch (RelationshipException $e) {
throw new Exception(Exception::RELATIONSHIP_VALUE_INVALID, $e->getMessage());
} catch (StructureException $e) {
throw new Exception(Exception::DOCUMENT_INVALID_STRUCTURE, $e->getMessage());
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

⚠️ Potential issue

transactions.operations never updated for staged single-document creates

WhentransactionId is supplied tocreateDocument, an entry is pushed totransactionLogs but the parent transaction’soperations counter isnot incremented nor is the batch-limit checked.
This bypasses the safety limits enforced in/operations, making it possible to exceeddatabasesBatchSize.

Update the transaction inside the same DB transaction used for logging:

$dbForProject->withTransaction(function () use ($dbForProject, $transaction) {    $dbForProject->createDocuments('transactionLogs', $operations);+   $dbForProject->updateDocument('transactions', $transaction->getId(), new Document([+       'operations' => $transaction->getAttribute('operations') + count($operations),+   ]));});

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In app/controllers/api/databases.php around lines 3896 to 3935, whentransactionId is provided, the code logs operations to transactionLogs but doesnot update the parent transaction's operations counter or check the batch limit,which can bypass safety limits. To fix this, modify the code to increment thetransaction's operations count and perform the batch size check within the samedatabase transaction that logs the operations, ensuring consistency andenforcing limits properly.

Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Reviewers

@coderabbitaicoderabbitai[bot]coderabbitai[bot] left review comments

At least 1 approving review is required to merge this pull request.

Assignees
No one assigned
Labels
None yet
Projects
None yet
Milestone
No milestone
Development

Successfully merging this pull request may close these issues.

1 participant
@abnegate

[8]ページ先頭

©2009-2025 Movatter.jp