Convert Figma logo to code with AI

kysely-org logokysely

A type-safe TypeScript SQL query builder

12,229
319
12,229
128

Top Related Projects

35,618

ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.

30,047

Feature-rich ORM for modern Node.js and TypeScript, it supports PostgreSQL (with JSON and JSONB support), MySQL, MariaDB, SQLite, MS SQL Server, Snowflake, Oracle DB (v6), DB2 and DB2 for IBM i.

42,699

Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB

19,894

A query builder for PostgreSQL, MySQL, CockroachDB, SQL Server, SQLite3 and Oracle, designed to be flexible, portable, and fun to use.

TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, MariaDB, MS SQL Server, PostgreSQL and SQLite/libSQL databases.

Headless TypeScript ORM with a head. Runs on Node, Bun and Deno. Lives on the Edge and yes, it's a JavaScript ORM too 😅

Quick Overview

Kysely is a type-safe and autocompletion-friendly TypeScript SQL query builder. It provides a fluent API for constructing SQL queries with full type safety, making it easier to write and maintain database queries in TypeScript projects.

Pros

  • Strong type safety and excellent TypeScript support
  • Fluent and intuitive API for building complex SQL queries
  • Supports multiple database dialects (PostgreSQL, MySQL, SQLite)
  • Lightweight with minimal dependencies

Cons

  • Steeper learning curve compared to some ORM solutions
  • Limited support for advanced database features compared to raw SQL
  • May require more boilerplate code for simple queries
  • Not as widely adopted as some other query builders or ORMs

Code Examples

  1. Basic select query:
const result = await db
  .selectFrom('users')
  .select(['id', 'name'])
  .where('age', '>', 18)
  .execute();
  1. Join operation:
const result = await db
  .selectFrom('orders')
  .innerJoin('users', 'users.id', 'orders.user_id')
  .select(['orders.id', 'users.name'])
  .execute();
  1. Insert operation:
const result = await db
  .insertInto('users')
  .values({ name: 'John Doe', age: 30 })
  .returning('id')
  .executeTakeFirst();
  1. Transaction example:
await db.transaction().execute(async (trx) => {
  await trx
    .insertInto('accounts')
    .values({ user_id: 1, balance: 1000 })
    .execute();

  await trx
    .updateTable('users')
    .set({ has_account: true })
    .where('id', '=', 1)
    .execute();
});

Getting Started

  1. Install Kysely and your database driver:
npm install kysely
npm install pg # for PostgreSQL
  1. Define your database structure:
import { Generated, ColumnType } from 'kysely';

interface Database {
  users: {
    id: Generated<number>
    name: string
    email: string
    created_at: ColumnType<Date, string | undefined, never>
  }
}
  1. Create a Kysely instance:
import { Kysely, PostgresDialect } from 'kysely';
import { Pool } from 'pg';

const db = new Kysely<Database>({
  dialect: new PostgresDialect({
    pool: new Pool({
      connectionString: 'postgresql://user:password@localhost:5432/database'
    })
  })
});
  1. Start querying your database:
const users = await db
  .selectFrom('users')
  .select(['id', 'name', 'email'])
  .execute();

Competitor Comparisons

35,618

ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.

Pros of TypeORM

  • More mature and widely adopted, with a larger community and ecosystem
  • Supports both Active Record and Data Mapper patterns
  • Offers a CLI tool for generating migrations and running commands

Cons of TypeORM

  • Heavier and more complex, with a steeper learning curve
  • Can be slower due to its ORM nature and automatic query generation
  • Less type-safe, especially when working with complex queries

Code Comparison

TypeORM:

@Entity()
class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;
}

const users = await repository.find({ where: { name: "John" } });

Kysely:

interface User {
  id: Generated<number>;
  name: string;
}

const users = await db
  .selectFrom('user')
  .where('name', '=', 'John')
  .selectAll()
  .execute();

TypeORM uses decorators and an ORM approach, while Kysely employs a more SQL-like query builder with better type safety. TypeORM's syntax is more abstracted from SQL, whereas Kysely's is closer to raw SQL while maintaining type safety.

30,047

Feature-rich ORM for modern Node.js and TypeScript, it supports PostgreSQL (with JSON and JSONB support), MySQL, MariaDB, SQLite, MS SQL Server, Snowflake, Oracle DB (v6), DB2 and DB2 for IBM i.

