Drizzle ORM is a TypeScript ORM for SQL databases, designed with maximum type safety in mind. It comes with drizzle-kit CLI for automatically generating SQL migrations.

Drizzle ORM is a library, not a framework. Its main philosophy is “if you know SQL, you know Drizzle ORM”, so it is designed to follow SQL-like syntax as much as possible, strongly typed and compiled at compile time fails, not at runtime.

function list

  • full type safety
  • Intelligent automatic migration generation
  • No ORM learning curve
  • SQL-like syntax for table definitions and queries
  • Best-in-class all-type connectivity
  • All types of partial and non-partial selections of any complexity
  • Automatically infer the TS type of the DB model for select and insert respectively
  • Zod schema generation
  • zero dependencies

supported database

Install

npm install drizzle-orm
npm install -D drizzle-kit

Function display (PostgreSQL)

NOTE: Don’t forget to install pg and @types/pg Bag.

import { drizzle } from 'drizzle-orm/node-postgres';
import { integer, pgTable, serial, text, timestamp, varchar } from 'drizzle-orm/pg-core';
import { InferModel, eq, sql } from 'drizzle-orm';
import { Pool } from 'pg';

export const users = pgTable('users', {
  id: serial('id').primaryKey(),
  fullName: text('full_name').notNull(),
  phone: varchar('phone', { length: 20 }).notNull(),
  role: text('role', { enum: ['user', 'admin'] }).default('user').notNull(),
  cityId: integer('city_id').references(() => cities.id),
  createdAt: timestamp('created_at').defaultNow().notNull(),
  updatedAt: timestamp('updated_at').defaultNow().notNull(),
});

export type User = InferModel<typeof users>;
export type NewUser = InferModel<typeof users, 'insert'>;

export const cities = pgTable('cities', {
  id: serial('id').primaryKey(),
  name: text('name').notNull(),
});

export type City = InferModel<typeof cities>;
export type NewCity = InferModel<typeof cities, 'insert'>;

const pool = new Pool({
  connectionString: 'postgres://user:password@host:port/db',
});

const db = drizzle(pool);

// Insert
const newUser: NewUser = {
  fullName: 'John Doe',
  phone: '+123456789',
};
const insertedUsers /* : User[] */ = await db.insert(users).values(newUser).returning();
const insertedUser = insertedUsers[0]!;

const newCity: NewCity = {
  name: 'New York',
};
const insertedCities /* : City[] */ = await db.insert(cities).values(newCity).returning();
const insertedCity = insertedCities[0]!;

// Update
const updateResult /* : { updated: Date }[] */ = await db.update(users)
  .set({ cityId: insertedCity.id, updatedAt: new Date() })
  .where(eq(users.id, insertedUser.id))
  .returning({ updated: users.updatedAt });

// Select
const allUsers /* : User[] */ = await db.select().from(users);

// Select custom fields
const upperCaseNames /* : { id: number; name: string }[] */ = await db
  .select({
    id: users.id,
    name: sql<string>`upper(${users.fullName})`,
  })
  .from(users);

// Joins
// You wouldn't BELIEVE how SMART the result type is! ????
const allUsersWithCities = await db
  .select({
    id: users.id,
    name: users.fullName,
    city: {
      id: cities.id,
      name: cities.name,
    },
  })
  .from(users)
  .leftJoin(cities, eq(users.cityId, cities.id));

// Delete
const deletedNames /* : { name: string }[] */ = await db.delete(users)
  .where(eq(users.id, insertedUser.id))
  .returning({ name: users.fullName });

#Drizzle #ORM #Homepage #Documentation #Downloads #TypeScript #ORM #SQL #Databases #News Fast Delivery

Leave a Comment

Your email address will not be published. Required fields are marked *