Skip to content

Commit fde8ecf

Browse files
authored
Merge pull request vercel#56 from erasta/patch-1
ensureTableExists to create users table on the first run
2 parents 6c5ca25 + 88e6577 commit fde8ecf

File tree

1 file changed

+28
-6
lines changed

1 file changed

+28
-6
lines changed

app/db.ts

+28-6
Original file line numberDiff line numberDiff line change
@@ -10,19 +10,41 @@ import { genSaltSync, hashSync } from 'bcrypt-ts';
1010
let client = postgres(`${process.env.POSTGRES_URL!}?sslmode=require`);
1111
let db = drizzle(client);
1212

13-
let users = pgTable('User', {
14-
id: serial('id').primaryKey(),
15-
email: varchar('email', { length: 64 }),
16-
password: varchar('password', { length: 64 }),
17-
});
18-
1913
export async function getUser(email: string) {
14+
const users = await ensureTableExists();
2015
return await db.select().from(users).where(eq(users.email, email));
2116
}
2217

2318
export async function createUser(email: string, password: string) {
19+
const users = await ensureTableExists();
2420
let salt = genSaltSync(10);
2521
let hash = hashSync(password, salt);
2622

2723
return await db.insert(users).values({ email, password: hash });
2824
}
25+
26+
async function ensureTableExists() {
27+
const result = await client`
28+
SELECT EXISTS (
29+
SELECT FROM information_schema.tables
30+
WHERE table_schema = 'public'
31+
AND table_name = 'User'
32+
);`;
33+
34+
if (!result[0].exists) {
35+
await client`
36+
CREATE TABLE "User" (
37+
id SERIAL PRIMARY KEY,
38+
email VARCHAR(64),
39+
password VARCHAR(64)
40+
);`;
41+
}
42+
43+
const table = pgTable('User', {
44+
id: serial('id').primaryKey(),
45+
email: varchar('email', { length: 64 }),
46+
password: varchar('password', { length: 64 }),
47+
});
48+
49+
return table;
50+
}

0 commit comments

Comments
 (0)