diff --git a/README.md b/README.md index e6594ad..2e3afc4 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1481 TILs and counting..._ +_1482 TILs and counting..._ --- @@ -27,6 +27,7 @@ _1481 TILs and counting..._ * [Deno](#deno) * [Devops](#devops) * [Docker](#docker) +* [Drizzle](#drizzle) * [Elixir](#elixir) * [Gatsby](#gatsby) * [Git](#git) @@ -208,6 +209,10 @@ _1481 TILs and counting..._ - [List Running Docker Containers](docker/list-running-docker-containers.md) - [Run A Basic PostgreSQL Server In Docker](docker/run-a-basic-postgresql-server-in-docker.md) +### Drizzle + +- [Create bigint Identity Column For Primary Key](drizzle/create-bigint-identity-column-for-primary-key.md) + ### Elixir - [All Values For A Key In A Keyword List](elixir/all-values-for-a-key-in-a-keyword-list.md) diff --git a/drizzle/create-bigint-identity-column-for-primary-key.md b/drizzle/create-bigint-identity-column-for-primary-key.md new file mode 100644 index 0000000..99a28e3 --- /dev/null +++ b/drizzle/create-bigint-identity-column-for-primary-key.md @@ -0,0 +1,48 @@ +# Create bigint Identity Column For Primary Key + +Using the Drizzle ORM with Postgres, here is how we can create a table that +uses a [`bigint` data +type](https://orm.drizzle.team/docs/column-types/pg#bigint) as a primary key +[identity +column](https://www.postgresql.org/docs/current/ddl-identity-columns.html). + +```typescript +import { + pgTable, + bigint, + text, + timestamp, +} from "drizzle-orm/pg-core"; + +// Users table +export const users = pgTable("users", { + id: bigint({ mode: 'bigint' }).primaryKey().generatedAlwaysAsIdentity(), + email: text("email").unique().notNull(), + name: text("name").notNull(), + createdAt: timestamp("created_at").defaultNow().notNull(), +}); +``` + +There are a couple key pieces here: + +1. We import `bigint` so that we can declare a column of that type. +2. We specify that it is a primary key with `.primaryKey()`. +3. We declare its default value as `generated always as identity` via + `.generatedAlwaysAsIdentity()`. + +Note: you need to specify the `mode` for `bigint` or else you will see a +`TypeError: Cannot read properties of undefined (reading 'mode')` error. + +If we run `npx drizzle-kit generate` the SQL migration file that gets +generated will contain something like this: + +```sql +--> statement-breakpoint +CREATE TABLE IF NOT EXISTS "users" ( + "id" bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "users_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 START WITH 1 CACHE 1), + "email" text NOT NULL, + "name" text NOT NULL, + "created_at" timestamp DEFAULT now() NOT NULL, + CONSTRAINT "users_email_unique" UNIQUE("email") +); +```