sutando icon indicating copy to clipboard operation
sutando copied to clipboard

Support Cloudflare D1

Open jjjrmy opened this issue 1 year ago • 5 comments

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.

jjjrmy avatar Apr 07 '24 02:04 jjjrmy

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();
  }
}

kiddyuchina avatar Apr 13 '24 16:04 kiddyuchina

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?

jjjrmy avatar Apr 13 '24 18:04 jjjrmy

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

kiddyuchina avatar Apr 13 '24 18:04 kiddyuchina

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

jjjrmy avatar Apr 13 '24 19:04 jjjrmy

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.

kiddyuchina avatar Apr 14 '24 20:04 kiddyuchina