xerini 0.3.1__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.
- xerini/__init__.py +0 -0
- xerini/enums.py +65 -0
- xerini/script.py +186 -0
- xerini/statement.py +177 -0
- xerini/supported_query_types.py +11 -0
- xerini/utilities.py +110 -0
- xerini-0.3.1.dist-info/METADATA +58 -0
- xerini-0.3.1.dist-info/RECORD +10 -0
- xerini-0.3.1.dist-info/WHEEL +4 -0
- xerini-0.3.1.dist-info/licenses/LICENSE +21 -0
xerini/__init__.py
ADDED
|
File without changes
|
xerini/enums.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Defines statement types and table writing types
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import Optional
|
|
6
|
+
from enum import StrEnum, auto
|
|
7
|
+
from sql_metadata import QueryType
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class StatementType(StrEnum):
|
|
11
|
+
"""Type of Statements we will deal with"""
|
|
12
|
+
|
|
13
|
+
MOVEMENT = auto()
|
|
14
|
+
UPDATE = auto()
|
|
15
|
+
VIEW = auto()
|
|
16
|
+
IGNORE_ME = auto()
|
|
17
|
+
|
|
18
|
+
@classmethod
|
|
19
|
+
def from_query_type(cls, smd_qt: Optional[QueryType] = None):
|
|
20
|
+
"""Maps QueryTypes to StatementTypes"""
|
|
21
|
+
ans = cls.IGNORE_ME
|
|
22
|
+
if smd_qt in {QueryType.INSERT, QueryType.CREATE}:
|
|
23
|
+
ans = cls.MOVEMENT
|
|
24
|
+
elif smd_qt in {
|
|
25
|
+
QueryType.UPDATE,
|
|
26
|
+
QueryType.DELETE,
|
|
27
|
+
QueryType.ALTER,
|
|
28
|
+
QueryType.DROP,
|
|
29
|
+
QueryType.TRUNCATE,
|
|
30
|
+
}:
|
|
31
|
+
ans = cls.UPDATE
|
|
32
|
+
elif smd_qt == QueryType.SELECT:
|
|
33
|
+
ans = cls.VIEW
|
|
34
|
+
else:
|
|
35
|
+
pass
|
|
36
|
+
return ans
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class TableWriteType(StrEnum):
|
|
40
|
+
"""Type of writing being done by a statement"""
|
|
41
|
+
|
|
42
|
+
UPDATING = auto()
|
|
43
|
+
REBUILDING = auto()
|
|
44
|
+
DELETING = auto()
|
|
45
|
+
NO_WRITING = auto()
|
|
46
|
+
|
|
47
|
+
@classmethod
|
|
48
|
+
def from_statement_query(
|
|
49
|
+
cls, stmt_tp: StatementType, qry_tp: Optional[QueryType] = None
|
|
50
|
+
):
|
|
51
|
+
"""Maps (StatementType, QueryType) to TableWriteType"""
|
|
52
|
+
ans = TableWriteType.NO_WRITING
|
|
53
|
+
if stmt_tp in {StatementType.UPDATE, StatementType.MOVEMENT} and qry_tp in {
|
|
54
|
+
QueryType.INSERT,
|
|
55
|
+
QueryType.UPDATE,
|
|
56
|
+
QueryType.ALTER,
|
|
57
|
+
}:
|
|
58
|
+
ans = TableWriteType.UPDATING
|
|
59
|
+
elif qry_tp in {QueryType.CREATE}:
|
|
60
|
+
ans = TableWriteType.REBUILDING
|
|
61
|
+
elif qry_tp in {QueryType.DROP, QueryType.TRUNCATE, QueryType.DELETE}:
|
|
62
|
+
ans = TableWriteType.DELETING
|
|
63
|
+
else:
|
|
64
|
+
pass
|
|
65
|
+
return ans
|
xerini/script.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module to define a SQL script
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import subprocess
|
|
6
|
+
from typing import Optional, Self
|
|
7
|
+
from functools import cached_property
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import networkx as nx
|
|
10
|
+
import sqlparse
|
|
11
|
+
from pydantic import BaseModel, validate_call
|
|
12
|
+
from xerini.statement import Statement
|
|
13
|
+
from xerini.enums import QueryType, TableWriteType, StatementType
|
|
14
|
+
from xerini.utilities import parallel_decomposition
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Script(BaseModel):
|
|
18
|
+
"""SQL Script class, basically a container for Statements"""
|
|
19
|
+
|
|
20
|
+
raw_code: Optional[str] = None
|
|
21
|
+
|
|
22
|
+
@classmethod
|
|
23
|
+
@validate_call
|
|
24
|
+
def from_string(cls, text: str) -> Self:
|
|
25
|
+
"""This is just a helper function"""
|
|
26
|
+
return cls(raw_code=text)
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
@validate_call
|
|
30
|
+
def from_file(cls, pth: Path) -> Self:
|
|
31
|
+
"""Constructs the Script object from the sql in a file"""
|
|
32
|
+
if pth.suffix.lower() != ".sql":
|
|
33
|
+
raise FileNotFoundError("I am only allowed to read *.sql files!")
|
|
34
|
+
with pth.open("r", encoding="utf-8") as fin:
|
|
35
|
+
text = fin.read()
|
|
36
|
+
return cls(raw_code=text)
|
|
37
|
+
|
|
38
|
+
@classmethod
|
|
39
|
+
@validate_call
|
|
40
|
+
def from_directory(cls, directory: Path) -> Self:
|
|
41
|
+
"""Constructs the Script object from a directory of sql files"""
|
|
42
|
+
if not directory.is_dir():
|
|
43
|
+
raise NotADirectoryError(f"{dir=} is not a directory!")
|
|
44
|
+
texts = []
|
|
45
|
+
for pth in directory.iterdir():
|
|
46
|
+
if pth.is_file() and pth.suffix.lower() == ".sql":
|
|
47
|
+
with pth.open("r", encoding="utf-8") as fin:
|
|
48
|
+
texts.append(fin.read())
|
|
49
|
+
return cls(raw_code="\n".join(texts))
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def formatted_text(self) -> str:
|
|
53
|
+
"""Render string"""
|
|
54
|
+
return "\n\n".join(stmt.formatted_text for stmt in self.statements)
|
|
55
|
+
|
|
56
|
+
def keys(self) -> set[str | None]:
|
|
57
|
+
"""The keys to the dictionary are the names of the affected table of the code"""
|
|
58
|
+
return {
|
|
59
|
+
stmt.affected_table
|
|
60
|
+
for stmt in self.statements
|
|
61
|
+
if stmt.write_type != TableWriteType.NO_WRITING
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
def __getitem__(self, item: str) -> list[Statement]:
|
|
65
|
+
"""Dictionary form to retrieve statements pertinent to an affected table"""
|
|
66
|
+
if item not in self.keys():
|
|
67
|
+
raise KeyError(f"{item=} is not an affected table of the script!")
|
|
68
|
+
return [
|
|
69
|
+
stmt
|
|
70
|
+
for stmt in self.statements
|
|
71
|
+
if (
|
|
72
|
+
(stmt.write_type != TableWriteType.NO_WRITING)
|
|
73
|
+
& (stmt.affected_table == item)
|
|
74
|
+
)
|
|
75
|
+
]
|
|
76
|
+
|
|
77
|
+
@cached_property
|
|
78
|
+
def statements(self) -> list[Statement]:
|
|
79
|
+
"""The list of statements that make up the script"""
|
|
80
|
+
return [Statement(text=sub) for sub in sqlparse.split(self.raw_code)]
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def statement_types(self) -> list[StatementType]:
|
|
84
|
+
"""The statement types"""
|
|
85
|
+
return [_s.statement_type for _s in self.statements]
|
|
86
|
+
|
|
87
|
+
@cached_property
|
|
88
|
+
def statement_query_types(self) -> list[QueryType | None]:
|
|
89
|
+
"""The statement query types"""
|
|
90
|
+
return [_s.query_type for _s in self.statements]
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def statement_write_types(self) -> list[TableWriteType]:
|
|
94
|
+
"""The statement write types"""
|
|
95
|
+
return [_s.write_type for _s in self.statements]
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
def is_valid(self) -> bool:
|
|
99
|
+
"""Are all the statements in the script valid ones"""
|
|
100
|
+
return all(_qt for _qt in self.statement_query_types)
|
|
101
|
+
|
|
102
|
+
@validate_call
|
|
103
|
+
def write(self, output: Path) -> None:
|
|
104
|
+
"""Formatted output to the file at the path"""
|
|
105
|
+
if not self.statements:
|
|
106
|
+
raise ValueError("Nothing to write, as the script is empty!")
|
|
107
|
+
with output.open("w") as fout:
|
|
108
|
+
for stmt in self.statements:
|
|
109
|
+
fout.write(stmt.formatted_text)
|
|
110
|
+
fout.write("\n")
|
|
111
|
+
|
|
112
|
+
@cached_property
|
|
113
|
+
def digraph(self) -> nx.DiGraph:
|
|
114
|
+
"""Returns a directed graph with the table dependency structure of the sql code"""
|
|
115
|
+
dsg = nx.DiGraph()
|
|
116
|
+
for stmt in self.statements:
|
|
117
|
+
if stmt.write_type != TableWriteType.NO_WRITING and stmt.affected_table:
|
|
118
|
+
for source in stmt.source_tables:
|
|
119
|
+
dsg.add_edge(source, stmt.affected_table)
|
|
120
|
+
dsg.edges[source, stmt.affected_table][
|
|
121
|
+
"tooltip"
|
|
122
|
+
] = stmt.formatted_text
|
|
123
|
+
for _n in dsg.nodes():
|
|
124
|
+
dsg.nodes[_n]["shape"] = "box"
|
|
125
|
+
dsg.nodes[_n]["color"] = "blue"
|
|
126
|
+
return dsg
|
|
127
|
+
|
|
128
|
+
@validate_call
|
|
129
|
+
def write_dot(self, file: Path, name: str = "dotted_script") -> Path:
|
|
130
|
+
"""Writes the dotfile for the graph representation"""
|
|
131
|
+
dsg = self.digraph
|
|
132
|
+
dsg.graph = {"name": name, "splines": "ortho", "rankdir": "LR"}
|
|
133
|
+
_adg = nx.nx_agraph.to_agraph(dsg)
|
|
134
|
+
_adg.write(file)
|
|
135
|
+
return file
|
|
136
|
+
|
|
137
|
+
@staticmethod
|
|
138
|
+
@validate_call
|
|
139
|
+
def write_svg(dot_file: Path) -> Path:
|
|
140
|
+
"""Produce the SVG from the dot_file"""
|
|
141
|
+
subprocess.call(["dot", "-Tsvg", dot_file, "-O"])
|
|
142
|
+
svg_file: Path = dot_file.parent / (dot_file.name + ".svg")
|
|
143
|
+
return svg_file
|
|
144
|
+
|
|
145
|
+
def stage_decomposition(self) -> list[set[str]]:
|
|
146
|
+
"""Use parallel decomposition of the graph representation
|
|
147
|
+
to produce a parallelized orchestration of the table builds
|
|
148
|
+
"""
|
|
149
|
+
if not self.statements:
|
|
150
|
+
raise ValueError("I can't decompose an empty script!")
|
|
151
|
+
pcg = list(parallel_decomposition(self.digraph))
|
|
152
|
+
ell = []
|
|
153
|
+
for stg in pcg[1:]:
|
|
154
|
+
tables = set()
|
|
155
|
+
for tbl in stg:
|
|
156
|
+
if tbl in self.keys():
|
|
157
|
+
tables.add(tbl)
|
|
158
|
+
ell.append(tables)
|
|
159
|
+
|
|
160
|
+
return ell
|
|
161
|
+
|
|
162
|
+
@validate_call
|
|
163
|
+
def write_orchestration(self, staged_directory: Path):
|
|
164
|
+
"""Write the script to disk"""
|
|
165
|
+
if not staged_directory.is_absolute():
|
|
166
|
+
staged_directory = staged_directory.expanduser().resolve()
|
|
167
|
+
|
|
168
|
+
if staged_directory.exists() and staged_directory.is_dir():
|
|
169
|
+
raise IsADirectoryError(
|
|
170
|
+
f"{staged_directory=} is an existing directory, I should not overwrite it!"
|
|
171
|
+
)
|
|
172
|
+
if staged_directory.exists() and staged_directory.is_file():
|
|
173
|
+
raise FileExistsError(
|
|
174
|
+
f"{staged_directory=} is an existing file, I should definitely not overwrite it!"
|
|
175
|
+
)
|
|
176
|
+
staged_directory.mkdir(parents=True, exist_ok=True)
|
|
177
|
+
decomposed = self.stage_decomposition()
|
|
178
|
+
for idx, stg in enumerate(decomposed):
|
|
179
|
+
stage = staged_directory / f"stage_{str(idx+1).zfill(2)}"
|
|
180
|
+
stage.mkdir()
|
|
181
|
+
for tbl in stg:
|
|
182
|
+
pth = stage / f"{tbl}.sql"
|
|
183
|
+
with pth.open("w", encoding="utf-8") as fout:
|
|
184
|
+
for stmt in self[tbl]:
|
|
185
|
+
fout.write(str(stmt))
|
|
186
|
+
fout.write("\n")
|
xerini/statement.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module to define a SQL Statement
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import Optional, Self, Set
|
|
6
|
+
|
|
7
|
+
import sqlparse
|
|
8
|
+
from pydantic import BaseModel, model_validator
|
|
9
|
+
from sql_metadata import Parser, QueryType
|
|
10
|
+
|
|
11
|
+
from xerini.enums import StatementType, TableWriteType
|
|
12
|
+
from xerini.utilities import (
|
|
13
|
+
meaningful_strings_count,
|
|
14
|
+
successive_pairs,
|
|
15
|
+
following_pairs_second_item,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
# pylint: disable=unused-import
|
|
19
|
+
from xerini.supported_query_types import SUPPORTED_QUERY_TYPES
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Statement(BaseModel):
|
|
23
|
+
"""SQL Statment class"""
|
|
24
|
+
|
|
25
|
+
text: str
|
|
26
|
+
_parsed_text: Optional[Parser] = None
|
|
27
|
+
_query_type: Optional[QueryType] = None
|
|
28
|
+
|
|
29
|
+
@model_validator(mode="before")
|
|
30
|
+
@classmethod
|
|
31
|
+
def only_one_statement(cls, data: dict):
|
|
32
|
+
"""Model validator to make sure that there is only a single sql statement in text"""
|
|
33
|
+
if not 0 < meaningful_strings_count(data["text"]) < 2:
|
|
34
|
+
raise ValueError(
|
|
35
|
+
f"Expected a string containing a single SQL statement, but {data['text']=} !"
|
|
36
|
+
)
|
|
37
|
+
return data
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def formatted_text(self) -> str:
|
|
41
|
+
"""Returns sqlparse.formatted text"""
|
|
42
|
+
return sqlparse.format(
|
|
43
|
+
self.text,
|
|
44
|
+
reindent=True,
|
|
45
|
+
keyword_case="upper",
|
|
46
|
+
strip_comments=True,
|
|
47
|
+
comma_first=True,
|
|
48
|
+
indent_tabs=True,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
@model_validator(mode="after")
|
|
52
|
+
def set_parsed_text(self) -> Self:
|
|
53
|
+
"""Model validator to set the parsed text"""
|
|
54
|
+
self._parsed_text = Parser(self.formatted_text)
|
|
55
|
+
return self
|
|
56
|
+
|
|
57
|
+
@model_validator(mode="after")
|
|
58
|
+
def set_query_type(self) -> Self:
|
|
59
|
+
"""Model validator to fix the augmented via the supported_query_types.py query type"""
|
|
60
|
+
self._query_type = None
|
|
61
|
+
try:
|
|
62
|
+
self._query_type = self.parsed_text.query_type
|
|
63
|
+
except ValueError as _ve:
|
|
64
|
+
pass
|
|
65
|
+
return self
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def query_type(self) -> QueryType | None:
|
|
69
|
+
"""The augmented via the supported_query_types.py query type"""
|
|
70
|
+
return self._query_type
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def parsed_text(self) -> Parser:
|
|
74
|
+
"""Parsed_text property"""
|
|
75
|
+
return self._parsed_text
|
|
76
|
+
|
|
77
|
+
def __str__(self) -> str:
|
|
78
|
+
"""Returns a string for printing"""
|
|
79
|
+
return self.text
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def statement_type(self) -> StatementType:
|
|
83
|
+
"""Whether the statement is a views, updates, or transfers data"""
|
|
84
|
+
return StatementType.from_query_type(self.query_type)
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def write_type(self) -> TableWriteType:
|
|
88
|
+
"""Whether the statement builds, updates, or temporarily write"""
|
|
89
|
+
return TableWriteType.from_statement_query(self.statement_type, self.query_type)
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def tables(self) -> Set[Optional[str]]:
|
|
93
|
+
"""Tables integral to the statement"""
|
|
94
|
+
ans: Set = set()
|
|
95
|
+
if self.query_type is not None:
|
|
96
|
+
ans = set(self.parsed_text.tables)
|
|
97
|
+
return ans
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def non_empty_tokens(self) -> list[sqlparse.sql.Token]:
|
|
101
|
+
"""From the sql_metadata Parser"""
|
|
102
|
+
ans = []
|
|
103
|
+
if self.query_type is None:
|
|
104
|
+
pass
|
|
105
|
+
else:
|
|
106
|
+
ans = self.parsed_text.non_empty_tokens
|
|
107
|
+
return ans
|
|
108
|
+
|
|
109
|
+
@property
|
|
110
|
+
def normalized_successive_token_pairs(self) -> list[tuple[str, str]]:
|
|
111
|
+
"""Needed to get to the affected tables"""
|
|
112
|
+
return [
|
|
113
|
+
(sp[0].normalized, sp[1].normalized)
|
|
114
|
+
for sp in successive_pairs(self.parsed_text.tokens)
|
|
115
|
+
]
|
|
116
|
+
|
|
117
|
+
@property
|
|
118
|
+
def affected_table(self) -> str | None:
|
|
119
|
+
"""Where the data is going, according to the statement"""
|
|
120
|
+
ans = None
|
|
121
|
+
if self.query_type in {QueryType.TRUNCATE, QueryType.DROP}:
|
|
122
|
+
ans = list(self.tables)[0]
|
|
123
|
+
elif self.query_type == QueryType.UPDATE:
|
|
124
|
+
ans = [
|
|
125
|
+
tbl
|
|
126
|
+
for tbl in self.tables
|
|
127
|
+
if tbl
|
|
128
|
+
and ("UPDATE", tbl.upper()) in self.normalized_successive_token_pairs
|
|
129
|
+
][0]
|
|
130
|
+
elif ("DELETE", "FROM") in self.normalized_successive_token_pairs:
|
|
131
|
+
ans = following_pairs_second_item(
|
|
132
|
+
self.normalized_successive_token_pairs, ("DELETE", "FROM")
|
|
133
|
+
)
|
|
134
|
+
elif ("CREATE", "TABLE") in self.normalized_successive_token_pairs:
|
|
135
|
+
ans = following_pairs_second_item(
|
|
136
|
+
self.normalized_successive_token_pairs, ("CREATE", "TABLE")
|
|
137
|
+
)
|
|
138
|
+
elif ("TEMP", "TABLE") in self.normalized_successive_token_pairs:
|
|
139
|
+
ans = following_pairs_second_item(
|
|
140
|
+
self.normalized_successive_token_pairs, ("TEMP", "TABLE")
|
|
141
|
+
)
|
|
142
|
+
elif ("TEMPORARY", "TABLE") in self.normalized_successive_token_pairs:
|
|
143
|
+
ans = following_pairs_second_item(
|
|
144
|
+
self.normalized_successive_token_pairs, ("TEMPORARY", "TABLE")
|
|
145
|
+
)
|
|
146
|
+
elif ("INSERT", "INTO") in self.normalized_successive_token_pairs:
|
|
147
|
+
ans = following_pairs_second_item(
|
|
148
|
+
self.normalized_successive_token_pairs, ("INSERT", "INTO")
|
|
149
|
+
)
|
|
150
|
+
else:
|
|
151
|
+
pass
|
|
152
|
+
return ans.lower() if ans is not None else None
|
|
153
|
+
|
|
154
|
+
def what_are_we_truncating_dropping(self) -> str | None:
|
|
155
|
+
"""We need to specify the destination table when we truncate"""
|
|
156
|
+
if not self.query_type in {QueryType.TRUNCATE, QueryType.DROP}:
|
|
157
|
+
raise TypeError(f"This method is unsupported for {self.query_type}!")
|
|
158
|
+
return self.affected_table
|
|
159
|
+
|
|
160
|
+
@property
|
|
161
|
+
def source_tables(self) -> Set[Optional[str]]:
|
|
162
|
+
"""Tables from which the data is being sourced, according to the statement"""
|
|
163
|
+
sources: Set = set()
|
|
164
|
+
if self.statement_type in {StatementType.UPDATE, StatementType.VIEW}:
|
|
165
|
+
if self.query_type in {QueryType.TRUNCATE, QueryType.DROP}:
|
|
166
|
+
pass
|
|
167
|
+
elif self.query_type == QueryType.DELETE:
|
|
168
|
+
sources = self.tables - {
|
|
169
|
+
self.affected_table,
|
|
170
|
+
}
|
|
171
|
+
else:
|
|
172
|
+
sources = self.tables
|
|
173
|
+
else:
|
|
174
|
+
sources = self.tables - {
|
|
175
|
+
self.affected_table,
|
|
176
|
+
}
|
|
177
|
+
return sources
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module to augment the SUPPORTED_QUERY_TYPES dictionary
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from sql_metadata import QueryType
|
|
6
|
+
from sql_metadata.keywords_lists import SUPPORTED_QUERY_TYPES
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
SUPPORTED_QUERY_TYPES["CREATETEMP"] = QueryType.CREATE
|
|
10
|
+
SUPPORTED_QUERY_TYPES["CREATETEMPORARY"] = QueryType.CREATE
|
|
11
|
+
SUPPORTED_QUERY_TYPES["CREATEORREPLACE"] = QueryType.CREATE
|
xerini/utilities.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""
|
|
2
|
+
## Module with useful functions
|
|
3
|
+
|
|
4
|
+
- successive_pairs
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import Iterable, TypeVar, Tuple, Optional, Collection, List, Iterator
|
|
8
|
+
from itertools import tee
|
|
9
|
+
from string import ascii_lowercase, digits
|
|
10
|
+
from random import choice, choices, shuffle
|
|
11
|
+
import sqlparse
|
|
12
|
+
import networkx as nx
|
|
13
|
+
|
|
14
|
+
Things = TypeVar("Things")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def successive_pairs(iterable: Iterable[Things]) -> Iterable[Tuple[Things, Things]]:
|
|
18
|
+
"""
|
|
19
|
+
Given an iterable this function returns a generator of the successive overlapping
|
|
20
|
+
pairs taken from the input iterable,
|
|
21
|
+
```python
|
|
22
|
+
>>> list(successive_pairs('ABCDEFG'))
|
|
23
|
+
[('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E'), ('E', 'F'), ('F', 'G')]
|
|
24
|
+
```
|
|
25
|
+
"""
|
|
26
|
+
_a, _b = tee(iterable)
|
|
27
|
+
next(_b, None)
|
|
28
|
+
return zip(_a, _b)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def following_pairs_second_item(
|
|
32
|
+
ell: List[Tuple[Things, Things]], search_pair: Tuple[Things, Things]
|
|
33
|
+
) -> Things:
|
|
34
|
+
"""Used to get affected table names"""
|
|
35
|
+
if search_pair not in ell:
|
|
36
|
+
raise ValueError(f"The {search_pair=} is not in {ell=}!")
|
|
37
|
+
idx: int = ell.index(search_pair)
|
|
38
|
+
if (idx + 1) == len(ell):
|
|
39
|
+
raise IndexError(f"{search_pair} was the last element of {ell=}!")
|
|
40
|
+
return ell[idx + 1][1]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def meaningful_strings_count(text: Optional[str] = None) -> int:
|
|
44
|
+
"""
|
|
45
|
+
We need this function to determine whether the text used to initialize a SQL Statement only has
|
|
46
|
+
a single statement
|
|
47
|
+
:param text: an arbitrary text
|
|
48
|
+
:param separator: space, tab, but most likely ;
|
|
49
|
+
:return: the number of meaningful string in the original text
|
|
50
|
+
"""
|
|
51
|
+
ans = 0
|
|
52
|
+
if text is None:
|
|
53
|
+
pass
|
|
54
|
+
if text:
|
|
55
|
+
ans = sum(bool(sub.replace(";", "")) for sub in sqlparse.split(text))
|
|
56
|
+
return ans
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def random_id8() -> str:
|
|
60
|
+
"""
|
|
61
|
+
Returns an ascii string of length 8 which starts with a lower case character
|
|
62
|
+
:return:
|
|
63
|
+
"""
|
|
64
|
+
alpha_numeric = ascii_lowercase + digits
|
|
65
|
+
first = choice(ascii_lowercase)
|
|
66
|
+
rest = "".join(choices(alpha_numeric, k=7))
|
|
67
|
+
return first + rest
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def random_partitions(
|
|
71
|
+
number_of_partitions, items: Collection[Things]
|
|
72
|
+
) -> Tuple[List[Things], ...]:
|
|
73
|
+
"""Partitions the elements of items into a tuple of random lists of roughly equal size"""
|
|
74
|
+
if len(items) < number_of_partitions:
|
|
75
|
+
raise ValueError(
|
|
76
|
+
f"The provided collection has less elements, {len(items)=}, "
|
|
77
|
+
f"than the number of partitions, {number_of_partitions=}!"
|
|
78
|
+
)
|
|
79
|
+
if number_of_partitions < 2:
|
|
80
|
+
raise ValueError(
|
|
81
|
+
f"The partition size, {number_of_partitions=}, should be greater than 2!"
|
|
82
|
+
)
|
|
83
|
+
_t: Tuple[List[Things], ...] = tuple([] for _ in range(number_of_partitions))
|
|
84
|
+
_ell = list(items)
|
|
85
|
+
shuffle(_ell)
|
|
86
|
+
for index, elem in enumerate(_ell):
|
|
87
|
+
_t[index % number_of_partitions].append(elem)
|
|
88
|
+
return _t
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def minimal_nodes(directed: nx.DiGraph) -> set:
|
|
92
|
+
"""
|
|
93
|
+
Returns the set of nodes in the network that have no incoming edges
|
|
94
|
+
:param directed: the graph from which we should extract the minimal nodes
|
|
95
|
+
:return: a set of mininal nodes
|
|
96
|
+
"""
|
|
97
|
+
if not isinstance(directed, nx.DiGraph):
|
|
98
|
+
raise TypeError(f"unable to compute minimal nodes for {type(directed)=}.")
|
|
99
|
+
return {node for node in directed.nodes() if directed.in_degree(node) == 0}
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def parallel_decomposition(directed: nx.DiGraph) -> Iterator[set]:
|
|
103
|
+
"""Decompose the DAG into stages"""
|
|
104
|
+
if not nx.is_directed_acyclic_graph(directed):
|
|
105
|
+
raise TypeError("parallel decomposition requires a directed acyclic graph.")
|
|
106
|
+
_ctdg = directed.copy()
|
|
107
|
+
while _ctdg.nodes():
|
|
108
|
+
minimals = minimal_nodes(_ctdg)
|
|
109
|
+
_ctdg.remove_nodes_from(minimals)
|
|
110
|
+
yield minimals
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: xerini
|
|
3
|
+
Version: 0.3.1
|
|
4
|
+
Summary: A minimal python library for orchestrating runs of large SQL scripts.
|
|
5
|
+
Author-email: "J. Tipan VERELLA" <tipan.verella@gmail.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Classifier: Intended Audience :: Developers
|
|
9
|
+
Classifier: Intended Audience :: Information Technology
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Requires-Python: >=3.11
|
|
21
|
+
Requires-Dist: networkx>=3.4.2
|
|
22
|
+
Requires-Dist: pydantic>=2.10.6
|
|
23
|
+
Requires-Dist: pygraphviz>=1.14
|
|
24
|
+
Requires-Dist: sql-metadata>=2.17.0
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# Sciurus
|
|
28
|
+

|
|
29
|
+
|
|
30
|
+
Sciurus is a python library for orchestrating runs of large `SQL` scripts.
|
|
31
|
+
|
|
32
|
+
You can explore the library by checking out [this documentation](https://sciurus-76b570.gitlab.io/).
|
|
33
|
+
|
|
34
|
+
You can quickly try it out if you have `docker`:
|
|
35
|
+
|
|
36
|
+
1. Run the following in the project directory after cloning it:
|
|
37
|
+
|
|
38
|
+
```zsh
|
|
39
|
+
docker build -t xerini -f Dockerfile .
|
|
40
|
+
docker run -it xerini zsh
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
2. When inside the container run:
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
```zsh
|
|
47
|
+
make
|
|
48
|
+
```
|
|
49
|
+
This will run `black`, `pylint`, `mypy`, and `pytest`
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
3. You can also build and use the deployment container:
|
|
53
|
+
|
|
54
|
+
```zsh
|
|
55
|
+
docker build -t xerini-deploy -f deploy.Dockerfile . --no-cache
|
|
56
|
+
docker run -it xerini-deploy python -c "from sciurus.utilities import random_id8; print(random_id8())"
|
|
57
|
+
```
|
|
58
|
+
This should produce a `random_id8()` string
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
xerini/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
xerini/enums.py,sha256=QmVeOyrtp1J5bXg81Al42BOnIoWkvE-j7s8bZZbLVvY,1790
|
|
3
|
+
xerini/script.py,sha256=MlYNDKHg6gDCh4N3GfKHqBE3CEgxzzwYEdvouvPEy7Y,6883
|
|
4
|
+
xerini/statement.py,sha256=r75VvoStCKXt3eM3VMDn_HVxmWPjN45RrShu3XAixTI,6161
|
|
5
|
+
xerini/supported_query_types.py,sha256=KeQC1kX0g_mnZDQ9pk93DTzpUKkI5ilJWzyqZ613n_E,338
|
|
6
|
+
xerini/utilities.py,sha256=ST6fDwX0texw8wkElk2kzjDimFdJnAYJG3ldQfL4kxw,3668
|
|
7
|
+
xerini-0.3.1.dist-info/METADATA,sha256=JHwOCehjqfW1Wo77NTEe1sb6hnbkyG2iGL1i8Eacbig,1932
|
|
8
|
+
xerini-0.3.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
9
|
+
xerini-0.3.1.dist-info/licenses/LICENSE,sha256=xba-Grv8OMJqLpb6eyMQBDQL2DvoFp6S9dodUcip83w,1073
|
|
10
|
+
xerini-0.3.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 J. Tipan Verella
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|