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,69 @@
1
+ import dis
2
+ from typing import Any, Callable, overload
3
+
4
+ from .nested_element import NestedElement
5
+ from .tree_instruction import TreeInstruction
6
+
7
+
8
+ class Disassembler[TProp1, TProp2: Any]:
9
+ """
10
+ class to dissambler lambda function to detach information from left to right of compare symbol.
11
+
12
+ >>> dis = Disassembler[DtoC, None](lambda d: d.c.b.b_data == "asdf")
13
+
14
+ >>> dis.cond_1.name # b_data
15
+ >>> dis.cond_1.parent.parent.parent.name # d
16
+ >>> dis.cond_1.parent.parent.name # c
17
+
18
+ >>> dis.cond_2.name, "asdf"
19
+
20
+ >>> dis.compare_op, "="
21
+
22
+ """
23
+
24
+ __slots__ = (
25
+ "_function",
26
+ "_bytecode_function",
27
+ "_cond_1",
28
+ "_cond_2",
29
+ "_compare_op",
30
+ )
31
+
32
+ @overload
33
+ def __init__(self, function: Callable[[], bool]) -> None: ...
34
+
35
+ @overload
36
+ def __init__(self, function: Callable[[TProp1], bool]) -> None: ...
37
+
38
+ @overload
39
+ def __init__(self, function: Callable[[TProp1, TProp2], bool]) -> None: ...
40
+
41
+ def __init__(self, function: Callable[[], bool] | Callable[[TProp1], bool] | Callable[[TProp1, TProp2], bool]) -> None:
42
+ self._function: Callable[[], bool] | Callable[[TProp1], bool] | Callable[[TProp1, TProp2], bool] = function
43
+ self._bytecode_function: dis.Bytecode = dis.Bytecode(function)
44
+ self.__init_custom__()
45
+
46
+ def __repr__(self) -> str:
47
+ return f"<{self.__class__.__name__}>: {self._cond_1.name} {self._cond_2.name} {self._compare_op}"
48
+
49
+ def __init_custom__(self):
50
+ tree = TreeInstruction(self._function)
51
+ dicc = tree.to_list()
52
+ self._compare_op: str = tree.compare_op[0]
53
+
54
+ self._cond_1: NestedElement[TProp1] = dicc[0].nested_element
55
+ self._cond_2: NestedElement[TProp2] = dicc[1].nested_element
56
+
57
+ return None
58
+
59
+ @property
60
+ def cond_1(self) -> NestedElement[str]:
61
+ return self._cond_1
62
+
63
+ @property
64
+ def cond_2(self) -> NestedElement[str]:
65
+ return self._cond_2
66
+
67
+ @property
68
+ def compare_op(self) -> str:
69
+ return self._compare_op
@@ -0,0 +1,103 @@
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
+ Numeric Data Types
19
+ Data type Description
20
+ 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.
21
+ 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)
22
+ BOOL Zero is considered as false, nonzero values are considered as true.
23
+ BOOLEAN Equal to BOOL
24
+ 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)
25
+ 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)
26
+ 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)
27
+ INTEGER(size) Equal to INT(size)
28
+ 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)
29
+ 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
30
+ 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()
31
+ 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
32
+ DOUBLE PRECISION(size, d)
33
+ 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.
34
+ DEC(size, d) Equal to DECIMAL(size,d)
35
+ 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.
36
+
37
+ Date and Time Data Types
38
+ Data type Description
39
+ DATE A date. Format: YYYY-MM-DD. The supported range is from '1000-01-01' to '9999-12-31'
40
+ 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
41
+ 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
42
+ TIME(fsp) A time. Format: hh:mm:ss. The supported range is from '-838:59:59' to '838:59:59'
43
+ YEAR A year in four-digit format. Values allowed in four-digit format: 1901 to 2155, and 0000.
44
+ MySQL 8.0 does not support year in two-digit format.
45
+ """
46
+
47
+ from typing import Literal
48
+
49
+
50
+ STRING = Literal[
51
+ "CHAR(size)",
52
+ "VARCHAR(size)",
53
+ "BINARY(size)",
54
+ "VARBINARY(size)",
55
+ "TINYBLOB",
56
+ "TINYTEXT",
57
+ "TEXT(size)",
58
+ "BLOB(size)",
59
+ "MEDIUMTEXT",
60
+ "MEDIUMBLOB",
61
+ "LONGTEXT",
62
+ "LONGBLOB",
63
+ "ENUM(val1, val2, val3, ...)",
64
+ "SET(val1, val2, val3, ...)",
65
+ ]
66
+
67
+ NUMERIC_SIGNED = Literal[
68
+ "BIT(size)",
69
+ "TINYINT(size)",
70
+ "BOOL",
71
+ "BOOLEAN",
72
+ "SMALLINT(size)",
73
+ "MEDIUMINT(size)",
74
+ "INT(size)",
75
+ "INTEGER(size)",
76
+ "BIGINT(size)",
77
+ "FLOAT(size, d)",
78
+ "FLOAT(p)",
79
+ "DOUBLE(size, d)",
80
+ "DOUBLE PRECISION(size, d)",
81
+ "DECIMAL(size, d)",
82
+ "DEC(size, d)",
83
+ ]
84
+
85
+ NUMERIC_UNSIGNED = Literal[
86
+ "BIT(size)",
87
+ "TINYINT(size)",
88
+ "BOOL",
89
+ "BOOLEAN",
90
+ "SMALLINT(size)",
91
+ "MEDIUMINT(size)",
92
+ "INT(size)",
93
+ "INTEGER(size)",
94
+ "BIGINT(size)",
95
+ "FLOAT(size, d)",
96
+ "FLOAT(p)",
97
+ "DOUBLE(size, d)",
98
+ "DOUBLE PRECISION(size, d)",
99
+ "DECIMAL(size, d)",
100
+ "DEC(size, d)",
101
+ ]
102
+
103
+ DATE = Literal["DATE", "DATETIME(fsp)", "TIMESTAMP(fsp)", "TIME(fsp)", "YEAR"]
@@ -0,0 +1,41 @@
1
+ import inspect
2
+ import re
3
+
4
+
5
+ def nameof(_, full_name=False) -> str:
6
+ """
7
+ Return the name of the variable passed as argument
8
+
9
+ >>> class C:
10
+ ... member = 5
11
+ >>> my_var = C()
12
+ >>> nameof(my_var)
13
+ 'my_var'
14
+ >>> nameof(my_var.member)
15
+ 'member'
16
+ >>> nameof(my_var.member, full_name=True)
17
+ 'my_var.member'
18
+
19
+ >>> nameof(4 + (my_var.member) + 11)
20
+ Traceback (most recent call last):
21
+ ...
22
+ RuntimeError: Invalid nameof invocation: nameof(4 + (my_var.member) + 11)
23
+ >>> nameof(4)
24
+ Traceback (most recent call last):
25
+ ...
26
+ RuntimeError: Invalid nameof invocation: nameof(4)
27
+ """
28
+ s = inspect.stack()
29
+ func_name = s[0].frame.f_code.co_name
30
+ call = s[1].code_context[0].strip()
31
+ # Simple search for first closing bracket or comma
32
+ arg = re.search(rf"{func_name}\(([^,)]+)[,)]", call)
33
+ if arg is not None:
34
+ var_parts = arg.group(1).split(".")
35
+ if arg is None or not all(map(str.isidentifier, var_parts)):
36
+ raise RuntimeError(f"Invalid {func_name} invocation: {call}")
37
+
38
+ if full_name:
39
+ return arg.group(1)
40
+ else:
41
+ return var_parts[-1]
@@ -0,0 +1,44 @@
1
+ from typing import Iterable
2
+
3
+
4
+ class NestedElement[T]:
5
+ def __init__(self, cond: T):
6
+ self._cond: T = cond
7
+ self._parent_list: list[str] = self._create_parent_list(cond)
8
+
9
+ def __repr__(self) -> str:
10
+ return f"{NestedElement.__name__}: {'.'.join(self._parent_list)}"
11
+
12
+ @property
13
+ def name(self) -> T:
14
+ if self._parent_list:
15
+ return self._parent_list[-1]
16
+ else:
17
+ return self._cond
18
+
19
+ @property
20
+ def parent(self) -> "NestedElement":
21
+ if not self._parent_list:
22
+ raise ValueError(f"Attribute '{self._cond}' has not parent values")
23
+ new_cond = self._parent_list[:-1]
24
+ return self.__get_parent(new_cond)
25
+
26
+ @property
27
+ def parents(self) -> list[T]:
28
+ return self._parent_list
29
+
30
+ def _create_parent_list(self, condition: T) -> Iterable[str]:
31
+ if isinstance(condition, Iterable) and not isinstance(condition, str):
32
+ return condition
33
+
34
+ try:
35
+ _list: list[str] = condition.split(".")
36
+
37
+ except Exception:
38
+ return []
39
+ else:
40
+ return _list
41
+
42
+ @staticmethod
43
+ def __get_parent(constructor: T) -> "NestedElement":
44
+ return NestedElement[T](constructor)
@@ -0,0 +1,145 @@
1
+ from collections import defaultdict
2
+ from typing import Any, Callable, NamedTuple, Self, Optional
3
+ from dis import Instruction, Bytecode
4
+ from ...common.enums.condition_types import ConditionType
5
+ from .dis_types import OpName
6
+ from .nested_element import NestedElement
7
+
8
+
9
+ class Node[T]:
10
+ def __init__(self, data: T):
11
+ self.data: T = data
12
+ self.children: list[Self[T]] = []
13
+
14
+ def __repr__(self) -> str:
15
+ return f"{Node.__name__}: data={self.data} children={self.children}"
16
+
17
+
18
+ class TupleInstruction(NamedTuple):
19
+ var: str
20
+ nested_element: NestedElement[str]
21
+
22
+
23
+ class TreeInstruction:
24
+ _FIRST_LEVEL: tuple[OpName] = (
25
+ OpName.LOAD_FAST,
26
+ OpName.LOAD_GLOBAL,
27
+ OpName.LOAD_CONST,
28
+ OpName.LOAD_DEREF,
29
+ )
30
+
31
+ def __init__[T, *Ts](self, lambda_: Callable[[T, *Ts], None]):
32
+ self._root: Node[Instruction] = Node[Instruction](None)
33
+
34
+ self._bytecode: Bytecode = Bytecode(lambda_)
35
+ self._compare_op: Optional[list[str]] = []
36
+ self._set_root()
37
+
38
+ def __repr__(self) -> str:
39
+ return f"{TreeInstruction.__name__} < at {hex(id(self))}>"
40
+
41
+ @staticmethod
42
+ def _transform__compare_op(compare_sybmol: ConditionType) -> str:
43
+ dicc_symbols: dict[ConditionType, str] = {
44
+ ConditionType.EQUAL: "=",
45
+ }
46
+ return dicc_symbols.get(compare_sybmol, compare_sybmol.value)
47
+
48
+ @staticmethod
49
+ def _transform_is_is_not(instr: Instruction) -> str:
50
+ if instr.argval == 1:
51
+ return ConditionType.IS_NOT.value
52
+ elif instr.argval == 0:
53
+ return ConditionType.IS.value
54
+ else:
55
+ raise Exception(f"argval value '{instr.argval}' not expected.")
56
+
57
+ def _set_root(self) -> None:
58
+ """
59
+ add instructions into self._root
60
+ """
61
+
62
+ def is_instruction_comparable(instr: Instruction) -> bool:
63
+ opname = OpName(instr.opname)
64
+ if opname in (OpName.COMPARE_OP, OpName.IS_OP):
65
+ return True
66
+ return False
67
+
68
+ def set_comparable(instr: Instruction) -> None:
69
+ opname = OpName(instr.opname)
70
+ if opname == OpName.COMPARE_OP:
71
+ return self._compare_op.append(self._transform__compare_op(ConditionType(x.argval)))
72
+ elif opname == OpName.IS_OP:
73
+ return self._compare_op.append(self._transform_is_is_not(x))
74
+ return None
75
+
76
+ for x in self._bytecode:
77
+ if is_instruction_comparable(x):
78
+ set_comparable(x)
79
+ else:
80
+ self.add_instruction(x)
81
+
82
+ def to_dict(self) -> dict[str, list[NestedElement[str]]]:
83
+ _dict: dict[str, list[NestedElement[str]]] = defaultdict(list)
84
+ for node in self.root.children:
85
+ argval = self._join_data_attributes_from_node(node)
86
+ _dict[node.data.argval].append(NestedElement[str](argval))
87
+ return _dict
88
+
89
+ def add_instruction(self, ins: Instruction) -> None:
90
+ opname = OpName(ins.opname)
91
+ if opname in TreeInstruction._FIRST_LEVEL:
92
+ self._root.children.append(Node[Instruction](ins))
93
+ return None
94
+
95
+ if OpName(ins.opname) == OpName.LOAD_ATTR:
96
+ last_fast_node = self._root.children[-1]
97
+ new_node = Node[Instruction](ins)
98
+ self._add_node(last_fast_node, new_node)
99
+ return None
100
+
101
+ def _add_node(self, parent_node: Node[Instruction], new_node: Node[Instruction]):
102
+ parent_node.children.append(new_node)
103
+ return None
104
+
105
+ def get_all_nodes_of(self, node: Node[Instruction]) -> list[Node[Optional[Instruction]]]:
106
+ def get_all_nodes(node: Node[Instruction], list: list[Node[Instruction]]):
107
+ if not node.children:
108
+ return list
109
+ for subnode in node.children:
110
+ if not subnode.children:
111
+ data = subnode
112
+ else:
113
+ data = self.get_all_nodes_of(subnode)
114
+ list.append(data)
115
+
116
+ lista = []
117
+ get_all_nodes(node, lista)
118
+ return lista
119
+
120
+ def to_list(self) -> list[TupleInstruction]:
121
+ """
122
+ Return list with tuple as data.
123
+ This tuple contains the variable name as the first element and all children as the second one, all inside a TupleInstruction NamedTuple.
124
+ """
125
+ _list: list[list[NestedElement[str]]] = []
126
+ for node in self.root.children:
127
+ argval = self._join_data_attributes_from_node(node)
128
+ _list.append(TupleInstruction(node.data.argval, NestedElement[str](argval)))
129
+ return _list
130
+
131
+ def _join_data_attributes_from_node(self, _node: Node[Instruction]) -> list[Any]:
132
+ lista = self.get_all_nodes_of(_node)
133
+ if not lista:
134
+ return _node.data.argval
135
+ else:
136
+ # We just want to retrieve argval not Instruction object itself
137
+ return [_node.data.argval] + [x.data.argval for x in lista]
138
+
139
+ @property
140
+ def root(self) -> Node[Instruction]:
141
+ return self._root
142
+
143
+ @property
144
+ def compare_op(self) -> Optional[list[str]]:
145
+ return self._compare_op
File without changes
@@ -0,0 +1,60 @@
1
+ from typing import Iterable
2
+ from collections import deque, defaultdict
3
+
4
+
5
+ class DFSTraversal:
6
+ """
7
+ Depth first search with Kahn's algorithm
8
+ """
9
+
10
+ @staticmethod
11
+ def sort[T](graph: dict[T, Iterable[T]], raise_: bool = False) -> tuple[T, ...]:
12
+ indegree: dict[T, int] = defaultdict(int)
13
+ for key, val in graph.items():
14
+ for node in val:
15
+ indegree[node] += 1
16
+
17
+ q: deque[T] = deque()
18
+ for key in graph:
19
+ if indegree[key] == 0:
20
+ q.append(key)
21
+
22
+ topo: list[T] = []
23
+ while q:
24
+ node: T = q.popleft()
25
+ topo.append(node)
26
+
27
+ for neighbor in graph[node]:
28
+ indegree[neighbor] -= 1
29
+ if indegree[neighbor] == 0:
30
+ q.append(neighbor)
31
+
32
+ if len(graph) != len(topo):
33
+ difference = set(graph).difference(set(topo))
34
+ msg = f"Cycle found near of nodes '{difference}'"
35
+ if raise_:
36
+ raise Exception(msg)
37
+ print(msg)
38
+ return tuple(topo[::-1])
39
+
40
+
41
+ if __name__ == "__main__":
42
+ adj = {
43
+ 0: [2, 3, 6],
44
+ 1: [4],
45
+ 2: [6],
46
+ 3: [1, 4],
47
+ 4: [5, 8],
48
+ 5: [],
49
+ 6: [7, 11],
50
+ 7: [4, 12],
51
+ 8: [0],
52
+ 9: [10],
53
+ 10: [6],
54
+ 11: [12],
55
+ 12: [8],
56
+ 13: [],
57
+ }
58
+
59
+ ans = DFSTraversal.sort(adj)
60
+ print(ans)