From b89fd2312a76c8b10b4cca5fc54f242947af54f8 Mon Sep 17 00:00:00 2001 From: Timur Shemsedinov Date: Mon, 10 Jul 2023 04:17:05 +0300 Subject: [PATCH] Auto returnung * as a quick patch Refs: https://github.com/metarhia/metasql/issues/272 --- lib/database.js | 8 +++----- test/sql.js | 36 +++++++++++++++++++++++++++++++++++- 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/lib/database.js b/lib/database.js index c335f68..c4a5f4e 100644 --- a/lib/database.js +++ b/lib/database.js @@ -172,11 +172,9 @@ class Modify { prepare() { const sql = [this.sql]; - const { returning } = this.options; - if (returning) { - if (returning[0] === '*') sql.push('RETURNING *'); - else sql.push('RETURNING "' + returning.join('", "') + '"'); - } + const { returning = ['*'] } = this.options; + if (returning[0] === '*') sql.push('RETURNING *'); + else sql.push('RETURNING "' + returning.join('", "') + '"'); return { sql: sql.join(' '), args: this.args }; } diff --git a/test/sql.js b/test/sql.js index a91d80a..34f9fd0 100644 --- a/test/sql.js +++ b/test/sql.js @@ -138,7 +138,8 @@ const metadomain = require('metadomain'); const expected2 = 'INSERT ' + 'INTO "City" ("name", "countryId") ' + - 'VALUES ("Odessa", "4")'; + 'VALUES ("Odessa", "4") ' + + 'RETURNING *'; test.strictEqual(sql2, expected2); test.end(); @@ -185,6 +186,39 @@ const metadomain = require('metadomain'); test.end(); }); + metatests.test('insert/update/delete: auto-returning', async (test) => { + const res1 = await db.insert('City', { name: 'Toulouse', countryId: 1 }); + test.strictEqual(res1.rowCount, 1); + test.strictEqual(parseInt(res1.rows[0].cityId) > 1, true); + + const res2 = await db.update( + 'City', + { name: 'TOULOUSE', countryId: undefined }, + { name: 'Toulouse', cityId: undefined }, + ); + test.strictEqual(res2.rowCount, 1); + + const res3 = await db.select('City', { name: 'TOULOUSE' }); + test.contains(res3[0], { name: 'TOULOUSE', countryId: '1' }); + + const res4 = await db.delete('City', { name: 'TOULOUSE' }).returning('*'); + test.strictEqual(res4.rowCount, 1); + + const res5 = await db.update('City', { name: null }, { name: 'TOULOUSE' }); + test.strictEqual(res5.rowCount, 0); + + const res6 = await db.insert('City', { name: 'Mediolanum', countryId: 6 }); + const [{ cityId }] = res6.rows; + + const res7 = await db + .update('City', { name: '' }, { cityId }) + .returning(['name']); + test.strictEqual(res7.rows[0].name, ''); + + await db.delete('City', { cityId }).returning('*'); + test.end(); + }); + metatests.test('database.insert into registry', async (test) => { const res1 = await db .insert('Division', { name: 'Quality control' })