|
| 1 | +"""Create an empty sqlite database. |
| 2 | +""" |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from pathlib import Path |
| 6 | +from typing import Union |
| 7 | + |
| 8 | +from .schemas import SQLiteDB |
| 9 | + |
| 10 | +def init_sqlite_db(db_definition: SQLiteDB = None): |
| 11 | + """Initialize an empty SQLite database. |
| 12 | +
|
| 13 | + Params: |
| 14 | + ------- |
| 15 | + - db_definition (SQLiteDB): An initialized SQLiteDB object defining the SQLite database to create. |
| 16 | + """ |
| 17 | + if db_definition is None: |
| 18 | + raise ValueError("Missing SQLiteDB object.") |
| 19 | + |
| 20 | + if db_definition.exists: |
| 21 | + print(f"Database already exists at {db_definition.db_path}") |
| 22 | + return False |
| 23 | + |
| 24 | + try: |
| 25 | + db_definition.create_empty_db() |
| 26 | + |
| 27 | + return True |
| 28 | + |
| 29 | + except Exception as exc: |
| 30 | + msg = Exception( |
| 31 | + f"Unhandled exception initializing empty SQLite database. Details: {exc}" |
| 32 | + ) |
| 33 | + print(msg) |
| 34 | + |
| 35 | + return False |
| 36 | + |
| 37 | + |
| 38 | +def get_demo_db() -> SQLiteDB: |
| 39 | + """Return an initialized SQLiteDB object with default settings. |
| 40 | +
|
| 41 | + A new database called "demo.db" will be created at the default '.db' path. |
| 42 | + """ |
| 43 | + try: |
| 44 | + _db: SQLiteDB = SQLiteDB() |
| 45 | + return _db |
| 46 | + except Exception as exc: |
| 47 | + raise Exception( |
| 48 | + f"Unhandled exception initializing default database. Details: {exc}" |
| 49 | + ) |
| 50 | + |
| 51 | + |
| 52 | +def get_sqlite_db(name: str = None, location: Union[str, Path] = None) -> SQLiteDB: |
| 53 | + """Initialize a SQLiteDB object. |
| 54 | +
|
| 55 | + This is the same as simply instantiating a SQLiteDB object, like: |
| 56 | + example_db: SQLiteDB = SQLiteDB(name=..., location=...) |
| 57 | +
|
| 58 | + Params: |
| 59 | + ------- |
| 60 | + - name (str): The name of the SQLite database. This will be used for the filename. |
| 61 | + - location (str|Path): The directory location to save the database. Note that Path values will be converted to string, then |
| 62 | + back to Path, so it is best to just pass the location as a string. |
| 63 | + """ |
| 64 | + if name is None: |
| 65 | + raise ValueError("Missing database name") |
| 66 | + if location is None: |
| 67 | + raise ValueError("Missing output path location for database") |
| 68 | + if isinstance(location, Path): |
| 69 | + location: str = str(location) |
| 70 | + |
| 71 | + try: |
| 72 | + _db: SQLiteDB = SQLiteDB(name=name, location=location) |
| 73 | + return _db |
| 74 | + except Exception as exc: |
| 75 | + raise Exception(f"Unhandled exception creating SQLite database. Details: {exc}") |
| 76 | + |
| 77 | + |
| 78 | +if __name__ == "__main__": |
| 79 | + demo_db: SQLiteDB = SQLiteDB() |
| 80 | + print(demo_db.stat_str) |
| 81 | + |
| 82 | + init_sqlite_db(demo_db) |
0 commit comments