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
7 changes: 7 additions & 0 deletions packages/database/src/DatabaseModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,13 @@ export class DatabaseModel {
return this.database.count(this.databaseRecord, ...args);
}

/**
* @returns {Promise<boolean>}
*/
async exists(...args) {
return await this.database.exists(this.databaseRecord, ...args);
}

async findById(id, customQueryOptions = {}) {
if (!id) {
throw new Error(`Cannot search for ${this.databaseRecord} by id without providing an id`);
Expand Down
9 changes: 9 additions & 0 deletions packages/database/src/TupaiaDatabase.js
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,15 @@ export class TupaiaDatabase {
return buildQuery(this.connection, ...args);
}

/**
* @returns {Promise<boolean>}
*/
async exists(...args) {
Copy link
Contributor

Choose a reason for hiding this comment

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

I think we could move this to the BaseDatabase?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

100% agree! But it doesn't exist on the base branch (this PR is off dev)

Unless you’re itching to use this (I have been), feel free to leave this PR for my return and I will integrate it into BaseDatabase and resolve merge conflicts

const innerQuery = this.find(...args);
const [{ exists }] = await this.executeSql('SELECT EXISTS(?);', [innerQuery]);
return exists;
}
Copy link

Choose a reason for hiding this comment

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

Bug: Race condition: Unready DB breaks subquery.

The exists method doesn't await this.find() before passing it to executeSql. When the database connection isn't ready, find returns a Promise-wrapped query via queryWhenConnected, not a Knex query builder. Passing this Promise to connection.raw() as a binding will fail because Knex expects a query builder object for subquery bindings, creating a race condition on startup.

Fix in Cursor Fix in Web


/**
*
* @param {string} recordType
Expand Down