Pros of Sequelize

  • More mature and widely adopted ORM with a larger ecosystem
  • Supports a broader range of databases out of the box
  • Offers built-in migration and seeding tools

Cons of Sequelize

  • Steeper learning curve due to its extensive feature set
  • Can be slower for complex queries compared to raw SQL
  • Potential for performance overhead in large-scale applications

Code Comparison

Sequelize:

const User = sequelize.define('User', {
  name: DataTypes.STRING,
  email: DataTypes.STRING
});

const users = await User.findAll({
  where: { name: 'John' }
});

Kysely:

const users = await db
  .selectFrom('users')
  .select(['name', 'email'])
  .where('name', '=', 'John')
  .execute();

Key Differences

  • Kysely is a type-safe query builder, while Sequelize is a full-featured ORM
  • Kysely focuses on compile-time type safety, whereas Sequelize relies more on runtime checks
  • Sequelize uses model definitions, while Kysely works directly with table structures
  • Kysely offers a more SQL-like query syntax, making it easier for SQL developers to transition
  • Sequelize provides more abstraction from the underlying database, which can be beneficial for complex applications but may sacrifice some performance

Both libraries have their strengths, and the choice between them depends on project requirements, team expertise, and performance considerations.

42,699

Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB

Pros of Prisma

  • Powerful schema management with automatic migrations
  • Rich ecosystem with extensive tooling and integrations
  • Strong type safety and auto-generated TypeScript types

Cons of Prisma

  • Steeper learning curve due to its unique query API
  • Less flexibility for complex queries compared to raw SQL
  • Potential performance overhead for some operations

Code Comparison

Prisma query:

const users = await prisma.user.findMany({
  where: { age: { gte: 18 } },
  include: { posts: true }
})

Kysely query:

const users = await db
  .selectFrom('user')
  .where('age', '>=', 18)
  .innerJoin('post', 'user.id', 'post.userId')
  .selectAll()
  .execute()

Prisma focuses on a declarative approach with its schema-first design, offering powerful features like automatic migrations and type generation. It excels in rapid development scenarios but may have limitations for complex queries.

Kysely, on the other hand, provides a more SQL-like query builder approach, offering greater flexibility for complex queries and potentially better performance for certain operations. However, it lacks some of the advanced schema management features and extensive ecosystem that Prisma provides.

The choice between the two depends on project requirements, team expertise, and the balance between development speed and query flexibility needed.

19,894

A query builder for PostgreSQL, MySQL, CockroachDB, SQL Server, SQLite3 and Oracle, designed to be flexible, portable, and fun to use.

Pros of Knex

  • Mature and widely adopted with a large community and ecosystem
  • Supports a broader range of databases out of the box
  • Offers both promise-based and callback-based APIs for flexibility

Cons of Knex

  • Less type-safe compared to Kysely's TypeScript-first approach
  • Query building can be more verbose and less intuitive
  • Lacks some advanced features like recursive CTEs and lateral joins

Code Comparison

Knex query:

knex('users')
  .select('name', 'email')
  .where('age', '>', 18)
  .orderBy('name')
  .limit(10)

Kysely query:

db.selectFrom('users')
  .select(['name', 'email'])
  .where('age', '>', 18)
  .orderBy('name')
  .limit(10)

Both Knex and Kysely provide fluent query builders, but Kysely offers stronger TypeScript support and a more modern API design. Knex has the advantage of broader database support and a larger ecosystem, while Kysely focuses on type safety and a more intuitive query-building experience. The choice between them often depends on project requirements, TypeScript usage, and the specific database being used.

TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, MariaDB, MS SQL Server, PostgreSQL and SQLite/libSQL databases.

Pros of MikroORM

  • Full-featured ORM with advanced features like identity map, unit of work, and lazy loading
  • Supports multiple database types (SQL and NoSQL)
  • Provides a rich ecosystem with CLI tools and integrations

Cons of MikroORM

  • Steeper learning curve due to its complexity and feature-rich nature
  • Potentially higher overhead for simpler database operations
  • Less flexible for raw SQL queries compared to query builders

Code Comparison

MikroORM:

