-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathdb_init.py
More file actions
49 lines (33 loc) · 1.34 KB
/
db_init.py
File metadata and controls
49 lines (33 loc) · 1.34 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
"""
Database initialization script.
This script can be used to init or re-init database tables.
CAUTION: it will DROP ALL DATA in the tables!
Uncomment the exit() line below to run it.
"""
exit("COMMENT THIS LINE IN ORDER TO RE-INIT DATABASE TABLES")
import asyncio
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
from db.database import ormar_config
from db.models import Member, Spam
async def reinit_db_tables() -> None:
"""Drop and recreate all database tables."""
logger.info("Connecting to database...")
if not ormar_config.database.is_connected:
await ormar_config.database.connect()
logger.warning("Dropping all tables...")
async with ormar_config.engine.begin() as conn:
await conn.run_sync(ormar_config.metadata.drop_all)
logger.info("Creating tables...")
async with ormar_config.engine.begin() as conn:
await conn.run_sync(ormar_config.metadata.create_all)
await ormar_config.database.disconnect()
await ormar_config.engine.dispose()
logger.info("Database tables recreated successfully!")
if __name__ == "__main__":
asyncio.run(reinit_db_tables())
exit("DONE")
# For SQLite you can also use synchronous version:
# ormar_config.metadata.drop_all(ormar_config.engine)
# ormar_config.metadata.create_all(ormar_config.engine)