Skip to content

Instantly share code, notes, and snippets.

@bwasti
Last active September 17, 2023 18:50
Show Gist options
  • Save bwasti/0fef15ee2ab604615dd14e9fffefd44f to your computer and use it in GitHub Desktop.
Save bwasti/0fef15ee2ab604615dd14e9fffefd44f to your computer and use it in GitHub Desktop.
Convert `sqlite3` to `bun:sqlite` ChatGPT prompt

Here's the API interface to bun:sqlite,

class Database {
  constructor(
    filename: string,
    options?:
      | number
      | {
          readonly?: boolean;
          create?: boolean;
          readwrite?: boolean;
        },
  );

  query<Params, ReturnType>(sql: string): Statement<Params, ReturnType>;
}

class Statement<Params, ReturnType> {
  all(params: Params): ReturnType[];
  get(params: Params): ReturnType | undefined;
  run(params: Params): void;
  values(params: Params): unknown[][];

  finalize(): void; // destroy statement and clean up resources
  toString(): string; // serialize to SQL

  columnNames: string[]; // the column names of the result set
  paramsCount: number; // the number of parameters expected by the statement
  native: any; // the native object representing the statement
}

type SQLQueryBindings =
  | string
  | bigint
  | TypedArray
  | number
  | boolean
  | null
  | Record<string, string | bigint | TypedArray | number | boolean | null>;

and here is some example usage:

const query = db.query("SELECT * FROM foo WHERE bar = $bar");
const results = query.all({
  $bar: "bar",
});

const query = db.query(`select $message;`);
const message_dict  = query.all({ $message: "Hello world" });
// => [{ message: "Hello world" }]

const query = db.query(`select $message;`);
const message_get = query.get({ $message: "Hello world" });
// => { $message: "Hello world" }

const query = db.query(`create table foo;`);
query.run();
// => undefined
const query = db.query(`select $message;`);
query.values({ $message: "Hello world" });

const vals = query.values(2);
// [
//   [ "Iron Man", 2008 ],
//   [ "The Avengers", 2012 ],
//   [ "Ant-Man: Quantumania", 2023 ],
// ]

Note that this API is synchronous and does not use the then() convention. Also note that you cannot just run db.query(...) but will need to call db.query(...).run() for any standalone database initialization code.

I have a project that uses sqlite3 in an asynchronous way. I'd like for it to use bun:sqlite in a synchronous way. Wrap each call to bun:sqlite to check for an exception and return the appropriate HTTP status.

Please convert all the code (do not skip any endpoints) below:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment