1.4.11 • Published 2 months ago

kysely-zod-sqlite v1.4.11

Weekly downloads
-
License
MIT
Repository
github
Last release
2 months ago

Intro

An flexible api for Cloudflare D1 and sqlite.

It has an simple api of Prisma and a powerful query with Kysely, runtime transform and validation model with zod.

Feature

  • validation and parse model by zod (json text string on sqlite)
  • remote call from your local app to worker or between worker by binding service
  • api like primsa (support 1 level relation)
  • unit testing D1 on local.

Install

npm install kysely-zod-sqlite

Usage

Define zod schema

Define zod and use it for kysely model.

import {z} from zod
import {
  zJsonObject,
  zJsonSchema,
  zRelationOne,
  zBoolean,
  zDate,
} from 'kysely-zod-sqlite';
export const userSchema = z.object({
  id: z.string(),
  name: z.string(),
  email: z.string().optional(),
  data: zJsonObject<UserData>(),  // it use JSON.parse
  config: zJsonSchema(z.object({  // it use zod.parse
    language:z.string(),
    status: z.enum(['busy', 'working' ]),
  })), 
  created_at: zDate(), //custom parse sqlite date
  updated_at: zDate(),
  isDelete: zBoolean(), // parse boolean 1,0 or you can use z.coerce.boolean()
});
export const postSchema = z.object({
  id: z.string(),
  name: z.string(),
  user_id: z.string(),
  is_published: zBoolean,
  data: z.string(),
  created_at: zDate,
  updated_at: zDate,
});
// define a relation
export const postRelationSchema = postSchema.extend({
  user: zRelationOne({
    schema: userSchema,
    ref: 'user_id',
    refTarget: 'id',
    table: 'test_users',
  }),
});
export const userRelationSchema = userSchema.extend({
  posts: zRelationMany({
    schema: postSchema,
    refTarget: 'user_id',
    ref: 'id',
    table: 'test_posts',
  }),
});
export type PostTable = z.infer<typeof postRelationSchema>;
export type UserTable = z.infer<typeof userRelationSchema>;
// define an api Database
export const dbSchema = z.object({
  test_users: userRelationSchema,
  test_posts: postRelationSchema,
});
export type DbSchema = typeof dbSchema;

use schema to define api

export class TestApi extends SqliteApi<DbSchema> {
  
  get test_users() {
    return this.table('test_users');
  } // api like prisma
  get test_posts() {
    return this.table('test_posts');
  }
}
const config = {}; 
const api = new TestApi({
  schema: dbSchema,
  config: {},
  kysely: createKyselySqlite({
    driver: new BetterDriver(new Database(':memory:'), config),
    schema: dbSchema,
  }),
})

Usage

prisma similar api

const post = await api.test_posts.selectFirst({
  where: { name: 'test' },
  include: {
    user: true, // query 1 level relation
  },
})
// access relation and json data 🔥
const language = post.user.config.language
await api.test_users.updateOne({
  where: {
    name: {
      like: 'user%', // it use kysely operation  = ('name' , 'like', 'user%') 
    }, 
  },
  data: { name: 'test' },
});

If you want to write a complex query you can use kysely

const data = await api.ky // this is a reference of kysely builder
    .selectFrom('test_posts')
    .limit(1)
    .innerJoin('test_users', 'test_posts.user_id', 'test_users.id')
    .selectAll()
    .execute();

Driver

Local enviroment and unit test

import { BetterSqlite3Driver } from 'kysely-zod-sqlite/driver/sqlite-driver';
const api = new TestApi({
  config,
  schema: dbSchema,
  kysely: createKyselySqlite({
    driver: new BetterDriver(new Database(':memory:'), config),
    schema: dbSchema,
  }),
});

Working inside worker and pages

import { D1Driver } from 'kysely-zod-sqlite/driver/d1-driver';
const api = new TestApi({
  config,
  schema: dbSchema,
  kysely: createKyselySqlite({
    driver: new FetchDriver({
      apiKey: process.env.API_KEY!,
      apiUrl: process.env.API_URL!,
    }),
    schema: dbSchema,
  }),
});

