Kysely

K

Kysely

Join the community to ask questions about Kysely and get answers from other members.

Join

help

query-showcase

announcements

How can I use Kysely migration inside NextJS 13 project?

I created a folder called kysely in root directory of next js then created a migrator.ts which contains migration code (Migrator) and created a folder inside kysely folder called migrations then I placed all migrations in it. I tried to run the migrator.ts file with ts-node but it's throwing some module import issues (cannot use import module outside a module) how can I run migration in nextjs
Solution:
Fixed the issue by replacing ts-node with tsx and also changed migrationFolder path to absolute path ```typescript const migrator = new Migrator({...

i am trying to select my id from type uuid

when i select all id from administrator table, it returns me status 200 and returns all id ``` const responseDb = await db .withSchema("schemaName")...

I am getting an error when entering an id with a uuid value

const uuid = uuidv4() await db .withSchema("schema_name") .insertInto("table_name")...
Solution:
Hey 👋 You should try casting it to uuid using sql template tag: ```ts...

How can i enable postgres Extensions (eg: uuid) with in Kysely Migration File

const query = sqlcreate extension "uuid-ossp";; how to execute this raw query inside migration file up method...
Solution:
Hey 👋 You can execute raw queries by passing your Kysely instance to .execute like this: ```ts...

Unable to insert geometry Postgres

Hey everyone 👋🏻 Greetings! I am trying to insert point data into my Postgresql table but getting error: parse error - invalid geometry error. Here is the code ...

Achieve Prisma-like nested selects

Hi. Is it possible to achieve Prisma-like nested selects with Kysely? I have the following code and it has the type below in Prisma, but I'm not sure how to achieve the same in Kysely without just doing an additional select * from CommitteeCountry where id in (select id from Committee) or something along those lines and then mapping the results in JS ```ts const data = await prisma.Committee.findMany({ include: { countries: true,...
Solution:
Hey 👋 Have you read this? https://kysely.dev/docs/recipes/relations...

Why is numUpdatedRows a BigInt?

Hi. I'd just like to ask as to why the number of updated rows in Kysely is a BigInt, as for all other ORMs that I've seen, it's just a normal number. Was there any reason for this decision?
Solution:
In reality it can't. That SSD would use up all the atoms in the universe 😄 It's more for consistency. The inserted row's ID in the InsertObject needs to be a bigint. Therefore all the others are too....

How to translate the WITH keyword in postgres when SELECT does not have FROM?

I'm trying to translate the following postgres function into pure Kysley: ```sql CREATE OR REPLACE FUNCTION rand.similarity_search(model TEXT, needle TEXT) RETURNS TABLE (...

Using column aliases in `.where()`

This is a supported feature in MySQL, but having issues here: https://kyse.link/?p=s&i=xxyMrfnfJ6CjbRlQZpMA Do I need to do something special for it to recognize the alias?...
Solution:
Hey 👋 Are you sure this is supported in MySQL? https://dev.mysql.com/doc/refman/8.0/en/problems-with-alias.html...

Using Postgres function in an insert with a field as a select

I'm trying to translate the following SQL: ```sql INSERT INTO sb.text_document_chunk (text_document_id, text) SELECT NEW.id, sentence...

create role in migration

Is it possible to create a role in a migration? And to do the grants and things as part of that?

How to insert JSONB types in postgres?

I've looked at https://kysely-org.github.io/kysely/classes/InsertQueryBuilder.html#values and it's not very clear how I'd apply JSON to that column type when inserting. Do I need to create some sort of special helper like in: https://github.com/kysely-org/kysely/blob/master/site/docs/recipes/extending-kysely.md Also for the interface, do we define the field as a Record type? What if the field is optional?...

Querying two different tables with subset of common columns

I have two tables that have an intersection of common columns that I'm looking to query. For each of the tables, I have identical conditional logic (.wheres) that I'd like to apply for both queries, and it's quite extensive so I'd prefer not to copy and paste. My query would only .select the common columns. Is there any Kysely-ic way of doing this?...

How to select from a function with parameters?

I understand that kysely will not natively support stored procedures / functions, and was wondering if there's a pattern for this:
select * from function_name(<parameters>)
select * from function_name(<parameters>)
I created a helper:...

In a transaction, how do you ignore generated field requirements?

``` export interface TextDocumentTable { id: Generated<number>; created_at: Generated<Date>; }...
Solution:
im assuming id/created_at are nullable on document

Cross database joins in MySQL

Hi all, Is it possible to do joins across databases within the same MySQL instance? i.e ```sql SELECT * FROM db1.table1 INNER JOIN db2.table2 ON db1.table1.id = db2.table2.id...

.where('x', 'is not', null) and correspond type's nullability

Not sure if this even possible in typescript (although all of the work Kysely already makes it seem magical). But let's say we have a column 'x' that has type string | null. Is it possible to write a query that ends up resulting in a final type of string after using .where('x', 'is not', null) or any similar method?
Solution:
Hey 👋 Due to compiler performance and type maintainability, Kysely doesnt narrow the type in this case. We've recently introduced the .$narrowType that allows you to narrow the output type safely....

What is the suggested way of adding/removing methods to expression builders?

Context: I am building a custom dialect for YDB https://github.com/Gaspero/kysely-ydb YDB is slightly different from standart dialects. E.g. create/drop index expressions are a part of alter table expression (ALTER TABLE ... ADD/DROP INDEX) https://ydb.tech/en/docs/yql/reference/syntax/alter_table#secondary-index There are also other differences that are not as critical, but I am thinking of the ways how I can protect library users from writing broken SQL queries. E.g. Insert/Replace/Update/Upsert do not support returning values and thus do not support RETURNING expression; CREATE TABLE expression only supports primary key constraint. ...
Solution:
Context: I am building a custom dialect for YDB https://github.com/Gaspero/kysely-ydb YDB is slightly different from standart dialects. E.g. create/drop index expressions are a part of alter table expression (ALTER TABLE ... ADD/DROP INDEX) https://ydb.tech/en/docs/yql/reference/syntax/alter_table#secondary-index There are also other differences that are not as critical, but I am thinking of the ways how I can protect library users from writing broken SQL queries. E.g. Insert/Replace/Update/Upsert do not support returning values and thus do not support RETURNING expression; CREATE TABLE expression only supports primary key constraint. ...

Running database agnostic queries (MySQL)

As part of my test suite, I drop/create databases programmatically. Is it possible to have a Kysely connection that isn't attached to a specific database, so that I could run queries like DROP DATABASE a or CREATE DATABASE a? Other similar use cases include: RESET QUERY CACHE, SELECT 1 (for latency check), etc...

Asserting type of .countAll() (MySQL)

I've noticed that the return type from the result of aggregation functions like countAll() and sum() are string | number | bigint. I assume this is in-case the number returned is too large to be stored in a JS "number." In my case, it appears to be being returned as strings. Is it possible to assert it as a number so that I don't need to wrap every query in a parseInt(result as string, 10)?...
Solution:
nvm got it ```ts await db .selectFrom("player_stats") .where("last_active", ">", dateThreshold)...