Skip to content

Commit

Permalink
Auto returnung * as a quick patch
Browse files Browse the repository at this point in the history
Refs: #272
  • Loading branch information
tshemsedinov committed Jul 10, 2023
1 parent dac260c commit b89fd23
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 6 deletions.
8 changes: 3 additions & 5 deletions lib/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
}

Expand Down
36 changes: 35 additions & 1 deletion test/sql.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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' })
Expand Down

0 comments on commit b89fd23

Please sign in to comment.