diff --git a/lib/database.js b/lib/database.js index bef96ee..36de08d 100644 --- a/lib/database.js +++ b/lib/database.js @@ -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); @@ -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]; }; @@ -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 ')); } @@ -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) { @@ -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 {