python-eigen-ingenuity-nocli 0.5.6__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.
- eigeningenuity/__init__.py +29 -0
- eigeningenuity/assetmodel.py +433 -0
- eigeningenuity/auth.py +178 -0
- eigeningenuity/core/__init__.py +236 -0
- eigeningenuity/elastic.py +171 -0
- eigeningenuity/events.py +88 -0
- eigeningenuity/historian.py +786 -0
- eigeningenuity/historianmulti.py +481 -0
- eigeningenuity/settings.py +87 -0
- eigeningenuity/smartdash.py +103 -0
- eigeningenuity/sql.py +132 -0
- eigeningenuity/util.py +548 -0
- modelbuilder/__init__.py +7 -0
- modelbuilder/src/__init__.py +0 -0
- modelbuilder/src/assetmodelbuilder.py +164 -0
- modelbuilder/src/assetmodelcsvwriter.py +31 -0
- modelbuilder/src/assetmodelutilities.py +51 -0
- modelbuilder/src/configmanager.py +500 -0
- modelbuilder/src/connectors/__init__.py +0 -0
- modelbuilder/src/connectors/boltconnector.py +108 -0
- modelbuilder/src/connectors/dbconnectors.py +40 -0
- modelbuilder/src/connectors/genericconnector.py +30 -0
- modelbuilder/src/connectors/httpsconnector.py +132 -0
- modelbuilder/src/csvcontentsmanager.py +135 -0
- modelbuilder/src/csvwriter.py +305 -0
- modelbuilder/src/fileanalyser.py +91 -0
- modelbuilder/src/filemanager.py +400 -0
- modelbuilder/src/messages.py +61 -0
- modelbuilder/src/processors/__init__.py +0 -0
- modelbuilder/src/processors/cypherfileprocessor.py +73 -0
- modelbuilder/src/processors/labelmanager.py +133 -0
- modelbuilder/src/processors/nodefileprocessor.py +282 -0
- modelbuilder/src/processors/propertymanager.py +129 -0
- modelbuilder/src/processors/relationshipfileprocessor.py +285 -0
- modelbuilder/src/processors/relationshipmanager.py +31 -0
- modelbuilder/src/queries/__init__.py +0 -0
- modelbuilder/src/queries/cypherbuilder.py +323 -0
- modelbuilder/src/queries/query.py +82 -0
- modelbuilder/src/queries/typedefs.py +180 -0
- modelbuilder/src/versionmanager.py +356 -0
- python_eigen_ingenuity_nocli-0.5.6.dist-info/METADATA +30 -0
- python_eigen_ingenuity_nocli-0.5.6.dist-info/RECORD +44 -0
- python_eigen_ingenuity_nocli-0.5.6.dist-info/WHEEL +5 -0
- python_eigen_ingenuity_nocli-0.5.6.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
from connectors.genericconnector import GenericConnector
|
|
2
|
+
import eigeningenuity.settings as settings
|
|
3
|
+
import eigeningenuity.auth as auth
|
|
4
|
+
import requests
|
|
5
|
+
from time import sleep
|
|
6
|
+
from queries.query import QueryResult
|
|
7
|
+
from messages import *
|
|
8
|
+
import assetmodelutilities
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class HTTPSConnector(GenericConnector):
|
|
12
|
+
|
|
13
|
+
def __init__(self, db_connection_details, config_manager, output_file, results_file):
|
|
14
|
+
super().__init__(db_connection_details, output_file, results_file)
|
|
15
|
+
self.url = db_connection_details['url']
|
|
16
|
+
self.config_manager = config_manager
|
|
17
|
+
|
|
18
|
+
def close(self):
|
|
19
|
+
super().close()
|
|
20
|
+
|
|
21
|
+
def convert_result(self, this_result, code=-1):
|
|
22
|
+
converted_result = QueryResult(False)
|
|
23
|
+
try:
|
|
24
|
+
converted_result.set_status(this_result.status_code)
|
|
25
|
+
except:
|
|
26
|
+
converted_result.set_status(code)
|
|
27
|
+
|
|
28
|
+
json_result = None
|
|
29
|
+
try:
|
|
30
|
+
json_result = this_result.json()
|
|
31
|
+
except:
|
|
32
|
+
converted_result.set_response(None)
|
|
33
|
+
|
|
34
|
+
if json_result:
|
|
35
|
+
try:
|
|
36
|
+
converted_result.set_response(json_result['data'])
|
|
37
|
+
try:
|
|
38
|
+
update_dict = {}
|
|
39
|
+
result = json_result['summary']
|
|
40
|
+
converted_result.set_updates_made(result['containsUpdates'])
|
|
41
|
+
update_dict['nodes created'] = result['nodesCreated']
|
|
42
|
+
update_dict['nodes deleted'] = result['nodesDeleted']
|
|
43
|
+
update_dict['properties set'] = result['propertiesSet']
|
|
44
|
+
update_dict['relationships created'] = result['relationshipsCreated']
|
|
45
|
+
update_dict['relationships deleted'] = result['relationshipsDeleted']
|
|
46
|
+
update_dict['labels added'] = result['labelsAdded']
|
|
47
|
+
update_dict['labels removed'] = result['labelsRemoved']
|
|
48
|
+
update_dict['indexes added'] = result['indexesAdded']
|
|
49
|
+
update_dict['indexes removed'] = result['indexesRemoved']
|
|
50
|
+
update_dict['constraints added'] = result['constraintsAdded']
|
|
51
|
+
update_dict['constraints removed'] = result['constraintsRemoved']
|
|
52
|
+
# 'systemUpdates' is not returned by the ei-applet
|
|
53
|
+
# update_dict['system updates'] = result['systemUpdates']
|
|
54
|
+
converted_result.set_updates(update_dict)
|
|
55
|
+
except:
|
|
56
|
+
converted_result.set_updates_made(False)
|
|
57
|
+
except:
|
|
58
|
+
converted_result.set_response(json_result)
|
|
59
|
+
|
|
60
|
+
return converted_result
|
|
61
|
+
|
|
62
|
+
def execute(self, query, query_num=-1):
|
|
63
|
+
super().execute(query, query_num)
|
|
64
|
+
query_text = query.text
|
|
65
|
+
if self.output_file is not None:
|
|
66
|
+
self.output_file.write(query_text + '\n')
|
|
67
|
+
update = {'cmd': 'EXECUTE', 'q': query_text}
|
|
68
|
+
try_count = 0
|
|
69
|
+
all_good = False
|
|
70
|
+
while not all_good and try_count < 3:
|
|
71
|
+
status_code = 0
|
|
72
|
+
try:
|
|
73
|
+
headers = {}
|
|
74
|
+
if settings._azure_auth_enabled_:
|
|
75
|
+
headers = auth._authenticate_azure_user(self.url.split("ei-applet")[0])
|
|
76
|
+
result = requests.get(url=self.url, params=update, headers=headers, verify=False)
|
|
77
|
+
status_code = result.status_code
|
|
78
|
+
all_good = True
|
|
79
|
+
if result.text.startswith('<h1>ERROR</h1>'):
|
|
80
|
+
if 'Invalid input' in result.text:
|
|
81
|
+
status_code = 505
|
|
82
|
+
elif 'ServiceUnavailable' in result.text:
|
|
83
|
+
status_code = 502
|
|
84
|
+
else:
|
|
85
|
+
status_code = 600
|
|
86
|
+
elif "<!-- Copyright (C) Microsoft Corporation. All rights reserved. -->" in result.text and "<title>Sign in to your account</title>" in result.text:
|
|
87
|
+
status_code = 401
|
|
88
|
+
except Exception as e:
|
|
89
|
+
info_message(
|
|
90
|
+
f'Query {self.query_id} failed at {assetmodelutilities.get_formatted_time_now_noms()} with error type {type(e)}, retrying...')
|
|
91
|
+
status_code = 600
|
|
92
|
+
finally:
|
|
93
|
+
if status_code != 200:
|
|
94
|
+
try_count += 1
|
|
95
|
+
all_good = False
|
|
96
|
+
if status_code == 414:
|
|
97
|
+
info_message(
|
|
98
|
+
f'Query {self.query_id} failed at {assetmodelutilities.get_formatted_time_now_noms()} - data too long!')
|
|
99
|
+
break
|
|
100
|
+
elif status_code == 505:
|
|
101
|
+
info_message(
|
|
102
|
+
f'Query {self.query_id} failed at {assetmodelutilities.get_formatted_time_now_noms()} - returned "ERROR"')
|
|
103
|
+
break
|
|
104
|
+
elif status_code == 401:
|
|
105
|
+
info_message(
|
|
106
|
+
f'Query {self.query_id} failed at {assetmodelutilities.get_formatted_time_now_noms()} - Missing Required Azure Auth Credentials')
|
|
107
|
+
exit()
|
|
108
|
+
elif status_code != 600:
|
|
109
|
+
info_message(
|
|
110
|
+
f'Query {self.query_id} failed at {assetmodelutilities.get_formatted_time_now_noms()} with error code {status_code}, retrying...')
|
|
111
|
+
sleep(2)
|
|
112
|
+
|
|
113
|
+
if not all_good:
|
|
114
|
+
warning_message(f'Query {self.query_id} not processed!')
|
|
115
|
+
elif try_count > 0:
|
|
116
|
+
info_message(f'Query {self.query_id} processed successfully on attempt {try_count + 1}')
|
|
117
|
+
|
|
118
|
+
converted_result = self.convert_result(result, status_code)
|
|
119
|
+
if self.results_file is not None:
|
|
120
|
+
self.write_response(converted_result.get_response())
|
|
121
|
+
|
|
122
|
+
return converted_result
|
|
123
|
+
|
|
124
|
+
def print_response(self, response):
|
|
125
|
+
if response is not None:
|
|
126
|
+
for r in response:
|
|
127
|
+
print(r)
|
|
128
|
+
|
|
129
|
+
def write_response(self, response):
|
|
130
|
+
if response is not None:
|
|
131
|
+
for r in response:
|
|
132
|
+
self.results_file.write(str(r) + '\n')
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import assetmodelutilities as amu
|
|
2
|
+
import processors.propertymanager as pm
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class CSVContentsManager:
|
|
6
|
+
|
|
7
|
+
# Manages the contents of a .CSV file
|
|
8
|
+
# Returns the data requested by the Processor classes
|
|
9
|
+
|
|
10
|
+
def __init__(self, csv_data, header_mappings, alias_mappings, default_data_type):
|
|
11
|
+
file_headers = next(csv_data)
|
|
12
|
+
self.data_list = list(csv_data)
|
|
13
|
+
unmapped_keys = []
|
|
14
|
+
mapped_keys = []
|
|
15
|
+
self.formats = []
|
|
16
|
+
self.types = []
|
|
17
|
+
|
|
18
|
+
def split_header(header):
|
|
19
|
+
# Format of header is key[:format][:type]
|
|
20
|
+
# If there is only one of [:format] and [:type], look to see if the value is in amu.all_types
|
|
21
|
+
# If it is, treat it as a type, otherwise as a format
|
|
22
|
+
|
|
23
|
+
format = ''
|
|
24
|
+
type = ''
|
|
25
|
+
header_parts = header.split(':')
|
|
26
|
+
key = header_parts[0].replace('\ufeff', '')
|
|
27
|
+
if len(header_parts) == 3:
|
|
28
|
+
format = ':' + header_parts[1]
|
|
29
|
+
type = ':' + header_parts[2]
|
|
30
|
+
elif len(header_parts) == 2:
|
|
31
|
+
part = header_parts[1]
|
|
32
|
+
if part and part in amu.all_types:
|
|
33
|
+
type = ':' + part
|
|
34
|
+
else:
|
|
35
|
+
format = ':' + part
|
|
36
|
+
|
|
37
|
+
return key, format, type
|
|
38
|
+
|
|
39
|
+
for header in file_headers:
|
|
40
|
+
|
|
41
|
+
this_key, this_format, this_type = split_header(header)
|
|
42
|
+
unmapped_keys += [this_key]
|
|
43
|
+
|
|
44
|
+
# Now apply key mappings from config file
|
|
45
|
+
if this_key in header_mappings:
|
|
46
|
+
mapped_key = header_mappings[this_key]
|
|
47
|
+
elif this_key + this_format in header_mappings:
|
|
48
|
+
mapped_key = header_mappings[this_key + this_format]
|
|
49
|
+
elif this_key + this_type in header_mappings:
|
|
50
|
+
mapped_key = header_mappings[this_key + this_type]
|
|
51
|
+
elif this_key + this_format + this_type in header_mappings:
|
|
52
|
+
mapped_key = header_mappings[this_key + this_format + this_type]
|
|
53
|
+
else:
|
|
54
|
+
mapped_key = this_key
|
|
55
|
+
|
|
56
|
+
if this_key in alias_mappings:
|
|
57
|
+
alias_mapped_key = alias_mappings[this_key]
|
|
58
|
+
else:
|
|
59
|
+
alias_mapped_key = this_key
|
|
60
|
+
|
|
61
|
+
if this_key != alias_mapped_key:
|
|
62
|
+
this_mapped_key = alias_mapped_key
|
|
63
|
+
elif this_key != mapped_key:
|
|
64
|
+
this_mapped_key, this_format, this_type = split_header(mapped_key)
|
|
65
|
+
else:
|
|
66
|
+
this_mapped_key = this_key
|
|
67
|
+
|
|
68
|
+
mapped_keys += [this_mapped_key]
|
|
69
|
+
|
|
70
|
+
self.formats += [this_format]
|
|
71
|
+
self.types += [this_type]
|
|
72
|
+
|
|
73
|
+
self.unmapped_keys = pm.validate_properties(unmapped_keys)
|
|
74
|
+
self.mapped_keys = pm.validate_properties(mapped_keys)
|
|
75
|
+
|
|
76
|
+
def get_row_count(self):
|
|
77
|
+
return len(self.data_list)
|
|
78
|
+
|
|
79
|
+
def get_column_count(self, column_name, type_list=[]):
|
|
80
|
+
# Find the number of columns in the files whose heading is in the provided list
|
|
81
|
+
return len(self.get_column_numbers_list(column_name, type_list))
|
|
82
|
+
|
|
83
|
+
def get_column_numbers_list(self, column_name, type_list=[]):
|
|
84
|
+
# Return a List containing the column numbers for each column in the given list of column names
|
|
85
|
+
if not(isinstance(column_name, list)):
|
|
86
|
+
name_list = [column_name]
|
|
87
|
+
else:
|
|
88
|
+
name_list = column_name
|
|
89
|
+
column_list = [i for i, j in enumerate(self.mapped_keys) if (j in name_list or len(set(self.types[i].split(':')).intersection(set(type_list))) != 0)]
|
|
90
|
+
return column_list
|
|
91
|
+
|
|
92
|
+
def get_other_column_numbers_list(self, column_name, type_list=[]):
|
|
93
|
+
# Return a List containing the column numbers for each column NOT in the given list of column names
|
|
94
|
+
if not(isinstance(column_name, list)):
|
|
95
|
+
name_list = [column_name]
|
|
96
|
+
else:
|
|
97
|
+
name_list = column_name
|
|
98
|
+
column_list = [i for i, j in enumerate(self.mapped_keys) if not(j in name_list or len(set(self.types[i].split(':')).intersection(set(type_list))) != 0)]
|
|
99
|
+
return column_list
|
|
100
|
+
|
|
101
|
+
def get_incomplete_rows(self):
|
|
102
|
+
num_headers = len(self.mapped_keys)
|
|
103
|
+
incomplete_rows = []
|
|
104
|
+
row_count = 0
|
|
105
|
+
for a_row in self.data_list:
|
|
106
|
+
row_count += 1
|
|
107
|
+
if len(a_row) < num_headers:
|
|
108
|
+
incomplete_rows.append(row_count)
|
|
109
|
+
return incomplete_rows
|
|
110
|
+
|
|
111
|
+
def get_column_values_list(self, row_number, column_numbers):
|
|
112
|
+
# Return the values in the given row, for the columns in the provided list (skips empty values)
|
|
113
|
+
# Returned as a List (of strings)
|
|
114
|
+
this_row = self.data_list[row_number]
|
|
115
|
+
columns_list = [this_row[i] for i in column_numbers if len(this_row[i]) > 0]
|
|
116
|
+
return columns_list
|
|
117
|
+
|
|
118
|
+
def get_column_values_list_with_formatted_keys(self, row_number, column_numbers):
|
|
119
|
+
# Return the values in the given row, for the columns in the provided list (skips empty values)
|
|
120
|
+
# Returned as a List (of strings)
|
|
121
|
+
this_row = self.data_list[row_number]
|
|
122
|
+
properties_list = [{self.mapped_keys[column]+self.formats[column]:this_row[column]} for column in column_numbers if len(this_row[column])]
|
|
123
|
+
return properties_list
|
|
124
|
+
|
|
125
|
+
def get_property_values_dict(self, row_number, column_numbers, allow_blank_property_list, default_key='', prefix=''):
|
|
126
|
+
this_row = self.data_list[row_number]
|
|
127
|
+
split_values = [this_row[column].split('::') for column in column_numbers]
|
|
128
|
+
this_list = {prefix + (self.mapped_keys[column] or default_key) + self.formats[column]: this_row[column] if len(split_values[count]) == 1 else {prefix + split_values[count][0] + self.formats[column]: split_values[count][1]} for count, column in enumerate(column_numbers) if this_row[column] or self.mapped_keys[column] in allow_blank_property_list or allow_blank_property_list == []}
|
|
129
|
+
return this_list
|
|
130
|
+
|
|
131
|
+
def get_property_values_list(self, row_number, column_numbers, default_key='', override_key=''):
|
|
132
|
+
this_row = self.data_list[row_number]
|
|
133
|
+
split_values = [this_row[column].split('::') for column in column_numbers]
|
|
134
|
+
this_list = [{(override_key or self.mapped_keys[column] or default_key) + self.formats[column]: this_row[column]} if len(split_values[count]) == 1 else {split_values[count][0] + self.formats[column]: split_values[count][1]} for count, column in enumerate(column_numbers) if this_row[column]]
|
|
135
|
+
return this_list
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import csv
|
|
2
|
+
from queries.query import Neo4jQuery
|
|
3
|
+
from queries.cypherbuilder import QueryBuilder, ValidAfterWhere
|
|
4
|
+
from queries.typedefs import *
|
|
5
|
+
from messages import *
|
|
6
|
+
import assetmodelutilities as amu
|
|
7
|
+
from processors import labelmanager as lm
|
|
8
|
+
|
|
9
|
+
class CSVFileWriter:
|
|
10
|
+
|
|
11
|
+
def __init__(self, config_manager, db_connector):
|
|
12
|
+
self.db_connector = db_connector
|
|
13
|
+
self.config_manager = config_manager
|
|
14
|
+
|
|
15
|
+
self.write_node_file = config_manager.get_node_csvfile_requested()
|
|
16
|
+
self.node_labels = config_manager.get_node_csv_labels()
|
|
17
|
+
self.csv_node_primary_property = config_manager.get_csv_node_property_list()
|
|
18
|
+
self.file_suffix = config_manager.get_csv_file_suffix()
|
|
19
|
+
self.write_relationship_file = config_manager.get_relationship_csvfile_requested()
|
|
20
|
+
self.to_labels = config_manager.get_to_csv_labels()
|
|
21
|
+
self.csv_to_primary_property = config_manager.get_csv_to_property_list()
|
|
22
|
+
if self.csv_to_primary_property != self.csv_node_primary_property:
|
|
23
|
+
self.to_prefix = self.csv_to_primary_property + '::'
|
|
24
|
+
else:
|
|
25
|
+
self.to_prefix = ''
|
|
26
|
+
|
|
27
|
+
self.batch_size = config_manager.get_batch_rate()
|
|
28
|
+
if self.batch_size == 0:
|
|
29
|
+
self.batch_size = 100
|
|
30
|
+
|
|
31
|
+
self.required_labels = config_manager.get_required_labels()
|
|
32
|
+
self.primary_property = config_manager.get_primary_property()
|
|
33
|
+
self.unique_id_property = config_manager.get_unique_id_property()
|
|
34
|
+
self.version_labels = config_manager.get_version_labels_list()
|
|
35
|
+
|
|
36
|
+
self.relationship_alias = config_manager.get_relationship_alias()[0]
|
|
37
|
+
self.from_alias = config_manager.get_from_alias()[0]
|
|
38
|
+
self.to_alias = config_manager.get_to_alias()[0]
|
|
39
|
+
self.node_label = config_manager.get_label_alias()[0]
|
|
40
|
+
self.from_label = config_manager.get_from_label_alias()[0]
|
|
41
|
+
self.to_label = config_manager.get_to_label_alias()[0]
|
|
42
|
+
|
|
43
|
+
self.all_keys = [self.node_label]
|
|
44
|
+
self.all_nodes = []
|
|
45
|
+
self.all_relationship_keys = [self.from_alias, self.to_alias, self.from_label, self.to_label, self.relationship_alias]
|
|
46
|
+
self.all_relationships = []
|
|
47
|
+
|
|
48
|
+
def pop_property(self, dictionary, property):
|
|
49
|
+
try:
|
|
50
|
+
dictionary.pop(property)
|
|
51
|
+
except:
|
|
52
|
+
pass
|
|
53
|
+
|
|
54
|
+
def find_property(self, data, options):
|
|
55
|
+
value = ''
|
|
56
|
+
key = self.primary_property
|
|
57
|
+
all_options = [self.primary_property, *options]
|
|
58
|
+
for option in all_options:
|
|
59
|
+
try:
|
|
60
|
+
value = data[option]
|
|
61
|
+
if option != self.primary_property:
|
|
62
|
+
value = option + '::' + value
|
|
63
|
+
key = option
|
|
64
|
+
break
|
|
65
|
+
except:
|
|
66
|
+
pass
|
|
67
|
+
|
|
68
|
+
return value, key
|
|
69
|
+
|
|
70
|
+
def write_data(self):
|
|
71
|
+
|
|
72
|
+
if self.write_node_file:
|
|
73
|
+
def_path = self.config_manager.get_default_path()
|
|
74
|
+
suffix = self.file_suffix
|
|
75
|
+
# label_suffix = '-'.join(label_set)
|
|
76
|
+
# output_file = def_path + 'Nodes ' + suffix + '-' + label_suffix.replace(':', '-') + '.csv'
|
|
77
|
+
output_file = def_path + 'Nodes ' + suffix
|
|
78
|
+
|
|
79
|
+
try:
|
|
80
|
+
with open(output_file+'.csv', 'w', newline='') as f:
|
|
81
|
+
writer = csv.DictWriter(f, fieldnames=self.all_keys, delimiter=';', quoting=csv.QUOTE_MINIMAL)
|
|
82
|
+
writer.writeheader()
|
|
83
|
+
writer.writerows(self.all_nodes)
|
|
84
|
+
except:
|
|
85
|
+
try:
|
|
86
|
+
with open(output_file+'.csv', 'w', encoding='UTF8', newline='') as f:
|
|
87
|
+
writer = csv.DictWriter(f, fieldnames=self.all_keys, delimiter=';', quoting=csv.QUOTE_MINIMAL)
|
|
88
|
+
writer.writeheader()
|
|
89
|
+
writer.writerows(self.all_nodes)
|
|
90
|
+
except:
|
|
91
|
+
pass
|
|
92
|
+
|
|
93
|
+
if self.write_relationship_file:
|
|
94
|
+
def_path = self.config_manager.get_default_path()
|
|
95
|
+
suffix = self.file_suffix
|
|
96
|
+
output_file = def_path + 'Relationships ' + suffix
|
|
97
|
+
|
|
98
|
+
try:
|
|
99
|
+
with open(output_file+'.csv', 'w', newline='') as f:
|
|
100
|
+
writer = csv.DictWriter(f, fieldnames=self.all_relationship_keys, delimiter=';', quoting=csv.QUOTE_MINIMAL)
|
|
101
|
+
writer.writeheader()
|
|
102
|
+
writer.writerows(self.all_relationships)
|
|
103
|
+
except:
|
|
104
|
+
try:
|
|
105
|
+
with open(output_file+'.csv', 'w', encoding='UTF8', newline='') as f:
|
|
106
|
+
writer = csv.DictWriter(f, fieldnames=self.all_relationship_keys, delimiter=';', quoting=csv.QUOTE_MINIMAL)
|
|
107
|
+
writer.writeheader()
|
|
108
|
+
writer.writerows(self.all_relationships)
|
|
109
|
+
except:
|
|
110
|
+
pass
|
|
111
|
+
|
|
112
|
+
def update_node_data(self, data):
|
|
113
|
+
|
|
114
|
+
for node in data:
|
|
115
|
+
|
|
116
|
+
properties = node['Properties']
|
|
117
|
+
properties[self.node_label] = lm.validate_output_labels(node['FromLabels'])
|
|
118
|
+
|
|
119
|
+
self.pop_property(properties, self.config_manager.get_update_time_property())
|
|
120
|
+
self.pop_property(properties, self.config_manager.get_creation_time_property())
|
|
121
|
+
try:
|
|
122
|
+
self.pop_property(properties, self.config_manager.get_version_counter())
|
|
123
|
+
except:
|
|
124
|
+
pass
|
|
125
|
+
|
|
126
|
+
primary_property_val, primary_key = self.find_property(properties, self.csv_node_primary_property)
|
|
127
|
+
properties[self.primary_property] = primary_property_val
|
|
128
|
+
|
|
129
|
+
if primary_key != self.primary_property:
|
|
130
|
+
properties.pop(primary_key)
|
|
131
|
+
if primary_key in self.all_keys:
|
|
132
|
+
self.all_keys.remove(primary_key)
|
|
133
|
+
|
|
134
|
+
these_keys = properties.keys()
|
|
135
|
+
self.all_keys = list(set([*these_keys, *self.all_keys]))
|
|
136
|
+
self.all_nodes.append(properties)
|
|
137
|
+
|
|
138
|
+
def update_relationship_data(self, data):
|
|
139
|
+
|
|
140
|
+
for relationship in data:
|
|
141
|
+
if relationship['Relationship']:
|
|
142
|
+
properties = relationship['RelationshipProperties']
|
|
143
|
+
|
|
144
|
+
properties[self.from_alias] = relationship['From']
|
|
145
|
+
properties[self.to_alias] = self.to_prefix + relationship['To']
|
|
146
|
+
properties[self.from_label] = lm.validate_output_labels(relationship['FromLabels'])
|
|
147
|
+
properties[self.to_label] = lm.validate_output_labels(relationship['ToLabels'])
|
|
148
|
+
properties[self.relationship_alias] = relationship['Relationship']
|
|
149
|
+
|
|
150
|
+
self.pop_property(properties, self.config_manager.get_update_time_property())
|
|
151
|
+
self.pop_property(properties, self.config_manager.get_creation_time_property())
|
|
152
|
+
|
|
153
|
+
if properties[self.from_alias] and properties[self.to_alias]:
|
|
154
|
+
these_keys = properties.keys()
|
|
155
|
+
self.all_relationship_keys = list(set([*these_keys, *self.all_relationship_keys]))
|
|
156
|
+
self.all_relationships.append(properties)
|
|
157
|
+
|
|
158
|
+
def combine_labels(self, label_set):
|
|
159
|
+
query_labels = []
|
|
160
|
+
if label_set:
|
|
161
|
+
requested_labels = label_set[1:].split(':')
|
|
162
|
+
|
|
163
|
+
required_labels = list({i for i in self.required_labels if (not (i.startswith('!') and ('!' + i not in self.required_labels)) and ('!' + i not in requested_labels))} | {i for i in requested_labels if not i.startswith('!')})
|
|
164
|
+
unwanted_labels = list({i[1:] for i in self.required_labels if (i.startswith('!') and (i[1:] not in requested_labels) and ('!' + i) not in requested_labels)} | {i[1:] for i in requested_labels if i.startswith('!') and not i.startswith('!!')})
|
|
165
|
+
query_labels.append([required_labels, unwanted_labels])
|
|
166
|
+
else:
|
|
167
|
+
query_labels = [i for i in self.required_labels if (not ('!' + i in self.required_labels) and not (i.startswith('!')) and i != '')]
|
|
168
|
+
query_labels = [[query_labels, []]]
|
|
169
|
+
|
|
170
|
+
return query_labels
|
|
171
|
+
|
|
172
|
+
def make_get_nodes_query(self, labels, list_name):
|
|
173
|
+
|
|
174
|
+
node_ref = 'gn'
|
|
175
|
+
incl_labels = labels[0]
|
|
176
|
+
excl_labels = labels[1]
|
|
177
|
+
where_literal = f'NOT {node_ref}:' + f' AND NOT {node_ref}:'.join(excl_labels)
|
|
178
|
+
response_text = f'{node_ref}.{self.csv_node_primary_property} AS {list_name}'
|
|
179
|
+
|
|
180
|
+
node_query_text = (QueryBuilder()
|
|
181
|
+
.match()
|
|
182
|
+
.node(labels=incl_labels, ref_name=node_ref)
|
|
183
|
+
)
|
|
184
|
+
if excl_labels:
|
|
185
|
+
node_query_text = node_query_text.where_literal(where_literal)
|
|
186
|
+
|
|
187
|
+
node_query_text = node_query_text.return_literal(response_text).toStr()
|
|
188
|
+
node_query = Neo4jQuery('get node list', node_query_text)
|
|
189
|
+
|
|
190
|
+
return node_query
|
|
191
|
+
|
|
192
|
+
def make_base_queries(self, labels, to_labels):
|
|
193
|
+
|
|
194
|
+
node_ref = 'cn'
|
|
195
|
+
from_node_ref = 'cfrom'
|
|
196
|
+
to_node_ref = 'cto'
|
|
197
|
+
rel_ref = 'crel'
|
|
198
|
+
|
|
199
|
+
incl_labels = labels[0]
|
|
200
|
+
excl_labels = labels[1]
|
|
201
|
+
to_incl_labels = to_labels[0]
|
|
202
|
+
to_excl_labels = to_labels[1]
|
|
203
|
+
|
|
204
|
+
where_literal = f'NOT {node_ref}:' + f' AND NOT {node_ref}:'.join(excl_labels)
|
|
205
|
+
to_where_literal = f'NOT {to_node_ref}:' + f' AND NOT {to_node_ref}:'.join(to_excl_labels)
|
|
206
|
+
|
|
207
|
+
node_query = (QueryBuilder()
|
|
208
|
+
.match()
|
|
209
|
+
.node(labels=incl_labels, ref_name=node_ref)
|
|
210
|
+
)
|
|
211
|
+
if excl_labels:
|
|
212
|
+
node_query = node_query.where_literal(where_literal)
|
|
213
|
+
|
|
214
|
+
node_response_text = f'{node_ref}{{.*}} as Properties, ' \
|
|
215
|
+
f'labels({node_ref}) AS FromLabels'
|
|
216
|
+
# f'{node_ref}.{self.csv_node_primary_property} AS From, ' \
|
|
217
|
+
|
|
218
|
+
relationship_query = (QueryBuilder()
|
|
219
|
+
.match_optional()
|
|
220
|
+
.node(ref_name=node_ref)
|
|
221
|
+
.related_to(ref_name=rel_ref)
|
|
222
|
+
.node(labels=to_incl_labels, ref_name=to_node_ref)
|
|
223
|
+
)
|
|
224
|
+
if to_excl_labels:
|
|
225
|
+
relationship_query = relationship_query.where_literal(to_where_literal)
|
|
226
|
+
|
|
227
|
+
relationship_response_text = f'{node_ref}.{self.csv_node_primary_property} AS From, ' \
|
|
228
|
+
f'{to_node_ref}.{self.csv_to_primary_property} AS To, ' \
|
|
229
|
+
f'labels({node_ref}) AS FromLabels, ' \
|
|
230
|
+
f'labels({to_node_ref}) AS ToLabels, ' \
|
|
231
|
+
f'type({rel_ref}) AS Relationship, ' \
|
|
232
|
+
f'{rel_ref}{{.*}} AS RelationshipProperties'
|
|
233
|
+
|
|
234
|
+
return node_query, node_response_text, relationship_query, relationship_response_text
|
|
235
|
+
|
|
236
|
+
def process_data(self, node_list, label_set, to_label_set):
|
|
237
|
+
|
|
238
|
+
num_nodes = len(node_list)
|
|
239
|
+
node_query, node_response_text, relationship_query, relationship_response_text = self.make_base_queries(label_set, to_label_set)
|
|
240
|
+
num_batches = int((num_nodes - 1) / self.batch_size) + 1
|
|
241
|
+
batch_num = 0
|
|
242
|
+
while batch_num < num_batches:
|
|
243
|
+
num_none = 0
|
|
244
|
+
message_no_cr(f'Processing batch {batch_num+1} of {num_batches} at {amu.get_formatted_time_now_noms()}{chr(13)}')
|
|
245
|
+
this_batch = node_list[batch_num * self.batch_size:(batch_num + 1) * self.batch_size]
|
|
246
|
+
while None in this_batch:
|
|
247
|
+
this_batch.remove(None)
|
|
248
|
+
num_none += 1
|
|
249
|
+
where_tests = {'cn.' + self.csv_node_primary_property: this_batch}
|
|
250
|
+
|
|
251
|
+
if 'WHERE' in node_query.toStr():
|
|
252
|
+
this_query = node_query.where_additional(Properties(where_tests), ' IN ', ' AND ')
|
|
253
|
+
else:
|
|
254
|
+
this_query = node_query.where_multiple(Properties(where_tests), ' IN ', ' AND ')
|
|
255
|
+
|
|
256
|
+
if self.write_node_file:
|
|
257
|
+
this_query_text = this_query.return_literal(node_response_text).toStr().replace('\\"', '"')
|
|
258
|
+
this_node_query = Neo4jQuery('get data', this_query_text)
|
|
259
|
+
result = self.db_connector.execute(this_node_query)
|
|
260
|
+
response = result.get_response()
|
|
261
|
+
if response:
|
|
262
|
+
self.update_node_data(response)
|
|
263
|
+
|
|
264
|
+
if self.write_relationship_file:
|
|
265
|
+
this_query_text = this_query.toStr().replace('\\"', '"') + ' ' + relationship_query.return_literal(relationship_response_text).toStr()
|
|
266
|
+
this_relationship_query = Neo4jQuery('get data', this_query_text)
|
|
267
|
+
result = self.db_connector.execute(this_relationship_query)
|
|
268
|
+
response = result.get_response()
|
|
269
|
+
if response:
|
|
270
|
+
self.update_relationship_data(response)
|
|
271
|
+
|
|
272
|
+
batch_num += 1
|
|
273
|
+
|
|
274
|
+
message('', False)
|
|
275
|
+
self.write_data()
|
|
276
|
+
|
|
277
|
+
def get_node_list(self, label_set):
|
|
278
|
+
|
|
279
|
+
list_name = 'NodeList'
|
|
280
|
+
nodes_query = self.make_get_nodes_query(label_set, list_name)
|
|
281
|
+
result = self.db_connector.execute(nodes_query)
|
|
282
|
+
response = result.get_response()
|
|
283
|
+
try:
|
|
284
|
+
nodes_found = [i[list_name] for i in response]
|
|
285
|
+
except:
|
|
286
|
+
nodes_found = 0
|
|
287
|
+
|
|
288
|
+
return nodes_found
|
|
289
|
+
|
|
290
|
+
def write_csv_files(self):
|
|
291
|
+
if self.write_node_file or self.write_relationship_file:
|
|
292
|
+
wanted_labels, unwanted_labels = lm.sort_output_labels(self.node_labels, self.version_labels)
|
|
293
|
+
wanted_to_labels, unwanted_to_labels = lm.sort_output_labels(self.to_labels, self.version_labels)
|
|
294
|
+
node_list = self.get_node_list([wanted_labels, unwanted_labels])
|
|
295
|
+
num_nodes_found = len(node_list)
|
|
296
|
+
if num_nodes_found == 1:
|
|
297
|
+
intro = 'There is 1 node'
|
|
298
|
+
else:
|
|
299
|
+
intro = f'There are {num_nodes_found} nodes'
|
|
300
|
+
print(f'{intro} with :{":".join(lm.strip_quotes(wanted_labels))}', end='')
|
|
301
|
+
if unwanted_labels:
|
|
302
|
+
print(f' but not :{" nor :".join(lm.strip_quotes(unwanted_labels))}')
|
|
303
|
+
else:
|
|
304
|
+
print()
|
|
305
|
+
self.process_data(node_list, [wanted_labels, unwanted_labels], [wanted_to_labels, unwanted_to_labels])
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import csv
|
|
2
|
+
|
|
3
|
+
import messages
|
|
4
|
+
from csvcontentsmanager import CSVContentsManager
|
|
5
|
+
import assetmodelutilities as amu
|
|
6
|
+
|
|
7
|
+
class FileAnalyser():
|
|
8
|
+
|
|
9
|
+
def __init__(self, config):
|
|
10
|
+
self.separator = config.get_separator()
|
|
11
|
+
self.def_path = config.get_default_path()
|
|
12
|
+
|
|
13
|
+
self.header_mappings, self.alias_mappings = config.get_header_mappings()
|
|
14
|
+
self.default_data_type = config.get_default_data_type()
|
|
15
|
+
|
|
16
|
+
self.node_alias = config.get_node_alias()
|
|
17
|
+
self.from_node_alias = config.get_from_alias()
|
|
18
|
+
self.to_node_alias = config.get_to_alias()
|
|
19
|
+
self.relationship_alias = config.get_relationship_alias()
|
|
20
|
+
self.ignore_nodes = config.get_ignore_nodes()
|
|
21
|
+
|
|
22
|
+
self.node_types = amu.node_types
|
|
23
|
+
self.from_types = amu.from_types
|
|
24
|
+
self.to_types = amu.to_types
|
|
25
|
+
self.relation_types = amu.relation_types
|
|
26
|
+
self.label_types = amu.label_types
|
|
27
|
+
self.all_types = amu.all_types
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def determine_file_type(self, filename, file_format):
|
|
31
|
+
|
|
32
|
+
contents = None
|
|
33
|
+
file_name = amu.find_file(self.def_path, filename)
|
|
34
|
+
if file_name is None:
|
|
35
|
+
return 'fnf', contents, []
|
|
36
|
+
|
|
37
|
+
match file_format:
|
|
38
|
+
case 'csv':
|
|
39
|
+
try:
|
|
40
|
+
with open(file_name, encoding='utf8') as csv_file:
|
|
41
|
+
csv_data = csv.reader(csv_file, delimiter=self.separator)
|
|
42
|
+
contents = CSVContentsManager(csv_data, self.header_mappings, self.alias_mappings, self.default_data_type)
|
|
43
|
+
except:
|
|
44
|
+
try:
|
|
45
|
+
with open(file_name) as csv_file:
|
|
46
|
+
csv_data = csv.reader(csv_file, delimiter=self.separator)
|
|
47
|
+
contents = CSVContentsManager(csv_data, self.header_mappings, self.alias_mappings, self.default_data_type)
|
|
48
|
+
except:
|
|
49
|
+
return 'incorrect file format', contents, []
|
|
50
|
+
case _:
|
|
51
|
+
pass
|
|
52
|
+
|
|
53
|
+
num_node_columns = contents.get_column_count(self.node_alias, self.node_types)
|
|
54
|
+
num_from_columns = contents.get_column_count(self.from_node_alias, self.from_types)
|
|
55
|
+
num_to_columns = contents.get_column_count(self.to_node_alias, self.to_types)
|
|
56
|
+
num_relation_columns = contents.get_column_count(self.relationship_alias, self.relation_types)
|
|
57
|
+
|
|
58
|
+
incomplete_rows = contents.get_incomplete_rows()
|
|
59
|
+
if len(incomplete_rows) > 0:
|
|
60
|
+
return 'incomplete row(s)', contents, incomplete_rows
|
|
61
|
+
|
|
62
|
+
# If there is a least one Node (including aliases) column, this could be a Node file
|
|
63
|
+
if num_node_columns > 0:
|
|
64
|
+
could_be_node = True
|
|
65
|
+
if num_node_columns > 1:
|
|
66
|
+
messages.warning_message(f'Multiple node columns found in ', f'{filename}')
|
|
67
|
+
else:
|
|
68
|
+
could_be_node = False
|
|
69
|
+
|
|
70
|
+
# Check if there are at least one each of From, To and Relationship (including aliases) columns
|
|
71
|
+
# If so, this could be a Relationship file
|
|
72
|
+
if num_from_columns > 0 and num_to_columns > 0 and num_relation_columns > 0:
|
|
73
|
+
could_be_relations = True
|
|
74
|
+
else:
|
|
75
|
+
could_be_relations = False
|
|
76
|
+
|
|
77
|
+
if could_be_node:
|
|
78
|
+
if could_be_relations:
|
|
79
|
+
if self.ignore_nodes:
|
|
80
|
+
file_type = 'relationships'
|
|
81
|
+
else:
|
|
82
|
+
file_type = 'both'
|
|
83
|
+
else:
|
|
84
|
+
file_type = 'nodes'
|
|
85
|
+
else:
|
|
86
|
+
if could_be_relations:
|
|
87
|
+
file_type = 'relationships'
|
|
88
|
+
else:
|
|
89
|
+
file_type = 'neither'
|
|
90
|
+
|
|
91
|
+
return file_type, contents, []
|