Skip to content

Cloudflare D1 adapter is inefficient - calls "create table if not exists" on instantiation #230

@treasureseth

Description

@treasureseth

The Cloudflare D1 Adapter has a private constructor and the only way to instantiate it is to call the static create method. That method internally calls init, which makes a "create table if not exists" query.

This means that simply instantiating the session storage driver would trigger this query - so effectively it pollutes the whole app. Instead, we should run a migration on setup and remove this superfluous query on instantiation.

private constructor(db: D1Database, tableName?: string) {
this.db = db;
this.tableName = tableName ?? defaultTableName;
}
static async create<T>(db: D1Database, tableName?: string): Promise<D1Adapter<T>> {
const adapter = new D1Adapter<T>(db, tableName);
await adapter.#init();
return adapter;
}
async #init() {
await this.db
.exec(`CREATE TABLE IF NOT EXISTS "${this.tableName}" (key TEXT PRIMARY KEY, value TEXT)`);
await this.db
.exec(`CREATE INDEX IF NOT EXISTS "IDX_${this.tableName}" ON ${this.tableName} (key)`);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions