ClickerMonkey / typed-query-builder

A fully featured fully typed query builder interface that supports multiple databases.
4 stars 0 forks source link

How to get actual SQL query text? #8

Open vsviridov opened 1 year ago

vsviridov commented 1 year ago

I don't think the documentation ever mentions how to transform

from(Users).select('*').where(() => Users.fields.id.eq(1));

into

select * from users where id = 1;

to supply to my database driver...

Can you elaborate on this?

And how to get back the type of the resulting data, so I can inform the rest of the application about what's going on...

vsviridov commented 1 year ago

Btw, I've written a quick-and-dirty codegen for sqlite that produces table definitions compatible with your library... https://gist.github.com/vsviridov/f09d82768fba96459870b80b9168f914

ClickerMonkey commented 1 year ago

That's pretty neat!

You can use exec function which takes a connection and creates a function that is passed a query which returns the desired types.

https://github.com/ClickerMonkey/typed-query-builder/blob/2ca1d93279208cc142a8e520a6c5a499fcee4c5e/packages/pgsql/test/index.spec.ts#L149

ClickerMonkey commented 1 year ago

I don't have explicit sqlite support yet but here's an example package that is for postgres:

https://github.com/ClickerMonkey/typed-query-builder/tree/master/packages/sql-pgsql

Essentially each DB only supports certain features, functions are named different things, etc. So these sql- packages is to support the types and functions as best as possible.

ClickerMonkey commented 1 year ago

To get the string and type data you use a Dialect (using the base dialect may be good enough for you if you don't want to implement a Sqlite one). There are a few helper types that can be seen here. These exec functions will return different things based on the options you pass:

https://github.com/ClickerMonkey/typed-query-builder/blob/2ca1d93279208cc142a8e520a6c5a499fcee4c5e/packages/pgsql/src/core.ts#L91

vsviridov commented 1 year ago

Thank you for the fast response. Another question... As I'm planning to use it with Bun's sqlite driver, and it favors prepared statements a lot.

Is there a way to have a query builder produce a query that has named placeholder values within the query text?

Such query is cached by the sqlite engine and can be invoked with parameters in a separate call...

ClickerMonkey commented 1 year ago

Yep, that's by default iirc. The base dialect should support named parameters just fine.

vsviridov commented 1 year ago

So, the exec method seems to exist only on the Postgres package... And creating a new package for sqlite might be a bit beyond me at this stage...