Passed
Push — main ( 5158dd...fd8883 )
by torrua
01:41
created

loglan_db.model_init.InitBase.stringer()   A

Complexity

Conditions 2

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nop 1
dl 0
loc 3
ccs 3
cts 3
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
# -*- coding: utf-8 -*-
2
3 1
"""
4
Initial common functions for LOD Model Classes
5
"""
6
7 1
from datetime import datetime
8 1
from typing import List, Set
9
10 1
from loglan_db import db
11
12
13 1
class InitBase:
14
    """
15
    Init class for common methods
16
    """
17
18 1
    def __repr__(self) -> str:
19 1
        return str(self.__dict__)
20
21 1
    def __str__(self) -> str:
22 1
        return str({
23
            k: v for k, v in sorted(self.__dict__.items())
24
            if not str(k).startswith("_") and k not in ["created", "updated"]})
25
26 1
    def __init__(self, **kwargs):
27 1
        for key in kwargs:
28 1
            setattr(self, key, kwargs[key])
29
30 1
    @classmethod
31
    def from_dict(cls, dic):
32
        """
33
34
        Args:
35
            dic:
36
37
        Returns:
38
39
        """
40 1
        return cls(**dic)
41
42 1
    def export(self):
43
        """
44
        Export record data from DB
45
        Should be redefine in model's class
46
        :return:
47
        """
48
49 1
    def import_(self):
50
        """
51
        Import txt data to DB
52
        Should be redefine in model's class
53
        :return:
54
        """
55
56 1
    @staticmethod
57 1
    def stringer(value) -> str:
58 1
        return str(value) if value else str()
59
60
61 1
class DBBase:
62
    """Common methods and attributes for basic models"""
63 1
    created = db.Column(db.TIMESTAMP, default=datetime.now(), nullable=False)
64 1
    updated = db.Column(db.TIMESTAMP, onupdate=db.func.now())
65 1
    __table__ = None
66 1
    __mapper__ = None
67 1
    id = None
68
69 1
    def save(self) -> None:
70
        """
71
        Add record to DB
72
        :return:
73
        """
74 1
        db.session.add(self)
75 1
        db.session.commit()
76
77 1
    def update(self, data) -> None:
78
        """
79
        Update record in DB
80
        :param data:
81
        :return:
82
        """
83 1
        for key, item in data.items():
84 1
            setattr(self, key, item)
85 1
        db.session.commit()
86
87 1
    def delete(self) -> None:
88
        """
89
        Delete record from DB
90
        :return:
91
        """
92 1
        db.session.delete(self)
93 1
        db.session.commit()
94
95 1
    @classmethod
96 1
    def get_all(cls) -> List:
97
        """
98
        Get all model objects from DB
99
        :return:
100
        """
101 1
        return db.session.query(cls).all()
102
103 1
    @classmethod
104 1
    def get_by_id(cls, cid: int):
105
        """
106
        Get model object from DB by it's id
107
        :param cid: cls id
108
        :return:
109
        """
110 1
        return db.session.query(cls).filter(cls.id == cid).first()
111
112 1
    @classmethod
113 1
    def attributes_all(cls) -> Set[str]:
114
        """
115
        :return:
116
        """
117 1
        return {key for key in cls.__mapper__.attrs.keys() if not key.startswith("_")}
118
119 1
    @classmethod
120 1
    def attributes_basic(cls) -> Set[str]:
121
        """
122
        :return:
123
        """
124 1
        return set(cls.attributes_all() - cls.relationships())
125
126 1
    @classmethod
127 1
    def attributes_extended(cls) -> Set[str]:
128
        """
129
        :return:
130
        """
131 1
        return set(cls.attributes_all() - cls.foreign_keys())
132
133 1
    @classmethod
134 1
    def relationships(cls) -> Set[str]:
135
        """
136
        :return:
137
        """
138 1
        return {key for key in cls.__mapper__.relationships.keys() if not key.startswith("_")}
139
140 1
    @classmethod
141 1
    def foreign_keys(cls) -> Set[str]:
142
        """
143
        :return:
144
        """
145 1
        return set(cls.attributes_all() - cls.relationships() - cls.non_foreign_keys())
146
147 1
    @classmethod
148 1
    def non_foreign_keys(cls) -> Set[str]:
149
        """
150
        :return:
151
        """
152 1
        return {column.name for column in cls.__table__.columns
153
                if not (column.foreign_keys or column.name.startswith("_"))}
154