|
| 1 | +import os |
| 2 | + |
| 3 | +from sqlalchemy import ( |
| 4 | + Boolean, |
| 5 | + Column, |
| 6 | + ForeignKey, |
| 7 | + Integer, |
| 8 | + MetaData, |
| 9 | + String, |
| 10 | + Table, |
| 11 | + Text, |
| 12 | + create_engine, |
| 13 | +) |
| 14 | +from sqlalchemy_utils import create_database, database_exists |
| 15 | + |
| 16 | + |
| 17 | +class DatabaseMigration: |
| 18 | + """Class for handling the postgresql database migration""" |
| 19 | + |
| 20 | + def __init__(self) -> None: |
| 21 | + """Initialize the Database object with a database connection""" |
| 22 | + try: |
| 23 | + self.engine = create_engine(os.getenv("DB_URI"), echo=True) |
| 24 | + except Exception as e: |
| 25 | + print(f"Error creating engine: {e}") |
| 26 | + else: |
| 27 | + self.connection = self.engine.connect() |
| 28 | + |
| 29 | + def create_database(self): |
| 30 | + """Create the database""" |
| 31 | + if not database_exists(self.engine.url): |
| 32 | + create_database(self.engine.url) |
| 33 | + |
| 34 | + def run_migrations(self): |
| 35 | + """Run the database migrations""" |
| 36 | + try: |
| 37 | + self.create_table_pages() |
| 38 | + # self.create_table_index() |
| 39 | + except Exception as e: |
| 40 | + print(f"Error running migrations: {e}") |
| 41 | + else: |
| 42 | + print("Migrations ran successfully") |
| 43 | + |
| 44 | + def create_table_pages(self): |
| 45 | + """Create the pages table""" |
| 46 | + metadata = MetaData() |
| 47 | + pages = Table( # noqa: F841 |
| 48 | + "pages", |
| 49 | + metadata, |
| 50 | + Column("id", Integer, primary_key=True), |
| 51 | + Column("title", String), |
| 52 | + Column("md", Text), |
| 53 | + Column("url", String), |
| 54 | + Column("sub_page", Boolean, default=False), |
| 55 | + ) |
| 56 | + index = Table( # noqa: F841 |
| 57 | + "index", |
| 58 | + metadata, |
| 59 | + Column("id", Integer, primary_key=True), |
| 60 | + Column("pages_id", ForeignKey("pages.id")), |
| 61 | + ) |
| 62 | + metadata.create_all(self.engine) |
| 63 | + self.connection.commit() |
| 64 | + |
| 65 | + def create_table_index(self): |
| 66 | + """Create the index table""" |
| 67 | + metadata = MetaData() |
| 68 | + index = Table( # noqa: F841 |
| 69 | + "index", |
| 70 | + metadata, |
| 71 | + Column("id", Integer, primary_key=True), |
| 72 | + Column("pages_id", ForeignKey("pages.id")), |
| 73 | + ) |
| 74 | + metadata.create_all(self.engine) |
| 75 | + |
| 76 | + def drop_tables(self): |
| 77 | + """Drop the tables""" |
| 78 | + metadata = MetaData() |
| 79 | + pages = Table("pages", metadata) # noqa: F841 |
| 80 | + index = Table("index", metadata) # noqa: F841 |
| 81 | + metadata.drop_all(self.engine) |
| 82 | + self.connection.commit() |
| 83 | + print("Tables dropped successfully") |
0 commit comments