Skip to content

Commit

Permalink
fix: don't crash for dashes at beginning and end of search queries
Browse files Browse the repository at this point in the history
  • Loading branch information
mkeen committed Jan 20, 2022
1 parent cddb940 commit b3adcc7
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 9 deletions.
20 changes: 15 additions & 5 deletions src/models/projects/projects.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,18 +170,28 @@ class Project extends Model {
if (columns.length) {
fields = columns.join(', ');
}

// hyphens cause errors in sqlite, but we can replace it with a + and
// the fulltext search will work the same
searchStr = searchStr = searchStr.replaceAll('-', '+');

searchStr = searchStr.replace(/[-](?=.*[-])/g, "+"); // Replace all but the final dash
searchStr = searchStr.replace('-', ''); //Replace the final dash with nothing
searchStr += '*'; // Query should end with asterisk for partial matching
if (searchStr === '*') { // * isn't a valid matcher on its own. return empty set
return {
count: 0,
rows: [],
}
}

if (searchStr.startsWith('+')) {
searchStr = searchStr.replace('+', '') // If query starts with +, replace it
}

let sql = `SELECT ${fields} FROM projects_fts WHERE projects_fts MATCH :search`;

if (orgUid) {
sql = `${sql} AND orgUid = :orgUid`;
}

const replacements = { search: `${searchStr}*`, orgUid };
const replacements = { search: searchStr, orgUid };

const count = (
await sequelize.query(sql, {
Expand Down
20 changes: 16 additions & 4 deletions src/models/units/units.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ class Unit extends Model {
unitMarketplaceLink,
cooresponingAdjustmentDeclaration,
correspondingAdjustmentStatus
) AGAINST ":search"
) AGAINST '":search"'
`;

if (orgUid) {
Expand Down Expand Up @@ -216,15 +216,27 @@ class Unit extends Model {
fields = columns.join(', ');
}

searchStr = searchStr = searchStr.replaceAll('-', '+');

searchStr = searchStr.replace(/[-](?=.*[-])/g, "+"); // Replace all but the final dash
searchStr = searchStr.replace('-', ''); //Replace the final dash with nothing
searchStr += '*'; // Query should end with asterisk for partial matching
if (searchStr === '*') { // * isn't a valid matcher on its own. return empty set
return {
count: 0,
rows: [],
}
}

if (searchStr.startsWith('+')) {
searchStr = searchStr.replace('+', '') // If query starts with +, replace it
}

let sql = `SELECT ${fields} FROM units_fts WHERE units_fts MATCH :search`;

if (orgUid) {
sql = `${sql} AND orgUid = :orgUid`;
}

const replacements = { search: `${searchStr}*`, orgUid };
const replacements = { search: searchStr, orgUid };

const count = (
await sequelize.query(sql, {
Expand Down

0 comments on commit b3adcc7

Please sign in to comment.