Kysely

K

Kysely

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

Join

help

query-showcase

announcements

Single source of truth (defaultAlias-schema-tableName)

Hi, is there any way how to set default alias to schema.table mapping to have single source of truth for kysely as well as for existing ORM implementation? We have existing project with huge sequelize implementation and want to take advantage of kysely simplicity for some specific queries. We have existing database architecture mapping in the following object: type ModelName = string; interface TableLocation {...

What's the pattern for writing migrations exactly?

I'm not familiar with SQL migrations, so my question is how do we create the migration files, what rules should it follow ? As seen in the kysely's GitHub repo example, the migration files have dates, but those files aren't generated, so where did the dates come from ? Well, let's say I don't want the migration files to have dates then I just create separate files for migrations and name them whatever? Ok, then how do I run them? Do I run them everytime the program starts ? Just help me out here, the docs doesn't mention anything about migrations I think it just assumes you are familiar with them already.....

writing a transaction that calls functions

Hey everyone, I like what I've got going here but before I did this for my whole code base I just wanted to make sure I was on the right path ```ts export async function createUser(user: NewUser, trx: Transaction<DB>) { return db .insertInto('User') .values({...

how to search inside a json type column, I'm using postgresql

I looked in the documentation, and it talks about using the jsonObjectFrom function that is in the kysely lib, but I didn't find it, should I have done the function?

.withSchema() and raw SQL

when doing sql <ReturnType> SELECT some_function(param);.execute(db) the function is not found because it doesn't exist in the public schema, although db was created with .withSchema('myschema'). If I change the call to SELECT myschema.some_function(param);.execute(db) it still doesn't work, because the function references tables in myschema...

JSON in columns (postgresql)

Hey <a:YA_Wave:743393941369651201> I am completely new to using SQL databases and have a (hopefully) simple question. I want to store JSON inside a column and want to make certain keys not null and/or set a default value, how would I do that? In this case, I have a language column and want to set a default value for the locale key...

Escaped paramaters in raw sql

For a few queries I made postgreSQL functions, this is the current way of how I call this function: ``ts export async function getRandomAnswerByQuestionId({ questionId, answerLimit }: { questionId: string, answerLimit: number }) { return sqlSELECT * FROM get_random_answers(${sql.val(questionId)}, ${sql.val(answerLimit)})`.execute(databaseClient); }...
Solution:
That's fine, but you don't even need to use sql.val in this case https://kyse.link/?p=s&i=MEBVYcJHvb7Uj4c6chaI...

Should database tables mimic form fields?

Hey everyone, this question is not Kysely specific just wanna point that out don't know where to ask but here. I have a form for business registration that looks like this

Best practice around building query functions

Hey, I've looked around the docs somewhat but still not confident if I should do this: ```ts export async function createUser(user: NewUser) { return await db .insertInto('User')...

Declaring types under 'kysely-codegen' module

Hey everyone, because I'm using Prisma to push schemas to my database (it's because my Zod Schemas) also getting generated from my Prisma schemas -- it's why I'm still using it incase you're wondering why I'm in this situation: I have a ./types/kysely-codegen.d.ts file which contains ```ts import { Insertable, Selectable, Updateable } from 'kysely'; import { User } from 'kysely-codegen';...

From Prisma Model to Kysely Schema

Hey everyone, I'm using this package https://github.com/valtyr/prisma-kysely, the output of this Prisma Model ```ts model Business { id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid email String name String @db.VarChar(100)...

[ERR_UNKNOWN_FILE_EXTENSION] when running migrations

I have a project with Sveltekit, TypeScript, and Kysely with SQLite. When I run my migrations, using the FileMigrationProvider, I get the following error: ``` TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /Users/crummy/code/finances/src/db/migrations/2023-06-22-initial.ts at new NodeError (node:internal/errors:399:5) at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:79:11)...
Solution:
I got it working by avoiding FileMigrationProvider. Kind of hacky, not sure if there's a better way to do these imports: https://github.com/crummy/finances/commit/3b4ff5ce86a7767baa8ef3da2f279bbfc71d1ae0...

Figuring out where in codebase an exception originated from

Hi all, This might be a stupid question, but what is the best way to figure out which .execute() call threw a SQL exception? I know ideally I should be doing error handling on each call, but I have a large codebase and I'm not sure where this error is coming from. Is there any easy way of figuring this out? Maybe a way to have a wrapper that prints out the query if malformed, or to print out the stack trace where the original call was executed? ``` You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ')' at line 1. Trace: Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ')' at line 1...

How to insert into all values (and columns) from another table / view?

I realize I could write the raw sql, however I was curious how I would go about creating the following insert statement using kysely. insert into <table> select * from <view_or_table> ...

Triggers vs stored procedures

Hey everyone, I don't think this is related to Kysely directly, so excuse me but this is the only SQL type of server I am in. I am wondering what is the best way to automatically update a table attribute based on when another attribute changes (in the same table or another table). For example, if I want to have the attributes updatedAt and lastLogin updated on their own from the Model below ```ts model User { id Int @id @default(autoincrement()) createdAt DateTime @default(now()) @db.Date updatedAt DateTime @db.Timestamp() ...

`Selectable`, `Insertable` and `Updateable` wrappers

Hey everyone, I am using this package: https://github.com/valtyr/prisma-kysely and I noticed that the output file does not include
export type Person = Selectable<PersonTable>
export type NewPerson = Insertable<PersonTable>
export type EditedPerson = Updateable<PersonTable>
export type Person = Selectable<PersonTable>
export type NewPerson = Insertable<PersonTable>
export type EditedPerson = Updateable<PersonTable>
...

How to sort by random?

Imagine this query: ```ts export default function findUsers() { return db...
Solution:
orderBy(sql`random()`)
orderBy(sql`random()`)
Should do it...

Using jsonArrayFrom with mariadb.

Hello, Madiadb does not have cast to JSON, and cannot reference nested subqueries. I'm a typescript newbie. 🙂 How can I rewrite this function to achieve a similar result with Mariadb?...

insert data into a table that has id of type bigserial

I created a table that has id(bigserial), cognitoId(varchar), subaccountInfo(json), I'm trying like this: ``` const obj = [{ nome: "nil", ...