Working outside cloudflare worker, pages

You need to deploy a custom worker then you can connect to it on your app

worker

import { FetchDriver } from 'kysely-zod-sqlite/driver/fetch-driver';
const api = new TestApi({
  config,
  schema: dbSchema, 
  kysely: createKyselySqlite({
    driver: new FetchDriver({
      apiKey: process.env.API_KEY!,
      apiUrl: process.env.API_URL!,
    }),
    schema: dbSchema,
  }),
});

Call from cloudflare pages to worker or from worker to worker

import { FetchDriver } from 'kysely-zod-sqlite/driver/fetch-driver';
const api = new TestApi({
  config,
  schema: dbSchema,
  kysely: createKyselySqlite({
    driver: new FetchDriver(env.D1_DB, {
      apiKey: 'test',
      apiUrl: 'https://{worker}.pages.dev',
      database: 'Test',
      bindingService: env.WORKER_BINDING,
      // it will use env.WORKER_BINDING.fetch not a global fetch
    }),
    schema: dbSchema,
  }),
});

Multiple driver per table

export class TestApi extends SqliteApi<Database> {
  //... another table use a default driver

  get TestLog(){
    return this.table('TestLog',{ driver: new FetchDriver(...)});
  }
}
// dynamic add schema and driver 
const api = new TestApi(...)

const extendApi = api.withTables(
  {
    TestExtend: z.object({
      id: z.number().optional(),
      name: z.string(),
    }),
  },
  { testExtend: o => o.table('TestExtend',{driver: new D1Driver(...)}),}
);

const check = await extendApi.testExtend.selectFirst({
  where: { name: 'testextend' },
});

Support batch

// raw sql query 
await api.batchOneSmt(
  sql`update test_users set name = ? where id = ?`, 
  [ ['aaa', 'id1'], ['bbb', 'id2'], ]
);
// run kysely query with multiple value
const check = await api.batchOneSmt(
    api.ky
      .updateTable('test_users')
      .set({
        data: sql` json_set(data, '$.value', ?)`,
      })
      .where('name', '=', '?'),
    [ ['aaa', 'user0'], ['bbb', 'user1'], ]
);
// run multiple query on batch
const result = await api.batchAllSmt([
  api.ky.selectFrom('test_users').selectAll(), // kysely query
  api.ky.insertInto('test_posts').values({
    id: uid(),
    name: 'post',
    data: '',
    is_published: true,
    user_id: userArr[0].id,
  }),
  api.test_users.$selectMany({  // prisma syntax (add $ before select)
      take: 10,
      include: {
        posts: true,
      },
      select: {
        id: true,
      },
  })
]);
const users = result.getMany<UserTable>(0);
const post = result.getOne<PostTable>(1);

Bulk method

working with array on batch method is difficult. when you run query depend on some condition so I create bulk. recommend use bulk for FetchDriver if you have multiple request

const check = await api.bulk({
  // skip that query for normal user
  allUser: isAdmin ? api.ky.selectFrom('test_users').selectAll(): undefined; 
  insert: api.ky.insertInto('test_posts').values({
    id: uid(),
    name: 'post',
    data: '',
    is_published: true,
    user_id: userArr[0].id,
  }),
});
// It use **key - value** to.
const allUser = check.getMany<UserTable>('allUser'); 
const allUser = check.getOne<any>('insert'); 

//prisma query can use on bulk too. You can even run batch inside of bulk 🥰
const check = await api.bulk({
  user:
    api.ky
      .updateTable('test_users')
      .set({
        data: sql` json_set(data, '$.value', ?)`,
      })
      .where('name', '=', '?'),
  ,
  topUser: api.test_users.$selectMany({
    take: 10,
    include: {
      posts: true,
    },
    select: {
      id: true,
    },
  }),
});

FAQ

Is that library is a ORM?

No, It just a wrapper around kysely. You can think it is an API with zod for validation and parse schema with kysely for query

Different between using this library vs kysely

api.table('aaa').insertOne({...}) // it is validation on runtime value with zod.
api.ky.insertInto('aaa').values({...}) // it is type checking.

