Casting part of a return type
Hi there,
Some of my queries return lots of fields. I want to be able to cast the return value of some of these fields. For example, I have a
SELECT
statement on a numeric field, but pg will parse this to a string. I want to be able to tell this in my output.
- I can't use $.castTo
because this destroys the other values in my SELECT
clause.
- I can't use $.narrowType
because I am casting from number
to string
, not narrowing
Does anyone have any suggestions?
Example:
Here, we lose information about pet_name
. I want to keep information about pet_name
, while also being able to say that first_name
will be returned as a number.17 Replies
Why not just fix the column type in your table interface?
Hey,
I can't because I have some operations like
eb("a", "-", "b")
(where b
is my column) which will then error
I presume you are talking about something like ColumnType<string, number | string, string | number>
I will try make a better minimal playground repro
Pretty much just like this https://kyse.link/UzWtJ
In my Postgres database this is specifically the numeric(9, 6)
type.eb("a", "-", "b")
will not fail even if a
and b
are strings.So pg will return values like
It might be because of my
coalesce
callYou can also configure postgres to return numbers instead of strings https://kysely.dev/docs/recipes/data-types#configuring-runtime-javascript-types
Data types | Kysely
When talking about data types in Kysely we need to make a distinction between the two kinds of types:
If you're sure javascript numbers are enough to represent your data
It's really hard for me to get a playground repro from this (when I use
string
in my types), but the error is something along the lines of
which gives something like
for some reason it works in playground though..Solution
https://kyse.link/sNH35
Here's one of my places where it fails using string
(using BETWEEN clause)
https://kyse.link/flAWw
Just match the types
the actual SQL is fine if you use
number
type, because internally it is numeric(9, 6)
I can't use .lit
there right, because that requires it to be a number? Have to use .val("0")
instead?You can use
sql.lit
eb.lit
doesn't allow strings as it's not safeyep
But just make postgres return numbers
What's the issue with that?
ok sweet, so probably doing things like
is the way to go?
I'm not so sure if I want to do that over my entire db
would be good if I could tell pg to only do that for a few columns
but i can't see that being possible
That works
aha I found my issue, I was using a CTE and
key being the
<number>
as the sum, rather than <string>
ok, thanks for your help and tips. think its good to close this now!