Kysely with Xata
Kysely is a TypeScript SQL query builder. It focuses on ensuring type safety and autocompletion and works with a growing number of database services. Kysely works in any JavaScript runtime, including Node.js, Cloudflare Workers, and Deno.
While the native Xata TypeScript SDK offers similar built-in functionality, using Kysely might be preferable if you are migrating from another database service, or if you are already using Kysely in your project.
This integration consists of a Xata dialect for Kysely.
Install both Kysely and @xata.io/kysely
with the Xata client. You can use the following package managers:
npm install kysely @xata.io/kysely @xata.io/client
pnpm add kysely @xata.io/kysely @xata.io/client
yarn add kysely @xata.io/kysely @xata.io/client
Kysely is a query builder library for TypeScript that helps in generating SQL queries. For compatibility with Xata, a specialized dialect has been developed for Kysely. The Xata dialect for Kysely enables the use of Xata-specific functionality with Kysely.
The following example, demonstrates how you can employ the Xata dialect for Kysely:
import { Kysely } from 'kysely';
import { XataDialect, Model } from '@xata.io/kysely';
import { DatabaseSchema, getXataClient } from 'xata'; // Generated client
const xata = getXataClient();
const db = new Kysely<Model<DatabaseSchema>>({
dialect: new XataDialect({ xata })
});
const drivers = await db
.selectFrom('drivers')
.select(['forename', 'surname'])
.where('nationality', '=', 'Spanish')
.execute();
In the provided code example, the following steps are taken to integrate Xata with Kysely:
- Install the Xata client. See our getting started guide for more information.
- Import
getXataClient
from the generated client (usually generated byxata pull
in a file of your project). - Instantiate Kysely with the Xata dialect. Note that the
Model
type adapts the Xata generatedDatabaseSchema
type to aModel
compatible with Kysely. - Use Kysely for type safety and autocompletion.