@Entity()
class User {
  @PrimaryKey()
  id!: number;

  @Property()
  name!: string;
}

const user = em.create(User, { name: 'John' });
await em.persistAndFlush(user);

Kysely:

const user = await db
  .insertInto('user')
  .values({ name: 'John' })
  .returningAll()
  .executeTakeFirstOrThrow();

MikroORM offers a more declarative approach with decorators and entity definitions, while Kysely provides a more SQL-like query building experience. MikroORM's code is more abstracted from the underlying SQL, whereas Kysely's code closely resembles the actual SQL operations.

Headless TypeScript ORM with a head. Runs on Node, Bun and Deno. Lives on the Edge and yes, it's a JavaScript ORM too 😅

Pros of Drizzle-orm

  • Supports more databases out of the box, including SQLite and MongoDB
  • Offers a more intuitive API for complex queries and joins
  • Provides built-in migration tools for easier schema management

Cons of Drizzle-orm

  • Less mature ecosystem and community compared to Kysely
  • May have a steeper learning curve for developers new to ORM concepts
  • Limited documentation and examples for advanced use cases

Code Comparison

Kysely query example:

const result = await db
  .selectFrom('users')
  .innerJoin('posts', 'users.id', 'posts.user_id')
  .select(['users.name', 'posts.title'])
  .where('users.id', '=', 1)
  .execute();

Drizzle-orm query example:

const result = await db
  .select({
    name: users.name,
    title: posts.title,
  })
  .from(users)
  .innerJoin(posts, eq(users.id, posts.userId))
  .where(eq(users.id, 1));

Both ORMs offer type-safe query building, but Drizzle-orm's API may be more intuitive for complex queries. Kysely's approach is more SQL-like, which might be preferred by developers with strong SQL backgrounds.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Stand With Ukraine

NPM Version Tests License Issues Pull Requests GitHub contributors Downloads Bundle Size

Join the discussion ⠀⠀⠀⠀⠀⠀⠀

Discord Bluesky

Get started

Postgres MySQL MicrosoftSQLServer SQLite & more!

Kysely

Kysely (pronounce “Key-Seh-Lee”) is a type-safe and autocompletion-friendly TypeScript SQL query builder. Inspired by Knex.js. Mainly developed for Node.js but also runs on all other JavaScript environments like Deno, Bun, Cloudflare Workers and web browsers.

Kysely makes sure you only refer to tables and columns that are visible to the part of the query you're writing. The result type only has the selected columns with correct types and aliases. As an added bonus you get autocompletion for all that stuff.

As shown in the gif above, through the pure magic of modern TypeScript, Kysely is even able to parse the alias given to pet.name and add the pet_name column to the result row type. Kysely is able to infer column names, aliases and types from selected subqueries, joined subqueries, with statements and pretty much anything you can think of.

Of course there are cases where things cannot be typed at compile time, and Kysely offers escape hatches for these situations. See the sql template tag and the DynamicModule for more info.

All API documentation is written in the typing files and you can simply hover over the module, class or method you're using to see it in your IDE. The same documentation is also hosted here.

If you start using Kysely and can't find something you'd want to use, please open an issue or join our Discord server.

Getting started

Please visit our documentation site kysely.dev to get started. We also have a comprehensive API documentation hosted here, but you can access the same documentation in your IDE by hovering over a class/method/property/whatever.

Core team

Project leads

Responsible for project direction, API design, maintenance, code reviews, community support, documentation, and working on some of the most impactful/challenging things.


Sami Koskimäki

(the author)

Igal Klebanov

(the dynamo)

Honorable mentions

People who had special impact on the project and its growth.


Fernando Hurtado

(1st docs)

Wirekang

(playground)

Tim Griesser

(Knex)

Robin Blomberg

(codegen)

Shoubhit Dash

(prisma idea)

Valtýr Örn Kjartansson

(prisma impl)

Dax Raad

(early adopter)

Theo Browne

(early promoter)

Lee Robinson

(early promoter)

Ethan Resnick

(timely feedback)

Harminder Virk

(dope writeup)

Johan Eliasson

(promoter/educator)

All contributors


Want to contribute? Check out our contribution guidelines.

Powered by Vercel

NPM DownloadsLast 30 Days