Write

Is it possible to print a relational query to SQL?
14 Replies
MAST
MAST17mo ago
I think they have a toSQL function on them. Basically call .toSQL() at the end of the query.
rphlmr ⚡
rphlmr ⚡17mo ago
Sadly, they don't. There is a hack though:
const query = db.query.users.findMany().prepare('test');
console.log(query["query"]); // ignore ts type error
const query = db.query.users.findMany().prepare('test');
console.log(query["query"]); // ignore ts type error
PizzaConsole
PizzaConsoleOP17mo ago
Hmmm, anyway to mock the connection to the database?
rphlmr ⚡
rphlmr ⚡17mo ago
That would be not recommended. What I do is writing my queries in a user.repository.ts and importing this in my user.service.ts (where my business rules are). I now can mock my repository file. To test my repository file, I write integrations tests on a real db.
Andrii Sherman
Andrii Sherman17mo ago
We will have it in next releases I've just added it so support batch api for libsql I'll do the same for postgres and mysql
jahir9991
jahir999117mo ago
any update on D1 batch ?
Andrii Sherman
Andrii Sherman17mo ago
I'm preparing libsql batch api after that will send a notes to a PR with D1, so it can be changed in a same way as libsql
PizzaConsole
PizzaConsoleOP17mo ago
Have you noticed that the toSQL() does not generated the column renames like it shows in the docs
const result = await db.select({
field1: users.id,
field2: users.name,
}).from(users);

const { field1, field2 } = result[0];
const result = await db.select({
field1: users.id,
field2: users.name,
}).from(users);

const { field1, field2 } = result[0];
select "users"."id" as "field1", "users"."name" as "field2" from "users";
select "users"."id" as "field1", "users"."name" as "field2" from "users";
Andrii Sherman
Andrii Sherman17mo ago
yes, it was a showcase of equivalent query to get same names drizzle get's just an array of arrays and map all of them itself
PizzaConsole
PizzaConsoleOP17mo ago
Gotcha, I noticed that mapping happened on the Drizzle side. Is this something that the team would consider changing in the future?
Andrii Sherman
Andrii Sherman17mo ago
changing docs? or changing runtime mapping?
PizzaConsole
PizzaConsoleOP17mo ago
Neither. Changing the toSql() to include the column renames
Andrii Sherman
Andrii Sherman17mo ago
is it needed?
PizzaConsole
PizzaConsoleOP17mo ago
I can see some use cases for it. Though I personally do not probably need it at this moment
Want results from more Discord servers?
Add your server