Azizul Hakim
commited on
app.py
Browse files
app.py
CHANGED
|
@@ -64,13 +64,29 @@ def get_database_names():
|
|
| 64 |
conn.close()
|
| 65 |
return databases
|
| 66 |
|
| 67 |
-
def create_table(db_name, columns, column_types):
|
| 68 |
-
"""Create a new table with specified column types"""
|
| 69 |
conn = sqlite3.connect(f'databases/{db_name}.db')
|
| 70 |
c = conn.cursor()
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
query = f'''CREATE TABLE IF NOT EXISTS data
|
| 73 |
-
({', '.join(
|
|
|
|
| 74 |
c.execute(query)
|
| 75 |
conn.commit()
|
| 76 |
conn.close()
|
|
@@ -85,9 +101,15 @@ def get_columns(db_name):
|
|
| 85 |
conn = sqlite3.connect(f'databases/{db_name}.db')
|
| 86 |
c = conn.cursor()
|
| 87 |
c.execute("PRAGMA table_info(data)")
|
| 88 |
-
columns = [(row[1], row[2]) for row in c.fetchall()]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
conn.close()
|
| 90 |
-
return columns
|
| 91 |
|
| 92 |
def delete_rows(db_name, condition_col, condition_val):
|
| 93 |
"""Delete rows based on condition"""
|
|
@@ -100,24 +122,39 @@ def delete_rows(db_name, condition_col, condition_val):
|
|
| 100 |
return deleted_count
|
| 101 |
|
| 102 |
def update_row(db_name, condition_col, condition_val, update_col, update_val):
|
| 103 |
-
"""Update row based on condition"""
|
| 104 |
conn = sqlite3.connect(f'databases/{db_name}.db')
|
| 105 |
c = conn.cursor()
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
def bulk_import_data(db_name, df):
|
| 114 |
"""Bulk import data from DataFrame"""
|
| 115 |
conn = sqlite3.connect(f'databases/{db_name}.db')
|
| 116 |
-
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
def main():
|
| 120 |
-
|
| 121 |
st.title("ποΈ Database Operations Tool")
|
| 122 |
|
| 123 |
# Sidebar for database operations
|
|
@@ -129,13 +166,13 @@ def main():
|
|
| 129 |
new_db_name = st.text_input("Database Name")
|
| 130 |
columns_input = st.text_input("Column Names (comma-separated)")
|
| 131 |
|
| 132 |
-
# Modified column type selection
|
| 133 |
if columns_input:
|
| 134 |
columns = [col.strip() for col in columns_input.split(",")]
|
| 135 |
column_types = []
|
| 136 |
|
| 137 |
# Create a select box for each column
|
| 138 |
-
st.write("Select type
|
| 139 |
for col in columns:
|
| 140 |
col_type = st.selectbox(
|
| 141 |
f"Type for {col}",
|
|
@@ -143,6 +180,20 @@ def main():
|
|
| 143 |
key=f"type_{col}" # Unique key for each selectbox
|
| 144 |
)
|
| 145 |
column_types.append(col_type)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
if st.button("Create Database"):
|
| 148 |
if new_db_name and columns_input and len(columns) > 0:
|
|
@@ -153,7 +204,15 @@ def main():
|
|
| 153 |
(new_db_name, datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
|
| 154 |
conn.commit()
|
| 155 |
conn.close()
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
st.success("β
Database created successfully!")
|
| 158 |
except sqlite3.IntegrityError:
|
| 159 |
st.error("β Database name already exists!")
|
|
@@ -167,7 +226,19 @@ def main():
|
|
| 167 |
|
| 168 |
if selected_db:
|
| 169 |
df = get_table_data(selected_db)
|
| 170 |
-
columns = get_columns(selected_db)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
tabs = st.tabs(["π Manage Data", "π Update Data", "ποΈ Delete Data", "π₯ Import/Export"])
|
| 173 |
|
|
@@ -178,7 +249,7 @@ def main():
|
|
| 178 |
|
| 179 |
st.subheader("Add New Row")
|
| 180 |
new_row_data = {}
|
| 181 |
-
for col, type_ in columns:
|
| 182 |
if type_ == 'DATE':
|
| 183 |
new_row_data[col] = st.date_input(f"Enter {col}")
|
| 184 |
elif type_ == 'INTEGER':
|
|
@@ -192,41 +263,62 @@ def main():
|
|
| 192 |
if all(str(val) != "" for val in new_row_data.values()):
|
| 193 |
conn = sqlite3.connect(f'databases/{selected_db}.db')
|
| 194 |
c = conn.cursor()
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
|
| 203 |
# Update Data Tab
|
| 204 |
with tabs[1]:
|
| 205 |
st.subheader("Update Records")
|
| 206 |
col1, col2 = st.columns(2)
|
| 207 |
-
|
| 208 |
with col1:
|
| 209 |
condition_col = st.selectbox("Select Column for Condition",
|
| 210 |
-
|
| 211 |
condition_val = st.text_input("Enter Value to Match")
|
| 212 |
-
|
| 213 |
with col2:
|
| 214 |
update_col = st.selectbox("Select Column to Update",
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
if st.button("Update Records"):
|
| 219 |
-
if condition_val and
|
|
|
|
|
|
|
|
|
|
| 220 |
updated = update_row(selected_db, condition_col,
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
|
|
|
|
|
|
|
|
|
| 224 |
|
| 225 |
# Delete Data Tab
|
| 226 |
with tabs[2]:
|
| 227 |
st.subheader("Delete Records")
|
| 228 |
del_col = st.selectbox("Select Column for Deletion Condition",
|
| 229 |
-
[col for col, _ in columns])
|
| 230 |
del_val = st.text_input("Enter Value to Delete")
|
| 231 |
|
| 232 |
if st.button("Delete Records"):
|
|
@@ -242,9 +334,10 @@ def main():
|
|
| 242 |
if uploaded_file is not None:
|
| 243 |
import_df = pd.read_csv(uploaded_file)
|
| 244 |
if st.button("Import Data"):
|
| 245 |
-
bulk_import_data(selected_db, import_df)
|
| 246 |
-
|
| 247 |
-
|
|
|
|
| 248 |
|
| 249 |
st.subheader("Export Data")
|
| 250 |
export_format = st.selectbox("Select Format",
|
|
|
|
| 64 |
conn.close()
|
| 65 |
return databases
|
| 66 |
|
| 67 |
+
def create_table(db_name, columns, column_types, primary_key=None, unique_columns=None):
|
| 68 |
+
"""Create a new table with specified column types, optional primary key, and unique columns"""
|
| 69 |
conn = sqlite3.connect(f'databases/{db_name}.db')
|
| 70 |
c = conn.cursor()
|
| 71 |
+
|
| 72 |
+
# Prepare column definitions
|
| 73 |
+
column_defs = []
|
| 74 |
+
for col, type_ in zip(columns, column_types):
|
| 75 |
+
col_def = f"{col} {type_}"
|
| 76 |
+
|
| 77 |
+
# Set primary key
|
| 78 |
+
if primary_key and col == primary_key:
|
| 79 |
+
col_def += " PRIMARY KEY"
|
| 80 |
+
|
| 81 |
+
# Set unique columns
|
| 82 |
+
if unique_columns and col in unique_columns:
|
| 83 |
+
col_def += " UNIQUE"
|
| 84 |
+
|
| 85 |
+
column_defs.append(col_def)
|
| 86 |
+
|
| 87 |
query = f'''CREATE TABLE IF NOT EXISTS data
|
| 88 |
+
({', '.join(column_defs)})'''
|
| 89 |
+
|
| 90 |
c.execute(query)
|
| 91 |
conn.commit()
|
| 92 |
conn.close()
|
|
|
|
| 101 |
conn = sqlite3.connect(f'databases/{db_name}.db')
|
| 102 |
c = conn.cursor()
|
| 103 |
c.execute("PRAGMA table_info(data)")
|
| 104 |
+
columns = [(row[1], row[2], row[5] == 1) for row in c.fetchall()] # name, type, is_primary_key
|
| 105 |
+
|
| 106 |
+
# Check for unique columns
|
| 107 |
+
c.execute("PRAGMA index_list(data)")
|
| 108 |
+
unique_columns = [row[1].replace('data_', '').replace('_unique', '')
|
| 109 |
+
for row in c.fetchall() if 'unique' in row[1]]
|
| 110 |
+
|
| 111 |
conn.close()
|
| 112 |
+
return columns, unique_columns
|
| 113 |
|
| 114 |
def delete_rows(db_name, condition_col, condition_val):
|
| 115 |
"""Delete rows based on condition"""
|
|
|
|
| 122 |
return deleted_count
|
| 123 |
|
| 124 |
def update_row(db_name, condition_col, condition_val, update_col, update_val):
|
| 125 |
+
"""Update row based on condition with more flexible value setting"""
|
| 126 |
conn = sqlite3.connect(f'databases/{db_name}.db')
|
| 127 |
c = conn.cursor()
|
| 128 |
+
|
| 129 |
+
try:
|
| 130 |
+
# Update with exact value assignment
|
| 131 |
+
c.execute(f"UPDATE data SET {update_col} = ? WHERE {condition_col} = ?",
|
| 132 |
+
(update_val, condition_val))
|
| 133 |
+
updated_count = c.rowcount
|
| 134 |
+
conn.commit()
|
| 135 |
+
return updated_count
|
| 136 |
+
except sqlite3.IntegrityError as e:
|
| 137 |
+
st.error(f"Update failed: {str(e)}")
|
| 138 |
+
return 0
|
| 139 |
+
except sqlite3.OperationalError as e:
|
| 140 |
+
st.error(f"SQL Error: {str(e)}")
|
| 141 |
+
return 0
|
| 142 |
+
finally:
|
| 143 |
+
conn.close()
|
| 144 |
|
| 145 |
def bulk_import_data(db_name, df):
|
| 146 |
"""Bulk import data from DataFrame"""
|
| 147 |
conn = sqlite3.connect(f'databases/{db_name}.db')
|
| 148 |
+
try:
|
| 149 |
+
df.to_sql('data', conn, if_exists='append', index=False)
|
| 150 |
+
return True
|
| 151 |
+
except sqlite3.IntegrityError as e:
|
| 152 |
+
st.error(f"Import failed: {str(e)}")
|
| 153 |
+
return False
|
| 154 |
+
finally:
|
| 155 |
+
conn.close()
|
| 156 |
|
| 157 |
def main():
|
|
|
|
| 158 |
st.title("ποΈ Database Operations Tool")
|
| 159 |
|
| 160 |
# Sidebar for database operations
|
|
|
|
| 166 |
new_db_name = st.text_input("Database Name")
|
| 167 |
columns_input = st.text_input("Column Names (comma-separated)")
|
| 168 |
|
| 169 |
+
# Modified column type and primary key selection
|
| 170 |
if columns_input:
|
| 171 |
columns = [col.strip() for col in columns_input.split(",")]
|
| 172 |
column_types = []
|
| 173 |
|
| 174 |
# Create a select box for each column
|
| 175 |
+
st.write("Select type and configure each column:")
|
| 176 |
for col in columns:
|
| 177 |
col_type = st.selectbox(
|
| 178 |
f"Type for {col}",
|
|
|
|
| 180 |
key=f"type_{col}" # Unique key for each selectbox
|
| 181 |
)
|
| 182 |
column_types.append(col_type)
|
| 183 |
+
|
| 184 |
+
# Primary key selection
|
| 185 |
+
primary_key = st.selectbox(
|
| 186 |
+
"Select Primary Key Column (optional)",
|
| 187 |
+
["None"] + columns,
|
| 188 |
+
index=0
|
| 189 |
+
)
|
| 190 |
+
primary_key = None if primary_key == "None" else primary_key
|
| 191 |
+
|
| 192 |
+
# Unique columns selection
|
| 193 |
+
unique_columns = st.multiselect(
|
| 194 |
+
"Select Unique Columns (optional)",
|
| 195 |
+
columns
|
| 196 |
+
)
|
| 197 |
|
| 198 |
if st.button("Create Database"):
|
| 199 |
if new_db_name and columns_input and len(columns) > 0:
|
|
|
|
| 204 |
(new_db_name, datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
|
| 205 |
conn.commit()
|
| 206 |
conn.close()
|
| 207 |
+
|
| 208 |
+
# Create table with primary key and unique columns
|
| 209 |
+
create_table(
|
| 210 |
+
new_db_name,
|
| 211 |
+
columns,
|
| 212 |
+
column_types,
|
| 213 |
+
primary_key,
|
| 214 |
+
unique_columns
|
| 215 |
+
)
|
| 216 |
st.success("β
Database created successfully!")
|
| 217 |
except sqlite3.IntegrityError:
|
| 218 |
st.error("β Database name already exists!")
|
|
|
|
| 226 |
|
| 227 |
if selected_db:
|
| 228 |
df = get_table_data(selected_db)
|
| 229 |
+
columns, unique_columns = get_columns(selected_db)
|
| 230 |
+
|
| 231 |
+
# Display current table constraints
|
| 232 |
+
st.sidebar.subheader("Table Constraints")
|
| 233 |
+
columns_info = [col for col, _, _ in columns]
|
| 234 |
+
|
| 235 |
+
# Highlight primary key and unique columns
|
| 236 |
+
primary_key = next((col for col, _, is_primary in columns if is_primary), None)
|
| 237 |
+
if primary_key:
|
| 238 |
+
st.sidebar.info(f"π Primary Key: {primary_key}")
|
| 239 |
+
|
| 240 |
+
if unique_columns:
|
| 241 |
+
st.sidebar.warning(f"π« Unique Columns: {', '.join(unique_columns)}")
|
| 242 |
|
| 243 |
tabs = st.tabs(["π Manage Data", "π Update Data", "ποΈ Delete Data", "π₯ Import/Export"])
|
| 244 |
|
|
|
|
| 249 |
|
| 250 |
st.subheader("Add New Row")
|
| 251 |
new_row_data = {}
|
| 252 |
+
for col, type_, is_primary in columns:
|
| 253 |
if type_ == 'DATE':
|
| 254 |
new_row_data[col] = st.date_input(f"Enter {col}")
|
| 255 |
elif type_ == 'INTEGER':
|
|
|
|
| 263 |
if all(str(val) != "" for val in new_row_data.values()):
|
| 264 |
conn = sqlite3.connect(f'databases/{selected_db}.db')
|
| 265 |
c = conn.cursor()
|
| 266 |
+
try:
|
| 267 |
+
placeholders = ','.join(['?' for _ in columns])
|
| 268 |
+
query = f"INSERT INTO data VALUES ({placeholders})"
|
| 269 |
+
c.execute(query, list(new_row_data.values()))
|
| 270 |
+
conn.commit()
|
| 271 |
+
st.success("β
Row added!")
|
| 272 |
+
st.rerun()
|
| 273 |
+
except sqlite3.IntegrityError as e:
|
| 274 |
+
st.error(f"β Insert failed: {str(e)}")
|
| 275 |
+
finally:
|
| 276 |
+
conn.close()
|
| 277 |
|
| 278 |
# Update Data Tab
|
| 279 |
with tabs[1]:
|
| 280 |
st.subheader("Update Records")
|
| 281 |
col1, col2 = st.columns(2)
|
| 282 |
+
|
| 283 |
with col1:
|
| 284 |
condition_col = st.selectbox("Select Column for Condition",
|
| 285 |
+
[col for col, _, _ in columns])
|
| 286 |
condition_val = st.text_input("Enter Value to Match")
|
| 287 |
+
|
| 288 |
with col2:
|
| 289 |
update_col = st.selectbox("Select Column to Update",
|
| 290 |
+
[col for col, _, _ in columns])
|
| 291 |
+
# Different input method based on column type
|
| 292 |
+
column_types_dict = {col: type_ for col, type_, _ in columns}
|
| 293 |
+
update_val_input = None
|
| 294 |
+
|
| 295 |
+
if column_types_dict[update_col] == 'INTEGER':
|
| 296 |
+
update_val_input = st.number_input(f"Enter New Value for {update_col}", step=1)
|
| 297 |
+
elif column_types_dict[update_col] == 'REAL':
|
| 298 |
+
update_val_input = st.number_input(f"Enter New Value for {update_col}", step=0.1)
|
| 299 |
+
elif column_types_dict[update_col] == 'DATE':
|
| 300 |
+
update_val_input = st.date_input(f"Enter New Value for {update_col}")
|
| 301 |
+
else:
|
| 302 |
+
update_val_input = st.text_input(f"Enter New Value for {update_col}")
|
| 303 |
+
|
| 304 |
if st.button("Update Records"):
|
| 305 |
+
if condition_val is not None and update_val_input is not None:
|
| 306 |
+
# Convert update_val_input to string to work with SQLite
|
| 307 |
+
update_val = str(update_val_input)
|
| 308 |
+
|
| 309 |
updated = update_row(selected_db, condition_col,
|
| 310 |
+
condition_val, update_col, update_val)
|
| 311 |
+
if updated > 0:
|
| 312 |
+
st.success(f"β
Updated {updated} records!")
|
| 313 |
+
st.rerun()
|
| 314 |
+
else:
|
| 315 |
+
st.warning("No records were updated. Check your conditions.")
|
| 316 |
|
| 317 |
# Delete Data Tab
|
| 318 |
with tabs[2]:
|
| 319 |
st.subheader("Delete Records")
|
| 320 |
del_col = st.selectbox("Select Column for Deletion Condition",
|
| 321 |
+
[col for col, _, _ in columns])
|
| 322 |
del_val = st.text_input("Enter Value to Delete")
|
| 323 |
|
| 324 |
if st.button("Delete Records"):
|
|
|
|
| 334 |
if uploaded_file is not None:
|
| 335 |
import_df = pd.read_csv(uploaded_file)
|
| 336 |
if st.button("Import Data"):
|
| 337 |
+
success = bulk_import_data(selected_db, import_df)
|
| 338 |
+
if success:
|
| 339 |
+
st.success("β
Data imported successfully!")
|
| 340 |
+
st.rerun()
|
| 341 |
|
| 342 |
st.subheader("Export Data")
|
| 343 |
export_format = st.selectbox("Select Format",
|