Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate schema from a sqlite_schema table query #33

Open
jlarmstrongiv opened this issue Aug 3, 2023 · 0 comments
Open

Generate schema from a sqlite_schema table query #33

jlarmstrongiv opened this issue Aug 3, 2023 · 0 comments

Comments

@jlarmstrongiv
Copy link
Contributor

jlarmstrongiv commented Aug 3, 2023

Being able to define the schema is great! It would be nice to have the option to generate it too.

The node script from my project:

import Database from "better-sqlite3";
import fs from "fs-extra";

async function start() {
  const db = new Database("chinook.db", {
    fileMustExist: true,
  });
  db.pragma("journal_mode = WAL");

  const statement = db.prepare("SELECT sql FROM sqlite_schema;");
  const rows = statement.all() as { sql: string }[];
  const schema = rows
    .map((row) => row.sql)
    // sql uses "\r\n"
    .join(";\r\n\r\n")
    // normalize to "\n"
    .replace(/\r\n/g, "\n")
    // remove type affinities
    .replace(/NVARCHAR/g, "TEXT")
    .replace(/DATETIME/g, "TEXT")
    .replace(/NUMERIC/g, "REAL")
    // remove braces
    .replace(/\[/g, "")
    .replace(/\]/g, "")
    // remove quotes
    .replace(/\"/g, "");
  const template = `import { schema } from "@vlcn.io/typed-sql";

export const generatedSchema = schema\`

${schema}

\`;
`;

  await fs.outputFile("./src/generated/schema.ts", template);
}

start();
@jlarmstrongiv jlarmstrongiv changed the title Generate schema from a SQLite database file Generate schema from a sqlite_schema table query Aug 12, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant