Skip to content

Commit

Permalink
Add IN support
Browse files Browse the repository at this point in the history
  • Loading branch information
AliusDieMorietur committed Jul 17, 2021
1 parent 3e63d44 commit 9b87fa7
Showing 1 changed file with 19 additions and 20 deletions.
39 changes: 19 additions & 20 deletions lib/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ const formatWhere = (where) =>
where
.filter((condition) => !!condition)
.map((condition) =>
Object.entries(condition).filter((entry) => entry[1] !== undefined)
Object.entries(condition).filter((entry) => {
if (Array.isArray(entry[1])) return entry[1].length !== 0;
return entry[1] !== undefined;
})
)
.filter((params) => params.length !== 0)
.map(Object.fromEntries);
Expand All @@ -21,11 +24,15 @@ const whereValue = (value) => {
return [op, value.substring(len)];
}
}

if (value.includes('*') || value.includes('?')) {
const mask = value.replace(/\*/g, '%').replace(/\?/g, '_');
return ['LIKE', mask];
}
}
if (Array.isArray(value)) {
return ['IN', value];
}
return ['=', value];
};

Expand All @@ -38,8 +45,15 @@ const buildWhere = (conditions, firstArgIndex = 1) => {
const keys = Object.keys(where);
for (const key of keys) {
const [operator, value] = whereValue(where[key]);
conjunction.push(`"${key}" ${operator} $${i++}`);
args.push(value);
if (Array.isArray(value)) {
conjunction.push(
`"${key}" ${operator} (${value.map(() => `$${i++}`).join(',')})`
);
args.push(...value);
} else {
conjunction.push(`"${key}" ${operator} $${i++}`);
args.push(value);
}
}
disjunction.push(conjunction.join(' AND '));
}
Expand All @@ -61,11 +75,13 @@ const updates = (delta, firstArgIndex = 1) => {

class Query {
constructor(db, table, fields, ...where) {
console.log(where, formatWhere(where));
this.db = db;
this.table = table;
this.fields = fields;
this.where = formatWhere(where);
this.options = {};
console.log('wwwwww', this.where);
}

order(field) {
Expand Down Expand Up @@ -109,23 +125,6 @@ class Query {
resolve(result.rows);
}, reject);
}

toObject() {
return {
table: this.table,
fields: [...this.fields],
where: this.where.map((cond) => ({ ...cond })),
options: this.options,
};
}

static from(db, metadata) {
const { table, fields, where, options } = metadata;
const conditions = where.map((cond) => ({ ...cond }));
const query = new Query(db, table, fields, ...conditions);
Object.assign(query.options, options);
return query;
}
}

class Database {
Expand Down

0 comments on commit 9b87fa7

Please sign in to comment.