-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
204 lines (176 loc) · 6.41 KB
/
app.py
File metadata and controls
204 lines (176 loc) · 6.41 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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
from flask import Flask, render_template, request
import mysql.connector
app = Flask(__name__)
# ---------- CONFIG ----------
DB_CONFIG = {
"host": "localhost",
"user": "root",
"password": "root@123", # <- change if needed
"database": "test_db"
}
db = mysql.connector.connect(**DB_CONFIG)
cursor = db.cursor(dictionary=True)
# ---------- HELPERS ----------
def get_tables():
cursor.execute("SHOW TABLES")
return [list(r.values())[0] for r in cursor.fetchall()]
def get_columns(table_name):
cursor.execute(f"DESCRIBE {table_name}")
return cursor.fetchall() # list of dicts: Field, Type, Null, Key, Default, Extra
def get_primary_column(table_name):
cursor.execute(f"SHOW KEYS FROM {table_name} WHERE Key_name='PRIMARY'")
r = cursor.fetchone()
return r['Column_name'] if r else None
def get_fk_map(table_name):
sql = """
SELECT COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME
FROM information_schema.KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s AND REFERENCED_TABLE_NAME IS NOT NULL
"""
cursor.execute(sql, (DB_CONFIG["database"], table_name))
res = cursor.fetchall()
fk = {}
for r in res:
fk[r['COLUMN_NAME']] = {
"ref_table": r['REFERENCED_TABLE_NAME'],
"ref_column": r['REFERENCED_COLUMN_NAME']
}
return fk
def get_display_column_for_table(table_name):
"""
Return a readable column name for building labels for dropdowns.
Prefer common names, otherwise first VARCHAR column, else primary key.
"""
cols = get_columns(table_name)
# Preferred names
for pref in ("name", "product_name", "designation", "Emergency_id"):
for c in cols:
if c['Field'].lower() == pref.lower():
return c['Field']
# pick first VARCHAR
for c in cols:
if 'varchar' in c['Type'].lower() or 'text' in c['Type'].lower():
return c['Field']
# fallback to primary key
pk = None
cursor.execute(f"SHOW KEYS FROM {table_name} WHERE Key_name='PRIMARY'")
r = cursor.fetchone()
if r:
return r['Column_name']
# else first column
return cols[0]['Field'] if cols else None
def get_fk_options(table_name):
fk_map = get_fk_map(table_name)
options = {}
for col, ref in fk_map.items():
ref_table = ref['ref_table']
ref_col = ref['ref_column']
# Find a readable display column
display_col = get_display_column_for_table(ref_table) or ref_col
cursor.execute(f"""
SELECT {ref_col} AS val, {display_col} AS lab
FROM {ref_table}
LIMIT 1000
""")
rows = cursor.fetchall()
opts = [(r['val'], f"{r['val']} — {r['lab']}") for r in rows]
options[col] = opts
return options
def get_fk_options(table_name):
fk_map = get_fk_map(table_name)
options = {}
for col, ref in fk_map.items():
ref_table = ref['ref_table']
ref_col = ref['ref_column']
# Find a readable display column
display_col = get_display_column_for_table(ref_table) or ref_col
cursor.execute(f"""
SELECT {ref_col} AS val, {display_col} AS lab
FROM {ref_table}
LIMIT 1000
""")
rows = cursor.fetchall()
opts = [(r['val'], f"{r['val']} — {r['lab']}") for r in rows]
options[col] = opts
return options
def insert_row(table_name, data_dict):
# remove empty dictionary
if not data_dict:
return
cols = ", ".join(data_dict.keys())
placeholders = ", ".join(["%s"] * len(data_dict))
values = list(data_dict.values())
sql = f"INSERT INTO {table_name} ({cols}) VALUES ({placeholders})"
cursor.execute(sql, values)
db.commit()
def delete_row(table_name, pk_value):
pk_col = get_primary_column(table_name)
if not pk_col:
return
cursor.execute(f"DELETE FROM {table_name} WHERE {pk_col} = %s", (pk_value,))
db.commit()
# ---------- ROUTE ----------
@app.route("/", methods=["GET", "POST"])
def home():
tables = get_tables()
selected_table = None
columns = None
data = None
msg = ""
fk_options = {}
# View table
if request.method == "POST" and request.form.get("action") == "view":
selected_table = request.form.get("table_name")
columns = get_columns(selected_table)
cursor.execute(f"SELECT * FROM {selected_table}")
data = cursor.fetchall()
fk_options = get_fk_options(selected_table)
# Add record
if request.method == "POST" and request.form.get("action") == "add_record":
table_name = request.form.get("table_name")
cols = get_columns(table_name)
# build insert dict: include every column that is NOT auto_increment
insert_data = {}
for c in cols:
field = c['Field']
if "auto_increment" in c['Extra']:
continue
# read value from form
v = request.form.get(field)
# treat empty string as None
if v is None or v == "":
v = None
insert_data[field] = v
try:
insert_row(table_name, insert_data)
msg = "Record added successfully!"
except mysql.connector.Error as e:
msg = f"ERROR: {e.msg}"
selected_table = table_name
columns = get_columns(selected_table)
cursor.execute(f"SELECT * FROM {selected_table}")
data = cursor.fetchall()
fk_options = get_fk_options(selected_table)
# Delete record
if request.method == "POST" and request.form.get("action") == "delete_record":
table_name = request.form.get("table_name")
pk_value = request.form.get("pk")
try:
delete_row(table_name, pk_value)
msg = "Record deleted."
except mysql.connector.Error as e:
msg = f"ERROR: {e.msg}"
selected_table = table_name
columns = get_columns(selected_table)
cursor.execute(f"SELECT * FROM {selected_table}")
data = cursor.fetchall()
fk_options = get_fk_options(selected_table)
return render_template("home.html",
tables=tables,
selected_table=selected_table,
columns=columns,
data=data,
fk_options=fk_options,
msg=msg)
if __name__ == "__main__":
app.run(debug=True)