Skip to content

Commit

Permalink
Increase timeout on model disconnect
Browse files Browse the repository at this point in the history
Fix typehint on column_type / sql_type
typehint Model.columns
optional `cascade` kwarg on `drop_table_sql()`

 + Applied **`black`** formatting.
  • Loading branch information
SylteA committed Jan 22, 2021
1 parent e2c3797 commit 2e73676
Show file tree
Hide file tree
Showing 8 changed files with 28 additions and 20 deletions.
6 changes: 4 additions & 2 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@

release = ""
with open("../postDB/__init__.py") as f:
release = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', f.read(), re.MULTILINE).group(1)
release = re.search(
r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', f.read(), re.MULTILINE
).group(1)

# The short X.Y version.
version = ".".join(release.split(".")[:2])
Expand All @@ -48,7 +50,7 @@
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.coverage",
'sphinx.ext.extlinks',
"sphinx.ext.extlinks",
"sphinx.ext.intersphinx",
"sphinx.ext.napoleon",
]
Expand Down
2 changes: 1 addition & 1 deletion examples/internal_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ async def main():
print(await Model.pool.fetch("SELECT * FROM users"))

try:
await asyncio.wait_for(Model.pool.close(), timeout=3.0)
await asyncio.wait_for(Model.pool.close(), timeout=10.0)
except asyncio.TimeoutError:
print("Exiting by timeout...")

Expand Down
4 changes: 2 additions & 2 deletions postDB/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
__version__ = "0.2.0"
__version__ = "0.2.1"
__author__ = "Sylte"
__licence__ = "MIT"
__copyright__ = "Copyright (c) 2020 Sylte"
Expand All @@ -18,7 +18,7 @@ def get_version(version: tuple):
return "%s %s.%s.%s" % (version[3], version[0], version[1], version[2])


VERSION = (0, 2, 0, "final", 0)
VERSION = (0, 2, 1, "final", 0)
version_info = VersionInfo(*VERSION)

logging.getLogger(__name__).addHandler(logging.NullHandler())
2 changes: 2 additions & 0 deletions postDB/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
class SchemaError(Exception):
"""Base error for the module."""

pass


class UniqueViolationError(SchemaError):
"""Raised when a unique constraint is violated."""

pass
8 changes: 4 additions & 4 deletions postDB/model/column.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import inspect
import typing

from postDB.exceptions import SchemaError
from postDB.types import SQLType, String

import inspect
import typing


class Column:
"""Class to define a column in a :class:`Model`."""
Expand All @@ -21,7 +21,7 @@ class Column:

def __init__(
self,
column_type: SQLType,
column_type: typing.Union[typing.Type[SQLType], SQLType],
*,
index: bool = False,
primary_key: bool = False,
Expand Down
4 changes: 3 additions & 1 deletion postDB/model/meta.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from postDB import Column

from typing import List


class ModelMeta(type):
"""Metaclass for Model class."""
Expand All @@ -12,7 +14,7 @@ def __new__(mcs, name, parents, data, **kwargs):

tablename = kwargs.get("tablename", name.lower() + "s")

columns = []
columns: List[Column] = []
for key, col in data.items():
if isinstance(col, Column):
if col.name is None:
Expand Down
16 changes: 9 additions & 7 deletions postDB/model/model.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import json
from asyncio import BaseEventLoop
from typing import Optional, List
from asyncio import BaseEventLoop
import json

from asyncpg import create_pool
from asyncpg.connection import Connection
from asyncpg import create_pool
from asyncpg.pool import Pool

from postDB.model.meta import ModelMeta
Expand Down Expand Up @@ -95,14 +95,15 @@ def create_table_sql(cls, *, exists_ok: bool = True) -> str:
return "\n".join(statements)

@classmethod
def drop_table_sql(cls, exists_ok: bool = True) -> str:
def drop_table_sql(cls, *, exists_ok: bool = True, cascade: bool = False) -> str:
"""Generates the ``DROP TABLE`` SQL statement."""
builder = ["DROP TABLE"]

if exists_ok:
builder.append("IF EXISTS")

builder.append("%s CASCADE;" % cls.__tablename__)
to_cascade = "CASCADE" if cascade else "RESTRICT"
builder.append("%s %s;" % (cls.__tablename__, to_cascade))
return " ".join(builder)

@classmethod
Expand Down Expand Up @@ -145,7 +146,7 @@ async def ensure_con(cls, con: Optional[Connection] = None) -> Connection:
return await cls.pool.acquire()

raise RuntimeWarning(
"Unable to get Connection, either call `Model.create_pool` or provide a con` argument."
"Unable to get Connection, either call `Model.create_pool` or provide a `con` argument."
)

@classmethod
Expand All @@ -172,12 +173,13 @@ async def drop_table(
con: Optional[Connection] = None,
*,
verbose: bool = False,
cascade: bool = True,
exists_ok: bool = True,
):
"""Drop the PostgreSQL Table for this Model."""
con = await cls.ensure_con(con=con)

sql = cls.drop_table_sql(exists_ok=exists_ok)
sql = cls.drop_table_sql(exists_ok=exists_ok, cascade=cascade)

if verbose:
print(sql)
Expand Down
6 changes: 3 additions & 3 deletions postDB/types.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Optional
from typing import Optional, Union, Type
import datetime
import inspect
import decimal
Expand Down Expand Up @@ -285,7 +285,7 @@ def __init__(
model: str,
column: str,
*,
sql_type: Optional[SQLType] = None,
sql_type: Optional[Union[Type[SQLType], SQLType]] = None,
on_delete: str = "CASCADE",
on_update: str = "NO ACTION"
):
Expand Down Expand Up @@ -344,7 +344,7 @@ class Array(SQLType):

python = list

def __init__(self, sql_type: SQLType):
def __init__(self, sql_type: Union[Type[SQLType], SQLType]):
if inspect.isclass(sql_type):
sql_type = sql_type()

Expand Down

0 comments on commit 2e73676

Please sign in to comment.