Skip to content

Commit 5e548ba

Browse files
Merge pull request #3 from GabrielTorelo/feat/SQLitePattern
feat/SQLitePattern - OK
2 parents de7eb88 + 9ec9ba3 commit 5e548ba

File tree

6 files changed

+56
-30
lines changed

6 files changed

+56
-30
lines changed

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,10 @@ Place the SQLite `(.db)` files you want to compare inside the `MOCK/DATA` folder
2525
![image](https://github.com/user-attachments/assets/4d439483-bdcb-4bb4-aa0e-7f73a28ae0b6)
2626

2727
### 3. Adding the reference file
28-
Add the file with the reference data to the `MOCK/PATTERN` folder. **The reference file can be in `.txt`, `.json` or `.db` format**.
28+
Add the file with the reference data to the `MOCK/PATTERN` folder. **The reference file can be in `.txt`, `.json`, `.sqlite` or `.db` format**.
2929

3030
### **Important**
31+
- **The `.sqlite` and `.db` files take precedence over the others**
3132
- The file must follow the pattern **_key-value_** _(key: value)_, with the **VALUE ALWAYS WRAPPED IN BRACKETS**.
3233
#### Examples for text file `(.txt)`:
3334
- **Example 1 (without line break):**
@@ -104,6 +105,7 @@ Tracking codes indicate the status of the process:
104105
- `07`: **Error generating JSON from databases**
105106
- `08`: **Error when fetching JSON files from databases**
106107
- `09`: **Error creating reference JSON**
108+
- `10`: **Invalid file extension**
107109
108110
## 🛠 Used Packages
109111

dao/db_sqlite.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@ def list_tables(db_path):
2323
columns = cursor.fetchall()
2424

2525
tables_info[table] = sorted([
26-
{'nome': col[1], 'tipo': col[2]} for col in columns if col[1] not in EXCLUDED_COLUMNS
27-
], key=lambda x: x['nome'])
26+
{'name': col[1], 'type': col[2]} for col in columns if col[1] not in EXCLUDED_COLUMNS
27+
], key=lambda x: x['name'])
2828

2929
connection.close()
3030
return tables_info

utils/files_handler.py

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
from os import path
22
from json import load
3+
from re import DOTALL, findall
34
from err import Errors
45
from constants import PATTERN_PATH_JSON
56
from utils.json_handler import create_json_from_data
67

78
def load_data() -> dict:
89
try:
910
if not path.exists(PATTERN_PATH_JSON):
10-
create_json_from_data()
11+
create_json_from_data(interpret_txt_file)
1112

1213
with open(PATTERN_PATH_JSON, 'r', encoding='utf-8') as file:
1314
data = load(file)
@@ -19,3 +20,31 @@ def load_data() -> dict:
1920
raise err
2021
except Exception as e:
2122
raise Errors(code=2, message=f"Error loading file {PATTERN_PATH_JSON}: {str(e)}")
23+
24+
def interpret_txt_file(file_path: str) -> dict:
25+
json_data = {}
26+
27+
try:
28+
with open(file_path, 'r', encoding='utf-8') as file:
29+
data = file.read()
30+
31+
sections = findall(r'(\w+):\[(.*?)\]', data, DOTALL)
32+
33+
for section_name, section_content in sections:
34+
entries = []
35+
matches = findall(r'\{name: (\w+), type: (\w+)\}', section_content)
36+
for name, typ in matches:
37+
entries.append({
38+
"name": name,
39+
"type": typ
40+
})
41+
42+
entries.sort(key=lambda x: x['name'])
43+
44+
json_data[section_name] = entries
45+
46+
return dict(sorted(json_data.items()))
47+
except FileNotFoundError:
48+
raise Errors(code=2, message=f"Directory {file_path} not found")
49+
except Exception as e:
50+
raise Errors(code=9, message=f"Error processing data: {str(e)}")

utils/iterable_handler.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,14 @@ def compare_with_default(data_default: dict, data: dict) -> tuple:
3030
missing_tables.append(table)
3131
else:
3232
missing_columns = [
33-
col for col in schema if col not in data[table] and col['nome'] not in EXCLUDED_COLUMNS
33+
col for col in schema if col not in data[table] and col['name'] not in EXCLUDED_COLUMNS
3434
]
3535

3636
if missing_columns:
3737
missing_data[table] = missing_columns
3838

3939
missing_tables.sort()
40-
missing_data = {table: sorted(columns, key=lambda x: x['nome']) for table, columns in sorted(missing_data.items())}
40+
missing_data = {table: sorted(columns, key=lambda x: x['name']) for table, columns in sorted(missing_data.items())}
4141

4242
return missing_tables, missing_data
4343
except Exception as e:

utils/json_handler.py

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
from re import DOTALL, findall
21
from json import dump, load
32
from os import listdir, makedirs, path, walk
3+
from typing import Callable
44
from err import Errors
55
from utils.iterable_handler import find_db_files
66
from utils.response_handler import get_ok_response
@@ -51,36 +51,38 @@ def generate_json(multiple_files = False, multiple_db_files = False) -> str:
5151
except Exception as e:
5252
raise Errors(code=7, message=f"Error generating JSON file: {str(e)}")
5353

54-
def create_json_from_data() -> None:
54+
def create_json_from_data(interpret_txt_file: Callable[[str], dict]) -> None:
5555
file_path = ""
5656
json_data = {}
57+
sqlite_file = False
5758

5859
try:
5960
for file in listdir(PATTERN_PATH):
60-
if file.endswith('.txt'):
61+
if file.endswith('.db') or file.endswith('.sqlite'):
6162
file_path = path.join(PATTERN_PATH, file)
63+
sqlite_file = True
6264
break
6365

64-
with open(file_path, 'r', encoding='utf-8') as file:
65-
data = file.read()
66+
if not sqlite_file:
67+
for file in listdir(PATTERN_PATH):
68+
if file.endswith('.txt'):
69+
file_path = path.join(PATTERN_PATH, file)
70+
break
71+
72+
if file_path == "":
73+
raise Errors(code=10, message="No valid file found")
6674

67-
sections = findall(r'(\w+):\[(.*?)\]', data, DOTALL)
68-
69-
for section_name, section_content in sections:
70-
entries = []
71-
matches = findall(r'\{nome: (\w+), tipo: (\w+)\}', section_content)
72-
for nome, tipo in matches:
73-
entries.append({
74-
"nome": nome,
75-
"tipo": tipo
76-
})
77-
78-
json_data[section_name] = entries
75+
if sqlite_file:
76+
json_data = list_tables(file_path)
77+
else:
78+
json_data = interpret_txt_file(file_path)
7979

8080
with open(PATTERN_PATH_JSON, 'w', encoding='utf-8') as json_file:
8181
dump(json_data, json_file, indent=4, ensure_ascii=False)
8282
except FileNotFoundError:
8383
raise Errors(code=3, message=f"Directory {file_path} not found")
84+
except Errors as err:
85+
raise err
8486
except Exception as e:
8587
raise Errors(code=9, message=f"Error processing data: {str(e)}")
8688

utils/messages.py

Lines changed: 0 additions & 7 deletions
This file was deleted.

0 commit comments

Comments
 (0)