drizzle-dbml-generator

repository·main·Indexed 42 days ago

https://github.com/l-mario564/drizzle-dbml-generator

A tool to convert Drizzle ORM schema definitions into DBML (Database Markup Language) markup. Version 0.10.0 supports PostgreSQL, MySQL, and SQLite dialects via dialect-specific functions like pgGenerate, mysqlGenerate, and sqliteGenerate. It includes a DBML class for programmatically constructing markup and supports optional relational mapping and file output.

Tokens
3.2K
Snippets
13
Records
13
Agent score
52%

What's inside drizzle-dbml-generator

  1. Install drizzle-dbml-generator and dependencies

    main

    To use the generator, you must install drizzle-orm, tsx (to execute TypeScript files), and drizzle-dbml-generator. Use the command corresponding to your package manager.

    # npm
    npm i drizzle-orm
    npm i -D drizzle-dbml-generator tsx
    
    # yarn
    yarn add drizzle-orm
    yarn add -D drizzle-dbml-generator tsx
    
    # pnpm
    pnpm add drizzle-orm
    pnpm add -D drizzle-dbml-generator tsx
  2. Generate DBML from a Drizzle schema

    main

    To generate DBML markup, create a TypeScript script that imports your Drizzle schema and calls the appropriate dialect-specific generate function (e.g., pgGenerate for PostgreSQL, mysqlGenerate for MySQL, or sqliteGenerate for SQLite).

    After creating your script (e.g., dbml.ts), run it using tsx to produce the .dbml file.

    import * as schema from './schema';
    import { pgGenerate } from 'drizzle-dbml-generator';
    
    const out = './schema.dbml';
    const relational = true;
    
    pgGenerate({ schema, out, relational });

    Then run:

    tsx dbml.ts
  3. Define a schema using the Schema type

    main

    A Schema is a record that maps names to Drizzle schema components. It can contain tables, relations, or dialect-specific types (like Enums in PostgreSQL).

    Supported schema types include:

    • AnySchema: A general schema record.
    • PgSchema: A PostgreSQL-specific schema that supports PgEnum.
    • MySqlSchema: A MySQL-specific schema.
    • SQLiteSchema: A SQLite-specific schema.
    // Example of a schema structure
    export type MySchema = {
      users: AnyTable;
      posts: AnyTable;
      userRelations: Relations;
      statusEnum: PgEnum<['active', 'inactive']>;
    };
  4. Configure the generator with the Options type

    main

    When using the generator, you provide a configuration object of type Options<Schema>. This object defines the source schema, the output destination, and whether to include relational data in the generated DBML.

    • schema: The Drizzle schema object containing your tables and relations.
    • out (optional): The file path where the generated DBML should be saved.
    • relational (optional): A boolean flag to enable/disable relational mapping in the output.
    const options: Options<AnySchema> = {
      schema: mySchema,
      out: './output.dbml',
      relational: true
    };
  5. Reference pgGenerate options

    main

    The pgGenerate function is used for PostgreSQL schemas. It returns the generated DBML as a string. Use the out option to specify a file path; if omitted, no file is written.

    | Option | Type | Description |
    | ---------- | -------- | ---------- |
    | schema | PgSchema | An object containing Postgres dialect tables, enums and relations |
    | out? | string | The output directory and file name. Uses the current working directory as the root. If not set, it will not write the DBML file. |
    | relational | boolean? | If set to true, it will create references based on the relations generated with the `relations` function instead of foreign keys. Useful for databases that don't support foreign keys. Default: `false`. |
  6. Reference sqliteGenerate options

    main

    The sqliteGenerate function is used for SQLite schemas. It returns the generated DBML as a string. Use the out option to specify a file path; if omitted, no file is written.

    | Option | Type | Description |
    | ---------- | -------- | ---------- |
    | schema | SQLiteSchema | An object containing SQLite dialect tables and relations |
    | out? | string | The output directory and file name. Uses the current working directory as the root. If not set, it will not write the DBML file. |
    | relational | boolean? | If set to true, it will create references based on the relations generated with the `relations` function instead of foreign keys. Useful for databases that don't support foreign keys. Default: `false`. |
  7. Reference mysqlGenerate options

    main

    The mysqlGenerate function is used for MySQL schemas. It returns the generated DBML as a string. Use the out option to specify a file path; if omitted, no file is written.

    | Option | Type | Description |
    | ---------- | -------- | ---------- |
    | schema | MySqlSchema | An object containing MySQL dialect tables and relations |
    | out? | string | The output directory and file name. Uses the current working directory as the root. If not set, it will not write the DBML file. |
    | relational | boolean? | If set to true, it will create references based on the relations generated with the `relations` function instead of foreign keys. Useful for databases that don't support foreign keys. Default: `false`. |
  8. Use the DBML class to build DBML markup

    main

    The DBML class provides a builder pattern for programmatically constructing DBML (Database Markup Language) strings. It allows you to insert raw strings, concatenate arrays of strings, handle character escaping for identifiers and types, and manage formatting like newlines and tabs. Most methods return this to support method chaining.

    Key Methods:

    • insert(str: string): Appends a raw string to the buffer.
    • concatAll(strs: string[]): Appends an array of strings, adding two newlines after each entry.
    • escapeSpaces(str: string): Wraps a string in double quotes if it contains non-word characters (\W) or starts with a digit or underscore.
    • escapeType(str: string): Wraps a type string in double quotes if it contains spaces or the sequence )[.
    • newLine(newLines: number = 1): Appends the specified number of newline characters.
    • tab(tabs: number = 1): Appends spaces (2 spaces per tab) for indentation.
    • build(): Returns the final constructed string with trailing whitespace removed.
    import { DBML } from './dbml';
    
    const dbml = new DBML()
      .insert('Table users {
    ')
      .tab(1)
      .insert('id integer [primary key]
    ')
      .tab(1)
      .escapeSpaces('first name') // results in "first name"
      .insert(' varchar
    ')
      .newLine(2)
      .insert('}')
      .build();
    
    console.log(dbml);
  9. Access dialect-specific generators via the main entrypoint

    main

    The drizzle-dbml-generator package provides dialect-specific generators for PostgreSQL, MySQL, and SQLite. You can import these generators directly from the package entrypoint to convert your Drizzle schema definitions into DBML (Database Markup Language).

    import { generatePgDbml, generateMysqlDbml, generateSqliteDbml } from 'drizzle-dbml-generator';
    
    // Use the generator corresponding to your database dialect
    const dbml = generatePgDbml(yourDrizzleSchema);
  10. Generate DBML for MySQL using mysqlGenerate()

    main

    Use the mysqlGenerate function to convert a Drizzle MySQL schema into a DBML string. You can optionally provide an out path in the options object to automatically write the resulting DBML to a file.

    Parameters:

    • options.schema: The Drizzle MySQL schema object.
    • options.relational: (Optional) Boolean indicating if the schema is relational. Defaults to false if not provided.
    • options.out: (Optional) File path where the generated DBML should be written.

    Returns:

    • A string containing the generated DBML content.
    import { mysqlGenerate } from 'drizzle-dbml-generator/mysql';
    
    const dbml = mysqlGenerate({
      schema: myMysqlSchema,
      out: './schema.dbml',
      relational: true
    });
  11. Use the Drizzle DBML Generator API

    main

    The drizzle-dbml-generator package exports its core functionality through the ./generators module. To generate DBML from Drizzle schemas, you should import the generator functions provided by the package. The primary entry point re-exports all generator logic, allowing you to access the tools needed to convert Drizzle ORM schema definitions into DBML (Database Markup Language) format.

    // The package re-exports all generators from the internal modules
    import { someGeneratorFunction } from 'drizzle-dbml-generator';
    
    // Usage depends on the specific generator exported
  12. Generate DBML from PostgreSQL schemas with pgGenerate()

    main

    Use the pgGenerate function to convert a Drizzle PostgreSQL schema into a DBML (Database Markup Language) string. You can optionally provide an out path in the options object to automatically write the resulting DBML to a file.

    Parameters:

    • options.schema: The Drizzle PostgreSQL schema object.
    • options.relational: (Optional boolean) Whether to generate the DBML in a relational format. Defaults to false if not provided.
    • options.out: (Optional string) The file path where the generated DBML should be written.
    import { pgGenerate } from 'drizzle-dbml-generator/pg';
    import { pgSchema, serial, text } from 'drizzle-orm/pg-core';
    
    const mySchema = pgSchema('my_schema', {
      tables: {
        users: {
          id: serial('id').primaryKey(),
          name: text('name'),
        },
      },
    });
    
    const dbml = pgGenerate({
      schema: mySchema,
      relational: false,
      out: './schema.dbml'
    });