The base driver does only the basic query formatting that's supported on the server level, which doesn't support dynamic table names.
This means the table name needs to be escaped on your side. You can either do this manually, or you can rely on a library that supports it, like the example below that uses pg-promise:
db.one('SELECT count(*) FROM $1:name', table, a => +a.count)
.then(count => {
// count = the integer record count
})
.catch(error => {
// either table doesn't exist, or a connectivity issue
});
Or, by using Named Parameters:
db.one('SELECT count(*) FROM ${table:name}', {table}, a => +a.count)
.then(count => {
// count = the integer record count
})
.catch(error => {
// either table doesn't exist, or a connectivity issue
});
Filter :name
tells the formatting engine to escape it as an SQL Name. This filter also has a shorter version ~
, if you prefer, i.e. $1~
or ${table~}
accordingly.
Also, we are using method one, because that query always expects one-row result back.