What is $ on table

api.table('aaa').selectMany() // use it to get data
api.table('aaa').$selectMany() 
// it is kysely query you can modify that query or use it on batch

column is null

when your database column can null. you need to use nullable not optional on your model

access_token: z.string().optional().nullable(),

Parse custom schema on query with join

api.parseMany<UserTable & { dynamic: number }>(
  data,
 'test_users', 
  // a joinSchema
  z.object({  
    dynamic: z.number(),
  })

migration

use the migration from kysely

Thank

kysely zod @subframe7536 @ryansonshine

Links

cloudflare better-sqlite3

1.4.11

2 months ago

1.4.10

3 months ago

1.4.9

3 months ago

1.4.8

4 months ago

1.4.7

4 months ago

1.4.6

4 months ago

1.4.5

6 months ago

1.4.4

6 months ago

1.4.3

6 months ago

1.4.2

6 months ago

1.4.1

6 months ago

1.4.0

6 months ago

1.3.2

6 months ago

1.2.0

6 months ago

1.3.1

6 months ago

1.3.0

6 months ago

1.1.29

7 months ago

1.1.28

7 months ago

1.1.30

7 months ago

1.1.31

7 months ago

1.1.12

8 months ago

1.1.11

8 months ago

1.1.16

8 months ago

1.1.15

8 months ago

1.1.14

8 months ago

1.1.13

8 months ago

1.1.19

8 months ago

1.1.17

8 months ago

1.1.23

8 months ago

1.1.22

8 months ago

1.1.21

8 months ago

1.1.20

8 months ago

1.1.27

7 months ago

1.1.26

7 months ago

1.1.25

7 months ago

1.1.24

7 months ago

1.0.0

8 months ago

1.1.1

9 months ago

1.1.0

9 months ago

1.1.9

8 months ago

1.1.8

8 months ago

1.1.7

9 months ago

1.1.6

9 months ago

1.1.5

9 months ago

1.1.4

9 months ago

1.1.3

9 months ago

1.1.2

9 months ago

1.1.10

8 months ago

1.0.67

9 months ago

1.0.66

9 months ago

1.0.65

9 months ago

1.0.64

9 months ago

1.0.63

9 months ago

1.0.62

9 months ago

1.0.61

9 months ago

1.0.60

9 months ago

1.0.59

9 months ago

1.0.58

9 months ago

1.0.57

9 months ago

1.0.56

9 months ago

1.0.55

9 months ago

1.0.54

9 months ago

1.0.53

10 months ago

1.0.52

10 months ago

1.0.51

10 months ago

1.0.50

10 months ago

1.0.49

10 months ago

1.0.48

10 months ago

1.0.47

10 months ago

1.0.46

10 months ago

1.0.45

10 months ago

1.0.44

10 months ago

1.0.43

10 months ago

1.0.42

10 months ago

1.0.41

10 months ago

1.0.40

10 months ago

1.0.39

10 months ago

1.0.38

10 months ago

1.0.37

10 months ago

1.0.36

10 months ago

1.0.35

10 months ago

1.0.34

10 months ago

1.0.33

10 months ago

1.0.32

10 months ago

1.0.31

10 months ago

1.0.30

10 months ago

1.0.29

10 months ago

1.0.28

10 months ago

1.0.27

10 months ago

1.0.26

10 months ago

1.0.25

10 months ago

1.0.24

10 months ago

1.0.23

10 months ago

1.0.22

10 months ago

1.0.21

10 months ago

1.0.20

10 months ago

1.0.19

10 months ago

1.0.18

10 months ago

1.0.17

10 months ago

1.0.16

10 months ago

1.0.15

10 months ago

1.0.14

10 months ago

1.0.13

10 months ago

1.0.12

10 months ago

1.0.11

10 months ago

1.0.10

10 months ago

1.0.9

10 months ago

1.0.8

10 months ago

1.0.7

10 months ago

1.0.6

10 months ago

1.0.5

10 months ago

1.0.4

10 months ago

1.0.3

10 months ago