sutandojs / sutando

Sutando is a modern Node.js ORM, like Laravel Eloquent.
https://sutando.org
MIT License
153 stars 15 forks source link

Support Cloudflare D1 #33

Open jjjrmy opened 2 months ago

jjjrmy commented 2 months ago

It would be amazing if this supported Cloudflare D1 (SQLite) https://developers.cloudflare.com/d1/

I'm not sure how you'd do it, you can bind the database to your application in your application or they also provide a HTTP API.

kiddyuchina commented 2 months ago

I created the library knex-cloudflare-d1 which allows Knex to use Cloudflare D1. Then upgraded sutando to 1.5.0 and it worked:

import { sutando } from 'sutando';
import ClientD1 from 'knex-cloudflare-d1';

export interface Env {
  DB: D1Database;
}

export default {
  fetch: (req: Request, env: Env) => {
    sutando.addConnection({
      client: ClientD1,
      connection: {
        database: env.DB
      },
      useNullAsDefault: true,
    });
  });
}

In addition, the table attributes need to be set explicitly when defining the model, and the D1 database cannot set auto-incrementing id, the HasUniqueIds plugin may be required.

import { Model, HasUniqueIds } from 'sutando';
import { v4 as uuid } from 'uuid';

const BaseModel = HasUniqueIds(Model) as typeof Model;

export class User extends BaseModel {
  table = 'users';

  newUniqueId(): string {
    return uuid();
  }
}
jjjrmy commented 2 months ago

Wow thanks @kiddyuchina !! I will try this out over the weekend, I'm very excited for this.

Why is it not possible to use AutoIncrement? That seems like it is supported as a feature of SQLite and D1. And why do we need to explicitly define the table itself?

kiddyuchina commented 2 months ago

The table needs to be defined explicitly because sutando uses the plural of the model class name as the table by default, but after being deployed to cloudflare, the class name will become a random string, so sutando cannot correctly generate the table name (currently only found in cloudflare workers this case).

Not being able to use AutoIncrement is just my guess as I didn't find where AutoIncrement is set in the D1 console. I looked at some other people's examples and they all used strings as IDs. If D1 supports it, please ignore what I said above :D

jjjrmy commented 2 months ago

Moved my comment to this issue: https://github.com/sutandojs/sutando/issues/36

kiddyuchina commented 2 months ago

The use of D1 is somewhat different from other databases. The connection of D1 can only be obtained in context.env, and the connection cannot be added outside the program. Therefore, sutando CLI migration is not supported. Please use the wrangler CLI instead.

Please refer to rest-hono-cf-d1 for examples.