fritzy / gatepost

Node.js module for binding postgres queries to models.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

db hint

vitaly-t opened this issue · comments

This is how the database code should never be written:

Book.fromSQL({
  name: 'insert',
  //using a template string
  sql: (args, model) => SQL`INSERT INTO books
(title, author, category)
VALUES (${model.title}, ${model.author}, ${model.category})
RETURNING id`,
  instance: true,
  oneResult: true
});

Why? Because ES6 template string formatting has no knowledge of how to convert JavaScript types into PostgreSQL-compliant data types. Only a postgres library would know that and provide a compliant type formatting.

For example, if any of your properties title, author or category contain a single-quote symbol ', it would immediately break the query. And there can be many examples like that.

The SQL template function breaks out all variables into its own array, and so the variables get sent to the pg module separately and replaced with $1, etc. There is no DB injection.

For example, SQLSELECT ${crap} AS crap turns into:

client.query('SELECT $1 AS crap', ['whatever crap is'], ...);

But it's a good point that I'm not showing that in the README properly.

Edit: was already mentioned in the README, but made it more prominent in a coming commit.

I logged it because what you saying happening isn't what your ReadMe.MD is showing.

Yes it is, it's using sql-template-string function in the READMEmd.