Sharaal / sql-pg

Complex queries can be written with normal SQL, including the values needs to be bound and prefixed with the sql tag.
MIT License
9 stars 0 forks source link

Support composable queries #10

Closed Sharaal closed 5 years ago

Sharaal commented 5 years ago

In some query builder like knex.js it's possible to compose SQL queries, e.g.:

function getLatest (query, limit) { 
  return query.orderBy('created_at', 'DESC').limit(limit)
}

With that function every query can be extended by composing the orderBy and limit part.

Sharaal commented 5 years ago

In SQL Tags it's not possible to support that kind of query building. A SQL query needs to get written at once. It can contain nested parts, but it's not possible to add certain parts after it's written.

Adding both parts at once only would work here because both logical parts (order by and limit) are together located in the SQL query:

function getLatest (limit) {
  return sql`ORDER BY created_at DESC ${sql.limit(limit)}`
}

const limit = 5
sql`SELECT * FROM table ${getLatest(limit)}`

But these is not really pretty. It will need changes in the actual SQL query if the function gets changed and need to add another parts.

With the SQL tags it's more the way to go just to write down all parts:

const limit = 5
sql`SELECT * FROM table ORDER BY created_at DESC ${sql.limit(limit)}`

To be able to support these, it would be needed the SQL tag understand the structure of the SQL query and be able to add/change certain parts. But because the SQL query is written in native SQL, it's needed to add a SQL parser.

This would increase the complexity of the library heavily, which speaks against the principles of the library and result in the decision it won't be supported.

So the cons not have the possibility to support composable queries:

If that is often needed, a logical not native SQL query builder like knex can be used for that queries.