ormlambda 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. ormlambda/__init__.py +4 -0
  2. ormlambda/common/__init__.py +2 -0
  3. ormlambda/common/abstract_classes/__init__.py +3 -0
  4. ormlambda/common/abstract_classes/abstract_model.py +302 -0
  5. ormlambda/common/abstract_classes/non_query_base.py +33 -0
  6. ormlambda/common/abstract_classes/query_base.py +10 -0
  7. ormlambda/common/enums/__init__.py +2 -0
  8. ormlambda/common/enums/condition_types.py +16 -0
  9. ormlambda/common/enums/join_type.py +10 -0
  10. ormlambda/common/interfaces/INonQueryCommand.py +9 -0
  11. ormlambda/common/interfaces/IQueryCommand.py +11 -0
  12. ormlambda/common/interfaces/IRepositoryBase.py +67 -0
  13. ormlambda/common/interfaces/IStatements.py +227 -0
  14. ormlambda/common/interfaces/__init__.py +4 -0
  15. ormlambda/components/__init__.py +0 -0
  16. ormlambda/components/delete/IDelete.py +6 -0
  17. ormlambda/components/delete/__init__.py +2 -0
  18. ormlambda/components/delete/abstract_delete.py +14 -0
  19. ormlambda/components/insert/IInsert.py +6 -0
  20. ormlambda/components/insert/__init__.py +2 -0
  21. ormlambda/components/insert/abstract_insert.py +21 -0
  22. ormlambda/components/select/ISelect.py +14 -0
  23. ormlambda/components/select/__init__.py +2 -0
  24. ormlambda/components/select/table_column.py +39 -0
  25. ormlambda/components/update/IUpdate.py +7 -0
  26. ormlambda/components/update/__init__.py +2 -0
  27. ormlambda/components/update/abstract_update.py +25 -0
  28. ormlambda/components/upsert/IUpsert.py +6 -0
  29. ormlambda/components/upsert/__init__.py +2 -0
  30. ormlambda/components/upsert/abstract_upsert.py +21 -0
  31. ormlambda/components/where/__init__.py +1 -0
  32. ormlambda/components/where/abstract_where.py +11 -0
  33. ormlambda/databases/__init__.py +0 -0
  34. ormlambda/databases/my_sql/__init__.py +2 -0
  35. ormlambda/databases/my_sql/clauses/__init__.py +13 -0
  36. ormlambda/databases/my_sql/clauses/create_database.py +29 -0
  37. ormlambda/databases/my_sql/clauses/delete.py +54 -0
  38. ormlambda/databases/my_sql/clauses/drop_database.py +19 -0
  39. ormlambda/databases/my_sql/clauses/drop_table.py +23 -0
  40. ormlambda/databases/my_sql/clauses/insert.py +70 -0
  41. ormlambda/databases/my_sql/clauses/joins.py +103 -0
  42. ormlambda/databases/my_sql/clauses/limit.py +17 -0
  43. ormlambda/databases/my_sql/clauses/offset.py +17 -0
  44. ormlambda/databases/my_sql/clauses/order.py +29 -0
  45. ormlambda/databases/my_sql/clauses/select.py +172 -0
  46. ormlambda/databases/my_sql/clauses/update.py +52 -0
  47. ormlambda/databases/my_sql/clauses/upsert.py +68 -0
  48. ormlambda/databases/my_sql/clauses/where_condition.py +219 -0
  49. ormlambda/databases/my_sql/repository.py +192 -0
  50. ormlambda/databases/my_sql/statements.py +86 -0
  51. ormlambda/model_base.py +36 -0
  52. ormlambda/utils/__init__.py +3 -0
  53. ormlambda/utils/column.py +65 -0
  54. ormlambda/utils/dtypes.py +104 -0
  55. ormlambda/utils/foreign_key.py +36 -0
  56. ormlambda/utils/lambda_disassembler/__init__.py +4 -0
  57. ormlambda/utils/lambda_disassembler/dis_types.py +136 -0
  58. ormlambda/utils/lambda_disassembler/disassembler.py +69 -0
  59. ormlambda/utils/lambda_disassembler/dtypes.py +103 -0
  60. ormlambda/utils/lambda_disassembler/name_of.py +41 -0
  61. ormlambda/utils/lambda_disassembler/nested_element.py +44 -0
  62. ormlambda/utils/lambda_disassembler/tree_instruction.py +145 -0
  63. ormlambda/utils/module_tree/__init__.py +0 -0
  64. ormlambda/utils/module_tree/dfs_traversal.py +60 -0
  65. ormlambda/utils/module_tree/dynamic_module.py +237 -0
  66. ormlambda/utils/table_constructor.py +308 -0
  67. ormlambda-0.1.0.dist-info/LICENSE +21 -0
  68. ormlambda-0.1.0.dist-info/METADATA +268 -0
  69. ormlambda-0.1.0.dist-info/RECORD +70 -0
  70. ormlambda-0.1.0.dist-info/WHEEL +4 -0
