jwutils: Move to jwutils -> jw.util
Move all implementation source code from the jwutils module to jw.util. For compatibility with existing Python modules, keep a thin, autogenerated compatibility shim under jwutils. Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
parent
bc7652fdf9
commit
a2684dd601
18 changed files with 678 additions and 52 deletions
42
src/python/jw/util/db/DataBase.py
Normal file
42
src/python/jw/util/db/DataBase.py
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Any
|
||||
|
||||
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 *
|
||||
|
||||
class DataBase(abc.ABC):
|
||||
|
||||
def __init__(self, schema: Schema, conf: Config) -> None:
|
||||
self.__conf = conf
|
||||
self.__schema = schema
|
||||
conf.dump(NOTICE, "Initializing database with configuration")
|
||||
|
||||
@abc.abstractmethod
|
||||
def _create_session(self):
|
||||
pass
|
||||
|
||||
def _delete_session(self, session: Session):
|
||||
del session
|
||||
|
||||
@property
|
||||
def schema(self):
|
||||
return self.__schema
|
||||
|
||||
@property
|
||||
def conf(self):
|
||||
return self.__conf
|
||||
|
||||
@contextmanager
|
||||
def session(self):
|
||||
ret = self._create_session()
|
||||
try:
|
||||
yield ret
|
||||
finally:
|
||||
self._delete_session(ret)
|
||||
4
src/python/jw/util/db/Makefile
Normal file
4
src/python/jw/util/db/Makefile
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
TOPDIR = ../../../../..
|
||||
|
||||
include $(TOPDIR)/make/proj.mk
|
||||
include $(JWBDIR)/make/py-mod.mk
|
||||
12
src/python/jw/util/db/Session.py
Normal file
12
src/python/jw/util/db/Session.py
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
import abc
|
||||
|
||||
class Session(abc.ABC): # export
|
||||
|
||||
def __init__(self, db):
|
||||
self.__db = db
|
||||
|
||||
@property
|
||||
def db(self):
|
||||
return self.__db
|
||||
84
src/python/jw/util/db/TableIoHandler.py
Normal file
84
src/python/jw/util/db/TableIoHandler.py
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Any, List, Union, Optional, Dict
|
||||
from abc import ABC, abstractmethod
|
||||
import re, csv, json
|
||||
|
||||
from ..log import *
|
||||
from ..cast import cast_str
|
||||
from .schema.Schema import Schema
|
||||
|
||||
from .rows import *
|
||||
|
||||
TType = Union[Any, Dict[str, Any]]
|
||||
|
||||
class TableIoHandler(ABC): # export
|
||||
|
||||
def __init__(self, schema: Schema):
|
||||
self.__table_meta = None
|
||||
self.__schema = schema
|
||||
|
||||
@property
|
||||
def _table_meta(self):
|
||||
if self.__table_meta is None:
|
||||
self.__table_meta = self.__schema.table_by_model_name(
|
||||
self.__class__.__name__, throw=True)
|
||||
return self.__table_meta
|
||||
|
||||
@property
|
||||
def _table_name(self):
|
||||
return self._table_meta.name
|
||||
|
||||
@property
|
||||
def _primary_keys(self):
|
||||
return self._table_meta.primary_keys
|
||||
|
||||
def _check_non_nullable(self, rows):
|
||||
buf = []
|
||||
non_nullable = self.__table_meta.not_null_insertible_columns
|
||||
try:
|
||||
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)
|
||||
if not buf:
|
||||
continue
|
||||
slog_m(ERR, f'\n{d} Null values in {cn} / {tn}: "{key}"\n')
|
||||
use_cols=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}')
|
||||
raise
|
||||
|
||||
@property
|
||||
def log_columns(self):
|
||||
return self._table_meta.log_columns
|
||||
|
||||
@abstractmethod
|
||||
def _load(self, uri: str, reference) -> TType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def _store(self, uri: str, data: TType):
|
||||
pass
|
||||
|
||||
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:
|
||||
slog(INFO, f'Checking duplicates in {self._table_name}')
|
||||
d = rows_duplicates(ret)
|
||||
if len(d):
|
||||
slog(ERR, f'Duplicates {d}')
|
||||
raise Exception("Duplicates")
|
||||
self._check_non_nullable(ret)
|
||||
#schema_missing_foreign_key_values(self._table_name, ret, reference)
|
||||
return ret
|
||||
|
||||
def store(self, uri: str, data: TType) -> None:
|
||||
return self._store(uri, data)
|
||||
4
src/python/jw/util/db/query/Makefile
Normal file
4
src/python/jw/util/db/query/Makefile
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
TOPDIR = ../../../../../..
|
||||
|
||||
include $(TOPDIR)/make/proj.mk
|
||||
include $(JWBDIR)/make/py-mod.mk
|
||||
82
src/python/jw/util/db/query/Queries.py
Normal file
82
src/python/jw/util/db/query/Queries.py
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Any
|
||||
|
||||
import abc
|
||||
|
||||
from ...log import *
|
||||
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
|
||||
|
||||
class Query(QueryBase):
|
||||
|
||||
def __init__(self: Any, query: QueryBase, name: str, location: str, func: Any):
|
||||
self.__query = query
|
||||
self.__func = func
|
||||
self.__location = location
|
||||
self.__name = name
|
||||
|
||||
# -- implement API
|
||||
|
||||
def _run(self, session, *args, **kwargs) -> QueryResult:
|
||||
return self.__func(session, *args, **kwargs)
|
||||
|
||||
def _register(self):
|
||||
raise Exception('Can\'t call register on this object')
|
||||
|
||||
def _column_names(self) -> list[str]:
|
||||
return self.__query.column_names
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return self.__name
|
||||
|
||||
def __init__(self, db: DataBase) -> None:
|
||||
assert(isinstance(db, DataBase))
|
||||
self.__db = db
|
||||
self.__queries: dict[str, Any] = dict()
|
||||
|
||||
def __getitem__(self, name) -> Query:
|
||||
try:
|
||||
return self.__queries[name]
|
||||
except Exception as e:
|
||||
slog(ERR, f'Failed to retrieve query {name} ({e})')
|
||||
slog_m(ERR, '\n'.join(self.__queries.keys()))
|
||||
raise
|
||||
|
||||
def keys(self):
|
||||
return self.__queries.keys()
|
||||
|
||||
@property
|
||||
def db(self) -> DataBase:
|
||||
return self.__db
|
||||
|
||||
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):
|
||||
c(self).register()
|
||||
|
||||
@property
|
||||
def schema(self) -> Schema:
|
||||
return self.__db.schema
|
||||
|
||||
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))
|
||||
#ret = self.Query(query, func)
|
||||
ret = self.Query(query, query_name, location, func)
|
||||
#setattr(ret, 'name', name)
|
||||
self.__queries[query_name] = ret
|
||||
self._add(ret)
|
||||
|
||||
# To be overriden in case the derived class wants to keep track
|
||||
def _add(self, query):
|
||||
pass
|
||||
61
src/python/jw/util/db/query/Query.py
Normal file
61
src/python/jw/util/db/query/Query.py
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Any
|
||||
|
||||
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
|
||||
|
||||
class Query(abc.ABC): # export
|
||||
|
||||
def __init__(self, parent: Any) -> None:
|
||||
self.__parent = parent
|
||||
|
||||
# -- pure virtuals
|
||||
|
||||
@abc.abstractmethod
|
||||
def _run(self, session: Session, *args, **kwargs) -> QueryResult:
|
||||
raise Exception('Called pure virtual _run()')
|
||||
|
||||
@abc.abstractmethod
|
||||
def _register(self):
|
||||
raise Exception('Called pure virtual _register()')
|
||||
|
||||
@abc.abstractmethod
|
||||
def _column_names(self) -> list[str]:
|
||||
raise Exception('Called pure virtual _column()')
|
||||
|
||||
# -- used by Queries class
|
||||
|
||||
def register(self):
|
||||
return self._register()
|
||||
|
||||
# -- to be used
|
||||
|
||||
def _add(self, query_name: str, location: str, func: Any):
|
||||
return self.__parent.add(self, query_name, location, func)
|
||||
|
||||
def run(self, session: Session, *args, **kwargs) -> QueryResult:
|
||||
return self._run(session, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def parent(self):
|
||||
return self.__parent
|
||||
|
||||
@property
|
||||
def db(self) -> DataBase:
|
||||
return self.__parent.db
|
||||
|
||||
@property
|
||||
def schema(self):
|
||||
return self.__parent.db.schema
|
||||
|
||||
@property
|
||||
def column_names(self) -> list[str]:
|
||||
return self._column_names()
|
||||
62
src/python/jw/util/db/query/QueryResult.py
Normal file
62
src/python/jw/util/db/query/QueryResult.py
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Any, Union
|
||||
|
||||
import abc
|
||||
from enum import Enum, auto
|
||||
|
||||
from ...log import *
|
||||
from ...Cmds import Cmds
|
||||
from ..DataBase import DataBase
|
||||
from ..Session import Session
|
||||
|
||||
class ResType(Enum): # export
|
||||
Statement = auto()
|
||||
Scalars = auto()
|
||||
One = auto()
|
||||
First = auto()
|
||||
Pages = auto()
|
||||
|
||||
class QueryResult(abc.ABC): # export
|
||||
|
||||
def __init__(self, session: Session, query: Any) -> None:
|
||||
self.__query = query
|
||||
self.__session = session
|
||||
|
||||
@property
|
||||
def db(self) -> DataBase:
|
||||
return self.__query.db
|
||||
|
||||
@property
|
||||
def query(self) -> DataBase:
|
||||
return self.__query
|
||||
|
||||
@property
|
||||
def session(self) -> Session:
|
||||
return self.__session
|
||||
|
||||
@property
|
||||
def schema(self):
|
||||
return self.__query.db.schema
|
||||
|
||||
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 one(self) -> Any:
|
||||
return self._cast(ResType.One)
|
||||
|
||||
def first(self) -> Any:
|
||||
return self._cast(ResType.First)
|
||||
|
||||
@property
|
||||
def statement(self) -> Any:
|
||||
return self._cast(ResType.Statement)
|
||||
|
||||
# -- pure virtuals
|
||||
|
||||
@abc.abstractmethod
|
||||
def _cast(self, res_type: ResType, **kwargs) -> Union[Any|list[Any]]:
|
||||
pass
|
||||
250
src/python/jw/util/db/rows.py
Normal file
250
src/python/jw/util/db/rows.py
Normal file
|
|
@ -0,0 +1,250 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
import io, os, re, textwrap, json, csv
|
||||
from tabulate import tabulate # type: ignore
|
||||
|
||||
from ..log import *
|
||||
|
||||
def rows_pretty(rows): # export
|
||||
if type(rows) == dict:
|
||||
rows = [rows]
|
||||
out = []
|
||||
for row in rows:
|
||||
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 __equal(r1, r2):
|
||||
for col in set(r1.keys()) | set(r2.keys()):
|
||||
if col in r1:
|
||||
if col not in r2:
|
||||
return False
|
||||
else:
|
||||
if col in r2:
|
||||
return False
|
||||
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)):
|
||||
if __equal(rows[last], rows[i]):
|
||||
ret.append(last)
|
||||
last -= 1
|
||||
break
|
||||
last -= 1
|
||||
return ret
|
||||
|
||||
def rows_remove(rows, callback=None, candidates=None, log_prio=INFO, caller=None): # export
|
||||
|
||||
def __is_remove_candidate(row):
|
||||
for remove_row in candidates:
|
||||
for col, val in row.items():
|
||||
if not col in remove_row.keys():
|
||||
break
|
||||
if val != remove_row[col]:
|
||||
break
|
||||
else:
|
||||
return True
|
||||
return False
|
||||
|
||||
if caller is None:
|
||||
caller = get_caller_pos()
|
||||
if callback is None:
|
||||
if candidates is not None:
|
||||
callback = __is_remove_candidate
|
||||
else:
|
||||
raise Exception('No criterion to remove rows')
|
||||
remove = list()
|
||||
index = -1
|
||||
for row in rows:
|
||||
index += 1
|
||||
if callback(row):
|
||||
remove.append(index)
|
||||
continue
|
||||
for index in reversed(remove):
|
||||
slog(log_prio, f'Removing row {rows[index]}', caller=caller)
|
||||
del rows[index]
|
||||
|
||||
def rows_select(rows, rules): # export
|
||||
ret = []
|
||||
for row in rows:
|
||||
for rule in rules:
|
||||
if type(rule) == tuple():
|
||||
search_rule = rule[0]
|
||||
else:
|
||||
search_rule = rule
|
||||
for col_name, expr in search_rule.items():
|
||||
if not re.search(expr, row[col_name]):
|
||||
break
|
||||
else:
|
||||
ret.append(row)
|
||||
break
|
||||
return ret
|
||||
|
||||
def rows_rewrite_regex(rows, rules): # export
|
||||
for row in rows:
|
||||
for rule in rules:
|
||||
try:
|
||||
for col_name, expr in rule[0].items():
|
||||
if not re.search(expr, row[col_name]):
|
||||
break
|
||||
else:
|
||||
for exec_col_name, exec_val in rule[1].items():
|
||||
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:
|
||||
keys = [keys]
|
||||
if caller is None:
|
||||
caller = get_caller_pos()
|
||||
count = 0
|
||||
stats = dict()
|
||||
if buf is None:
|
||||
buf = []
|
||||
else:
|
||||
buf.clear()
|
||||
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)
|
||||
buf.append(row)
|
||||
if stat_key is not None:
|
||||
stat_val = row[stat_key]
|
||||
if not stat_val in stats.keys():
|
||||
stats[stat_val] = 0
|
||||
stats[stat_val] += 1
|
||||
count += 1
|
||||
break
|
||||
if count > 0:
|
||||
if stat_key is not None:
|
||||
i = 0
|
||||
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)
|
||||
if throw:
|
||||
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
|
||||
|
||||
headers = 'keys'
|
||||
dump_rows = rows
|
||||
if use_cols is not None:
|
||||
#dump_rows = {col: rows[col] for col in use_cols}
|
||||
new_dump_rows = []
|
||||
for row in dump_rows:
|
||||
new_dump_rows.append({col: row.get(col) for col in use_cols})
|
||||
dump_rows = new_dump_rows
|
||||
if skip_cols is not None:
|
||||
new_dump_rows = []
|
||||
for row in dump_rows:
|
||||
new_row = {}
|
||||
for col, val in row.items():
|
||||
if col in skip_cols:
|
||||
continue
|
||||
new_row[col] = val
|
||||
new_dump_rows.append(new_row)
|
||||
dump_rows = new_dump_rows
|
||||
out = header = footer = ""
|
||||
match tablefmt:
|
||||
case 'html':
|
||||
if heading is not None:
|
||||
heading = f'<h1>{heading}</h1>\n'
|
||||
if type(lead) == str:
|
||||
lead = f'<div class="lead">\n {lead}\n</div>\n'
|
||||
elif type(lead) == list:
|
||||
l = '<ul>\n'
|
||||
for li in lead:
|
||||
l += f'<li>{li}</li>\n'
|
||||
l += '</ul>\n'
|
||||
lead = l
|
||||
header=textwrap.dedent('''\
|
||||
<html>
|
||||
<head>
|
||||
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
|
||||
<script>
|
||||
$(document).ready(function()
|
||||
{
|
||||
$("tr:odd").css({ "background-color":"#ffa"});
|
||||
});
|
||||
</script>
|
||||
<style>
|
||||
tbody td {
|
||||
/* padding: 30px; */
|
||||
}
|
||||
tbody tr:nth-child(odd) {
|
||||
background-color: #4C8BF5;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
''')
|
||||
footer = textwrap.dedent('''
|
||||
</body>
|
||||
</html>
|
||||
''')
|
||||
case _:
|
||||
if type(heading) == str:
|
||||
heading = '\n' + heading
|
||||
if type(lead) == str:
|
||||
pass
|
||||
elif type(lead) == list:
|
||||
l =''
|
||||
for li in lead:
|
||||
l += f' - {li}\n'
|
||||
lead = '\n\n' + l + '\n'
|
||||
|
||||
if heading is None:
|
||||
heading = ''
|
||||
if lead is None:
|
||||
lead = ''
|
||||
|
||||
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
|
||||
|
||||
if not prio_gets_logged(log_prio):
|
||||
return
|
||||
|
||||
if caller is None:
|
||||
caller = get_caller_pos()
|
||||
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)
|
||||
|
||||
match out_path:
|
||||
case 'log':
|
||||
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 __write(rows, out):
|
||||
writer = csv.DictWriter(out, fieldnames=field_names, delimiter=';', quotechar='"', quoting=csv.QUOTE_NONNUMERIC)
|
||||
writer.writeheader()
|
||||
for row in rows:
|
||||
writer.writerow(row)
|
||||
|
||||
field_names = []
|
||||
for row in rows:
|
||||
for col in row.keys():
|
||||
if col not in field_names:
|
||||
field_names.append(col)
|
||||
if True:
|
||||
out = io.StringIO()
|
||||
__write(rows, out)
|
||||
return out.getvalue()
|
||||
import tempfile
|
||||
with tempfile.TemporaryFile(mode='w', newline='') as out:
|
||||
__write(rows, out)
|
||||
out.seek(0)
|
||||
return out.read()
|
||||
120
src/python/jw/util/db/schema/Column.py
Normal file
120
src/python/jw/util/db/schema/Column.py
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Optional, Any
|
||||
|
||||
import abc
|
||||
|
||||
from .DataType import DataType
|
||||
from ...log import *
|
||||
|
||||
class Column(abc.ABC): # export
|
||||
|
||||
def __init__(self, table, name, data_type: DataType):
|
||||
self.__name: str = name
|
||||
self.__table: Any = table
|
||||
self.__is_nullable: Optional[bool] = None
|
||||
self.__is_null_insertible: Optional[bool] = None
|
||||
self.__is_primary_key: Optional[bool] = None
|
||||
self.__default_value: Optional[Any] = None
|
||||
self.__default_value_cached: bool = False
|
||||
self.__is_auto_increment: Optional[bool] = None
|
||||
self.__translate: Optional[bool] = None
|
||||
self.__data_type: DataType = data_type
|
||||
self.__foreign_keys: Optional[Any] = None
|
||||
self.__foreign_keys_cached: bool = False
|
||||
self.__foreign_keys_by_table: Optional[dict[str, Any]] = None
|
||||
|
||||
def __repr__(self):
|
||||
return f'{self.__table.name}.{self.__name}: {self.__data_type}'
|
||||
|
||||
def __eq__(self, rhs) -> bool:
|
||||
if isinstance(rhs, Column):
|
||||
if self.__table != rhs.__table:
|
||||
return False
|
||||
if self.__name != rhs.__name:
|
||||
return False
|
||||
return True
|
||||
elif isinstance(rhs, str):
|
||||
if self.__name != rhs:
|
||||
return False
|
||||
return True
|
||||
throw(ERR, f'Tried to compare column {self} to type {type(rhs)}: {rhs}')
|
||||
return False # Unreachable but requested by mypy
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return self.__name
|
||||
|
||||
@property
|
||||
def data_type(self):
|
||||
return self.__data_type
|
||||
|
||||
@property
|
||||
def table(self) -> str:
|
||||
return self.__table
|
||||
|
||||
@property
|
||||
def is_nullable(self) -> bool:
|
||||
if self.__is_nullable is None:
|
||||
self.__is_nullable = self.__name in self.__table.nullable_columns
|
||||
return self.__is_nullable
|
||||
|
||||
@property
|
||||
def is_null_insertible(self):
|
||||
if self.__is_null_insertible is None:
|
||||
ret = False
|
||||
if self.is_nullable:
|
||||
ret = True
|
||||
elif self.is_auto_increment:
|
||||
ret = True
|
||||
elif self.default_value is not None:
|
||||
ret = True
|
||||
self.__is_null_insertible = ret
|
||||
return self.__is_null_insertible
|
||||
|
||||
@property
|
||||
def is_primary_key(self) -> bool:
|
||||
if self.__is_primary_key is None:
|
||||
self.__is_primary_key = self.__name in self.__table.primary_keys
|
||||
return self.__is_primary_key
|
||||
|
||||
@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
|
||||
return self.__is_auto_increment
|
||||
|
||||
@property
|
||||
def translate(self) -> bool:
|
||||
if self.__translate is None:
|
||||
self.__translate = self.__name in self.__table.translate_columns
|
||||
return self.__translate
|
||||
|
||||
@property
|
||||
def default_value(self) -> Optional[Any]:
|
||||
if self.__default_value_cached is False:
|
||||
self.__default_value = self.__table.column_default(self.name)
|
||||
self.__default_value_cached = True
|
||||
return self.__default_value
|
||||
|
||||
# Returns Column object on parent table
|
||||
@property
|
||||
def foreign_keys(self) -> Optional[Any]:
|
||||
if not self.__foreign_keys_cached:
|
||||
fks: list[Any] = []
|
||||
for cfk in self.__table.foreign_key_constraints:
|
||||
for fk in cfk:
|
||||
if fk.child_column == self:
|
||||
fks.append(fk.parent_column)
|
||||
self.__foreign_keys_cached = True
|
||||
self.__foreign_keys = fks if fks else None
|
||||
return self.__foreign_keys
|
||||
|
||||
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)
|
||||
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)
|
||||
43
src/python/jw/util/db/schema/ColumnSet.py
Normal file
43
src/python/jw/util/db/schema/ColumnSet.py
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Optional, Iterable, Any
|
||||
|
||||
class ColumnSet: # export
|
||||
|
||||
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)
|
||||
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)
|
||||
|
||||
def __len__(self):
|
||||
return len(self.__columns)
|
||||
|
||||
def __iter__(self):
|
||||
yield from self.__columns
|
||||
|
||||
def __repr__(self):
|
||||
return '|'.join([col.name for col in self.__columns])
|
||||
|
||||
def __getitem__(self, index):
|
||||
return self.__columns[index]
|
||||
|
||||
def __eq__(self, rhs):
|
||||
if self.__table != rhs.__table:
|
||||
return False
|
||||
if len(self.__columns) != len(rhs.__columns):
|
||||
return False
|
||||
for i in range(0, len(self.__columns)):
|
||||
if self.__columns[i].name != rhs.__columns[i].name:
|
||||
return False
|
||||
return True
|
||||
|
||||
@property
|
||||
def columns(self) -> list[Any]:
|
||||
return self.__columns
|
||||
103
src/python/jw/util/db/schema/CompositeForeignKey.py
Normal file
103
src/python/jw/util/db/schema/CompositeForeignKey.py
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Optional, Any
|
||||
|
||||
from ...log import *
|
||||
|
||||
from .ColumnSet import ColumnSet
|
||||
from .SingleForeignKey import SingleForeignKey
|
||||
|
||||
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
|
||||
for c in s:
|
||||
if ret is None:
|
||||
ret = c.table
|
||||
else:
|
||||
assert(ret == c.table)
|
||||
assert(ret is not None)
|
||||
return ret
|
||||
|
||||
self.__child_col_set = child_col_set
|
||||
self.__parent_col_set = parent_col_set
|
||||
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))
|
||||
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
|
||||
self.__child_columns_by_parent_column: Optional[dict[str, Any]] = None
|
||||
|
||||
def __table_rel_str(self):
|
||||
return f'{self.__child_table.name} => {self.__parent_table.name}'
|
||||
|
||||
def __cols_rel_str(self, child, parent):
|
||||
return f'{child.name} -> {parent.name}'
|
||||
|
||||
def __len__(self):
|
||||
return self.__len
|
||||
|
||||
def __iter__(self):
|
||||
yield from self.column_relations
|
||||
|
||||
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])
|
||||
return ret
|
||||
|
||||
def __eq__(self, rhs):
|
||||
if rhs.__child_col_set != self.__child_col_set:
|
||||
return False
|
||||
if rhs.__parent_col_set != self.__parent_col_set:
|
||||
return False
|
||||
return True
|
||||
|
||||
@property
|
||||
def child_table(self) -> Any:
|
||||
return self.__child_table
|
||||
|
||||
@property
|
||||
def parent_table(self) -> Any:
|
||||
return self.__parent_table
|
||||
|
||||
@property
|
||||
def child_columns(self) -> ColumnSet:
|
||||
return self.__child_col_set
|
||||
|
||||
@property
|
||||
def parent_columns(self) -> ColumnSet:
|
||||
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
|
||||
if self.__parent_columns_by_child_column is None:
|
||||
d: dict[str, Any] = {}
|
||||
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
|
||||
if self.__child_columns_by_parent_column is None:
|
||||
d: dict[str, Any] = {}
|
||||
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
|
||||
return self.__child_columns_by_parent_column[parent_column]
|
||||
|
||||
@property
|
||||
def column_relations(self) -> list[Any]:
|
||||
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]))
|
||||
self.__column_relations = ret
|
||||
return self.__column_relations
|
||||
83
src/python/jw/util/db/schema/DataType.py
Normal file
83
src/python/jw/util/db/schema/DataType.py
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Optional
|
||||
from enum import Enum, auto
|
||||
from datetime import datetime
|
||||
|
||||
from ...log import *
|
||||
|
||||
class Id(Enum):
|
||||
Integer = auto()
|
||||
SmallInteger = auto()
|
||||
Currency = auto()
|
||||
Single = auto()
|
||||
DateTime = auto()
|
||||
String = auto()
|
||||
Text = auto()
|
||||
Invalid = auto()
|
||||
|
||||
def py_type(type_id: Id) -> type: # export
|
||||
|
||||
match type_id:
|
||||
case Id.Integer:
|
||||
return int
|
||||
case Id.SmallInteger:
|
||||
return int
|
||||
case Id.Currency:
|
||||
return int
|
||||
case Id.Single:
|
||||
return int
|
||||
case Id.DateTime:
|
||||
return datetime
|
||||
case Id.String:
|
||||
return str
|
||||
case Id.Text:
|
||||
return str
|
||||
case Id.DateTime:
|
||||
return datetime
|
||||
|
||||
raise Exception(f'Unknown column type-id "{type_id}"')
|
||||
|
||||
class DataType: # export
|
||||
|
||||
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)}')
|
||||
if size is not None:
|
||||
assert(isinstance(size, int))
|
||||
assert(size > 0)
|
||||
self.__id = type_id
|
||||
self.__size = size
|
||||
|
||||
def __repr__(self):
|
||||
ret = f'{self.__id.name}'
|
||||
if self.__size is not None:
|
||||
ret += f'({self.__size})'
|
||||
return ret
|
||||
|
||||
def __eq__(self, rhs):
|
||||
if self.__id != rhs.__id:
|
||||
return False
|
||||
if self.__size != rhs.__size:
|
||||
return False
|
||||
return True
|
||||
|
||||
@property
|
||||
def type_id(self) -> Id:
|
||||
return self.__id
|
||||
|
||||
@property
|
||||
def size(self) -> Optional[int]:
|
||||
return self.__size
|
||||
|
||||
@property
|
||||
def py_type(self) -> type:
|
||||
return py_type(self.__id)
|
||||
|
||||
@property
|
||||
def py_type_str(self) -> str:
|
||||
return self.py_type.__name__
|
||||
|
||||
@property
|
||||
def py_type_annotation(self) -> str:
|
||||
return self.py_type_str # FIXME: This is not always correct
|
||||
4
src/python/jw/util/db/schema/Makefile
Normal file
4
src/python/jw/util/db/schema/Makefile
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
TOPDIR = ../../../../../..
|
||||
|
||||
include $(TOPDIR)/make/proj.mk
|
||||
include $(JWBDIR)/make/py-mod.mk
|
||||
109
src/python/jw/util/db/schema/Schema.py
Normal file
109
src/python/jw/util/db/schema/Schema.py
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Optional, Iterable
|
||||
|
||||
import abc
|
||||
|
||||
from ...log import *
|
||||
|
||||
from .Table import Table
|
||||
from .Column import Column
|
||||
from .DataType import DataType
|
||||
from .CompositeForeignKey import CompositeForeignKey
|
||||
|
||||
class Schema(abc.ABC): # export
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.___tables: Optional[list[Table]] = None
|
||||
self.__foreign_keys: Optional[list[CompositeForeignKey]] = None
|
||||
self.__access_defining_columns: Optional[list[str]] = None
|
||||
|
||||
@property
|
||||
def __tables(self):
|
||||
if self.___tables is None:
|
||||
ret = dict()
|
||||
for name in self._table_names():
|
||||
slog(DEBUG, f'Caching metadata for table "{name}"')
|
||||
assert(isinstance(name, str))
|
||||
ret[name] = self._table(name)
|
||||
self.___tables = ret
|
||||
return self.___tables
|
||||
|
||||
# ------ API to be implemented
|
||||
|
||||
@abc.abstractmethod
|
||||
def _table_names(self) -> Iterable[str]:
|
||||
throw(ERR, "Called pure virtual base class method")
|
||||
return []
|
||||
|
||||
@abc.abstractmethod
|
||||
def _table(self, name: str) -> Table:
|
||||
throw(ERR, "Called pure virtual base class method")
|
||||
return None # type: ignore
|
||||
|
||||
@abc.abstractmethod
|
||||
def _foreign_keys(self) -> list[CompositeForeignKey]:
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
def _access_defining_columns(self):
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
def _model_module_search_paths(self) -> list[tuple[str, type]]:
|
||||
pass
|
||||
|
||||
# ------ API to be called
|
||||
|
||||
def __len__(self):
|
||||
return len(self.__tables)
|
||||
|
||||
def __iter__(self):
|
||||
yield from self.__tables.values()
|
||||
|
||||
def __repr__(self):
|
||||
return '|'.join([table.name for table in self.__tables])
|
||||
|
||||
def __getitem__(self, index):
|
||||
return self.__tables[index]
|
||||
|
||||
@property
|
||||
def table_names(self) -> Iterable[str]:
|
||||
return self.__tables.keys()
|
||||
|
||||
@property
|
||||
def tables(self) -> Iterable[Table]:
|
||||
return self.__tables.values()
|
||||
|
||||
@property
|
||||
def access_defining_columns(self):
|
||||
if self.__access_defining_columns is None:
|
||||
self.__access_defining_columns = self._access_defining_columns()
|
||||
return self.__access_defining_columns
|
||||
|
||||
@property
|
||||
def foreign_key_constraints(self) -> list[CompositeForeignKey]:
|
||||
if self.__foreign_keys is None:
|
||||
self.__foreign_keys = self._foreign_keys()
|
||||
return self.__foreign_keys
|
||||
|
||||
def table(self, name: str) -> Table:
|
||||
return self.__tables[name]
|
||||
|
||||
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
|
||||
|
||||
def primary_keys(self, table_name: str) -> Iterable[str]:
|
||||
return self.__tables[table_name].primary_keys
|
||||
|
||||
def columns(self, table_name: str) -> Iterable[Column]:
|
||||
return self.__tables[table_name].columns
|
||||
|
||||
@property
|
||||
def model_module_search_paths(self) -> list[tuple[str, type]]:
|
||||
return self._model_module_search_paths()
|
||||
33
src/python/jw/util/db/schema/SingleForeignKey.py
Normal file
33
src/python/jw/util/db/schema/SingleForeignKey.py
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Optional, Any
|
||||
|
||||
from .Column import Column
|
||||
from .ColumnSet import ColumnSet
|
||||
|
||||
class SingleForeignKey:
|
||||
|
||||
def __init__(self, child_col: Column, parent_col: Column):
|
||||
self.__child_col = child_col
|
||||
self.__parent_col = parent_col
|
||||
self.__iterable = (self.__child_col, self.__parent_col)
|
||||
|
||||
def __len__(self):
|
||||
return 2
|
||||
|
||||
def __iter__(self):
|
||||
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}'
|
||||
|
||||
def __getitem__(self, index):
|
||||
return self.__iterable[index]
|
||||
|
||||
@property
|
||||
def child_column(self):
|
||||
return self.__child_col
|
||||
|
||||
@property
|
||||
def parent_column(self):
|
||||
return self.__parent_col
|
||||
469
src/python/jw/util/db/schema/Table.py
Normal file
469
src/python/jw/util/db/schema/Table.py
Normal file
|
|
@ -0,0 +1,469 @@
|
|||
# -*- 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
|
||||
|
||||
import abc
|
||||
from collections import OrderedDict
|
||||
from urllib.parse import quote_plus
|
||||
|
||||
from ...log import *
|
||||
from ...misc import load_class
|
||||
|
||||
from .ColumnSet import ColumnSet
|
||||
from .DataType import DataType
|
||||
from .CompositeForeignKey import CompositeForeignKey
|
||||
from .Column import Column
|
||||
|
||||
class Table(abc.ABC): # export
|
||||
|
||||
def __init__(self, schema, 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.__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.__foreign_keys_to_parent_table: Optional[OrderedDict[str, Any]] = None
|
||||
self.__relationships: Optional[list[tuple[str, Self]]] = None
|
||||
self.__model_class: Optional[Any] = None
|
||||
self.___relationship_by_foreign_table: Optional[dict[str, Self]] = None
|
||||
|
||||
@property
|
||||
def __columns(self) -> OrderedDict[str, Any]:
|
||||
if self.___columns is None:
|
||||
ret: OrderedDict[str, Any] = OrderedDict()
|
||||
for name in self._column_names():
|
||||
ret[name] = Column(self, name, self._column_data_type(name))
|
||||
self.___columns = ret
|
||||
return self.___columns
|
||||
|
||||
@property
|
||||
def __foreign_key_parent_tables(self) -> OrderedDict[str, Any]:
|
||||
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
|
||||
return self.___foreign_key_parent_tables
|
||||
|
||||
@property
|
||||
def __relationship_by_foreign_table(self) -> dict[str, Self]:
|
||||
if self.___relationship_by_foreign_table is None:
|
||||
ret: dict[str, Self] = dict()
|
||||
for member_name, table_name in self.relationships:
|
||||
ret[member_name] = self.schema[table_name]
|
||||
self.___relationship_by_foreign_table = ret
|
||||
return self.___relationship_by_foreign_table
|
||||
|
||||
@property
|
||||
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)
|
||||
if rule is None:
|
||||
continue
|
||||
ret[foreign_table_name] = rule
|
||||
self.___add_child_row_location_rules = ret
|
||||
return self.___add_child_row_location_rules
|
||||
|
||||
def __len__(self):
|
||||
return len(self.__columns)
|
||||
|
||||
def __iter__(self):
|
||||
yield from self.__columns.values()
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return self.__name
|
||||
|
||||
def __getitem__(self, index):
|
||||
return self.__columns[index]
|
||||
|
||||
def __eq__(self, rhs) -> bool:
|
||||
if isinstance(rhs, Table):
|
||||
if self.__name != rhs.__name:
|
||||
return False
|
||||
return True
|
||||
elif isinstance(rhs, str):
|
||||
if self.__name != rhs:
|
||||
return False
|
||||
return True
|
||||
throw(ERR, f'Tried to compare table {self} to type {type(rhs)}: {rhs}')
|
||||
return False # Unreachable but requested by mypy
|
||||
|
||||
def __hash__(self) -> int:
|
||||
return hash(self.name)
|
||||
|
||||
# -- To be reimplemented
|
||||
|
||||
@abc.abstractmethod
|
||||
def _column_names(self) -> Iterable[str]:
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
def _column_data_type(self, name) -> DataType:
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
def _primary_keys(self) -> Iterable[str]:
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
def _log_columns(self) -> Iterable[str]:
|
||||
pass
|
||||
|
||||
def _edit_columns(self) -> Iterable[str]:
|
||||
return self._log_columns()
|
||||
|
||||
@abc.abstractmethod
|
||||
def _display_columns(self) -> Optional[Iterable[str]]:
|
||||
return None
|
||||
#return self._primary_keys()
|
||||
|
||||
@abc.abstractmethod
|
||||
def _default_sort_columns(self) -> Optional[Iterable[str]]:
|
||||
return None
|
||||
|
||||
@abc.abstractmethod
|
||||
def _nullable_columns(self) -> Iterable[str]:
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
def _auto_increment_columns(self) -> Iterable[str]:
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
def _translate_columns(self) -> Iterable[str]:
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
def _column_default(self, name) -> Any:
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
def _unique_constraints(self) -> list[list[str]]:
|
||||
pass
|
||||
|
||||
def _model_name(self) -> Optional[str]:
|
||||
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
|
||||
|
||||
@abc.abstractmethod
|
||||
def _query_name(self) -> str:
|
||||
return 'tbl/' + self.__name
|
||||
|
||||
def _relationships(self) -> list[Self]:
|
||||
return []
|
||||
|
||||
@abc.abstractmethod
|
||||
def _row_query_name(self) -> str:
|
||||
return 'row/' + self.__name
|
||||
|
||||
# -- common URL schema for all data
|
||||
def _base_location_rule(self) -> Optional[str]:
|
||||
return f'/{self.name}'
|
||||
|
||||
def _location_rule(self) -> Optional[str]:
|
||||
ret = ''
|
||||
for col in self.__schema.access_defining_columns:
|
||||
if col in self.primary_keys:
|
||||
ret += f'/<{col}>'
|
||||
ret += self.base_location_rule
|
||||
return ret
|
||||
|
||||
def _row_location_rule(self) -> Optional[str]:
|
||||
ret = self._location_rule()
|
||||
if ret is not None:
|
||||
for col in self.primary_keys:
|
||||
if col not in self.__schema.access_defining_columns:
|
||||
ret += f'/<{col}>'
|
||||
return ret
|
||||
|
||||
def _add_row_location_rule(self) -> Optional[str]:
|
||||
rule = self._location_rule()
|
||||
if rule is None:
|
||||
return None
|
||||
return rule + '/new'
|
||||
|
||||
def _add_child_row_location_rule(self, parent_table_name: str) -> Optional[str]:
|
||||
parent_table = self.schema[parent_table_name]
|
||||
ret = self._add_row_location_rule()
|
||||
if ret is None:
|
||||
return None
|
||||
for cfk in self.foreign_keys_to_parent_table(parent_table):
|
||||
for fk in cfk:
|
||||
token = f'/<{fk.child_column.name}>'
|
||||
if ret.find(token) != -1:
|
||||
continue
|
||||
ret += f'/<{fk.child_column.name}>'
|
||||
return ret
|
||||
|
||||
# -- To be used
|
||||
|
||||
def column_default(self, name) -> Any:
|
||||
if self.__column_default is None:
|
||||
ret: dict[str, Any] = dict()
|
||||
for name in self.column_names:
|
||||
ret[name] = self._column_default(name)
|
||||
self.__column_default = ret
|
||||
return self.__column_default[name]
|
||||
|
||||
@property
|
||||
def columns(self):
|
||||
return self.__columns.values()
|
||||
|
||||
def column(self, name):
|
||||
return self.__columns[name]
|
||||
|
||||
@property
|
||||
def column_names(self) -> Iterable[str]:
|
||||
return self.__columns.keys()
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return self.__name
|
||||
|
||||
@property
|
||||
def schema(self):
|
||||
return self.__schema
|
||||
|
||||
@property
|
||||
def model_name(self) -> Optional[str]:
|
||||
return self._model_name()
|
||||
|
||||
@property
|
||||
def model_class(self) -> Any:
|
||||
if self.__model_class is None:
|
||||
model_name = self.model_name
|
||||
if model_name is None:
|
||||
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)
|
||||
if ret is not None:
|
||||
self.__model_class = ret
|
||||
break
|
||||
else:
|
||||
throw(ERR, f'No model class found for model {self.model_name}')
|
||||
return self.__model_class
|
||||
|
||||
def query_name(self) -> str:
|
||||
return self._query_name()
|
||||
|
||||
def row_query_name(self) -> str:
|
||||
return self._row_query_name()
|
||||
|
||||
@property
|
||||
def base_location_rule(self):
|
||||
if self.__base_location_rule is None:
|
||||
self.__base_location_rule = self._base_location_rule()
|
||||
return self.__base_location_rule
|
||||
|
||||
@property
|
||||
def location_rule(self):
|
||||
if self.__location_rule is None:
|
||||
self.__location_rule = self._location_rule()
|
||||
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 = re.sub(f'<{token}>', quote_plus(quote_plus(str(val))), ret)
|
||||
return ret
|
||||
|
||||
@property
|
||||
def row_location_rule(self):
|
||||
if self.__row_location_rule is None:
|
||||
self.__row_location_rule = self._row_location_rule()
|
||||
return self.__row_location_rule
|
||||
|
||||
def row_location(self, *args, **kwargs):
|
||||
ret = self.row_location_rule
|
||||
for col in self.primary_keys:
|
||||
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
|
||||
|
||||
@property
|
||||
def add_row_location_rule(self):
|
||||
if self.__add_row_location_rule is None:
|
||||
self.__add_row_location_rule = self._add_row_location_rule()
|
||||
return self.__add_row_location_rule
|
||||
|
||||
def add_row_location(self, *args, **kwargs) -> Optional[str]:
|
||||
ret = self.add_row_location_rule
|
||||
for col in self.primary_keys:
|
||||
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
|
||||
|
||||
@property
|
||||
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]:
|
||||
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]:
|
||||
ret = self.add_child_row_location_rule(parent_table)
|
||||
if isinstance(parent_table, str):
|
||||
parent_table = self.schema[parent_table]
|
||||
if ret is None:
|
||||
return None
|
||||
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)
|
||||
return ret
|
||||
|
||||
@property
|
||||
def primary_keys(self) -> Iterable[str]:
|
||||
if self.__primary_keys is None:
|
||||
self.__primary_keys = self._primary_keys()
|
||||
return self.__primary_keys
|
||||
|
||||
@property
|
||||
def log_columns(self):
|
||||
if self.__log_columns is None:
|
||||
self.__log_columns = self._log_columns()
|
||||
return self.__log_columns
|
||||
|
||||
@property
|
||||
def edit_columns(self):
|
||||
if self.__edit_columns is None:
|
||||
self.__edit_columns = self._edit_columns()
|
||||
return self.__edit_columns
|
||||
|
||||
@property
|
||||
def display_columns(self):
|
||||
if self.__display_columns is None:
|
||||
self.__display_columns = self._display_columns()
|
||||
return self.__display_columns
|
||||
|
||||
@property
|
||||
def default_sort_columns(self):
|
||||
if self.__default_sort_columns is None:
|
||||
self.__default_sort_columns = self._default_sort_columns()
|
||||
return self.__default_sort_columns
|
||||
|
||||
@property
|
||||
def auto_increment_columns(self) -> Iterable[str]:
|
||||
return self._auto_increment_columns()
|
||||
|
||||
@property
|
||||
def translate_columns(self) -> Iterable[str]:
|
||||
if self.__translate_columns is None:
|
||||
self.__translate_columns = self._translate_columns()
|
||||
return self.__translate_columns
|
||||
|
||||
@property
|
||||
def nullable_columns(self) -> Iterable[str]:
|
||||
if self.__nullable_columns is None:
|
||||
self.__nullable_columns = self._nullable_columns()
|
||||
return self.__nullable_columns
|
||||
|
||||
@property
|
||||
def non_nullable_columns(self) -> Iterable[str]:
|
||||
if self.__non_nullable_columns is None:
|
||||
ret = []
|
||||
all_cols = self.column_names
|
||||
nullable_columns = self.nullable_columns
|
||||
for col in all_cols:
|
||||
if col not in nullable_columns:
|
||||
ret.append(col)
|
||||
self.__non_nullable_columns = ret
|
||||
return self.__non_nullable_columns
|
||||
|
||||
@property
|
||||
def null_insertible_columns(self) -> Iterable[str]:
|
||||
if self.__null_insertible_columns is None:
|
||||
ret: list[str] = []
|
||||
for col in self.__columns.values():
|
||||
if col.is_null_insertible:
|
||||
ret.append(col.name)
|
||||
self.__null_insertible_columns = ret
|
||||
return self.__null_insertible_columns
|
||||
|
||||
@property
|
||||
def not_null_insertible_columns(self) -> Iterable[str]:
|
||||
if self.__not_null_insertible_columns is None:
|
||||
ret: list[str] = []
|
||||
for col in self.__columns.values():
|
||||
if not col.is_null_insertible:
|
||||
ret.append(col.name)
|
||||
self.__not_null_insertible_columns = ret
|
||||
return self.__not_null_insertible_columns
|
||||
|
||||
@property
|
||||
def unique_constraints(self) -> list[ColumnSet]:
|
||||
if self.__unique_constraints is None:
|
||||
ret: list[ColumnSet] = []
|
||||
impl = self._unique_constraints()
|
||||
if impl is not None:
|
||||
for columns in impl:
|
||||
ret.append(ColumnSet(columns=columns))
|
||||
self.__unique_constraints = ret
|
||||
return self.__unique_constraints
|
||||
|
||||
@property
|
||||
def foreign_key_constraints(self) -> list[CompositeForeignKey]:
|
||||
if self.__foreign_key_constraints is None:
|
||||
ret: list[Any] = []
|
||||
for composite_key in self.__schema.foreign_key_constraints:
|
||||
if composite_key.child_table == self:
|
||||
ret.append(composite_key)
|
||||
self.__foreign_key_constraints = ret
|
||||
return self.__foreign_key_constraints
|
||||
|
||||
@property
|
||||
def foreign_key_parent_tables(self):
|
||||
return self.__foreign_key_parent_tables.values()
|
||||
|
||||
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:
|
||||
pt = cfk.parent_table.name
|
||||
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 []
|
||||
|
||||
@property
|
||||
def relationships(self) -> list[tuple[str, Self]]:
|
||||
if self.__relationships is None:
|
||||
ret = []
|
||||
for member_name, table_name in self._relationships():
|
||||
ret.append((member_name, self.schema[table_name]))
|
||||
self.__relationships = ret
|
||||
return self.__relationships
|
||||
|
||||
def relationship(self, table: Union[Self, str]) -> Optional[Self]:
|
||||
if isinstance(table, Table):
|
||||
table = table.name
|
||||
return self.__relationship_by_foreign_table.get(table)
|
||||
12
src/python/jw/util/db/schema/utils.py
Normal file
12
src/python/jw/util/db/schema/utils.py
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from .Schema import Schema
|
||||
|
||||
from ...log import *
|
||||
|
||||
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}')
|
||||
Loading…
Reference in a new issue