python-glowplug 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,9 @@
1
+
2
+
3
+ Copyright 2024 Joe Nudell
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,38 @@
1
+ Metadata-Version: 2.1
2
+ Name: python-glowplug
3
+ Version: 0.1.0
4
+ Summary:
5
+ Home-page: https://github.com/jnu/python-glowplug
6
+ License: MIT
7
+ Author: Joe Nudell
8
+ Author-email: jnudell@hks.harvard.edu
9
+ Requires-Python: >=3.9,<4.0
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Requires-Dist: sqlalchemy (>=2,<3)
17
+ Project-URL: Repository, https://github.com/jnu/python-glowplug
18
+ Description-Content-Type: text/markdown
19
+
20
+ Glowplug
21
+ ===
22
+
23
+ A consistent interface for maintenance operations on database engines not covered by SQLAlchemy.
24
+
25
+ Chooses opinionated drivers with both async + sync support.
26
+
27
+ ## Supported operations
28
+
29
+ - `exists` - Check if database exists
30
+ - `create` - Create a new database
31
+ - `init` - Create all tables in the given database, optionally dropping first
32
+
33
+ ## Supported databases
34
+
35
+ - SQLite (`aiosqlite`)
36
+ - Postgres (`asyncpg`)
37
+ - MS Sql (`pyodbc` and `aioodbc`)
38
+
@@ -0,0 +1,18 @@
1
+ Glowplug
2
+ ===
3
+
4
+ A consistent interface for maintenance operations on database engines not covered by SQLAlchemy.
5
+
6
+ Chooses opinionated drivers with both async + sync support.
7
+
8
+ ## Supported operations
9
+
10
+ - `exists` - Check if database exists
11
+ - `create` - Create a new database
12
+ - `init` - Create all tables in the given database, optionally dropping first
13
+
14
+ ## Supported databases
15
+
16
+ - SQLite (`aiosqlite`)
17
+ - Postgres (`asyncpg`)
18
+ - MS Sql (`pyodbc` and `aioodbc`)
@@ -0,0 +1,23 @@
1
+ [tool.poetry]
2
+ name = "python-glowplug"
3
+ version = "0.1.0"
4
+ description = ""
5
+ authors = ["Joe Nudell <jnudell@hks.harvard.edu>"]
6
+ readme = "README.md"
7
+ license = "MIT"
8
+ repository = "https://github.com/jnu/python-glowplug"
9
+ packages = [
10
+ { include = "glowplug", from = "src" }
11
+ ]
12
+
13
+ [tool.poetry.dependencies]
14
+ python = "^3.9"
15
+ sqlalchemy = "^2"
16
+
17
+
18
+ [tool.poetry.group.dev.dependencies]
19
+ pre-commit = "^3.7.0"
20
+
21
+ [build-system]
22
+ requires = ["poetry-core"]
23
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1,6 @@
1
+ from .base import DbDriver
2
+ from .pg import PostgresDriver
3
+ from .sqlite import SqliteDriver
4
+ from .mssql import MsSqlDriver
5
+
6
+ __all__ = ["DbDriver", "PostgresDriver", "SqliteDriver", "MsSqlDriver"]
@@ -0,0 +1,65 @@
1
+ from abc import ABC, abstractmethod
2
+ from functools import cached_property
3
+
4
+ from sqlalchemy import Engine, create_engine
5
+ from sqlalchemy.ext.asyncio import (
6
+ AsyncEngine,
7
+ AsyncSession,
8
+ async_sessionmaker,
9
+ create_async_engine,
10
+ )
11
+ from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
12
+
13
+
14
+ class DbDriver(ABC):
15
+ def __init__(self, debug: bool = False) -> None:
16
+ self.debug = debug
17
+
18
+ @abstractmethod
19
+ async def exists(self) -> bool:
20
+ """Check if the database exists."""
21
+ ...
22
+
23
+ @abstractmethod
24
+ async def create(self) -> None:
25
+ """Create the database."""
26
+ ...
27
+
28
+ @property
29
+ @abstractmethod
30
+ def async_uri(self) -> str:
31
+ """The async uri."""
32
+ ...
33
+
34
+ @property
35
+ @abstractmethod
36
+ def sync_uri(self) -> str:
37
+ """The sync uri."""
38
+ ...
39
+
40
+ async def init(self, base: DeclarativeBase, drop_first: bool = False) -> None:
41
+ """Initialize the database."""
42
+ engine = self.get_async_engine()
43
+ async with engine.begin() as conn:
44
+ if drop_first:
45
+ await conn.run_sync(base.metadata.drop_all)
46
+ await conn.run_sync(base.metadata.create_all)
47
+ await engine.dispose()
48
+
49
+ def get_async_engine(self) -> AsyncEngine:
50
+ """Get an async engine."""
51
+ return create_async_engine(self.async_uri, echo=self.debug)
52
+
53
+ def get_sync_engine(self) -> Engine:
54
+ """Get a sync engine."""
55
+ return create_engine(self.sync_uri, echo=self.debug)
56
+
57
+ @cached_property
58
+ def async_session(self) -> AsyncSession:
59
+ """Get an async session."""
60
+ return async_sessionmaker(self.get_async_engine(), expire_on_commit=False)
61
+
62
+ @cached_property
63
+ def sync_session(self) -> Session:
64
+ """Get a sync session."""
65
+ return sessionmaker(self.get_sync_engine(), expire_on_commit=False)
@@ -0,0 +1,61 @@
1
+ from sqlalchemy.ext.asyncio import create_async_engine
2
+ from .base import DbDriver
3
+
4
+
5
+ class MsSqlDriver(DbDriver):
6
+ """Microsoft SQL Server database driver."""
7
+
8
+ path: str
9
+
10
+ def __init__(self, path: str, **kwargs):
11
+ """Initialize the driver.
12
+
13
+ Args:
14
+ path (str): The path to connect to the database.
15
+ """
16
+ super().__init__(**kwargs)
17
+ self.path = path
18
+
19
+ async def exists(self) -> bool:
20
+ """Check if the database exists."""
21
+ # Get a database-less path and the db name
22
+ path, database = self._split_path()
23
+ # Connect to the database-less path
24
+ engine = create_async_engine(f"mssql+aioodbc://{path}")
25
+ async with engine.connect() as conn:
26
+ # Check if the database exists
27
+ result = await conn.execute(
28
+ f"SELECT name FROM sys.databases WHERE name = '{database}'"
29
+ )
30
+ row = await result.fetchone()
31
+ return row is not None
32
+
33
+ async def create(self) -> None:
34
+ """Create the database."""
35
+ # Get a database-less path and the db name
36
+ path, database = self._split_path()
37
+ # Connect to the database-less path
38
+ engine = create_async_engine(f"mssql+aioodbc://{path}")
39
+ async with engine.connect() as conn:
40
+ # Create the database
41
+ await conn.execute(f"CREATE DATABASE {database}")
42
+
43
+ @property
44
+ def async_uri(self) -> str:
45
+ """Connect with aioodbc."""
46
+ return f"mssql+aioodbc://{self.path}"
47
+
48
+ @property
49
+ def sync_uri(self) -> str:
50
+ """Connect with pyodbc."""
51
+ return f"mssql+pyodbc://{self.path}"
52
+
53
+ def _split_path(self) -> tuple[str, str]:
54
+ """Extract the database name from the rest of the path."""
55
+ # Split the path into everything before the / and after
56
+ head, tail = self.path.split("/", 1)
57
+ # Extract the database name from the tail
58
+ database, query = tail.split("?", 1)
59
+ # Re-join the query to the beginning of the path
60
+ path = f"{head}/?{query}"
61
+ return path, database
@@ -0,0 +1,72 @@
1
+ from sqlalchemy.ext.asyncio import create_async_engine
2
+ from sqlalchemy.sql import text
3
+
4
+ from .base import DbDriver
5
+
6
+
7
+ class PostgresDriver(DbDriver):
8
+ """PostgreSQL database driver."""
9
+
10
+ url: str
11
+
12
+ def __init__(self, url: str, maintenance_db: str | None = None, **kwargs) -> None:
13
+ """Initialize the driver.
14
+
15
+ Args:
16
+ url (str): The url to connect to the database.
17
+ maintenance_db (str | None): The maintenance database to use when
18
+ checking if the database exists and creating the database. Postgres
19
+ needs at least one database to exist in order to do anything! If
20
+ not provided, postgres defaults to using the user name.
21
+ """
22
+ super().__init__(**kwargs)
23
+ self.url = url
24
+ self.maintenance_db = maintenance_db
25
+
26
+ async def exists(self) -> bool:
27
+ """Check if the database exists."""
28
+ # Split the url on the last / to get base url & db name
29
+ base_url, db_name = self._split_url()
30
+ # If a maintenance db is provided, use that to check if the db exists
31
+ if self.maintenance_db:
32
+ base_url = f"{base_url}/{self.maintenance_db}"
33
+ engine = create_async_engine(
34
+ f"postgresql+asyncpg://{base_url}", echo=self.debug
35
+ )
36
+ exists = False
37
+ async with engine.connect() as conn:
38
+ result = await conn.execute(
39
+ text("SELECT 1 FROM pg_catalog.pg_database WHERE datname = :db_name"),
40
+ {"db_name": db_name},
41
+ )
42
+ exists = bool(result.first())
43
+ await engine.dispose()
44
+ return exists
45
+
46
+ async def create(self) -> None:
47
+ """Create the database."""
48
+ base_url, db_name = self._split_url()
49
+ # If a maintenance db is provided, use that to create the db
50
+ if self.maintenance_db:
51
+ base_url = f"{base_url}/{self.maintenance_db}"
52
+ engine = create_async_engine(
53
+ f"postgresql+asyncpg://{base_url}", echo=self.debug
54
+ )
55
+ async with engine.connect() as conn:
56
+ await conn.execute(f"CREATE DATABASE {db_name}")
57
+ await engine.dispose()
58
+
59
+ @property
60
+ def async_uri(self) -> str:
61
+ """Async connection string."""
62
+ return f"postgresql+asyncpg://{self.url}"
63
+
64
+ @property
65
+ def sync_uri(self) -> str:
66
+ """Sync connection stringe."""
67
+ return f"postgresql://{self.url}"
68
+
69
+ def _split_url(self) -> tuple[str, str]:
70
+ """Split the url on the last / to get base url & db name."""
71
+ url, db = self.url.rsplit("/", 1)
72
+ return url, db
@@ -0,0 +1,41 @@
1
+ import os
2
+
3
+ from .base import DbDriver
4
+
5
+
6
+ class SqliteDriver(DbDriver):
7
+ """SQLite database driver."""
8
+
9
+ path: str
10
+
11
+ def __init__(self, path: str, **kwargs) -> None:
12
+ super().__init__(**kwargs)
13
+ self.path = path
14
+
15
+ @property
16
+ def is_memory(self) -> bool:
17
+ return self.path == ":memory:"
18
+
19
+ async def exists(self) -> bool:
20
+ if self.is_memory:
21
+ return True
22
+ return os.path.exists(self.path)
23
+
24
+ async def create(self) -> None:
25
+ if self.is_memory:
26
+ return
27
+ # Make sure directories exist. The file itself will be created
28
+ # when the first connection is made.
29
+ os.makedirs(os.path.dirname(self.path), exist_ok=True)
30
+
31
+ @property
32
+ def async_uri(self) -> str:
33
+ if self.is_memory:
34
+ return "sqlite+aiosqlite://"
35
+ return f"sqlite+aiosqlite:///{self.path}"
36
+
37
+ @property
38
+ def sync_uri(self) -> str:
39
+ if self.is_memory:
40
+ return "sqlite://"
41
+ return f"sqlite:///{self.path}"