jw-python/tools/python/jwutils/db/schema/Column.py
Jan Lindemann 17ab47e96a Add db.schema framework
jw.db.schema is a set of classes meant as an interface to describe a database schema.

Signed-off-by: Jan Lindemann <jan@janware.com>
2025-01-28 10:18:57 +01:00

75 lines
2.2 KiB
Python

# -*- coding: utf-8 -*-
from typing import Optional, Any
import abc
from ...log import *
from .DataType import DataType
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.__data_type: DataType = data_type
def __repr__(self):
return f'{self.__table.name}.{self.__name}: {self.__data_type}'
@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 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