Back to Drizzle Orm

QueryNile

src/mdx/get-started/postgresql/QueryNile.mdx

latest1.7 KB
Original Source

import CodeWithProps from "@mdx/CodeWithProps.astro";

Let's update the src/index.ts file with queries to create, read, update, and delete tenants and todos.

<CodeWithProps dialect='node-postgres' env_variable='NILEDB_URL'> ```typescript copy filename="src/index.ts" import 'dotenv/config'; import { drizzle } from 'drizzle-orm/$dialect$'; import { eq, sql } from 'drizzle-orm'; import { tenantsTable, todosTable } from './db/schema';

const db = drizzle(process.env.$env_variable$!);

async function main() { const tenant: typeof tenantsTable.$inferInsert = { name: 'AwesomeSauce Inc.', };

await db.insert(tenantsTable).values(tenant); console.log('New tenant created!')

const tenants = await db.select().from(tenantsTable); console.log('Getting all tenants from the database: ', tenants)

const todo: typeof todosTable.$inferInsert = { tenantId: tenants[0].id, title: 'Update pitch deck with AI stuff' }

await db.insert(todosTable).values(todo); console.log('New todo created!')

const todos = await db.select().from(todosTable); console.log('Getting all todos from the database: ', todos)

await db.execute(sqlSET nile.tenant_id = '${sql.raw(tenants[0].id)}'); console.log("Set tenant context");

// note the lack of tenant_id in the query const tenant_todos = await db.select().from(todosTable); console.log('Getting all todos from the tenant virtual database: ', tenant_todos)

await db .update(todosTable) .set({ complete: true, }) .where(eq(todosTable.id, todo.id)); console.log('Todo marked as done!')

await db.delete(todosTable).where(eq(todosTable.id, todo.id)); console.log('Todo deleted!') }

main();

</CodeWithProps>