metarhia/metasql

Add parameters for select

MidoMiddle opened this issue · 2 comments

Current method:

/database.js

  async select(table, fields = ['*'], conditions = null) {
    const keys = fields[0] === '*' ? '*' : '"' + fields.join('", "') + '"';
    const sql = `SELECT ${keys} FROM "${table}"`;
    let whereClause = '';
    let args = [];
    if (conditions) {
      const whereData = where(conditions);
      whereClause = ' WHERE ' + whereData.clause;
      args = whereData.args;
    }
    const res = await this.query(sql + whereClause, args);
    return res.rows;
  }

Propose:

  async select(table, fields = ['*'], conditions = null, otherParams = null) {
    const keys = fields[0] === '*' ? '*' : '"' + fields.join('", "') + '"';
    const sql = `SELECT ${keys} FROM "${table}"`;
    let whereClause = '';
    let args = [];
    if (conditions) {
      const whereData = where(conditions);
      whereClause = ' WHERE ' + whereData.clause;
      args = whereData.args;
    }
// ------------ add this ---------
    let additional = ''; 
    if (otherParams) { 
      Object.keys(otherParams).map(d => {
        additional += ` ${d} ${otherParams[d]}`;
      });
    }
// -------------------
    const res = await this.query(sql + whereClause + additional, args);
    return res.rows;
  }

for example:

db.select('some_table', ['*'], { price: 5 }, { 'order by': 'id desc', limit: 15 })
            .then(d => { console.log({ d }) })
            .catch(e => console.error(e));

Better syntax

try {
  const result = await db.select('Goods', { price: 10 }).desc('name').limit(50);
  console.log({ result });
} catch (err) {
  console.error(err);
}

Now we have Query class with methods: order, desc, limit, offset.
See PR: #135
Examples:

metasql/test/sql.js

Lines 46 to 69 in a4960d3

metatests.test('Query.limit/offset', async (test) => {
const res1 = await db.select('City').limit(3);
test.strictEqual(res1.length, 3);
test.strictEqual(res1[0].name, 'Beijing');
const res2 = await db.select('City').offset(2);
test.strictEqual(res2.length, 5);
test.strictEqual(res2[0].name, 'Kiev');
const res3 = await db.select('City').limit(4).offset(1);
test.strictEqual(res3.length, 4);
test.strictEqual(res3[0].name, 'Wuhan');
test.end();
});
metatests.test('Query.order/desc', async (test) => {
const res1 = await db.select('City').order('name');
test.strictEqual(res1[0].name, 'Beijing');
const res2 = await db.select('City').desc('name');
test.strictEqual(res2[0].name, 'Wuhan');
const res3 = await db.select('City').order('name').desc('name');
test.strictEqual(res3[0].name, 'Wuhan');
const res4 = await db.select('City').desc('name').order('name');
test.strictEqual(res4[0].name, 'Beijing');
test.end();
});