You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I can successfully create code that reads data from Postgres database by following the explanation like [1]. The code looks like this
// through psql
// CREATE TABLE Person(id TEXT, name TEXT, age INT);
// INSERT INTO Person VALUES ('1', 'John', 33);
// INSERT INTO Person VALUES ('2', 'Smith', 24);
const sql = postgres(`postgres://myusername:mypassword@localhost:5432/mydatabase`);
const result = await sql`SELECT (id, name, age) FROM PERSON;`;
console.log(result[0]['row']);
But I have a problem when attempting to wrap the code into a class. For instance,
// typescript
class MyWrapper {
sql: Sql;
constructor(host: string, port: number, db: string, user: string, pass: string) {
this.sql = postgres(`postgre://${user}:${pass}@${host}/${db}`)
}
async run(sqlstr: string) {
await this.sql`${sqlstr}`; // this will cause syntax error at or near $1
// await this.sql`${this.sql(sqlstr)}`; // this will cause syntax error at or near ""SELECT id, name, age FROM Person""
}
}
// the code that calls the wrapper is as below
const postgresql = MyWrapper(...);
postgresql.run(`SELECT id, name, age FROM Person;`) // this cause the syntax error at or near error.
This seems that it's related to [2], but I do not know to fix it. Any advice? Many thanks.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
I can successfully create code that reads data from Postgres database by following the explanation like [1]. The code looks like this
But I have a problem when attempting to wrap the code into a class. For instance,
This seems that it's related to [2], but I do not know to fix it. Any advice? Many thanks.
[1]. https://github.com/porsager/postgres?tab=readme-ov-file#usage
[2]. https://github.com/porsager/postgres?tab=readme-ov-file#quick-primer-on-interpolation
Beta Was this translation helpful? Give feedback.
All reactions