Skip to content

Commit

Permalink
feat: Implement 'Like' predicate in entity storage
Browse files Browse the repository at this point in the history
This acts like the SQL 'LIKE' keyword, allowing partial string matches.
  • Loading branch information
AtkinsSJ committed Apr 24, 2024
1 parent d733119 commit a854a0d
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
18 changes: 17 additions & 1 deletion packages/backend/src/om/entitystorage/SQLES.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const { BaseES } = require("./BaseES");
const APIError = require("../../api/APIError");
const { Entity } = require("./Entity");
const { WeakConstructorTrait } = require("../../traits/WeakConstructorTrait");
const { And, Or, Eq, Predicate, Null, PredicateUtil } = require("../query/query");
const { And, Or, Eq, Like, Null, Predicate, PredicateUtil } = require("../query/query");
const { DB_WRITE } = require("../../services/database/consts");

class RawCondition extends AdvancedBase {
Expand Down Expand Up @@ -355,6 +355,22 @@ class SQLES extends BaseES {

return new RawCondition({ sql, values });
}

if ( om_query instanceof Like ) {
const key = om_query.key;
let value = om_query.value;
const prop = this.om.properties[key];

value = await prop.sql_reference(value);

const options = prop.descriptor.sql ?? {};
const col_name = options.column_name ?? prop.name;

const sql = `${col_name} LIKE ?`;
const values = [value];

return new RawCondition({ sql, values });
}
}
}
}
Expand Down
10 changes: 10 additions & 0 deletions packages/backend/src/om/query/query.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,15 @@ class Eq extends Predicate {
}
}

class Like extends Predicate {
async check (entity) {
// Convert SQL LIKE pattern to RegExp
// TODO: Support escaping the pattern characters
const regex = new RegExp(this.value.replaceAll('%', '.*').replaceAll('_', '.'), 'i');
return regex.test(await entity.get(this.key));
}
}

Predicate.prototype.and = function (other) {
return new And({ children: [this, other] });
}
Expand Down Expand Up @@ -105,4 +114,5 @@ module.exports = {
And,
Or,
Eq,
Like,
};

0 comments on commit a854a0d

Please sign in to comment.