@@ -0,0 +1,192 @@
1
+ # Standard libraries
2
+ from pathlib import Path
3
+ from typing import Any, Type, override
4
+
5
+
6
+ # from mysql.connector.pooling import MySQLConnectionPool
7
+ from mysql.connector import MySQLConnection, Error # noqa: F401
8
+
9
+ # Custom libraries
10
+ from ...common.interfaces import IRepositoryBase
11
+ from ...utils.module_tree.dynamic_module import ModuleTree
12
+
13
+ from .clauses import CreateDatabase, TypeExists
14
+ from .clauses import DropDatabase
15
+ from .clauses import DropTable
16
+
17
+
18
+ class Response[TFlavour, *Ts]:
19
+ def __init__(self, response_values: list[tuple[*Ts]], columns: tuple[str], flavour: Type[TFlavour], **kwargs) -> None:
20
+ self._response_values: list[tuple[*Ts]] = response_values
21
+ self._columns: tuple[str] = columns
22
+ self._flavour: Type[TFlavour] = flavour
23
+ self._kwargs: dict[str, Any] = kwargs
24
+
25
+ self._response_values_index: int = len(self._response_values)
26
+ # self.select_values()
27
+
28
+ @property
29
+ def is_one(self) -> bool:
30
+ return self._response_values_index == 1
31
+
32
+ @property
33
+ def is_there_response(self) -> bool:
34
+ return self._response_values_index != 0
35
+
36
+ @property
37
+ def is_many(self) -> bool:
38
+ return self._response_values_index > 1
39
+
40
+ @property
41
+ def response(self) -> tuple[dict[str, tuple[*Ts]]] | tuple[tuple[*Ts]] | tuple[TFlavour]:
42
+ if not self.is_there_response:
43
+ return tuple([])
44
+
45
+ return tuple(self._cast_to_flavour(self._response_values))
46
+
47
+ def _cast_to_flavour(self, data: list[tuple[*Ts]]) -> list[dict[str, tuple[*Ts]]] | list[tuple[*Ts]] | list[TFlavour]:
48
+ def _dict() -> list[dict[str, tuple[*Ts]]]:
49
+ return [dict(zip(self._columns, x)) for x in data]
50
+
51
+ def _tuple() -> list[tuple[*Ts]]:
52
+ return data
53
+
54
+ def _default() -> list[TFlavour]:
55
+ return [self._flavour(x, **self._kwargs) for x in data]
56
+
57
+ selector: dict[Type[object], Any] = {dict: _dict, tuple: _tuple}
58
+
59
+ return selector.get(self._flavour, _default)()
60
+
61
+
62
+ class MySQLRepository(IRepositoryBase[MySQLConnection]):
63
+ def __init__(self, **kwargs: Any) -> None:
64
+ self._data_config: dict[str, Any] = kwargs
65
+ self._connection: MySQLConnection = MySQLConnection()
66
+ # self._pool_connection: MySQLConnection = MySQLConnection(**kwargs)
67
+ pass
68
+
69
+ @override
70
+ def is_connected(self) -> bool:
71
+ return self._connection.is_connected()
72
+
73
+ @override
74
+ def connect(self) -> IRepositoryBase[MySQLConnection]:
75
+ # return MySQLConnectionPool(pool_name="mypool", pool_size=5, **kwargs)
76
+ self._connection.connect(**self._data_config)
77
+ return None
78
+
79
+ @override
80
+ def close_connection(self) -> None:
81
+ if self._connection.is_connected():
82
+ self._connection.close()
83
+ return None
84
+
85
+ @override
86
+ @IRepositoryBase.check_connection
87
+ def read_sql[TFlavour](self, query: str, flavour: Type[TFlavour] = tuple, **kwargs) -> tuple[TFlavour]:
88
+ """
89
+ Return tuple of tuples by default.
90
+
91
+ ATTRIBUTE
92
+ -
93
+ - query:str: string of request to the server
94
+ - flavour: Type[TFlavour]: Useful to return tuple of any Iterable type as dict,set,list...
95
+ """
96
+
97
+ with self._connection.cursor(buffered=True) as cursor:
98
+ cursor.execute(query)
99
+ values: list[tuple] = cursor.fetchall()
100
+ columns: tuple[str] = cursor.column_names
101
+ return Response[TFlavour](response_values=values, columns=columns, flavour=flavour, **kwargs).response
102
+
103
+ # FIXME [ ]: this method does not comply with the implemented interface
104
+ @IRepositoryBase.check_connection
105
+ def create_tables_code_first(self, path: str | Path) -> None:
106
+ if not isinstance(path, Path | str):
107
+ raise ValueError
108
+
109
+ if isinstance(path, str):
110
+ path = Path(path).resolve()
111
+
112
+ if not path.exists():
113
+ raise FileNotFoundError
114
+
115
+ module_tree: ModuleTree = ModuleTree(path)
116
+
117
+ queries_list: list[str] = module_tree.get_queries()
118
+
119
+ for query in queries_list:
120
+ with self._connection.cursor(buffered=True) as cursor:
121
+ cursor.execute(query)
122
+ self._connection.commit()
123
+ return None
124
+
125
+ @override
126
+ @IRepositoryBase.check_connection
127
+ def executemany_with_values(self, query: str, values) -> None:
128
+ with self._connection.cursor(buffered=True) as cursor:
129
+ cursor.executemany(query, values)
130
+ self._connection.commit()
131
+ return None
132
+
133
+ @override
134
+ @IRepositoryBase.check_connection
135
+ def execute_with_values(self, query: str, values) -> None:
136
+ with self._connection.cursor(buffered=True) as cursor:
137
+ cursor.execute(query, values)
138
+ self._connection.commit()
139
+ return None
140
+
141
+ @override
142
+ @IRepositoryBase.check_connection
143
+ def execute(self, query: str) -> None:
144
+ with self._connection.cursor(buffered=True) as cursor:
145
+ cursor.execute(query)
146
+ self._connection.commit()
147
+ return None
148
+
149
+ @override
150
+ @IRepositoryBase.check_connection
151
+ def drop_table(self, name: str) -> None:
152
+ return DropTable(self).execute(name)
153
+
154
+ @override
155
+ @IRepositoryBase.check_connection
156
+ def database_exists(self, name: str) -> bool:
157
+ query = "SHOW DATABASES LIKE %s;"
158
+ with self._connection.cursor(buffered=True) as cursor:
159
+ cursor.execute(query, (name,))
160
+ res = cursor.fetchmany(1)
161
+ return len(res) > 0
162
+
163
+ @override
164
+ @IRepositoryBase.check_connection
165
+ def drop_database(self, name: str) -> None:
166
+ return DropDatabase(self).execute(name)
167
+
168
+ @override
169
+ @IRepositoryBase.check_connection
170
+ def table_exists(self, name: str) -> bool:
171
+ if not self._connection.database:
172
+ raise Exception("No database selected")
173
+
174
+ query = "SHOW TABLES LIKE %s;"
175
+ with self._connection.cursor(buffered=True) as cursor:
176
+ cursor.execute(query, (name,))
177
+ res = cursor.fetchmany(1)
178
+ return len(res) > 0
179
+
180
+ @override
181
+ @IRepositoryBase.check_connection
182
+ def create_database(self, name: str, if_exists: TypeExists = "fail") -> None:
183
+ return CreateDatabase(self).execute(name, if_exists)
184
+
185
+ @override
186
+ @property
187
+ def connection(self) -> MySQLConnection:
188
+ return self._connection
189
+
190
+ @override
191
+ def set_config(self, value: dict[str, Any]) -> dict[str, Any]:
192
+ return self._data_config.update(value)
@@ -0,0 +1,86 @@
1
+ from typing import override, Type
2
+
3
+
4
+ from ...common.abstract_classes import AbstractSQLStatements
5
+ from ...utils import Table
6
+ from ...common.interfaces import IQuery, IRepositoryBase
7
+ from ...components.select import ISelect
8
+
9
+ from .clauses import DeleteQuery
10
+ from .clauses import InsertQuery
11
+ from .clauses import JoinSelector
12
+ from .clauses import LimitQuery
13
+ from .clauses import OffsetQuery
14
+ from .clauses import OrderQuery
15
+ from .clauses import SelectQuery
16
+ from .clauses import UpsertQuery
17
+ from .clauses import UpdateQuery
18
+ from .clauses import WhereCondition
19
+
20
+ from mysql.connector import MySQLConnection
21
+
22
+
23
+ class MySQLStatements[T: Table](AbstractSQLStatements[T, MySQLConnection]):
24
+ def __init__(self, model: T, repository: IRepositoryBase[MySQLConnection]) -> None:
25
+ super().__init__(model, repository=repository)
26
+
27
+ # region Private methods
28
+ def __repr__(self):
29
+ return f"<Model: {self.__class__.__name__}>"
30
+
31
+ # endregion
32
+
33
+ @property
34
+ @override
35
+ def INSERT_QUERY(self) -> Type[InsertQuery]:
36
+ return InsertQuery
37
+
38
+ @property
39
+ @override
40
+ def UPSERT_QUERY(self) -> Type[UpsertQuery]:
41
+ return UpsertQuery
42
+
43
+ @property
44
+ @override
45
+ def UPDATE_QUERY(self) -> Type[UpsertQuery]:
46
+ return UpdateQuery
47
+
48
+ @override
49
+ @property
50
+ def DELETE_QUERY(self) -> Type[DeleteQuery]:
51
+ return DeleteQuery
52
+
53
+ @property
54
+ @override
55
+ def LIMIT_QUERY(self) -> Type[IQuery]:
56
+ return LimitQuery
57
+
58
+ @property
59
+ @override
60
+ def OFFSET_QUERY(self) -> Type[IQuery]:
61
+ return OffsetQuery
62
+
63
+ @property
64
+ @override
65
+ def JOIN_QUERY(self) -> Type[IQuery]:
66
+ return JoinSelector
67
+
68
+ @property
69
+ @override
70
+ def WHERE_QUERY(self) -> Type[IQuery]:
71
+ return WhereCondition
72
+
73
+ @property
74
+ @override
75
+ def ORDER_QUERY(self) -> Type[IQuery]:
76
+ return OrderQuery
77
+
78
+ @property
79
+ @override
80
+ def SELECT_QUERY(self) -> Type[ISelect]:
81
+ return SelectQuery
82
+
83
+ @property
84
+ @override
85
+ def repository(self) -> IRepositoryBase[MySQLConnection]:
86
+ return self._repository
@@ -0,0 +1,36 @@
1
+ # region imports
2
+ from typing import Type
3
+
4
+
5
+ from .utils import Table
6
+ from .common.interfaces import IRepositoryBase, IStatements_two_generic
7
+ from .common.abstract_classes import AbstractSQLStatements
8
+ from .databases.my_sql import MySQLStatements, MySQLRepository
9
+
10
+
11
+
12
+ # endregion
13
+
14
+
15
+ class BaseModel[T: Table]:
16
+ """
17
+ Class to select the correct AbstractSQLStatements class depends on the repository.
18
+
19
+ Contiene los metodos necesarios para hacer consultas a una tabla
20
+ """
21
+
22
+ statements_dicc: dict[Type[IRepositoryBase], Type[AbstractSQLStatements[T, IRepositoryBase]]] = {
23
+ MySQLRepository: MySQLStatements,
24
+ }
25
+
26
+ # region Constructor
27
+
28
+ def __new__[TRepo](cls, model: T, repository: IRepositoryBase[TRepo]) -> IStatements_two_generic[T, TRepo]:
29
+ cls: AbstractSQLStatements[T, TRepo] = cls.statements_dicc.get(type(repository), None)
30
+
31
+ if not cls:
32
+ raise Exception(f"Repository selected does not exits '{repository}'")
33
+
34
+ self = object().__new__(cls)
35
+ cls.__init__(self, model, repository)
36
+ return self
@@ -0,0 +1,3 @@
1
+ from .column import Column # noqa: F401
2
+ from .foreign_key import ForeignKey # noqa: F401
3
+ from .table_constructor import Table # noqa: F401
@@ -0,0 +1,65 @@
1
+ from typing import Type
2
+
3
+ class Column[T]:
4
+ __slots__ = (
5
+ "dtype",
6
+ "column_name",
7
+ "column_value",
8
+ "is_primary_key",
9
+ "is_auto_generated",
10
+ "is_auto_increment",
11
+ "is_unique",
12
+ )
13
+
14
+ def __init__(
15
+ self,
16
+ dtype:Type[T] = None,
17
+ column_name: str = None,
18
+ column_value: T = None,
19
+ *,
20
+ is_primary_key: bool = False,
21
+ is_auto_generated: bool = False,
22
+ is_auto_increment: bool = False,
23
+ is_unique: bool = False,
24
+ ) -> None:
25
+ self.dtype = dtype
26
+ self.column_name = column_name
27
+ self.column_value: T = column_value
28
+ self.is_primary_key: bool = is_primary_key
29
+ self.is_auto_generated: bool = is_auto_generated
30
+ self.is_auto_increment: bool = is_auto_increment
31
+ self.is_unique: bool = is_unique
32
+
33
+ def __repr__(self) -> str:
34
+ return f"<Column: {self.column_name}>"
35
+
36
+ def __to_string__(self, name: str, var_name: T, type_: str):
37
+ dicc: dict = {
38
+ "dtype":type_,
39
+ "column_name": f"'{name}'",
40
+ "column_value": var_name, # must be the same variable name as the instance variable name in Table's __init__ class
41
+ }
42
+ exec_str: str = f"{Column.__name__}[{type_}]("
43
+ for x in self.__slots__:
44
+ self_value = getattr(self, x)
45
+
46
+ exec_str += f" {x}={dicc.get(x,self_value)},\n"
47
+ exec_str += ")"
48
+ return exec_str
49
+
50
+ def __hash__(self) -> int:
51
+ return hash(
52
+ (
53
+ self.column_name,
54
+ self.column_value,
55
+ self.is_primary_key,
56
+ self.is_auto_generated,
57
+ self.is_auto_increment,
58
+ self.is_unique,
59
+ )
60
+ )
61
+
62
+ def __eq__(self, value: "Column") -> bool:
63
+ if isinstance(value, Column):
64
+ return self.__hash__() == value.__hash__()
65
+ return False
@@ -0,0 +1,104 @@
1
+ """
2
+ String Data Types
3
+ Data type Description
4
+ CHAR(size) A FIXED length string (can contain letters, numbers, and special characters). The size parameter specifies the column length in characters - can be from 0 to 255. Default is 1
5
+ VARCHAR(size) A VARIABLE length string (can contain letters, numbers, and special characters). The size parameter specifies the maximum column length in characters - can be from 0 to 65535
6
+ BINARY(size) Equal to CHAR(), but stores binary byte strings. The size parameter specifies the column length in bytes. Default is 1
7
+ VARBINARY(size) Equal to VARCHAR(), but stores binary byte strings. The size parameter specifies the maximum column length in bytes.
8
+ TINYBLOB For BLOBs (Binary Large OBjects). Max length: 255 bytes
9
+ TINYTEXT Holds a string with a maximum length of 255 characters
10
+ TEXT(size) Holds a string with a maximum length of 65,535 bytes
11
+ BLOB(size) For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data
12
+ MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters
13
+ MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data
14
+ LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters
15
+ LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data
16
+ ENUM(val1, val2, val3, ...) A string object that can have only one value, chosen from a list of possible values. You can list up to 65535 values in an ENUM list. If a value is inserted that is not in the list, a blank value will be inserted. The values are sorted in the order you enter them
17
+ SET(val1, val2, val3, ...) A string object that can have 0 or more values, chosen from a list of possible values. You can list up to 64 values in a SET list
18
+
19
+
20
+
21
+ Numeric Data Types
22
+ Data type Description
23
+ BIT(size) A bit-value type. The number of bits per value is specified in size. The size parameter can hold a value from 1 to 64. The default value for size is 1.
24
+ TINYINT(size) A very small integer. Signed range is from -128 to 127. Unsigned range is from 0 to 255. The size parameter specifies the maximum display width (which is 255)
25
+ BOOL Zero is considered as false, nonzero values are considered as true.
26
+ BOOLEAN Equal to BOOL
27
+ SMALLINT(size) A small integer. Signed range is from -32768 to 32767. Unsigned range is from 0 to 65535. The size parameter specifies the maximum display width (which is 255)
28
+ MEDIUMINT(size) A medium integer. Signed range is from -8388608 to 8388607. Unsigned range is from 0 to 16777215. The size parameter specifies the maximum display width (which is 255)
29
+ INT(size) A medium integer. Signed range is from -2147483648 to 2147483647. Unsigned range is from 0 to 4294967295. The size parameter specifies the maximum display width (which is 255)
30
+ INTEGER(size) Equal to INT(size)
31
+ BIGINT(size) A large integer. Signed range is from -9223372036854775808 to 9223372036854775807. Unsigned range is from 0 to 18446744073709551615. The size parameter specifies the maximum display width (which is 255)
32
+ FLOAT(size, d) A floating point number. The total number of digits is specified in size. The number of digits after the decimal point is specified in the d parameter. This syntax is deprecated in MySQL 8.0.17, and it will be removed in future MySQL versions
33
+ FLOAT(p) A floating point number. MySQL uses the p value to determine whether to use FLOAT or DOUBLE for the resulting data type. If p is from 0 to 24, the data type becomes FLOAT(). If p is from 25 to 53, the data type becomes DOUBLE()
34
+ DOUBLE(size, d) A normal-size floating point number. The total number of digits is specified in size. The number of digits after the decimal point is specified in the d parameter
35
+ DOUBLE PRECISION(size, d)
36
+ DECIMAL(size, d) An exact fixed-point number. The total number of digits is specified in size. The number of digits after the decimal point is specified in the d parameter. The maximum number for size is 65. The maximum number for d is 30. The default value for size is 10. The default value for d is 0.
37
+ DEC(size, d) Equal to DECIMAL(size,d)
38
+ Note: All the numeric data types may have an extra option: UNSIGNED or ZEROFILL. If you add the UNSIGNED option, MySQL disallows negative values for the column. If you add the ZEROFILL option, MySQL automatically also adds the UNSIGNED attribute to the column.
39
+
40
+ Date and Time Data Types
41
+ Data type Description
42
+ DATE A date. Format: YYYY-MM-DD. The supported range is from '1000-01-01' to '9999-12-31'
43
+ DATETIME(fsp) A date and time combination. Format: YYYY-MM-DD hh:mm:ss. The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'. Adding DEFAULT and ON UPDATE in the column definition to get automatic initialization and updating to the current date and time
44
+ TIMESTAMP(fsp) A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD hh:mm:ss. The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC. Automatic initialization and updating to the current date and time can be specified using DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP in the column definition
45
+ TIME(fsp) A time. Format: hh:mm:ss. The supported range is from '-838:59:59' to '838:59:59'
46
+ YEAR A year in four-digit format. Values allowed in four-digit format: 1901 to 2155, and 0000.
47
+ MySQL 8.0 does not support year in two-digit format.
48
+ """
49
+
50
+ from decimal import Decimal
51
+ import datetime
52
+ from typing import Any,Literal
53
+ import numpy as np
54
+
55
+ from .column import Column
56
+
57
+
58
+ STRING = Literal["CHAR(size)", "VARCHAR(size)", "BINARY(size)", "VARBINARY(size)", "TINYBLOB", "TINYTEXT", "TEXT(size)", "BLOB(size)", "MEDIUMTEXT", "MEDIUMBLOB", "LONGTEXT", "LONGBLOB", "ENUM(val1, val2, val3, ...)", "SET(val1, val2, val3, ...)"]
59
+ NUMERIC_SIGNED = Literal["BIT(size)", "TINYINT(size)", "BOOL", "BOOLEAN", "SMALLINT(size)", "MEDIUMINT(size)", "INT(size)", "INTEGER(size)", "BIGINT(size)", "FLOAT(size, d)", "FLOAT(p)", "DOUBLE(size, d)", "DOUBLE PRECISION(size, d)", "DECIMAL(size, d)", "DEC(size, d)"]
60
+ NUMERIC_UNSIGNED = Literal["BIT(size)", "TINYINT(size)", "BOOL", "BOOLEAN", "SMALLINT(size)", "MEDIUMINT(size)", "INT(size)", "INTEGER(size)", "BIGINT(size)", "FLOAT(size, d)", "FLOAT(p)", "DOUBLE(size, d)", "DOUBLE PRECISION(size, d)", "DECIMAL(size, d)", "DEC(size, d)"]
61
+ DATE = Literal["DATE", "DATETIME(fsp)", "TIMESTAMP(fsp)", "TIME(fsp)", "YEAR"]
62
+
63
+
64
+
65
+
66
+
67
+
68
+ # FIXME [ ]: this method does not comply with the implemented interface; we need to adjust it in the future to scale it to other databases
69
+ @staticmethod
70
+ def transform_py_dtype_into_query_dtype(dtype: Any) -> str:
71
+ # TODOL: must be found a better way to convert python data type into SQL clauses
72
+ # float -> DECIMAL(5,2) is an error
73
+ dicc: dict[Any, str] = {
74
+ int: "INTEGER",
75
+ float: "FLOAT(5,2)",
76
+ Decimal: "FLOAT",
77
+ datetime.datetime: "DATETIME",
78
+ datetime.date: "DATE",
79
+ bytes: "BLOB",
80
+ str: "VARCHAR(255)",
81
+ np.uint64: "BIGINT UNSIGNED"
82
+ }
83
+
84
+ return dicc[dtype]
85
+
86
+
87
+
88
+
89
+ # FIXME [ ]: this method does not comply with the implemented interface; we need to adjust it in the future to scale it to other databases
90
+ def get_query_clausule(column_obj: Column) -> str:
91
+ dtype: str = transform_py_dtype_into_query_dtype(column_obj.dtype)
92
+ query: str = f"{column_obj.column_name} {dtype}"
93
+
94
+ # FIXME [ ]: that's horrible but i'm tired; change it in the future
95
+ if column_obj.is_primary_key:
96
+ query += " PRIMARY KEY"
97
+ if column_obj.is_auto_generated:
98
+ if column_obj.dtype is datetime.datetime:
99
+ query += " DEFAULT CURRENT_TIMESTAMP"
100
+ if column_obj.is_auto_increment:
101
+ query += " AUTO_INCREMENT"
102
+ if column_obj.is_unique:
103
+ query += " UNIQUE"
104
+ return query
@@ -0,0 +1,36 @@
1
+ from collections import defaultdict
2
+ from typing import Callable, TYPE_CHECKING, Type
3
+ from .lambda_disassembler import Disassembler
4
+
5
+ if TYPE_CHECKING:
6
+ from .table_constructor import Table
7
+
8
+
9
+ class ForeignKey[Tbl1:Table, Tbl2:Table]:
10
+ MAPPED: dict[Tbl1, dict[Tbl2, Callable[[Tbl1, Tbl2], bool]]] = defaultdict(dict)
11
+
12
+ def __new__(
13
+ cls,
14
+ orig_table: str,
15
+ referenced_table: Type[Tbl2],
16
+ relationship: Callable[[Tbl1, Tbl2], bool],
17
+ ) -> Tbl2:
18
+ cls.add_foreign_key(orig_table, referenced_table, relationship)
19
+
20
+ return referenced_table
21
+
22
+ @classmethod
23
+ def add_foreign_key(cls, orig_table: str, referenced_table: "Table", relationship: Callable[[Tbl1, Tbl2], bool]) -> None:
24
+ cls.MAPPED[orig_table][referenced_table] = relationship
25
+ return None
26
+
27
+ @classmethod
28
+ def create_query(cls, orig_table: "Table") -> list[str]:
29
+ clauses: list[str] = []
30
+ for referenced_table, _lambda in ForeignKey[Tbl1, Tbl2].MAPPED[orig_table].items():
31
+ dissambler: Disassembler = Disassembler(_lambda)
32
+ orig_col: str = dissambler.cond_1.name
33
+ referenced_col: str = dissambler.cond_2.name
34
+
35
+ clauses.append(f"FOREIGN KEY ({orig_col}) REFERENCES {referenced_table.__table_name__}({referenced_col})")
36
+ return clauses
@@ -0,0 +1,4 @@
1
+ from .disassembler import Disassembler # noqa: F401
2
+ from .nested_element import NestedElement # noqa: F401
3
+ from .tree_instruction import TreeInstruction, TupleInstruction # noqa: F401
4
+ from .name_of import nameof # noqa: F401
@@ -0,0 +1,136 @@
1
+ from enum import Enum
2
+
3
+
4
+
5
+
6
+
7
+ class OpName(Enum):
8
+ CACHE = "CACHE"
9
+ POP_TOP = "POP_TOP"
10
+ PUSH_NULL = "PUSH_NULL"
11
+ INTERPRETER_EXIT = "INTERPRETER_EXIT"
12
+ END_FOR = "END_FOR"
13
+ END_SEND = "END_SEND"
14
+ NOP = "NOP"
15
+ UNARY_NEGATIVE = "UNARY_NEGATIVE"
16
+ UNARY_NOT = "UNARY_NOT"
17
+ UNARY_INVERT = "UNARY_INVERT"
18
+ RESERVED = "RESERVED"
19
+ BINARY_SUBSCR = "BINARY_SUBSCR"
20
+ BINARY_SLICE = "BINARY_SLICE"
21
+ STORE_SLICE = "STORE_SLICE"
22
+ GET_LEN = "GET_LEN"
23
+ MATCH_MAPPING = "MATCH_MAPPING"
24
+ MATCH_SEQUENCE = "MATCH_SEQUENCE"
25
+ MATCH_KEYS = "MATCH_KEYS"
26
+ PUSH_EXC_INFO = "PUSH_EXC_INFO"
27
+ CHECK_EXC_MATCH = "CHECK_EXC_MATCH"
28
+ CHECK_EG_MATCH = "CHECK_EG_MATCH"
29
+ WITH_EXCEPT_START = "WITH_EXCEPT_START"
30
+ GET_AITER = "GET_AITER"
31
+ GET_ANEXT = "GET_ANEXT"
32
+ BEFORE_ASYNC_WITH = "BEFORE_ASYNC_WITH"
33
+ BEFORE_WITH = "BEFORE_WITH"
34
+ END_ASYNC_FOR = "END_ASYNC_FOR"
35
+ CLEANUP_THROW = "CLEANUP_THROW"
36
+ STORE_SUBSCR = "STORE_SUBSCR"
37
+ DELETE_SUBSCR = "DELETE_SUBSCR"
38
+ GET_ITER = "GET_ITER"
39
+ GET_YIELD_FROM_ITER = "GET_YIELD_FROM_ITER"
40
+ LOAD_BUILD_CLASS = "LOAD_BUILD_CLASS"
41
+ LOAD_ASSERTION_ERROR = "LOAD_ASSERTION_ERROR"
42
+ RETURN_GENERATOR = "RETURN_GENERATOR"
43
+ RETURN_VALUE = "RETURN_VALUE"
44
+ SETUP_ANNOTATIONS = "SETUP_ANNOTATIONS"
45
+ LOAD_LOCALS = "LOAD_LOCALS"
46
+ POP_EXCEPT = "POP_EXCEPT"
47
+ UNPACK_SEQUENCE = "UNPACK_SEQUENCE"
48
+ UNPACK_EX = "UNPACK_EX"
49
+ SWAP = "SWAP"
50
+ LOAD_CONST = "LOAD_CONST"
51
+ BUILD_TUPLE = "BUILD_TUPLE"
52
+ BUILD_LIST = "BUILD_LIST"
53
+ BUILD_SET = "BUILD_SET"
54
+ BUILD_MAP = "BUILD_MAP"
55
+ COMPARE_OP = "COMPARE_OP"
56
+ IS_OP = "IS_OP"
57
+ CONTAINS_OP = "CONTAINS_OP"
58
+ RERAISE = "RERAISE"
59
+ COPY = "COPY"
60
+ RETURN_CONST = "RETURN_CONST"
61
+ BINARY_OP = "BINARY_OP"
62
+ LOAD_FAST = "LOAD_FAST"
63
+ STORE_FAST = "STORE_FAST"
64
+ DELETE_FAST = "DELETE_FAST"
65
+ LOAD_FAST_CHECK = "LOAD_FAST_CHECK"
66
+ RAISE_VARARGS = "RAISE_VARARGS"
67
+ GET_AWAITABLE = "GET_AWAITABLE"
68
+ MAKE_FUNCTION = "MAKE_FUNCTION"
69
+ BUILD_SLICE = "BUILD_SLICE"
70
+ MAKE_CELL = "MAKE_CELL"
71
+ LOAD_CLOSURE = "LOAD_CLOSURE"
72
+ LOAD_DEREF = "LOAD_DEREF"
73
+ STORE_DEREF = "STORE_DEREF"
74
+ DELETE_DEREF = "DELETE_DEREF"
75
+ CALL_FUNCTION_EX = "CALL_FUNCTION_EX"
76
+ LOAD_FAST_AND_CLEAR = "LOAD_FAST_AND_CLEAR"
77
+ EXTENDED_ARG = "EXTENDED_ARG"
78
+ LIST_APPEND = "LIST_APPEND"
79
+ SET_ADD = "SET_ADD"
80
+ MAP_ADD = "MAP_ADD"
81
+ COPY_FREE_VARS = "COPY_FREE_VARS"
82
+ YIELD_VALUE = "YIELD_VALUE"
83
+ RESUME = "RESUME"
84
+ MATCH_CLASS = "MATCH_CLASS"
85
+ FORMAT_VALUE = "FORMAT_VALUE"
86
+ BUILD_CONST_KEY_MAP = "BUILD_CONST_KEY_MAP"
87
+ BUILD_STRING = "BUILD_STRING"
88
+ LIST_EXTEND = "LIST_EXTEND"
89
+ SET_UPDATE = "SET_UPDATE"
90
+ DICT_MERGE = "DICT_MERGE"
91
+ DICT_UPDATE = "DICT_UPDATE"
92
+ CALL = "CALL"
93
+ KW_NAMES = "KW_NAMES"
94
+ CALL_INTRINSIC_1 = "CALL_INTRINSIC_1"
95
+ CALL_INTRINSIC_2 = "CALL_INTRINSIC_2"
96
+ LOAD_FROM_DICT_OR_DEREF = "LOAD_FROM_DICT_OR_DEREF"
97
+ INSTRUMENTED_LOAD_SUPER_ATTR = "INSTRUMENTED_LOAD_SUPER_ATTR"
98
+ INSTRUMENTED_POP_JUMP_IF_NONE = "INSTRUMENTED_POP_JUMP_IF_NONE"
99
+ INSTRUMENTED_POP_JUMP_IF_NOT_NONE = "INSTRUMENTED_POP_JUMP_IF_NOT_NONE"
100
+ INSTRUMENTED_RESUME = "INSTRUMENTED_RESUME"
101
+ INSTRUMENTED_CALL = "INSTRUMENTED_CALL"
102
+ INSTRUMENTED_RETURN_VALUE = "INSTRUMENTED_RETURN_VALUE"
103
+ INSTRUMENTED_YIELD_VALUE = "INSTRUMENTED_YIELD_VALUE"
104
+ INSTRUMENTED_CALL_FUNCTION_EX = "INSTRUMENTED_CALL_FUNCTION_EX"
105
+ INSTRUMENTED_JUMP_FORWARD = "INSTRUMENTED_JUMP_FORWARD"
106
+ INSTRUMENTED_JUMP_BACKWARD = "INSTRUMENTED_JUMP_BACKWARD"
107
+ INSTRUMENTED_RETURN_CONST = "INSTRUMENTED_RETURN_CONST"
108
+ INSTRUMENTED_FOR_ITER = "INSTRUMENTED_FOR_ITER"
109
+ INSTRUMENTED_POP_JUMP_IF_FALSE = "INSTRUMENTED_POP_JUMP_IF_FALSE"
110
+ INSTRUMENTED_POP_JUMP_IF_TRUE = "INSTRUMENTED_POP_JUMP_IF_TRUE"
111
+ INSTRUMENTED_END_FOR = "INSTRUMENTED_END_FOR"
112
+ INSTRUMENTED_END_SEND = "INSTRUMENTED_END_SEND"
113
+ INSTRUMENTED_INSTRUCTION = "INSTRUMENTED_INSTRUCTION"
114
+ INSTRUMENTED_LINE = "INSTRUMENTED_LINE"
115
+ FOR_ITER= 'FOR_ITER'
116
+ JUMP_FORWARD= 'JUMP_FORWARD'
117
+ POP_JUMP_IF_FALSE= 'POP_JUMP_IF_FALSE'
118
+ POP_JUMP_IF_TRUE= 'POP_JUMP_IF_TRUE'
119
+ SEND= 'SEND'
120
+ POP_JUMP_IF_NOT_NONE= 'POP_JUMP_IF_NOT_NONE'
121
+ POP_JUMP_IF_NONE= 'POP_JUMP_IF_NONE'
122
+ JUMP_BACKWARD_NO_INTERRUPT= 'JUMP_BACKWARD_NO_INTERRUPT'
123
+ JUMP_BACKWARD= 'JUMP_BACKWARD'
124
+ STORE_NAME= 'STORE_NAME'
125
+ DELETE_NAME= 'DELETE_NAME'
126
+ STORE_ATTR= 'STORE_ATTR'
127
+ DELETE_ATTR= 'DELETE_ATTR'
128
+ STORE_GLOBAL= 'STORE_GLOBAL'
129
+ DELETE_GLOBAL= 'DELETE_GLOBAL'
130
+ LOAD_NAME= 'LOAD_NAME'
131
+ LOAD_ATTR= 'LOAD_ATTR'
132
+ IMPORT_NAME= 'IMPORT_NAME'
133
+ IMPORT_FROM= 'IMPORT_FROM'
134
+ LOAD_GLOBAL= 'LOAD_GLOBAL'
135
+ LOAD_SUPER_ATTR= 'LOAD_SUPER_ATTR'
136
+ LOAD_FROM_DICT_OR_GLOBALS= 'LOAD_FROM_DICT_OR_GLOBALS'