Pg-promise: Best practice for dynamic column names?

Created on 10 Oct 2017  路  5Comments  路  Source: vitaly-t/pg-promise

One time the query should look like

SELECT colum1 FROM table...
INNER JOIN...

but it should also be able to look like this

SELECT colum1, colum2, column3,
INNER JOIN ...
LEFT JOIN...

Can this be done with query files? If not, how would it look like in Javascript?

Thanks!

question

All 5 comments

It can very easily be done within SQL files...

SELECT ${columns:name} FROM table...
INNER JOIN...

in JavaScript:

const values = {
    columns: ['column1']
};

if (/*need to add columns*/) {
    values.columns.push('column2', 'column3');
}

Filter :name, for [SQL Names], has a special logic to it, and it can be:

  • a simple text string, which is normal, to represent a single column name
  • string * (asterisks), which is detected automatically
  • array of strings, in which case it is considered a list of column names
  • any object, to pull all property names automatically.

In our example we use the latter to provide a list of columns.


Here's another example, when by default we would select all columns, and only on a condition we would select specific columns:

const values = {
    columns: '*' // all columns
};

if (/*need specific columns*/) {
    values.columns = ['column1', 'column2', 'column3'];
}

Following this question, I did a complete rewrite of the [SQL Names] documentation, which now explains everything nicely, with examples.

Thank you for your detailed answer!

Regarding adding addtional JOINS and other parts of the query dynamically . Would I have to use "Raw Text" then?

Regarding adding addtional JOINS and other parts of the query dynamically . Would I have to use "Raw Text" then?

Yes, you can use [Raw Text] for that.

Alternatively, if other parts are too complex, you can always have your query file use another query file, i.e. as a composite query file.

Okay, thank you!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dzaman picture dzaman  路  3Comments

leemhenson picture leemhenson  路  5Comments

illarionvk picture illarionvk  路  3Comments

seanh1414 picture seanh1414  路  4Comments

ForbesLindesay picture ForbesLindesay  路  3Comments