Back to Drizzle Orm

IntrospectMySQL

src/mdx/get-started/mysql/IntrospectMySQL.mdx

latest1.6 KB
Original Source

Drizzle Kit provides a CLI command to introspect your database and generate a schema file with migrations. The schema file contains all the information about your database tables, columns, relations, and indices.

For example, you have such table in your database:

sql
CREATE TABLE `users_table` (
	`id` serial AUTO_INCREMENT NOT NULL,
	`name` varchar(255) NOT NULL,
	`age` int NOT NULL,
	`email` varchar(255) NOT NULL,
	CONSTRAINT `users_table_id` PRIMARY KEY(`id`),
	CONSTRAINT `users_table_email_unique` UNIQUE(`email`)
);

Pull your database schema:

bash
npx drizzle-kit pull --init

The result of introspection will be a schema.ts file, meta folder with snapshots of your database schema, sql file with the migration and relations.ts file for relational queries.

Here is an example of the generated schema.ts file:

typescript
// table schema generated by introspection
import {
  mysqlTable,
  mysqlSchema,
  AnyMySqlColumn,
  primaryKey,
  unique,
  serial,
  varchar,
  int,
} from 'drizzle-orm/mysql-core';
import { sql } from 'drizzle-orm';

export const usersTable = mysqlTable(
  'users_table',
  {
    id: serial().notNull(),
    name: varchar({ length: 255 }).notNull(),
    age: int().notNull(),
    email: varchar({ length: 255 }).notNull(),
  },
  (table) => [
    primaryKey({ columns: [table.id], name: 'users_table_id' }),
    unique('id').on(table.id),
    unique('users_table_email_unique').on(table.email),
  ],
);

Learn more about introspection in the documentation.