-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathstart.ts
More file actions
130 lines (113 loc) · 4.26 KB
/
start.ts
File metadata and controls
130 lines (113 loc) · 4.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import dotenv from "dotenv";
import path from "path";
// Local-only: try to load .env / .env.local when running tools like db:migrate.
// In Vercel Lambdas these files don't exist, so these calls are harmless no-ops.
const cwd = process.cwd();
dotenv.config({ path: path.join(cwd, ".env") });
dotenv.config({ path: path.join(cwd, ".env.local") });
import { neon } from "@neondatabase/serverless";
const connectionString = process.env.DATABASE_URL;
if (!connectionString) {
// Fail fast on the server side so misconfiguration is obvious in logs.
throw new Error(
"DATABASE_URL is not set. Configure it in ./.env for the current Neon branch.",
);
}
export const sql = neon(connectionString);
async function runSchemaMigrations() {
// users table
await sql`
CREATE TABLE IF NOT EXISTS users (
telegram_username TEXT PRIMARY KEY,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
last_login_at TIMESTAMPTZ,
last_tma_seen_at TIMESTAMPTZ,
locale TEXT,
time_zone TEXT,
default_wallet BIGINT
);
`;
// wallets table
await sql`
CREATE TABLE IF NOT EXISTS wallets (
id BIGSERIAL PRIMARY KEY,
telegram_username TEXT NOT NULL REFERENCES users(telegram_username),
wallet_address TEXT NOT NULL,
wallet_blockchain TEXT NOT NULL,
wallet_net TEXT NOT NULL,
type TEXT NOT NULL,
label TEXT,
is_default BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
last_used_at TIMESTAMPTZ,
last_seen_balance_at TIMESTAMPTZ,
source TEXT,
notes TEXT,
UNIQUE (telegram_username, wallet_address, wallet_blockchain, wallet_net)
);
`;
// pending_transactions table
await sql`
CREATE TABLE IF NOT EXISTS pending_transactions (
id TEXT PRIMARY KEY,
telegram_username TEXT NOT NULL REFERENCES users(telegram_username),
wallet_address TEXT NOT NULL,
wallet_blockchain TEXT NOT NULL,
wallet_net TEXT NOT NULL,
payload JSONB NOT NULL,
status TEXT NOT NULL CHECK (status IN ('pending', 'confirmed', 'rejected', 'failed')),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
`;
// Helpful indexes
await sql`
CREATE INDEX IF NOT EXISTS idx_wallets_user
ON wallets(telegram_username);
`;
await sql`
CREATE INDEX IF NOT EXISTS idx_pending_tx_user
ON pending_transactions(telegram_username);
`;
await sql`
CREATE INDEX IF NOT EXISTS idx_pending_tx_status
ON pending_transactions(status);
`;
// messages table (AI: bot + TMA)
await sql`
CREATE TABLE IF NOT EXISTS messages (
id BIGSERIAL PRIMARY KEY,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
user_telegram TEXT NOT NULL REFERENCES users(telegram_username),
thread_id BIGINT NOT NULL,
type TEXT NOT NULL CHECK (type IN ('bot', 'app')),
role TEXT NOT NULL CHECK (role IN ('user', 'assistant', 'system')),
content TEXT,
telegram_update_id BIGINT
);
`;
await sql`
CREATE INDEX IF NOT EXISTS idx_messages_thread
ON messages(user_telegram, thread_id, type, created_at);
`;
await sql`
CREATE UNIQUE INDEX IF NOT EXISTS idx_messages_bot_update_id
ON messages(user_telegram, thread_id, type, telegram_update_id)
WHERE telegram_update_id IS NOT NULL;
`;
}
let schemaInitPromise: Promise<void> | null = null;
export function ensureSchema(): Promise<void> {
if (!schemaInitPromise) {
schemaInitPromise = runSchemaMigrations().catch((err) => {
console.error("[db] schema init failed", err);
schemaInitPromise = null;
throw err;
});
}
return schemaInitPromise;
}
// Schema runs at deploy via `npm run db:migrate` in buildCommand. No schema work
// in the request path — keeps /api/telegram and other routes fast (no 504).