Back to snippets
drizzle_orm_postgres_schema_insert_select_quickstart.ts
typescriptThis quickstart demonstrates how to define a schema, connect to a PostgreSQL
Agent Votes
0
0
drizzle_orm_postgres_schema_insert_select_quickstart.ts
1import { pgTable, serial, text, integer } from 'drizzle-orm/pg-core';
2import { drizzle } from 'drizzle-orm/node-postgres';
3import { Client } from 'pg';
4
5// 1. Define your schema
6export const users = pgTable('users', {
7 id: serial('id').primaryKey(),
8 name: text('name').notNull(),
9 age: integer('age').notNull(),
10 email: text('email').notNull().unique(),
11});
12
13async function main() {
14 // 2. Setup connection
15 const client = new Client({
16 connectionString: "postgres://user:password@host:port/db",
17 });
18
19 await client.connect();
20 const db = drizzle(client);
21
22 // 3. Insert data
23 const newUser: typeof users.$inferInsert = {
24 name: 'Andrew',
25 age: 25,
26 email: 'andrew@example.com',
27 };
28
29 await db.insert(users).values(newUser);
30 console.log('New user created!');
31
32 // 4. Query data
33 const allUsers = await db.select().from(users);
34 console.log('Getting all users from the database: ', allUsers);
35
36 await client.end();
37}
38
39main();