Module osbot_utils.helpers.sqlite.Sqlite__Field
Expand source code
import inspect
import typing
from decimal import Decimal
from enum import auto, Enum
from typing import Optional, Union
from osbot_utils.base_classes.Kwargs_To_Self import Kwargs_To_Self
from osbot_utils.helpers.sqlite.models.Sqlite__Field__Type import Sqlite__Field__Type
class Sqlite__Field(Kwargs_To_Self):
cid : int
name : str
type : Sqlite__Field__Type
notnull : bool
dflt_value : Optional[Union[int, str, float, bytes]]
pk : bool
autoincrement : bool
unique : bool
is_foreign_key : bool # Indicates if the field is a foreign key
references_table : Optional[str] # The table the foreign key references
references_column: Optional[str] # The column in the referenced table
on_delete_action : Optional[str] # Action on delete (e.g., CASCADE, SET NULL)
precision : Optional[int] # Precision for decimal types
scale : Optional[int] # Scale for decimal types
check_constraint : Optional[str] # Check constraint expression
def text_for_create_table(self):
parts = [self.name] # Start with name
if self.type == Sqlite__Field__Type.DECIMAL and self.precision is not None and self.scale is not None:
parts.append(f"DECIMAL({self.precision}, {self.scale})")
else:
parts.append(self.type.name)
if self.pk:
parts.append("PRIMARY KEY")
if self.autoincrement:
parts.append("AUTOINCREMENT")
if self.unique:
parts.append("UNIQUE")
if self.notnull:
parts.append("NOT NULL")
if self.check_constraint:
parts.append(f"CHECK ({self.check_constraint})")
if self.is_foreign_key and self.references_table and self.references_column:
fk_constraint = f"FOREIGN KEY ({self.name}) REFERENCES {self.references_table} ({self.references_column})"
if self.on_delete_action:
fk_constraint += f" ON DELETE {self.on_delete_action}"
return fk_constraint
return " ".join(parts)
@classmethod
def fix_from_json_data(cls, json_data):
if type(json_data) is dict:
type_type = json_data.get('type')
mapped_type = Sqlite__Field__Type.type_map().get(type_type)
if mapped_type:
json_data['type'] = mapped_type
return mapped_type
@classmethod
def from_json(cls, json_data):
cls.fix_from_json_data(json_data)
return super(Sqlite__Field, cls).from_json(json_data)
Classes
class Sqlite__Field (**kwargs)
-
A mixin class to strictly assign keyword arguments to pre-defined instance attributes during initialization.
This base class provides an init method that assigns values from keyword arguments to instance attributes. If an attribute with the same name as a key from the kwargs is defined in the class, it will be set to the value from kwargs. If the key does not match any predefined attribute names, an exception is raised.
This behavior enforces strict control over the attributes of instances, ensuring that only predefined attributes can be set at the time of instantiation and avoids silent attribute creation which can lead to bugs in the code.
Usage
class MyConfigurableClass(Kwargs_To_Self): attribute1 = 'default_value' attribute2 = True attribute3 : str attribute4 : list attribute4 : int = 42
# Other methods can be added here
Correctly override default values by passing keyword arguments
instance = MyConfigurableClass(attribute1='new_value', attribute2=False)
This will raise an exception as 'attribute3' is not predefined
instance = MyConfigurableClass(attribute3='invalid_attribute')
this will also assign the default value to any variable that has a type defined. In the example above the default values (mapped by default__kwargs and locals) will be: attribute1 = 'default_value' attribute2 = True attribute3 = '' # default value of str attribute4 = [] # default value of list attribute4 = 42 # defined value in the class
Note
It is important that all attributes which may be set at instantiation are predefined in the class. Failure to do so will result in an exception being raised.
Methods
init(**kwargs): The initializer that handles the assignment of keyword arguments to instance attributes. It enforces strict attribute assignment rules, only allowing attributes that are already defined in the class to be set.
Initialize an instance of the derived class, strictly assigning provided keyword arguments to corresponding instance attributes.
Parameters
**kwargs: Variable length keyword arguments.
Raises
Exception
- If a key from kwargs does not correspond to any attribute pre-defined in the class, an exception is raised to prevent setting an undefined attribute.
Expand source code
class Sqlite__Field(Kwargs_To_Self): cid : int name : str type : Sqlite__Field__Type notnull : bool dflt_value : Optional[Union[int, str, float, bytes]] pk : bool autoincrement : bool unique : bool is_foreign_key : bool # Indicates if the field is a foreign key references_table : Optional[str] # The table the foreign key references references_column: Optional[str] # The column in the referenced table on_delete_action : Optional[str] # Action on delete (e.g., CASCADE, SET NULL) precision : Optional[int] # Precision for decimal types scale : Optional[int] # Scale for decimal types check_constraint : Optional[str] # Check constraint expression def text_for_create_table(self): parts = [self.name] # Start with name if self.type == Sqlite__Field__Type.DECIMAL and self.precision is not None and self.scale is not None: parts.append(f"DECIMAL({self.precision}, {self.scale})") else: parts.append(self.type.name) if self.pk: parts.append("PRIMARY KEY") if self.autoincrement: parts.append("AUTOINCREMENT") if self.unique: parts.append("UNIQUE") if self.notnull: parts.append("NOT NULL") if self.check_constraint: parts.append(f"CHECK ({self.check_constraint})") if self.is_foreign_key and self.references_table and self.references_column: fk_constraint = f"FOREIGN KEY ({self.name}) REFERENCES {self.references_table} ({self.references_column})" if self.on_delete_action: fk_constraint += f" ON DELETE {self.on_delete_action}" return fk_constraint return " ".join(parts) @classmethod def fix_from_json_data(cls, json_data): if type(json_data) is dict: type_type = json_data.get('type') mapped_type = Sqlite__Field__Type.type_map().get(type_type) if mapped_type: json_data['type'] = mapped_type return mapped_type @classmethod def from_json(cls, json_data): cls.fix_from_json_data(json_data) return super(Sqlite__Field, cls).from_json(json_data)
Ancestors
Class variables
var autoincrement : bool
var check_constraint : Optional[str]
var cid : int
var dflt_value : Union[int, str, float, bytes, ForwardRef(None)]
var is_foreign_key : bool
var name : str
var notnull : bool
var on_delete_action : Optional[str]
var pk : bool
var precision : Optional[int]
var references_column : Optional[str]
var references_table : Optional[str]
var scale : Optional[int]
var type : Sqlite__Field__Type
var unique : bool
Static methods
def fix_from_json_data(json_data)
-
Expand source code
@classmethod def fix_from_json_data(cls, json_data): if type(json_data) is dict: type_type = json_data.get('type') mapped_type = Sqlite__Field__Type.type_map().get(type_type) if mapped_type: json_data['type'] = mapped_type return mapped_type
def from_json(json_data)
-
Expand source code
@classmethod def from_json(cls, json_data): cls.fix_from_json_data(json_data) return super(Sqlite__Field, cls).from_json(json_data)
Methods
def text_for_create_table(self)
-
Expand source code
def text_for_create_table(self): parts = [self.name] # Start with name if self.type == Sqlite__Field__Type.DECIMAL and self.precision is not None and self.scale is not None: parts.append(f"DECIMAL({self.precision}, {self.scale})") else: parts.append(self.type.name) if self.pk: parts.append("PRIMARY KEY") if self.autoincrement: parts.append("AUTOINCREMENT") if self.unique: parts.append("UNIQUE") if self.notnull: parts.append("NOT NULL") if self.check_constraint: parts.append(f"CHECK ({self.check_constraint})") if self.is_foreign_key and self.references_table and self.references_column: fk_constraint = f"FOREIGN KEY ({self.name}) REFERENCES {self.references_table} ({self.references_column})" if self.on_delete_action: fk_constraint += f" ON DELETE {self.on_delete_action}" return fk_constraint return " ".join(parts)
Inherited members