Skip to content
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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Full text search #248

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
23 changes: 17 additions & 6 deletions lib/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,29 @@

const { Pool } = require('pg');

const OPERATORS = ['>=', '<=', '<>', '>', '<'];
const OPERATORS = [
{ val: '>=' },
{ val: '<=' },
{ val: '<>' },
{ val: '>' },
{ val: '<' },
{ val: '@@', transform: (value) => `to_tsquery(${value})` },
];
vmkul marked this conversation as resolved.
Show resolved Hide resolved

const whereValue = (value) => {
if (typeof value === 'string') {
for (const op of OPERATORS) {
const len = op.length;
if (value.startsWith(op)) {
const len = op.val.length;
if (value.startsWith(op.val)) {
return [op, value.substring(len)];
}
}
if (value.includes('*') || value.includes('?')) {
const mask = value.replace(/\*/g, '%').replace(/\?/g, '_');
return ['LIKE', mask];
return [{ val: 'LIKE' }, mask];
}
}
return ['=', value];
return [{ val: '=' }, value];
};

const buildFields = (fields) => {
Expand All @@ -39,7 +46,11 @@ const buildWhere = (conditions, firstArgIndex = 1) => {
for (const key of keys) {
const [operator, value] = whereValue(where[key]);
if (value !== undefined) {
conjunction.push(`"${key}" ${operator} $${i++}`);
conjunction.push(
`"${key}" ${operator.val} ${
operator.transform ? operator.transform('$' + i++) : '$' + i++
}`,
);
args.push(value);
}
}
Expand Down
7 changes: 7 additions & 0 deletions test/sql.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,13 @@ const metadomain = require('metadomain');
test.strictEqual(name, 'Beijing');
const res4 = await db.select('City', { cityId: '3', name: undefined });
test.strictEqual(res4[0], { cityId: '3', name: 'Kiev', countryId: '1' });
const res5 = await db.select('Country', { name: '@@Soviet | China' });
test.strictEqual(res5.length, 2);
const res6 = await db.select('Country', { name: '@@People & China' });
test.strictEqual(res6[0], {
countryId: '2',
name: "People's Republic of China",
});
test.end();
});

Expand Down