Build a Finance SaaS Platform -5 (Database Neon)

Sign up Neon

Go to https://neon.tech/ ,Sign up,and get sql connetion string and add it to .env:

1
DATABASE_URL=postgresql://xxxx

Install drizzle-orm

1
2
npm i drizzle-orm @neondatabase/serverless
npm i -D drizzle-kit

Add Drizzle config

Add db/drizzle.ts

1
2
3
4
5
6
import { neon } from '@neondatabase/serverless';
import { drizzle } from 'drizzle-orm/neon-http';

export const sql = neon(process.env.DATABASE_URL!);
export const db = drizzle(sql);

Add Schema

Add db/schema.ts

1
2
3
4
5
6
7
import { pgTable, PgTable, text} from "drizzle-orm/pg-core"

export const accounts = pgTable("accounts", {
id: text("id").primaryKey(),
name: text("name").notNull(),
userId: text("user_id").notNull(),
})

Instal dotenv

1
npm i -D dotenv

Add migrate file

Add scripts/migrate.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { config } from "dotenv";
import { neon } from "@neondatabase/serverless";
import { drizzle } from "drizzle-orm/neon-http";
import { migrate } from "drizzle-orm/neon-http/migrator";

config({ path:".env.local"});

const sql = neon(process.env.DATABASE_URL!);
const db = drizzle(sql);

const main = async () => {""
try {
await migrate(db, { migrationsFolder: "drizzle" });
} catch (error) {
console.error("Error during migration:", error );
process.exit();
}
};

main();

Install tsx

1
npm i tsx

Edit package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"name": "finance-demo",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"db:generate": "drizzle-kit generate --dialect=postgresql --schema=./db/schema.ts --out=./drizzle",
"db:migrate": "tsx ./scripts/migrate.ts",
"db:studio": "drizzle-kit studio"
},
...

Run Script:

1
2
npm run db:generate

请我喝杯咖啡吧~

支付宝
微信