Makefile: Include py-topdir.mk
Include py-topdir.mk, which entails loads of fallout from make check. Fix it. Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
parent
7212850b22
commit
e9845b5a1f
15 changed files with 1796 additions and 1191 deletions
|
|
@ -1,15 +1,16 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Any
|
||||
from __future__ import annotations
|
||||
|
||||
import abc
|
||||
from contextlib import contextmanager
|
||||
|
||||
from ..Config import Config
|
||||
from .schema.Schema import Schema
|
||||
from ..Cmds import Cmds
|
||||
from .Session import Session
|
||||
from ..log import *
|
||||
from contextlib import contextmanager
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from ..log import NOTICE
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..Config import Config
|
||||
from .schema.Schema import Schema
|
||||
from .Session import Session
|
||||
|
||||
class DataBase(abc.ABC):
|
||||
|
||||
|
|
@ -37,6 +38,7 @@ class DataBase(abc.ABC):
|
|||
def session(self):
|
||||
ret = self._create_session()
|
||||
try:
|
||||
yield ret
|
||||
yield ret
|
||||
finally:
|
||||
self._delete_session(ret)
|
||||
if ret is not None:
|
||||
self._delete_session(ret)
|
||||
|
|
|
|||
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
import abc
|
||||
|
||||
class Session(abc.ABC): # export
|
||||
class Session(abc.ABC): # export
|
||||
|
||||
def __init__(self, db):
|
||||
self.__db = db
|
||||
|
|
|
|||
|
|
@ -1,18 +1,17 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, List, Union, Optional, Dict
|
||||
from abc import ABC, abstractmethod
|
||||
import re, csv, json
|
||||
from typing import TYPE_CHECKING, Any, Dict, Union
|
||||
|
||||
from ..log import *
|
||||
from ..cast import cast_str
|
||||
from .schema.Schema import Schema
|
||||
from ..log import ERR, INFO, OFF, slog, slog_m
|
||||
from .rows import rows_check_not_null, rows_dump, rows_duplicates
|
||||
|
||||
from .rows import *
|
||||
if TYPE_CHECKING:
|
||||
from .schema.Schema import Schema
|
||||
|
||||
TType = Union[Any, Dict[str, Any]]
|
||||
|
||||
class TableIoHandler(ABC): # export
|
||||
class TableIoHandler(ABC): # export
|
||||
|
||||
def __init__(self, schema: Schema):
|
||||
self.__table_meta = None
|
||||
|
|
@ -22,7 +21,8 @@ class TableIoHandler(ABC): # export
|
|||
def _table_meta(self):
|
||||
if self.__table_meta is None:
|
||||
self.__table_meta = self.__schema.table_by_model_name(
|
||||
self.__class__.__name__, throw=True)
|
||||
self.__class__.__name__, throw = True
|
||||
)
|
||||
return self.__table_meta
|
||||
|
||||
@property
|
||||
|
|
@ -35,24 +35,29 @@ class TableIoHandler(ABC): # export
|
|||
|
||||
def _check_non_nullable(self, rows):
|
||||
buf = []
|
||||
non_nullable = self.__table_meta.not_null_insertible_columns
|
||||
non_nullable = self._table_meta.not_null_insertible_columns
|
||||
try:
|
||||
rows_check_not_null(rows, non_nullable, buf=buf)
|
||||
rows_check_not_null(rows, non_nullable, buf = buf)
|
||||
except:
|
||||
cn = self.__class__.__name__
|
||||
tn = self._table_name
|
||||
d = '========================================================='
|
||||
slog_m(ERR, f'{d} Null values in {cn}\n')
|
||||
for key in non_nullable:
|
||||
buf = rows_check_not_null(rows, key, log_prio=OFF, throw=False)
|
||||
buf = rows_check_not_null(rows, key, log_prio = OFF, throw = False)
|
||||
if not buf:
|
||||
continue
|
||||
slog_m(ERR, f'\n{d} Null values in {cn} / {tn}: "{key}"\n')
|
||||
use_cols=self.log_columns
|
||||
use_cols = list(self.log_columns)
|
||||
if key not in use_cols:
|
||||
use_cols.append(key)
|
||||
rows_dump(buf, use_cols=use_cols, log_prio=ERR)
|
||||
rows_dump(buf, use_cols=use_cols, out_path=f'/tmp/missing_{key}_in_{tn}.html', heading=f'Missing "{key}" in table {tn}')
|
||||
rows_dump(buf, use_cols = use_cols, log_prio = ERR)
|
||||
rows_dump(
|
||||
buf,
|
||||
use_cols = use_cols,
|
||||
out_path = f'/tmp/missing_{key}_in_{tn}.html',
|
||||
heading = f'Missing "{key}" in table {tn}'
|
||||
)
|
||||
raise
|
||||
|
||||
@property
|
||||
|
|
@ -67,7 +72,9 @@ class TableIoHandler(ABC): # export
|
|||
def _store(self, uri: str, data: TType):
|
||||
pass
|
||||
|
||||
def load(self, uri: str, reference, check_duplicates=False, write_csv=None) -> TType:
|
||||
def load(
|
||||
self, uri: str, reference, check_duplicates = False, write_csv = None
|
||||
) -> TType:
|
||||
slog(INFO, f'Reading table "{self._table_name}" from "{uri}"')
|
||||
ret = self._load(uri, reference)
|
||||
if check_duplicates:
|
||||
|
|
|
|||
|
|
@ -1,18 +1,18 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Any
|
||||
from __future__ import annotations
|
||||
from typing import Any, TYPE_CHECKING
|
||||
|
||||
import abc
|
||||
|
||||
from ...log import *
|
||||
from ...log import slog, slog_m, ERR, INFO
|
||||
from ...misc import load_classes
|
||||
from ...Cmds import Cmds
|
||||
from ..DataBase import DataBase
|
||||
from ..schema.Schema import Schema
|
||||
from .Query import Query as QueryBase
|
||||
from .QueryResult import QueryResult
|
||||
|
||||
class Queries(abc.ABC): # export
|
||||
if TYPE_CHECKING:
|
||||
from ..schema.Schema import Schema
|
||||
from .QueryResult import QueryResult
|
||||
|
||||
class Queries(abc.ABC): # export
|
||||
|
||||
class Query(QueryBase):
|
||||
|
||||
|
|
@ -38,7 +38,7 @@ class Queries(abc.ABC): # export
|
|||
return self.__name
|
||||
|
||||
def __init__(self, db: DataBase) -> None:
|
||||
assert(isinstance(db, DataBase))
|
||||
assert (isinstance(db, DataBase))
|
||||
self.__db = db
|
||||
self.__queries: dict[str, Any] = dict()
|
||||
|
||||
|
|
@ -57,7 +57,7 @@ class Queries(abc.ABC): # export
|
|||
def db(self) -> DataBase:
|
||||
return self.__db
|
||||
|
||||
def load(self, modules: list[str], cls=QueryBase):
|
||||
def load(self, modules: list[str], cls = QueryBase):
|
||||
for path in modules:
|
||||
slog(INFO, f'Loading modules from {path}')
|
||||
for c in load_classes(path, cls):
|
||||
|
|
@ -69,8 +69,8 @@ class Queries(abc.ABC): # export
|
|||
|
||||
def add(self, query: QueryBase, query_name: str, location: str, func: Any):
|
||||
slog(INFO, f'Adding query "{query_name}" on location "{location}"')
|
||||
assert(isinstance(query_name, str))
|
||||
assert(isinstance(location, str))
|
||||
assert (isinstance(query_name, str))
|
||||
assert (isinstance(location, str))
|
||||
#ret = self.Query(query, func)
|
||||
ret = self.Query(query, query_name, location, func)
|
||||
#setattr(ret, 'name', name)
|
||||
|
|
|
|||
|
|
@ -1,18 +1,15 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Any
|
||||
from __future__ import annotations
|
||||
|
||||
import abc
|
||||
|
||||
from ...log import *
|
||||
from ...misc import load_classes
|
||||
from ...Cmds import Cmds
|
||||
from ..DataBase import DataBase
|
||||
from ..Session import Session
|
||||
from .QueryResult import QueryResult
|
||||
#from .Queries import Queries
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
class Query(abc.ABC): # export
|
||||
if TYPE_CHECKING:
|
||||
from ..DataBase import DataBase
|
||||
from ..Session import Session
|
||||
from .QueryResult import QueryResult
|
||||
|
||||
class Query(abc.ABC): # export
|
||||
|
||||
def __init__(self, parent: Any) -> None:
|
||||
self.__parent = parent
|
||||
|
|
|
|||
|
|
@ -1,23 +1,22 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Any, Union
|
||||
from __future__ import annotations
|
||||
|
||||
import abc
|
||||
|
||||
from enum import Enum, auto
|
||||
from typing import TYPE_CHECKING, Any, Union
|
||||
|
||||
from ...log import *
|
||||
from ...Cmds import Cmds
|
||||
from ..DataBase import DataBase
|
||||
from ..Session import Session
|
||||
if TYPE_CHECKING:
|
||||
from ..DataBase import DataBase
|
||||
from ..Session import Session
|
||||
|
||||
class ResType(Enum): # export
|
||||
Statement = auto()
|
||||
Scalars = auto()
|
||||
One = auto()
|
||||
First = auto()
|
||||
Pages = auto()
|
||||
class ResType(Enum): # export
|
||||
Statement = auto()
|
||||
Scalars = auto()
|
||||
One = auto()
|
||||
First = auto()
|
||||
Pages = auto()
|
||||
|
||||
class QueryResult(abc.ABC): # export
|
||||
class QueryResult(abc.ABC): # export
|
||||
|
||||
def __init__(self, session: Session, query: Any) -> None:
|
||||
self.__query = query
|
||||
|
|
@ -42,8 +41,8 @@ class QueryResult(abc.ABC): # export
|
|||
def rows(self) -> list[Any]:
|
||||
return self._cast(ResType.Scalars)
|
||||
|
||||
def pages(self, per_page=20, page=1) -> Any:
|
||||
return self._cast(ResType.Pages, per_page=per_page, page=page)
|
||||
def pages(self, per_page = 20, page = 1) -> Any:
|
||||
return self._cast(ResType.Pages, per_page = per_page, page = page)
|
||||
|
||||
def one(self) -> Any:
|
||||
return self._cast(ResType.One)
|
||||
|
|
@ -58,5 +57,5 @@ class QueryResult(abc.ABC): # export
|
|||
# -- pure virtuals
|
||||
|
||||
@abc.abstractmethod
|
||||
def _cast(self, res_type: ResType, **kwargs) -> Union[Any|list[Any]]:
|
||||
def _cast(self, res_type: ResType, **kwargs) -> Union[Any, list[Any]]:
|
||||
pass
|
||||
|
|
|
|||
|
|
@ -1,19 +1,24 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import textwrap
|
||||
|
||||
import io, os, re, textwrap, json, csv
|
||||
from tabulate import tabulate # type: ignore
|
||||
from tabulate import TableFormat, tabulate # type: ignore
|
||||
|
||||
from ..log import *
|
||||
from ..log import (ERR, INFO, WARNING, get_caller_pos, prio_gets_logged, slog, slog_m)
|
||||
|
||||
def rows_pretty(rows): # export
|
||||
if type(rows) == dict:
|
||||
def rows_pretty(rows): # export
|
||||
if isinstance(rows, dict):
|
||||
rows = [rows]
|
||||
out = []
|
||||
for row in rows:
|
||||
out.append(json.dumps(row, sort_keys=True, indent=4, default=str))
|
||||
out.append(json.dumps(row, sort_keys = True, indent = 4, default = str))
|
||||
return '\n'.join(out)
|
||||
|
||||
def rows_duplicates(rows, log_prio=INFO, caller=None): # export
|
||||
def rows_duplicates(rows, log_prio = INFO, caller = None): # export
|
||||
|
||||
def __equal(r1, r2):
|
||||
for col in set(r1.keys()) | set(r2.keys()):
|
||||
if col in r1:
|
||||
|
|
@ -25,11 +30,12 @@ def rows_duplicates(rows, log_prio=INFO, caller=None): # export
|
|||
if r1[col] != r2[col]:
|
||||
return False
|
||||
return True
|
||||
|
||||
ret = []
|
||||
last = len(rows) - 1
|
||||
i = last
|
||||
while last > 0:
|
||||
for i in reversed(range(0, last-1)):
|
||||
for i in reversed(range(0, last - 1)):
|
||||
if __equal(rows[last], rows[i]):
|
||||
ret.append(last)
|
||||
last -= 1
|
||||
|
|
@ -37,12 +43,15 @@ def rows_duplicates(rows, log_prio=INFO, caller=None): # export
|
|||
last -= 1
|
||||
return ret
|
||||
|
||||
def rows_remove(rows, callback=None, candidates=None, log_prio=INFO, caller=None): # export
|
||||
def rows_remove( # export
|
||||
rows, callback = None, candidates = None, log_prio = INFO, caller = None
|
||||
):
|
||||
|
||||
def __is_remove_candidate(row):
|
||||
assert candidates is not None, 'Candidates is None'
|
||||
for remove_row in candidates:
|
||||
for col, val in row.items():
|
||||
if not col in remove_row.keys():
|
||||
if col not in remove_row.keys():
|
||||
break
|
||||
if val != remove_row[col]:
|
||||
break
|
||||
|
|
@ -65,14 +74,14 @@ def rows_remove(rows, callback=None, candidates=None, log_prio=INFO, caller=None
|
|||
remove.append(index)
|
||||
continue
|
||||
for index in reversed(remove):
|
||||
slog(log_prio, f'Removing row {rows[index]}', caller=caller)
|
||||
slog(log_prio, f'Removing row {rows[index]}', caller = caller)
|
||||
del rows[index]
|
||||
|
||||
def rows_select(rows, rules): # export
|
||||
def rows_select(rows, rules): # export
|
||||
ret = []
|
||||
for row in rows:
|
||||
for rule in rules:
|
||||
if type(rule) == tuple():
|
||||
if isinstance(rule, tuple):
|
||||
search_rule = rule[0]
|
||||
else:
|
||||
search_rule = rule
|
||||
|
|
@ -84,7 +93,7 @@ def rows_select(rows, rules): # export
|
|||
break
|
||||
return ret
|
||||
|
||||
def rows_rewrite_regex(rows, rules): # export
|
||||
def rows_rewrite_regex(rows, rules): # export
|
||||
for row in rows:
|
||||
for rule in rules:
|
||||
try:
|
||||
|
|
@ -93,14 +102,25 @@ def rows_rewrite_regex(rows, rules): # export
|
|||
break
|
||||
else:
|
||||
for exec_col_name, exec_val in rule[1].items():
|
||||
slog(INFO, f'Rewriting {row} {row.get(exec_col_name)} -> {exec_val}')
|
||||
slog(
|
||||
INFO,
|
||||
f'Rewriting {row} {row.get(exec_col_name)} -> {exec_val}'
|
||||
)
|
||||
row[exec_col_name] = exec_val
|
||||
except Exception as e:
|
||||
slog(ERR, f'Failed to run rule {rule} against {row} ({e})')
|
||||
raise
|
||||
|
||||
def rows_check_not_null(rows, keys, log_prio=WARNING, buf=None, stat_key=None, throw=True, caller=None): # export
|
||||
if type(keys) == str:
|
||||
def rows_check_not_null( # export
|
||||
rows,
|
||||
keys,
|
||||
log_prio = WARNING,
|
||||
buf = None,
|
||||
stat_key = None,
|
||||
throw = True,
|
||||
caller = None
|
||||
):
|
||||
if isinstance(keys, str):
|
||||
keys = [keys]
|
||||
if caller is None:
|
||||
caller = get_caller_pos()
|
||||
|
|
@ -113,11 +133,11 @@ def rows_check_not_null(rows, keys, log_prio=WARNING, buf=None, stat_key=None, t
|
|||
for row in rows:
|
||||
for key in keys:
|
||||
if row.get(key) is None:
|
||||
slog(log_prio, f'{key} is missing in row {row}', caller=caller)
|
||||
slog(log_prio, f'{key} is missing in row {row}', caller = caller)
|
||||
buf.append(row)
|
||||
if stat_key is not None:
|
||||
stat_val = row[stat_key]
|
||||
if not stat_val in stats.keys():
|
||||
if stat_val not in stats.keys():
|
||||
stats[stat_val] = 0
|
||||
stats[stat_val] += 1
|
||||
count += 1
|
||||
|
|
@ -125,14 +145,27 @@ def rows_check_not_null(rows, keys, log_prio=WARNING, buf=None, stat_key=None, t
|
|||
if count > 0:
|
||||
if stat_key is not None:
|
||||
i = 0
|
||||
for k, v in reversed(sorted(stats.items(), key=lambda item: item[1])):
|
||||
for k, v in reversed(sorted(stats.items(), key = lambda item: item[1])):
|
||||
i += 1
|
||||
slog(ERR, f'{i:>3}. {k:<23}: {v}', caller=caller)
|
||||
slog(ERR, f'{i:>3}. {k:<23}: {v}', caller = caller)
|
||||
if throw:
|
||||
raise Exception(f'Found {count} rows violating null-constraint for keys {keys}')
|
||||
raise Exception(
|
||||
f'Found {count} rows violating null-constraint for keys {keys}'
|
||||
)
|
||||
return buf
|
||||
|
||||
def rows_dumps(rows, log_prio=INFO, caller=None, use_cols=None, skip_cols=None, table_name=None, out_path='log', heading=None, lead=None, tablefmt=None): # export
|
||||
def rows_dumps( # export
|
||||
rows,
|
||||
log_prio = INFO,
|
||||
caller = None,
|
||||
use_cols = None,
|
||||
skip_cols = None,
|
||||
table_name = None,
|
||||
out_path = 'log',
|
||||
heading = None,
|
||||
lead = None,
|
||||
tablefmt = None
|
||||
):
|
||||
|
||||
headers = 'keys'
|
||||
dump_rows = rows
|
||||
|
|
@ -152,20 +185,21 @@ def rows_dumps(rows, log_prio=INFO, caller=None, use_cols=None, skip_cols=None,
|
|||
new_row[col] = val
|
||||
new_dump_rows.append(new_row)
|
||||
dump_rows = new_dump_rows
|
||||
out = header = footer = ""
|
||||
header = footer = ""
|
||||
match tablefmt:
|
||||
case 'html':
|
||||
if heading is not None:
|
||||
heading = f'<h1>{heading}</h1>\n'
|
||||
if type(lead) == str:
|
||||
if isinstance(lead, str):
|
||||
lead = f'<div class="lead">\n {lead}\n</div>\n'
|
||||
elif type(lead) == list:
|
||||
l = '<ul>\n'
|
||||
elif isinstance(lead, list):
|
||||
lst = '<ul>\n'
|
||||
for li in lead:
|
||||
l += f'<li>{li}</li>\n'
|
||||
l += '</ul>\n'
|
||||
lead = l
|
||||
header=textwrap.dedent('''\
|
||||
lst += f'<li>{li}</li>\n'
|
||||
lst += '</ul>\n'
|
||||
lead = lst
|
||||
header = textwrap.dedent(
|
||||
'''\
|
||||
<html>
|
||||
<head>
|
||||
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
|
||||
|
|
@ -185,30 +219,47 @@ def rows_dumps(rows, log_prio=INFO, caller=None, use_cols=None, skip_cols=None,
|
|||
</style>
|
||||
</head>
|
||||
<body>
|
||||
''')
|
||||
footer = textwrap.dedent('''
|
||||
'''
|
||||
)
|
||||
footer = textwrap.dedent(
|
||||
'''
|
||||
</body>
|
||||
</html>
|
||||
''')
|
||||
'''
|
||||
)
|
||||
case _:
|
||||
if type(heading) == str:
|
||||
if isinstance(heading, str):
|
||||
heading = '\n' + heading
|
||||
if type(lead) == str:
|
||||
if isinstance(lead, str):
|
||||
pass
|
||||
elif type(lead) == list:
|
||||
l =''
|
||||
elif isinstance(lead, list):
|
||||
lst = ''
|
||||
for li in lead:
|
||||
l += f' - {li}\n'
|
||||
lead = '\n\n' + l + '\n'
|
||||
lst += f' - {li}\n'
|
||||
lead = '\n\n' + lst + '\n'
|
||||
|
||||
if heading is None:
|
||||
heading = ''
|
||||
if lead is None:
|
||||
lead = ''
|
||||
|
||||
return header + heading + lead + tabulate(dump_rows, headers=headers, tablefmt=tablefmt) + footer
|
||||
assert isinstance(tablefmt, str) or isinstance(tablefmt, TableFormat), 'tablefmt'
|
||||
return header + heading + lead + tabulate(
|
||||
dump_rows, headers = headers, tablefmt = tablefmt
|
||||
) + footer
|
||||
|
||||
def rows_dump(rows, log_prio=INFO, caller=None, use_cols=None, skip_cols=None, table_name=None, out_path='log', heading=None, lead=None, tablefmt=None): # export
|
||||
def rows_dump( # export
|
||||
rows,
|
||||
log_prio = INFO,
|
||||
caller = None,
|
||||
use_cols = None,
|
||||
skip_cols = None,
|
||||
table_name = None,
|
||||
out_path = 'log',
|
||||
heading = None,
|
||||
lead = None,
|
||||
tablefmt = None
|
||||
):
|
||||
|
||||
if not prio_gets_logged(log_prio):
|
||||
return
|
||||
|
|
@ -218,18 +269,35 @@ def rows_dump(rows, log_prio=INFO, caller=None, use_cols=None, skip_cols=None, t
|
|||
if tablefmt is None and out_path:
|
||||
tablefmt = os.path.splitext(out_path)[1][1:]
|
||||
|
||||
out = rows_dumps(rows, log_prio=log_prio, caller=caller, use_cols=use_cols, skip_cols=skip_cols, table_name=table_name, heading=heading, lead=lead, tablefmt=tablefmt)
|
||||
out = rows_dumps(
|
||||
rows,
|
||||
log_prio = log_prio,
|
||||
caller = caller,
|
||||
use_cols = use_cols,
|
||||
skip_cols = skip_cols,
|
||||
table_name = table_name,
|
||||
heading = heading,
|
||||
lead = lead,
|
||||
tablefmt = tablefmt
|
||||
)
|
||||
|
||||
match out_path:
|
||||
case 'log':
|
||||
slog_m(log_prio, out, caller=caller)
|
||||
slog_m(log_prio, out, caller = caller)
|
||||
case _:
|
||||
with open(out_path, 'w') as fp:
|
||||
fp.write(out)
|
||||
|
||||
def rows_to_csv(rows, use_tmpfile=False): # export
|
||||
def rows_to_csv(rows, use_tmpfile = False): # export
|
||||
|
||||
def __write(rows, out):
|
||||
writer = csv.DictWriter(out, fieldnames=field_names, delimiter=';', quotechar='"', quoting=csv.QUOTE_NONNUMERIC)
|
||||
writer = csv.DictWriter(
|
||||
out,
|
||||
fieldnames = field_names,
|
||||
delimiter = ';',
|
||||
quotechar = '"',
|
||||
quoting = csv.QUOTE_NONNUMERIC
|
||||
)
|
||||
writer.writeheader()
|
||||
for row in rows:
|
||||
writer.writerow(row)
|
||||
|
|
@ -244,7 +312,7 @@ def rows_to_csv(rows, use_tmpfile=False): # export
|
|||
__write(rows, out)
|
||||
return out.getvalue()
|
||||
import tempfile
|
||||
with tempfile.TemporaryFile(mode='w', newline='') as out:
|
||||
with tempfile.TemporaryFile(mode = 'w', newline = '') as out:
|
||||
__write(rows, out)
|
||||
out.seek(0)
|
||||
return out.read()
|
||||
|
|
|
|||
|
|
@ -1,17 +1,20 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Optional, Any
|
||||
from __future__ import annotations
|
||||
|
||||
import abc
|
||||
|
||||
from .DataType import DataType
|
||||
from ...log import *
|
||||
from typing import TYPE_CHECKING, Any, Optional
|
||||
|
||||
class Column(abc.ABC): # export
|
||||
from ...log import ERR, throw
|
||||
|
||||
def __init__(self, table, name, data_type: DataType):
|
||||
if TYPE_CHECKING:
|
||||
from .DataType import DataType
|
||||
from .Table import Table
|
||||
|
||||
class Column(abc.ABC): # export
|
||||
|
||||
def __init__(self, table: Table, name: str, data_type: DataType) -> None:
|
||||
self.__name: str = name
|
||||
self.__table: Any = table
|
||||
self.__table: Table = table
|
||||
self.__is_nullable: Optional[bool] = None
|
||||
self.__is_null_insertible: Optional[bool] = None
|
||||
self.__is_primary_key: Optional[bool] = None
|
||||
|
|
@ -39,18 +42,18 @@ class Column(abc.ABC): # export
|
|||
return False
|
||||
return True
|
||||
throw(ERR, f'Tried to compare column {self} to type {type(rhs)}: {rhs}')
|
||||
return False # Unreachable but requested by mypy
|
||||
return False # Unreachable but requested by mypy
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return self.__name
|
||||
|
||||
@property
|
||||
def data_type(self):
|
||||
def data_type(self) -> DataType:
|
||||
return self.__data_type
|
||||
|
||||
@property
|
||||
def table(self) -> str:
|
||||
def table(self) -> Table:
|
||||
return self.__table
|
||||
|
||||
@property
|
||||
|
|
@ -60,7 +63,7 @@ class Column(abc.ABC): # export
|
|||
return self.__is_nullable
|
||||
|
||||
@property
|
||||
def is_null_insertible(self):
|
||||
def is_null_insertible(self) -> bool:
|
||||
if self.__is_null_insertible is None:
|
||||
ret = False
|
||||
if self.is_nullable:
|
||||
|
|
@ -81,7 +84,9 @@ class Column(abc.ABC): # export
|
|||
@property
|
||||
def is_auto_increment(self) -> bool:
|
||||
if self.__is_auto_increment is None:
|
||||
self.__is_auto_increment = self.__name in self.__table.auto_increment_columns
|
||||
self.__is_auto_increment = (
|
||||
self.__name in self.__table.auto_increment_columns
|
||||
)
|
||||
return self.__is_auto_increment
|
||||
|
||||
@property
|
||||
|
|
@ -113,8 +118,8 @@ class Column(abc.ABC): # export
|
|||
def foreign_key(self, table) -> Optional[Any]:
|
||||
if self.__foreign_keys_by_table is None:
|
||||
self.__foreign_keys_by_table = dict()
|
||||
for col in self.foreign_keys: # type: ignore # Any not iterable
|
||||
assert(col.table.name not in self.__foreign_keys_by_table)
|
||||
for col in self.foreign_keys: # type: ignore # Any not iterable
|
||||
assert (col.table.name not in self.__foreign_keys_by_table)
|
||||
self.__foreign_keys_by_table[col.table.name] = col
|
||||
table_name = table if isinstance(table, str) else table.name
|
||||
return self.__foreign_keys_by_table.get(table_name)
|
||||
|
|
|
|||
|
|
@ -1,20 +1,24 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from typing import Optional, Any
|
||||
|
||||
from typing import Optional, Iterable, Any
|
||||
class ColumnSet: # export
|
||||
|
||||
class ColumnSet: # export
|
||||
|
||||
def __init__(self, *args: list[Any], columns: list[Any]=[], table: Optional[Any]=None, names: Optional[list[str]]=None):
|
||||
def __init__(
|
||||
self,
|
||||
*args: list[Any],
|
||||
columns: list[Any] = [],
|
||||
table: Optional[Any] = None,
|
||||
names: Optional[list[str]] = None
|
||||
):
|
||||
self.__columns: list[Any] = [*args]
|
||||
self.__columns.extend(columns)
|
||||
self.__table = table
|
||||
if names is not None:
|
||||
assert(table is not None)
|
||||
assert (table is not None)
|
||||
for name in names:
|
||||
self.__columns.append(table.column(name))
|
||||
if self.__table is not None:
|
||||
for col in columns:
|
||||
assert(col.table == self.__table)
|
||||
assert (col.table == self.__table)
|
||||
|
||||
def __len__(self):
|
||||
return len(self.__columns)
|
||||
|
|
|
|||
|
|
@ -1,15 +1,18 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional, Any
|
||||
from typing import TYPE_CHECKING, Any, Optional
|
||||
|
||||
from ...log import *
|
||||
|
||||
from .ColumnSet import ColumnSet
|
||||
from ...log import WARNING, slog
|
||||
from .SingleForeignKey import SingleForeignKey
|
||||
|
||||
class CompositeForeignKey: # export
|
||||
if TYPE_CHECKING:
|
||||
from .ColumnSet import ColumnSet
|
||||
|
||||
def __init__(self, child_col_set: ColumnSet, parent_col_set: ColumnSet): # TODO: Implement alternative ways to construct
|
||||
class CompositeForeignKey: # export
|
||||
|
||||
def __init__(
|
||||
self, child_col_set: ColumnSet, parent_col_set: ColumnSet
|
||||
): # TODO: Implement alternative ways to construct
|
||||
|
||||
def __table(s):
|
||||
ret = None
|
||||
|
|
@ -17,8 +20,8 @@ class CompositeForeignKey: # export
|
|||
if ret is None:
|
||||
ret = c.table
|
||||
else:
|
||||
assert(ret == c.table)
|
||||
assert(ret is not None)
|
||||
assert (ret == c.table)
|
||||
assert (ret is not None)
|
||||
return ret
|
||||
|
||||
self.__child_col_set = child_col_set
|
||||
|
|
@ -26,7 +29,7 @@ class CompositeForeignKey: # export
|
|||
self.__child_table = __table(child_col_set)
|
||||
self.__parent_table = __table(parent_col_set)
|
||||
|
||||
assert(len(self.__child_col_set) == len(self.__parent_col_set))
|
||||
assert (len(self.__child_col_set) == len(self.__parent_col_set))
|
||||
self.__len = len(self.__child_col_set)
|
||||
self.__column_relations: Optional[list[SingleForeignKey]] = None
|
||||
self.__parent_columns_by_child_column: Optional[dict[str, Any]] = None
|
||||
|
|
@ -46,7 +49,12 @@ class CompositeForeignKey: # export
|
|||
|
||||
def __repr__(self):
|
||||
ret = self.__table_rel_str()
|
||||
ret += ': ' + ', '.join([self.__cols_rel_str(rel.child_column, rel.parent_column) for rel in self.column_relations])
|
||||
ret += ': ' + ', '.join(
|
||||
[
|
||||
self.__cols_rel_str(rel.child_column, rel.parent_column)
|
||||
for rel in self.column_relations
|
||||
]
|
||||
)
|
||||
return ret
|
||||
|
||||
def __eq__(self, rhs):
|
||||
|
|
@ -73,21 +81,25 @@ class CompositeForeignKey: # export
|
|||
return self.__parent_col_set
|
||||
|
||||
def parent_column(self, child_column) -> Any:
|
||||
child_column_name = child_column if isinstance(child_column, str) else child_column.name
|
||||
child_column if isinstance(child_column, str) else child_column.name
|
||||
if self.__parent_columns_by_child_column is None:
|
||||
d: dict[str, Any] = {}
|
||||
assert(len(self.__child_col_set) == len(self.__parent_col_set))
|
||||
assert (len(self.__child_col_set) == len(self.__parent_col_set))
|
||||
for i in range(0, len(self.__child_col_set)):
|
||||
d[self.__child_col_set[i].name] = self.__parent_col_set[i]
|
||||
self.__parent_columns_by_child_column = d
|
||||
return self.__parent_columns_by_child_column[child_column]
|
||||
|
||||
def child_column(self, parent_column) -> Any:
|
||||
slog(WARNING, f'{self}: Looking for child column belonging to parent column "{parent_column}"')
|
||||
parent_column_name = parent_column if isinstance(parent_column, str) else parent_column.name
|
||||
slog(
|
||||
WARNING,
|
||||
f'{self}: Looking for child column belonging to parent column '
|
||||
f'"{parent_column}"'
|
||||
)
|
||||
parent_column if isinstance(parent_column, str) else parent_column.name
|
||||
if self.__child_columns_by_parent_column is None:
|
||||
d: dict[str, Any] = {}
|
||||
assert(len(self.__parent_col_set) == len(self.__child_col_set))
|
||||
assert (len(self.__parent_col_set) == len(self.__child_col_set))
|
||||
for i in range(0, len(self.__parent_col_set)):
|
||||
d[self.__parent_col_set[i].name] = self.__child_col_set[i]
|
||||
self.__child_columns_by_parent_column = d
|
||||
|
|
@ -98,6 +110,8 @@ class CompositeForeignKey: # export
|
|||
ret = []
|
||||
if self.__column_relations is None:
|
||||
for i in range(0, self.__len):
|
||||
ret.append(SingleForeignKey(self.__child_col_set[i], self.__parent_col_set[i]))
|
||||
ret.append(
|
||||
SingleForeignKey(self.__child_col_set[i], self.__parent_col_set[i])
|
||||
)
|
||||
self.__column_relations = ret
|
||||
return self.__column_relations
|
||||
|
|
|
|||
|
|
@ -1,10 +1,8 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Optional
|
||||
from enum import Enum, auto
|
||||
from datetime import datetime
|
||||
from enum import Enum, auto
|
||||
from typing import Optional
|
||||
|
||||
from ...log import *
|
||||
from ...log import ERR, throw
|
||||
|
||||
class Id(Enum):
|
||||
Integer = auto()
|
||||
|
|
@ -16,7 +14,7 @@ class Id(Enum):
|
|||
Text = auto()
|
||||
Invalid = auto()
|
||||
|
||||
def py_type(type_id: Id) -> type: # export
|
||||
def py_type(type_id: Id) -> type: # export
|
||||
|
||||
match type_id:
|
||||
case Id.Integer:
|
||||
|
|
@ -38,14 +36,17 @@ def py_type(type_id: Id) -> type: # export
|
|||
|
||||
raise Exception(f'Unknown column type-id "{type_id}"')
|
||||
|
||||
class DataType: # export
|
||||
class DataType: # export
|
||||
|
||||
def __init__(self, type_id: Id, size: Optional[int]=None):
|
||||
def __init__(self, type_id: Id, size: Optional[int] = None):
|
||||
if not isinstance(type_id, Id):
|
||||
throw(ERR, f'Passed type id "{type_id}" with unsupported data type {type(type_id)}')
|
||||
throw(
|
||||
ERR,
|
||||
f'Passed type id "{type_id}" with unsupported data type {type(type_id)}'
|
||||
)
|
||||
if size is not None:
|
||||
assert(isinstance(size, int))
|
||||
assert(size > 0)
|
||||
assert (isinstance(size, int))
|
||||
assert (size > 0)
|
||||
self.__id = type_id
|
||||
self.__size = size
|
||||
|
||||
|
|
@ -80,4 +81,4 @@ class DataType: # export
|
|||
|
||||
@property
|
||||
def py_type_annotation(self) -> str:
|
||||
return self.py_type_str # FIXME: This is not always correct
|
||||
return self.py_type_str # FIXME: This is not always correct
|
||||
|
|
|
|||
|
|
@ -1,20 +1,20 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Optional, Iterable
|
||||
from __future__ import annotations
|
||||
|
||||
import abc
|
||||
|
||||
from ...log import *
|
||||
from typing import TYPE_CHECKING, Iterable, Optional
|
||||
|
||||
from .Table import Table
|
||||
from .Column import Column
|
||||
from .DataType import DataType
|
||||
from .CompositeForeignKey import CompositeForeignKey
|
||||
from ...log import DEBUG, ERR, slog, throw
|
||||
|
||||
class Schema(abc.ABC): # export
|
||||
if TYPE_CHECKING:
|
||||
from .Column import Column
|
||||
from .CompositeForeignKey import CompositeForeignKey
|
||||
from .Table import Table
|
||||
|
||||
class Schema(abc.ABC): # export
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.___tables: Optional[list[Table]] = None
|
||||
self.___tables: Optional[dict[str, Table]] = None
|
||||
self.__foreign_keys: Optional[list[CompositeForeignKey]] = None
|
||||
self.__access_defining_columns: Optional[list[str]] = None
|
||||
|
||||
|
|
@ -24,7 +24,7 @@ class Schema(abc.ABC): # export
|
|||
ret = dict()
|
||||
for name in self._table_names():
|
||||
slog(DEBUG, f'Caching metadata for table "{name}"')
|
||||
assert(isinstance(name, str))
|
||||
assert (isinstance(name, str))
|
||||
ret[name] = self._table(name)
|
||||
self.___tables = ret
|
||||
return self.___tables
|
||||
|
|
@ -39,7 +39,7 @@ class Schema(abc.ABC): # export
|
|||
@abc.abstractmethod
|
||||
def _table(self, name: str) -> Table:
|
||||
throw(ERR, "Called pure virtual base class method")
|
||||
return None # type: ignore
|
||||
return None # type: ignore
|
||||
|
||||
@abc.abstractmethod
|
||||
def _foreign_keys(self) -> list[CompositeForeignKey]:
|
||||
|
|
@ -50,7 +50,7 @@ class Schema(abc.ABC): # export
|
|||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
def _model_module_search_paths(self) -> list[tuple[str, type]]:
|
||||
def _model_module_search_paths(self) -> list[tuple[str, type]]:
|
||||
pass
|
||||
|
||||
# ------ API to be called
|
||||
|
|
@ -62,7 +62,7 @@ class Schema(abc.ABC): # export
|
|||
yield from self.__tables.values()
|
||||
|
||||
def __repr__(self):
|
||||
return '|'.join([table.name for table in self.__tables])
|
||||
return '|'.join([table.name for table in self.__tables.values()])
|
||||
|
||||
def __getitem__(self, index):
|
||||
return self.__tables[index]
|
||||
|
|
@ -90,13 +90,13 @@ class Schema(abc.ABC): # export
|
|||
def table(self, name: str) -> Table:
|
||||
return self.__tables[name]
|
||||
|
||||
def table_by_model_name(self, name: str, throw=False) -> Table:
|
||||
def table_by_model_name(self, name: str, throw = False) -> Table:
|
||||
for table in self.__tables.values():
|
||||
if table.model_name == name:
|
||||
return table
|
||||
if throw:
|
||||
raise Exception(f'Table "{name}" not found in database metadata')
|
||||
return None # type: ignore
|
||||
return None # type: ignore
|
||||
|
||||
def primary_keys(self, table_name: str) -> Iterable[str]:
|
||||
return self.__tables[table_name].primary_keys
|
||||
|
|
@ -105,5 +105,5 @@ class Schema(abc.ABC): # export
|
|||
return self.__tables[table_name].columns
|
||||
|
||||
@property
|
||||
def model_module_search_paths(self) -> list[tuple[str, type]]:
|
||||
def model_module_search_paths(self) -> list[tuple[str, type]]:
|
||||
return self._model_module_search_paths()
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional, Any
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .Column import Column
|
||||
from .ColumnSet import ColumnSet
|
||||
if TYPE_CHECKING:
|
||||
from .Column import Column
|
||||
|
||||
class SingleForeignKey:
|
||||
|
||||
|
|
@ -19,7 +19,10 @@ class SingleForeignKey:
|
|||
yield from self.__iterable
|
||||
|
||||
def __repr__(self):
|
||||
return f'{self.__child_col.table.name}.{self.__child_col.name} -> {self.__parent_col.table.name}.{self.__parent_col.name}'
|
||||
return (
|
||||
f'{self.__child_col.table.name}.{self.__child_col.name} -> '
|
||||
'{self.__parent_col.table.name}.{self.__parent_col.name}'
|
||||
)
|
||||
|
||||
def __getitem__(self, index):
|
||||
return self.__iterable[index]
|
||||
|
|
|
|||
|
|
@ -1,47 +1,51 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Optional, Union, Iterable, Self, Any # TODO: Need any for many things, as I can't figure out how to avoid circular imports from here
|
||||
from __future__ import annotations
|
||||
|
||||
import abc
|
||||
import re
|
||||
|
||||
from collections import OrderedDict
|
||||
from typing import TYPE_CHECKING
|
||||
from urllib.parse import quote_plus
|
||||
|
||||
from ...log import *
|
||||
from ...log import ERR, WARNING, slog, throw
|
||||
from ...misc import load_class
|
||||
|
||||
from .ColumnSet import ColumnSet
|
||||
from .DataType import DataType
|
||||
from .CompositeForeignKey import CompositeForeignKey
|
||||
from .Column import Column
|
||||
from .ColumnSet import ColumnSet
|
||||
|
||||
class Table(abc.ABC): # export
|
||||
if TYPE_CHECKING:
|
||||
from typing import Any, Iterable, Optional, Self, Union
|
||||
|
||||
from .CompositeForeignKey import CompositeForeignKey
|
||||
from .DataType import DataType
|
||||
|
||||
class Table(abc.ABC): # export
|
||||
|
||||
def __init__(self, schema, name: str):
|
||||
assert(isinstance(name, str))
|
||||
assert (isinstance(name, str))
|
||||
self.__schema = schema
|
||||
self.__name = name
|
||||
|
||||
self.___columns: Optional[OrderedDict[str, Any]] = None
|
||||
self.___foreign_key_parent_tables: Optional[OrderedDict[str, Any]] = None
|
||||
self.___foreign_key_parent_tables: Optional[OrderedDict[str, Any]] = None
|
||||
|
||||
self.__primary_keys: Optional[Iterable[str]] = None
|
||||
self.__unique_constraints: Optional[list[ColumnSet]] = None
|
||||
self.__foreign_key_constraints: Optional[list[CompositeForeignKey]] = None
|
||||
self.__nullable_columns: Optional[Iterable[str]] = None
|
||||
self.__non_nullable_columns: Optional[Iterable[str]] = None
|
||||
self.__null_insertible_columns: Optional[Iterable[str]] = None
|
||||
self.__not_null_insertible_columns: Optional[Iterable[str]] = None
|
||||
self.__log_columns: Optional[Iterable[str]] = None
|
||||
self.__edit_columns: Optional[Iterable[str]] = None
|
||||
self.__translate_columns: Optional[Iterable[str]] = None
|
||||
self.__display_columns: Optional[Iterable[str]] = None
|
||||
self.__default_sort_columns: Optional[Iterable[str]] = None
|
||||
self.__column_default: Optional[dict[str, Any]] = None
|
||||
self.__base_location_rule: Optional[Iterable[str]] = None
|
||||
self.__location_rule: Optional[Iterable[str]] = None
|
||||
self.__row_location_rule: Optional[Iterable[str]] = None
|
||||
self.__add_row_location_rule: Optional[Iterable[str]] = None
|
||||
self.___add_child_row_location_rules: Optional[dict[str, str]] = None
|
||||
self.__nullable_columns: Optional[Iterable[str]] = None
|
||||
self.__non_nullable_columns: Optional[Iterable[str]] = None
|
||||
self.__null_insertible_columns: Optional[Iterable[str]] = None
|
||||
self.__not_null_insertible_columns: Optional[Iterable[str]] = None
|
||||
self.__log_columns: Optional[Iterable[str]] = None
|
||||
self.__edit_columns: Optional[Iterable[str]] = None
|
||||
self.__translate_columns: Optional[Iterable[str]] = None
|
||||
self.__display_columns: Optional[Iterable[str]] = None
|
||||
self.__default_sort_columns: Optional[Iterable[str]] = None
|
||||
self.__column_default: Optional[dict[str, Any]] = None
|
||||
self.__base_location_rule: Optional[Iterable[str]] = None
|
||||
self.__location_rule: Optional[Iterable[str]] = None
|
||||
self.__row_location_rule: Optional[Iterable[str]] = None
|
||||
self.__add_row_location_rule: Optional[Iterable[str]] = None
|
||||
self.___add_child_row_location_rules: Optional[dict[str, str]] = None
|
||||
self.__foreign_keys_to_parent_table: Optional[OrderedDict[str, Any]] = None
|
||||
self.__relationships: Optional[list[tuple[str, Self]]] = None
|
||||
self.__model_class: Optional[Any] = None
|
||||
|
|
@ -61,7 +65,8 @@ class Table(abc.ABC): # export
|
|||
if self.___foreign_key_parent_tables is None:
|
||||
self.___foreign_key_parent_tables = OrderedDict()
|
||||
for cfk in self.foreign_key_constraints:
|
||||
self.___foreign_key_parent_tables[cfk.parent_table.name] = cfk.parent_table
|
||||
self.___foreign_key_parent_tables[cfk.parent_table.name
|
||||
] = cfk.parent_table
|
||||
return self.___foreign_key_parent_tables
|
||||
|
||||
@property
|
||||
|
|
@ -77,12 +82,12 @@ class Table(abc.ABC): # export
|
|||
def __add_child_row_location_rules(self) -> dict[str, str]:
|
||||
if self.___add_child_row_location_rules is None:
|
||||
ret: dict[str, str] = {}
|
||||
for foreign_table_name, foreign_table in self.__relationship_by_foreign_table.items():
|
||||
if len([self.foreign_keys_to_parent_table(foreign_table)]):
|
||||
rule = self._add_child_row_location_rule(foreign_table_name)
|
||||
for table_name, table in self.__relationship_by_foreign_table.items():
|
||||
if len([self.foreign_keys_to_parent_table(table)]):
|
||||
rule = self._add_child_row_location_rule(table_name)
|
||||
if rule is None:
|
||||
continue
|
||||
ret[foreign_table_name] = rule
|
||||
ret[table_name] = rule
|
||||
self.___add_child_row_location_rules = ret
|
||||
return self.___add_child_row_location_rules
|
||||
|
||||
|
|
@ -108,7 +113,7 @@ class Table(abc.ABC): # export
|
|||
return False
|
||||
return True
|
||||
throw(ERR, f'Tried to compare table {self} to type {type(rhs)}: {rhs}')
|
||||
return False # Unreachable but requested by mypy
|
||||
return False # Unreachable but requested by mypy
|
||||
|
||||
def __hash__(self) -> int:
|
||||
return hash(self.name)
|
||||
|
|
@ -167,8 +172,9 @@ class Table(abc.ABC): # export
|
|||
slog(WARNING, f'Returning None model name for table {self.name}')
|
||||
return None
|
||||
|
||||
def _model_module_search_paths(self) -> list[tuple[str, type]]:
|
||||
return self.schema.model_module_search_paths # Fall back to Schema-global default
|
||||
def _model_module_search_paths(self) -> list[tuple[str, type]]:
|
||||
# Fall back to Schema-global default
|
||||
return self.schema.model_module_search_paths
|
||||
|
||||
@abc.abstractmethod
|
||||
def _query_name(self) -> str:
|
||||
|
|
@ -190,7 +196,9 @@ class Table(abc.ABC): # export
|
|||
for col in self.__schema.access_defining_columns:
|
||||
if col in self.primary_keys:
|
||||
ret += f'/<{col}>'
|
||||
ret += self.base_location_rule
|
||||
base = self.base_location_rule
|
||||
if base is not None:
|
||||
ret += base if isinstance(base, str) else 'what-goes-here?'.join(base)
|
||||
return ret
|
||||
|
||||
def _row_location_rule(self) -> Optional[str]:
|
||||
|
|
@ -261,7 +269,7 @@ class Table(abc.ABC): # export
|
|||
return None
|
||||
pattern = r'^' + model_name + '$'
|
||||
for module_path, base_class in self._model_module_search_paths():
|
||||
ret = load_class(module_path, base_class, class_name_filter=pattern)
|
||||
ret = load_class(module_path, base_class, class_name_filter = pattern)
|
||||
if ret is not None:
|
||||
self.__model_class = ret
|
||||
break
|
||||
|
|
@ -288,8 +296,8 @@ class Table(abc.ABC): # export
|
|||
return self.__location_rule
|
||||
|
||||
def location(self, *args, **kwargs):
|
||||
ret = self.location_rule
|
||||
for token, val in kwargs.items(): # FIXME: Poor man's row location assembly
|
||||
ret = str(self.location_rule)
|
||||
for token, val in kwargs.items(): # FIXME: Poor man's row location assembly
|
||||
ret = re.sub(f'<{token}>', quote_plus(quote_plus(str(val))), ret)
|
||||
return ret
|
||||
|
||||
|
|
@ -300,9 +308,9 @@ class Table(abc.ABC): # export
|
|||
return self.__row_location_rule
|
||||
|
||||
def row_location(self, *args, **kwargs):
|
||||
ret = self.row_location_rule
|
||||
ret = str(self.row_location_rule)
|
||||
for col in self.primary_keys:
|
||||
if col in kwargs: # FIXME: Poor man's row location assembly
|
||||
if col in kwargs: # FIXME: Poor man's row location assembly
|
||||
ret = re.sub(f'<{col}>', quote_plus(quote_plus(str(kwargs[col]))), ret)
|
||||
return ret
|
||||
|
||||
|
|
@ -313,9 +321,9 @@ class Table(abc.ABC): # export
|
|||
return self.__add_row_location_rule
|
||||
|
||||
def add_row_location(self, *args, **kwargs) -> Optional[str]:
|
||||
ret = self.add_row_location_rule
|
||||
ret = str(self.add_row_location_rule)
|
||||
for col in self.primary_keys:
|
||||
if col in kwargs: # FIXME: Poor man's row location assembly
|
||||
if col in kwargs: # FIXME: Poor man's row location assembly
|
||||
ret = re.sub(f'<{col}>', quote_plus(quote_plus(str(kwargs[col]))), ret)
|
||||
return ret
|
||||
|
||||
|
|
@ -323,12 +331,14 @@ class Table(abc.ABC): # export
|
|||
def add_child_row_location_rules(self) -> Iterable[str]:
|
||||
return self.__add_child_row_location_rules.values()
|
||||
|
||||
def add_child_row_location_rule(self, child_table: Union[Self, str]) -> Optional[str]:
|
||||
def add_child_row_location_rule(self, child_table: Union[Self,
|
||||
str]) -> Optional[str]:
|
||||
if isinstance(child_table, Table):
|
||||
child_table = child_table.name
|
||||
return self.__add_child_row_location_rules.get(child_table)
|
||||
|
||||
def add_child_row_location(self, parent_table: Union[Self, str], **kwargs) -> Optional[str]:
|
||||
def add_child_row_location(self, parent_table: Union[Self, str],
|
||||
**kwargs) -> Optional[str]:
|
||||
ret = self.add_child_row_location_rule(parent_table)
|
||||
if isinstance(parent_table, str):
|
||||
parent_table = self.schema[parent_table]
|
||||
|
|
@ -337,7 +347,11 @@ class Table(abc.ABC): # export
|
|||
for cfk in self.foreign_keys_to_parent_table(parent_table):
|
||||
for fk in cfk:
|
||||
if fk.parent_column.name in kwargs:
|
||||
ret = re.sub(f'<{fk.child_column.name}>', quote_plus(quote_plus(str(kwargs[fk.parent_column.name]))), ret)
|
||||
ret = re.sub(
|
||||
f'<{fk.child_column.name}>',
|
||||
quote_plus(quote_plus(str(kwargs[fk.parent_column.name]))),
|
||||
ret
|
||||
)
|
||||
return ret
|
||||
|
||||
@property
|
||||
|
|
@ -425,7 +439,7 @@ class Table(abc.ABC): # export
|
|||
impl = self._unique_constraints()
|
||||
if impl is not None:
|
||||
for columns in impl:
|
||||
ret.append(ColumnSet(columns=columns))
|
||||
ret.append(ColumnSet(columns = columns))
|
||||
self.__unique_constraints = ret
|
||||
return self.__unique_constraints
|
||||
|
||||
|
|
@ -443,7 +457,8 @@ class Table(abc.ABC): # export
|
|||
def foreign_key_parent_tables(self):
|
||||
return self.__foreign_key_parent_tables.values()
|
||||
|
||||
def foreign_keys_to_parent_table(self, parent_table) -> Iterable[CompositeForeignKey]:
|
||||
def foreign_keys_to_parent_table(self,
|
||||
parent_table) -> Iterable[CompositeForeignKey]:
|
||||
if self.__foreign_keys_to_parent_table is None:
|
||||
self.__foreign_keys_to_parent_table = OrderedDict()
|
||||
for cfk in self.foreign_key_constraints:
|
||||
|
|
@ -451,8 +466,12 @@ class Table(abc.ABC): # export
|
|||
if pt not in self.__foreign_keys_to_parent_table:
|
||||
self.__foreign_keys_to_parent_table[pt] = []
|
||||
self.__foreign_keys_to_parent_table[pt].append(cfk)
|
||||
parent_table_name = parent_table if isinstance(parent_table, str) else parent_table.name
|
||||
return self.__foreign_keys_to_parent_table[parent_table_name] if parent_table_name in self.__foreign_keys_to_parent_table else []
|
||||
parent_table_name = parent_table if isinstance(
|
||||
parent_table, str
|
||||
) else parent_table.name
|
||||
return self.__foreign_keys_to_parent_table[
|
||||
parent_table_name
|
||||
] if parent_table_name in self.__foreign_keys_to_parent_table else []
|
||||
|
||||
@property
|
||||
def relationships(self) -> list[tuple[str, Self]]:
|
||||
|
|
|
|||
|
|
@ -1,12 +1,18 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import annotations
|
||||
|
||||
from .Schema import Schema
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from ...log import *
|
||||
from ...log import NOTICE, slog
|
||||
|
||||
def check_schema(schema: Schema): # export
|
||||
if TYPE_CHECKING:
|
||||
from .Schema import Schema
|
||||
|
||||
def check_schema(schema: Schema): # export
|
||||
slog(NOTICE, f'There are {len(schema)} tables in the database')
|
||||
for cfk in schema.foreign_key_constraints:
|
||||
for fk in cfk:
|
||||
if fk.child_column.data_type != fk.parent_column.data_type:
|
||||
raise Exception(f'Type mismatch in foreign key {fk}: {fk.child_column.data_type} != {fk.parent_column.data_type}')
|
||||
raise Exception(
|
||||
f'Type mismatch in foreign key {fk}: {fk.child_column.data_type} '
|
||||
f'!= {fk.parent_column.data_type}'
|
||||
)
|
||||
|
|
|
|||
Loading…
Reference in a new issue