- Notifications
You must be signed in to change notification settings - Fork 8
Description
Imagine you have a project
// query to database1 const query1 = sql`SELECT * FROM items;` // query to database2 const query2 = sql`SELECT * FROM something;`Also a more extensive example of this
function sql(query, dbname?) { console.log('dbname', dbname) console.log('query', query[0]) return query } ///////////////// // expressions // ///////////////// // Database1 const query1 = sql`SELECT * FROM items;` // variable de // database 2 const query2 = sql` SELECT * FROM items; ${'database1'} `Notes:
Check how the existing SQLx project handles this problem https://github.com/launchbadge/sqlx
I can think of a few phases to solve this issue gradually
Phase 1
We only support 1 database, we will call it a default database. Having support for only the default database should satisfy most of the use cases IMO. Let's keep the existing implementation of grabbing DB_xxx environment variables
- https://github.com/JasonShin/sqlx-ts/blob/main/sqlx-ts-common/src/config.rs#L16
- https://github.com/JasonShin/sqlx-ts/blob/main/src/main.rs#L20
Also, you can pass these variables via CLI arguments.
Technically phase 1 is already done and working.
Phase 2
We provide a way to manage connections to multiple databases via introducing an additional configuration. This time it will be in JSON format
{ db1: { DB_TYPE: mysql | postgres | mssql | sqlite DB_HOST: ... DB_PORT: ... DB_USER: ... DB_PASS: ... }, db2: { DB_TYPE: mysql | postgres | mssql | sqlite DB_HOST: ... DB_PORT: ... DB_USER: ... DB_PASS: ... }, db3: { DB_TYPE: mysql | postgres | mssql | sqlite DB_HOST: ... DB_PORT: ... DB_USER: ... DB_PASS: ... }, } when the user writes an SQLx query, they can specify the connection's unique name such as db1, db2 or db3 via inline comment.
// query to database1 const query1 = sql` # db1 SELECT * FROM items; ` // query to database2 const query2 = sql` # db2 SELECT * FROM something; `Phase 3
In Phase 3, we can provide a slightly more typesafe way to maintain different types of connections to databases. Tagged template literals can take generics. It means we can use the JSON configuration that we wrote above and generate typings that represent a connection to DB. Then in our compiler logic, we can pick up the type to determine the type of DB to connect.
function sql<DBType>(query) { return query } // query to database 1 const query1 = sql<DB1_CONN>` SELECT * FROM items; ` // query to database 2 const query2 = sql<DB2_CONN>` INSERT INTO items (food_type, time_takes_to_cook, table_id, points) VALUES ('sushi', 1, 1, 20);` `