waliullah123 commited on
Commit
c81673d
·
verified ·
1 Parent(s): e9d657c

Upload init_db.py

Browse files
Files changed (1) hide show
  1. init_db.py +62 -0
init_db.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ init_db.py — Creates the users table if it does not exist.
3
+ Works with both Neon PostgreSQL (production) and SQLite (local dev).
4
+ """
5
+
6
+ from db import get_conn, USE_POSTGRES
7
+ import logging
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ def init_db():
13
+ conn = get_conn()
14
+ try:
15
+ cursor = conn.cursor()
16
+
17
+ if USE_POSTGRES:
18
+ # PostgreSQL schema
19
+ cursor.execute('''
20
+ CREATE TABLE IF NOT EXISTS users (
21
+ id SERIAL PRIMARY KEY,
22
+ username TEXT UNIQUE NOT NULL,
23
+ email TEXT,
24
+ password TEXT NOT NULL,
25
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
26
+ )
27
+ ''')
28
+ else:
29
+ # SQLite schema
30
+ cursor.execute('''
31
+ CREATE TABLE IF NOT EXISTS users (
32
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
33
+ username TEXT UNIQUE NOT NULL,
34
+ email TEXT,
35
+ password TEXT NOT NULL,
36
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
37
+ )
38
+ ''')
39
+ # Migration safety for existing SQLite DBs
40
+ try:
41
+ cursor.execute('ALTER TABLE users ADD COLUMN email TEXT')
42
+ except Exception:
43
+ pass # column already exists
44
+
45
+ conn.commit()
46
+ logger.info("Database initialized successfully.")
47
+ except Exception as e:
48
+ try:
49
+ conn.rollback()
50
+ except Exception:
51
+ pass
52
+ logger.warning(f"Database init warning: {e}")
53
+ finally:
54
+ try:
55
+ conn.close()
56
+ except Exception:
57
+ pass
58
+
59
+
60
+ if __name__ == '__main__':
61
+ init_db()
62
+ print("Database initialized.")