python-eigen-ingenuity-nocli 0.5.27__py3-none-any.whl → 0.5.28__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.
@@ -7,6 +7,7 @@ sys.path.append(current_dir)
7
7
  from configmanager import ConfigManager
8
8
  from connectors.dbconnectors import ConnectionManager
9
9
  from filemanager import FileManager
10
+ from querymanager import QueryManager
10
11
 
11
12
  import sys
12
13
  import inspect
@@ -146,8 +147,11 @@ def _asset_model_builder_():
146
147
  if config_manager.get_error_count() > 0:
147
148
  sys.exit()
148
149
 
150
+ # Create a Query Manager
151
+ query_manager = QueryManager(config_manager.get_parameters())
152
+
149
153
  # Create a csv file Manager to process all the input files
150
- file_manager = FileManager(config_manager)
154
+ file_manager = FileManager(config_manager, query_manager)
151
155
  file_manager.analyse_files()
152
156
 
153
157
  # Create a connection to the database
@@ -211,7 +211,7 @@ class ConfigManager:
211
211
  except:
212
212
  database_num = None
213
213
 
214
- if not (database_num is None):
214
+ if database_num is not None:
215
215
  # Database number provided, so check if it's valid
216
216
  if database_num < len(database_name_list):
217
217
  database_index = database_num
@@ -312,6 +312,25 @@ class ConfigManager:
312
312
  except:
313
313
  self.alias_header_mappings_dict[s] = {}
314
314
 
315
+ # Read lists of parameters
316
+ params = {s: self.get_config_value_list(s, "Parameters", "") for s in self.available_sections}
317
+ self.parameters = {}
318
+ this_parm = ''
319
+ parm_list = []
320
+ for s in self.available_sections:
321
+ self.parameters[s] = {}
322
+ for parm in params[s]:
323
+ parm = parm.strip()
324
+ if parm[0] == '$':
325
+ if this_parm != '':
326
+ self.parameters[s][this_parm] = parm_list
327
+ this_parm = parm.split(':')[0][1:]
328
+ parm_list = [parm.split(':')[1]]
329
+ else:
330
+ parm_list.append(parm)
331
+ if this_parm != '':
332
+ self.parameters[s][this_parm] = parm_list
333
+
315
334
  def get_error_list(self):
316
335
  return self.error_list
317
336
 
@@ -593,3 +612,6 @@ class ConfigManager:
593
612
  for error in self.error_list:
594
613
  error_message(error)
595
614
  return len(self.error_list)
615
+
616
+ def get_parameters(self):
617
+ return self.parameters
@@ -1,5 +1,4 @@
1
1
  import assetmodelutilities as amu
2
- import processors.propertymanager as pm
3
2
  from property import Neo4jProperty
4
3
 
5
4
  class CSVContentsManager:
@@ -11,8 +11,9 @@ import os
11
11
 
12
12
  class FileManager:
13
13
 
14
- def __init__(self, config_manager):
14
+ def __init__(self, config_manager, query_manager):
15
15
  self.config_manager = config_manager
16
+ self.query_manager = query_manager
16
17
  self.validation_mode = config_manager.in_validation_mode()
17
18
  self.report_queries = config_manager.get_show_query()
18
19
  self.show_progress = config_manager.get_display_rate()
@@ -47,6 +48,8 @@ class FileManager:
47
48
  self.file_analysers = {s: FileAnalyser(config_manager, s) for s in config_manager.get_available_sections()}
48
49
  self.version_managers = {s: VersionManager(config_manager, s) for s in config_manager.get_available_sections()}
49
50
 
51
+ self.batch_debug = False
52
+
50
53
  def check_section(self, in_file, empty_section_response):
51
54
  file = in_file.split('#')[0].strip()
52
55
  if file.startswith('#') or file == '':
@@ -225,19 +228,19 @@ class FileManager:
225
228
  config_section = 'DEFAULT'
226
229
  if config_section not in self.config_manager.get_available_sections():
227
230
  # Use NodeFileProcessor as placeholder. It won't be used, other than to process the errors
228
- this_csv_file_processor = NodeFileProcessor(csv_file, self.config_manager, None, 'DEFAULT')
231
+ this_csv_file_processor = NodeFileProcessor(csv_file, self.config_manager, None, 'DEFAULT', self.query_manager)
229
232
  self.add_file_to_list(this_csv_file_processor, 'invalid config section', [])
230
233
  else:
231
234
  # Analyse each of the specified input .csv files to determine if they contain Nodes or Relationships
232
235
  # If the file doesn't have a valid combination of columns (or is missing) they are placed in the appropriate list
233
236
  this_csv_file_type, csv_contents, file_errors = self.file_analysers[config_section].determine_file_type(csv_file, 'csv')
234
237
  if this_csv_file_type == 'nodes':
235
- this_csv_file_processor = NodeFileProcessor(csv_file, self.config_manager, csv_contents, config_section)
238
+ this_csv_file_processor = NodeFileProcessor(csv_file, self.config_manager, csv_contents, config_section, self.query_manager)
236
239
  elif this_csv_file_type == 'relationships':
237
- this_csv_file_processor = RelationshipFileProcessor(csv_file, self.config_manager, csv_contents, config_section)
240
+ this_csv_file_processor = RelationshipFileProcessor(csv_file, self.config_manager, csv_contents, config_section, self.query_manager)
238
241
  else:
239
242
  # Use NodeFileProcessor as placeholder. It won't be used, other than to process the errors
240
- this_csv_file_processor = NodeFileProcessor(csv_file, self.config_manager, csv_contents, config_section)
243
+ this_csv_file_processor = NodeFileProcessor(csv_file, self.config_manager, csv_contents, config_section, self.query_manager)
241
244
  self.add_file_to_list(this_csv_file_processor, this_csv_file_type, file_errors)
242
245
 
243
246
  def analyse_cypher_file(self, query_file):
@@ -390,8 +393,9 @@ class FileManager:
390
393
  except:
391
394
  display_rate = 0
392
395
 
393
- ## total_new_nodes = 0
394
- ## total_new_relationships = 0
396
+ if self.batch_debug:
397
+ total_new_nodes = 0
398
+ total_new_relationships = 0
395
399
 
396
400
  if display_rate > 0:
397
401
  message(f'0 of {num_queries} queries processed at {amu.get_formatted_time_now()}', False)
@@ -413,14 +417,15 @@ class FileManager:
413
417
  if result.get_status() == 200:
414
418
 
415
419
  # Display info on how many of each batch were created
416
- ## new_nodes = result.get_updates()['nodes created']
417
- ## total_new_nodes += new_nodes
418
- ## new_relationships = result.get_updates()['relationships created']
419
- ## total_new_relationships += new_relationships
420
- ## if new_nodes > 0 or new_relationships > 0:
421
- ## if (query.type == 'batch node' and new_nodes != query.batch_size) or (query.type == 'batch relationship' and new_relationships != query.batch_size):
422
- ## info_message(f'Batch {query_count} contained {query.batch_size} updates: only {new_nodes+new_relationships} created')
423
- ## print(query.text)
420
+ if self.batch_debug:
421
+ new_nodes = result.get_updates()['nodes created']
422
+ total_new_nodes += new_nodes
423
+ new_relationships = result.get_updates()['relationships created']
424
+ total_new_relationships += new_relationships
425
+ if new_nodes > 0 or new_relationships > 0:
426
+ if (query.type == 'batch node' and new_nodes != query.batch_size) or (query.type == 'batch relationship' and new_relationships != query.batch_size):
427
+ info_message(f'Batch {query_count} contained {query.batch_size} updates: only {new_nodes+new_relationships} created')
428
+ print(query.text)
424
429
 
425
430
  if self.report_queries:
426
431
  result.print_results('Updates made: ')
@@ -456,9 +461,10 @@ class FileManager:
456
461
  if display_rate > 0 and not self.report_queries:
457
462
  if query_count % display_rate == 0 or query_count == num_queries:
458
463
  message(f'{query_count} of {num_queries} queries processed at {amu.get_formatted_time_now()} ({query_count / num_queries * 100:.2f}%)', False)
459
- ## message(f'{query_count} of {num_queries} queries processed at {amu.get_formatted_time_now()} ({query_count / num_queries * 100:.2f}%) Nodes: {total_new_nodes}, Relationships: {total_new_relationships}', False)
460
- ## total_new_nodes = 0
461
- ## total_new_relationships = 0
464
+ if self.batch_debug:
465
+ message(f'{query_count} of {num_queries} queries processed at {amu.get_formatted_time_now()} ({query_count / num_queries * 100:.2f}%) Nodes: {total_new_nodes}, Relationships: {total_new_relationships}', False)
466
+ total_new_nodes = 0
467
+ total_new_relationships = 0
462
468
  else:
463
469
  message_no_cr(f'{query_count} of {num_queries} queries processed ({batch_info}{query_count / num_queries * 100:.2f}%) {chr(13)}')
464
470
 
@@ -26,7 +26,7 @@ class CypherFileProcessor:
26
26
  entry_count = 0
27
27
  while entry_count < cypher_file_size:
28
28
  this_entry = cypher_list[entry_count].strip()
29
- if not this_entry.startswith('#') and not this_entry == '\n':
29
+ if not this_entry.startswith('#') and not this_entry == '\n' and not this_entry == '':
30
30
  next_query += this_entry + '\n'
31
31
  if not this_entry.endswith(',') and not this_entry.endswith('\\'):
32
32
  while next_query.endswith('\n'):
@@ -11,9 +11,11 @@ from property import Neo4jProperty
11
11
 
12
12
  class NodeFileProcessor:
13
13
 
14
- def __init__(self, filename, config, contents, section):
14
+ def __init__(self, filename, config, contents, section, query_manager):
15
15
  self.filename = filename
16
16
  self.contents = contents
17
+ self.section = section
18
+ self.query_manager = query_manager
17
19
 
18
20
  self.primary_property = config.get_primary_property()[section]
19
21
  self.add_system_properties = not config.get_no_system_properties()
@@ -41,8 +43,6 @@ class NodeFileProcessor:
41
43
  self.label_types = amu.label_types
42
44
  self.all_types = amu.all_types
43
45
 
44
- self.section = section
45
-
46
46
  def get_last_row(self, num_rows):
47
47
  if self.last_row < 0:
48
48
  last_row = num_rows
@@ -108,13 +108,12 @@ class NodeFileProcessor:
108
108
  query_text = query_text.set(properties=calculated_properties, property_ref=property_ref_dot)
109
109
 
110
110
  query_text = query_text.toStr()
111
-
112
- query = Neo4jQuery('node', query_text, time_now, merge_labels, new_labels, primary_property, properties, self.section)
113
-
114
- if self.validate_only and not self.summarise:
115
- print(query.text)
116
-
117
- queries.append(query)
111
+ query_list = self.query_manager.parameterise(query_text, self.section)
112
+ for a_query in query_list:
113
+ query = Neo4jQuery('node', a_query, time_now, merge_labels, new_labels, primary_property, properties, self.section)
114
+ if self.validate_only and not self.summarise:
115
+ print(a_query)
116
+ queries.append(query)
118
117
 
119
118
  this_row += 1
120
119
  messages.message_no_cr(f'Generating queries... {100 * (this_row - self.start_from + 1) / num_rows:.0f}%{chr(13)}')
@@ -170,8 +169,14 @@ class NodeFileProcessor:
170
169
  all_properties = pm.combine_properties(properties, primary_property_dict)
171
170
 
172
171
  explicit_properties, calculated_properties = pm.split_out_functional_properties(all_properties)
172
+ param_explicit_props = self.query_manager.parameterise_dict(explicit_properties, self.section)
173
+ param_calc_props = self.query_manager.parameterise_dict(calculated_properties, self.section)
174
+
175
+ query_data_list = []
176
+ for count in range(max(len(param_explicit_props), len(param_calc_props))):
177
+ query_data_list += [[param_explicit_props[min(count, len(param_explicit_props)-1)], param_calc_props[min(count, len(param_calc_props)-1)], time_now]]
173
178
 
174
- query_data = [explicit_properties, calculated_properties, time_now]
179
+ # prop_data = [explicit_properties, calculated_properties, time_now]
175
180
 
176
181
  # So now we know all about this particular update. Let's put it in the query dictionary
177
182
  # We'll group these by unique combinations of labels and primary key type
@@ -179,12 +184,12 @@ class NodeFileProcessor:
179
184
  dictionary_key = [new_labels, merge_labels, remove_labels, [primary_property.key], calculated_properties.keys()]
180
185
  try:
181
186
  dictionary_index = batch_keys.index(dictionary_key)
182
- query_dictionary[dictionary_index].append(query_data)
187
+ query_dictionary[dictionary_index] += query_data_list
183
188
  except:
184
189
  dictionary_index = len(batch_keys)
185
- query_dictionary[dictionary_index] = [query_data]
190
+ query_dictionary[dictionary_index] = query_data_list
186
191
  batch_keys.append(dictionary_key)
187
- dict_size += 1
192
+ dict_size += len(query_data_list)
188
193
 
189
194
  this_row += 1
190
195
  messages.message_no_cr(f'Analysing file... {100 * (this_row - self.start_from + 1) / num_rows:.0f}%{chr(13)}')
@@ -221,8 +226,9 @@ class NodeFileProcessor:
221
226
  formatted_payload = []
222
227
  property_count = 0
223
228
  for a_payload in payload:
224
- formatted_payload.append(property.format(a_payload, property_ref_dot))
225
- property_count += len(a_payload)
229
+ formatted_pload = property.format(a_payload, property_ref_dot, self.query_manager, self.section)
230
+ formatted_payload += formatted_pload
231
+ property_count += len(a_payload)*len(formatted_pload)
226
232
 
227
233
  # Build a MERGE query using queries
228
234
  merge_labels = batch_keys[new_labels][1]
@@ -11,10 +11,11 @@ from property import Neo4jProperty
11
11
 
12
12
  class RelationshipFileProcessor:
13
13
 
14
- def __init__(self, filename, config, contents, section):
14
+ def __init__(self, filename, config, contents, section, query_manager):
15
15
  self.filename = filename
16
16
  self.contents = contents
17
17
  self.section = section
18
+ self.query_manager = query_manager
18
19
 
19
20
  self.primary_property = config.get_primary_property()[section]
20
21
  self.add_system_properties = not config.get_no_system_properties()
@@ -130,12 +131,13 @@ class RelationshipFileProcessor:
130
131
  query_text = query_text.set(properties=calculated_properties, property_ref=relation_ref_dot)
131
132
 
132
133
  query_text = query_text.toStr()
133
- query = Neo4jQuery('relationship', query_text, time_now)
134
+ query_list = self.query_manager.parameterise(query_text, self.section)
134
135
 
135
- if self.validate_only and not self.summarise:
136
- print(query.text)
137
-
138
- queries.append(query)
136
+ for a_query in query_list:
137
+ query = Neo4jQuery('node', a_query, time_now)
138
+ if self.validate_only and not self.summarise:
139
+ print(a_query)
140
+ queries.append(query)
139
141
 
140
142
  this_row += 1
141
143
  messages.message_no_cr(f'Generating queries... {100 * (this_row - self.start_from + 1) / num_rows:.0f}%{chr(13)}')
@@ -172,6 +174,7 @@ class RelationshipFileProcessor:
172
174
  # Since the dictionary key can't be a list, we will create a list (of lists) and use the index in that list as the key
173
175
  # When we have worked through all the input and grouped the queries by label and relationship combinations, we will create the queries
174
176
 
177
+ new_labels_list = []
175
178
  batch_keys = []
176
179
  query_dictionary = {}
177
180
  dict_size = 0
@@ -203,18 +206,29 @@ class RelationshipFileProcessor:
203
206
  if relation:
204
207
 
205
208
  explicit_properties, calculated_properties = pm.split_out_functional_properties(properties)
206
- new_labels = [from_labels, to_labels, relation, from_node.key, to_node.key, calculated_properties]
207
- query_data = [from_node.value.replace('\\\\n', '\n'), to_node.value.replace('\\\\n', '\n'), explicit_properties, calculated_properties, time_now]
209
+
210
+ param_from_nodes = self.query_manager.parameterise_list([from_node], self.section)
211
+ param_to_nodes = self.query_manager.parameterise_list([to_node], self.section)
212
+ param_explicit_props = self.query_manager.parameterise_dict(explicit_properties, self.section)
213
+ param_calc_props = self.query_manager.parameterise_dict(calculated_properties, self.section)
214
+
215
+ query_data_list = []
216
+ for count in range(max(len(param_from_nodes), len(param_to_nodes), len(param_explicit_props), len(param_calc_props))):
217
+ new_labels_list = [[from_labels, to_labels, relation, from_node.key, to_node.key, param_calc_props[min(count, len(param_calc_props) - 1)]]]
218
+ query_data_list += [[param_from_nodes[min(count, len(param_from_nodes) - 1)].value.replace('\\\\n', '\n'), param_to_nodes[min(count, len(param_to_nodes) - 1)].value.replace('\\\\n', '\n'), param_explicit_props[min(count, len(param_explicit_props) - 1)], param_calc_props[min(count, len(param_calc_props) - 1)], time_now]]
208
219
 
209
220
  # So now we know all about this particular update. Let's put it in the query dictionary
210
- try:
211
- dictionary_index = batch_keys.index(new_labels)
212
- query_dictionary[dictionary_index].append(query_data)
213
- except:
214
- dictionary_index = len(batch_keys)
215
- query_dictionary[dictionary_index] = [query_data]
216
- batch_keys.append(new_labels)
217
- dict_size += 1
221
+ q_count = 0
222
+ for count in range(len(new_labels_list)):
223
+ q_count += 1
224
+ try:
225
+ dictionary_index = batch_keys.index(new_labels_list[count])
226
+ query_dictionary[dictionary_index] += query_data_list
227
+ except:
228
+ dictionary_index = len(batch_keys)
229
+ query_dictionary[dictionary_index] = query_data_list
230
+ batch_keys.append(new_labels_list[count])
231
+ dict_size += len(query_data_list)
218
232
 
219
233
  this_row += 1
220
234
  messages.message_no_cr(f'Analysing file... {100 * (this_row - self.start_from + 1) / num_rows:.0f}%{chr(13)}')
@@ -256,7 +270,9 @@ class RelationshipFileProcessor:
256
270
 
257
271
  formatted_payload = []
258
272
  for a_payload in payload:
259
- formatted_payload.append(property.format(a_payload))
273
+ formatted_pload = property.format(a_payload, '', self.query_manager, self.section)
274
+ formatted_payload += formatted_pload
275
+
260
276
  # Build a MERGE query using queries
261
277
  from_keys = " {" + from_node + ":" + payload_ref_dot + from_ref + "}"
262
278
  to_keys = " {" + to_node + ":" + payload_ref_dot + to_ref + "}"
@@ -2,6 +2,7 @@ import datetime
2
2
  import messages
3
3
  import ast
4
4
  import processors.propertymanager as pm
5
+ from querymanager import QueryManager
5
6
 
6
7
  class Neo4jProperty():
7
8
 
@@ -25,10 +26,11 @@ class Neo4jProperty():
25
26
 
26
27
  # Now check to see if the value might be a formula
27
28
  if '{' in self.value or '}' in self.value:
28
- self.formula, self.is_formula = parse_value(value, 'n.')
29
+ self.formula, self.is_formula, self.parameter_number = parse_value(value, 'n.')
29
30
  else:
30
31
  self.formula = None
31
32
  self.is_formula = False
33
+ self.parameter_number = -1
32
34
 
33
35
  def set_format(self, new_format):
34
36
  # If the format has changed, update it (otherwise, no need to do anything)
@@ -43,6 +45,12 @@ class Neo4jProperty():
43
45
  self.value = new_value
44
46
  # And say the value hasn't been formatted using the new format
45
47
  self.formatted_values = {}
48
+ if '{' in self.value or '}' in self.value:
49
+ self.formula, self.is_formula, self.parameter_number = parse_value(new_value, 'n.')
50
+ else:
51
+ self.formula = None
52
+ self.is_formula = False
53
+ self.parameter_number = -1
46
54
 
47
55
  def get_value(self, ref):
48
56
  # Check to see if we have a formatted value, and if not do it now
@@ -52,142 +60,160 @@ class Neo4jProperty():
52
60
  return self.formatted_values[ref]
53
61
 
54
62
 
55
- def format_value(self, ref):
63
+ def detect_type(value: str) -> str:
64
+ """Detects the type of a string value."""
65
+ value = value.strip()
66
+
67
+ # Boolean
68
+ if value.lower() in ("true", "false"):
69
+ return "bool"
70
+
71
+ # Integer
72
+ if value.isdigit() or (value.startswith('-') and value[1:].isdigit()):
73
+ return "int"
74
+
75
+ # Float
76
+ try:
77
+ if '.' in value or 'e' in value.lower():
78
+ float(value)
79
+ return "float"
80
+ except ValueError:
81
+ pass
82
+
83
+ # Python literals: list, tuple, dict
84
+ try:
85
+ obj = ast.literal_eval(value)
86
+ if isinstance(obj, (list, tuple, dict)):
87
+ return type(obj).__name__
88
+ except (ValueError, SyntaxError):
89
+ pass
90
+
91
+ # Datetime / date / time
92
+ datetime_formats = {
93
+ "%Y-%m-%d %H:%M:%S": "datetime",
94
+ "%Y-%m-%d": "date",
95
+ "%H:%M:%S": "time",
96
+ "%H:%M": "time",
97
+ }
98
+ for fmt, label in datetime_formats.items():
99
+ try:
100
+ datetime.datetime.strptime(value, fmt)
101
+ return label
102
+ except ValueError:
103
+ continue
104
+
105
+ # Fallback
106
+ return "str"
56
107
 
57
- quote = '"'
58
- value = self.value
59
- given_data_format = self.format
60
-
61
- # Redo the formula if ref is not 'n.' (which we did in the init section) and it is a real formula
62
- if self.is_formula and ref != 'n.':
63
- self.formula, self.is_formula = parse_value(self.value, ref)
64
- formula = self.formula
65
-
66
- if self.is_formula and formula != '':
67
- match given_data_format:
68
- case 'str':
69
- result = f'toString({formula})'
70
- case 'int':
71
- result = f'toInteger({formula})'
72
- case 'float':
73
- result = f'toFloat({formula})'
74
- case 'date':
75
- result = f'date({formula})'
76
- case 'datetime':
77
- result = f'datetime({formula})'
78
- case 'bool':
79
- result = f'toBoolean({formula})'
80
- case '' | _:
81
- result = formula
82
- elif self.is_formula:
83
- result = ''
108
+
109
+ def format_value(self, ref):
110
+ quote = '"'
111
+ value = self.value
112
+ given_data_format = self.format
113
+
114
+ # Handle formulas
115
+ if self.is_formula and ref != 'n.':
116
+ self.formula, self.is_formula, self.parameter_number = parse_value(value, ref)
117
+ formula = self.formula
118
+
119
+ if self.is_formula and formula != '':
120
+ match given_data_format:
121
+ case 'str':
122
+ result = f'toString({formula})'
123
+ case 'int':
124
+ result = f'toInteger({formula})'
125
+ case 'float':
126
+ result = f'toFloat({formula})'
127
+ case 'date':
128
+ result = f'date({formula})'
129
+ case 'datetime':
130
+ result = f'datetime({formula})'
131
+ case 'bool':
132
+ result = f'toBoolean({formula})'
133
+ case '' | _:
134
+ result = formula
135
+ elif self.is_formula:
136
+ result = ''
137
+ else:
138
+ # Determine type if format is missing
139
+ if not given_data_format:
140
+ detected_format = detect_type(value)
141
+ self.format = detected_format
84
142
  else:
85
- try:
86
- match given_data_format:
87
- case 'str':
88
- result = quote + (formula or value) + quote
89
- case 'int':
90
- if value != '0':
91
- # Remove any leading zeroes because the literal_eval function does not support them
92
- while value.startswith('0'):
93
- value = value[1:]
94
- result = int(ast.literal_eval(value))
95
- if result != ast.literal_eval(value):
96
- messages.warning_message('Invalid data: ', f'{value} is not a valid Integer, {result} used instead')
97
- else:
98
- result = 0
99
- case 'float':
100
- result = float(ast.literal_eval(value))
101
- case 'bool' | 'boolean':
102
- result = ast.literal_eval(value.capitalize())
103
- if str(result) not in ['True', 'False']:
104
- messages.error_message('Invalid data: ', f'{value} is not a valid boolean so not set')
105
- result = '""'
106
- case 'date':
107
- formatted_date = try_dates(value)
108
- if formatted_date:
109
- result = 'date("' + str(formatted_date) + '")'
110
- else:
111
- messages.error_message(f'Invalid data: {value} is not a valid date so value not set')
112
- result = '""'
113
- case 'datetime':
114
- formatted_datetime = try_datetimes(value)
115
- if formatted_datetime:
116
- result = 'datetime("' + str(formatted_datetime) + '")'
117
- else:
118
- messages.error_message(f'Invalid data: {value} is not a valid datetime so value not set')
119
- result = '""'
120
- case None | '':
121
- # No format requested, so we'll try to work it out
122
- try:
123
- # Use .capitalize() here to catch incorrectly formatted Booleans (e.g. 'true')
124
- boolean_check = value.capitalize()
125
- if boolean_check in ['True', 'False']:
126
- data_type = bool
127
- result = boolean_check
128
- # Update value for use in Version management in VersionManager.are_there_changes()
129
- self.value = boolean_check
130
- self.format = 'bool'
131
- else:
132
- data_type = type(ast.literal_eval(value))
133
- except:
134
- # Now see if it's a date or datetime
135
- formatted_date = try_dates(value)
136
- formatted_time = try_times(value)
137
- if formatted_date:
138
- if formatted_time:
139
- data_type = 'datetime'
140
- # Some legacy data has a space between the date and time, so replace it with 'T'
141
- if value[10] == ' ':
142
- value = value[:10] + 'T' + value[11:]
143
- result = 'datetime("' + str(value) + '")'
144
- self.format = 'datetime'
145
- else:
146
- data_type = 'date'
147
- result = 'date("' + str(formatted_date) + '")'
148
- self.format = 'date'
149
- else:
150
- data_type = 'str'
151
- self.format = 'str'
152
-
153
- match str(data_type):
154
- case 'str':
155
- result = quote + (formula or value) + quote
156
- self.format = 'str'
157
- case "<class 'int'>":
158
- if value != '0' and value.startswith('0'):
159
- # Has a leading 0, so treat as a string
160
- result = quote + value + quote
161
- else:
162
- result = int(ast.literal_eval(value))
163
- if result != ast.literal_eval(value):
164
- messages.warning_message('Invalid data: ', f'{value} is not a valid Integer, {result} used instead')
165
- self.format = 'int'
166
- case "<class 'float'>":
167
- result = ast.literal_eval(value)
168
- self.format = 'float'
169
- case "<class 'bool'>":
170
- # result already set above, so
171
- pass
172
- case 'date' | 'datetime':
173
- # result already set above, so
174
- pass
175
- case "<class 'list'>":
176
- result = value
177
- case _:
178
- # Shouldn't get here, but just in case use a string
179
- result = quote + value + quote
180
- self.format = 'str'
181
-
182
- case _:
183
- # Treat unsupported formats as strings
184
- result = quote + value + quote
185
- self.format = 'str'
186
- except:
187
- messages.error_message('Invalid data: ', f"{value} is not valid for property {self.key} with type '{given_data_format}' so value not set!")
188
- result = '""'
189
-
190
- return result
143
+ detected_format = given_data_format
144
+
145
+ # Match and format
146
+ match detected_format:
147
+ case 'str':
148
+ result = quote + (formula or value) + quote
149
+ case 'int':
150
+ # remove leading zeros
151
+ clean_value = value.lstrip('0') or '0'
152
+ try:
153
+ result = int(clean_value)
154
+ if result != int(value):
155
+ messages.warning_message(
156
+ 'Invalid data: ', f'{value} is not a valid Integer, {result} used instead'
157
+ )
158
+ except ValueError:
159
+ messages.error_message(
160
+ 'Invalid data: ', f'{value} is not a valid Integer'
161
+ )
162
+ result = '""'
163
+ case 'float':
164
+ try:
165
+ result = float(value)
166
+ except ValueError:
167
+ messages.error_message(
168
+ 'Invalid data: ', f'{value} is not a valid Float'
169
+ )
170
+ result = '""'
171
+ case 'bool':
172
+ val = value.capitalize()
173
+ if val in ['True', 'False']:
174
+ result = val
175
+ self.value = val
176
+ else:
177
+ messages.error_message(
178
+ 'Invalid data: ', f'{value} is not a valid Boolean'
179
+ )
180
+ result = '""'
181
+ case 'date':
182
+ formatted_date = try_dates(value)
183
+ if formatted_date:
184
+ result = f'date("{formatted_date}")'
185
+ else:
186
+ messages.error_message(
187
+ f'Invalid data: {value} is not a valid date'
188
+ )
189
+ result = '""'
190
+ case 'datetime':
191
+ formatted_dt = try_datetimes(value)
192
+ if formatted_dt:
193
+ result = f'datetime("{formatted_dt}")'
194
+ else:
195
+ messages.error_message(
196
+ f'Invalid data: {value} is not a valid datetime'
197
+ )
198
+ result = '""'
199
+ case 'time':
200
+ formatted_time = try_times(value)
201
+ if formatted_time:
202
+ result = f'time("{formatted_time}")'
203
+ else:
204
+ messages.error_message(
205
+ f'Invalid data: {value} is not a valid time'
206
+ )
207
+ result = '""'
208
+ case 'list' | 'tuple' | 'dict':
209
+ result = value
210
+ case _:
211
+ # fallback string
212
+ result = quote + value + quote
213
+ self.format = 'str'
214
+
215
+ return result
216
+
191
217
 
192
218
 
193
219
  def parse_value(formula, ref):
@@ -196,6 +222,7 @@ def parse_value(formula, ref):
196
222
  parsed = ''
197
223
  index = 0
198
224
  open = False
225
+ param_num = -1
199
226
  property_name = ''
200
227
  while index < len(formula):
201
228
  this_char = formula[index]
@@ -211,6 +238,15 @@ def parse_value(formula, ref):
211
238
  open = True
212
239
  property_name = ''
213
240
  num_open += 1
241
+ elif this_char == '$' and next_char == '{':
242
+ end_parm = formula[index+1:].find('}')
243
+ if end_parm >= 0:
244
+ parsed += formula[index:index+end_parm+2]
245
+ param_num = formula[index+2:index+end_parm+1]
246
+ index += end_parm+1
247
+ else:
248
+ parsed += this_char
249
+ index += 1
214
250
  elif this_char == '}':
215
251
  if next_char == '}':
216
252
  if open:
@@ -236,7 +272,7 @@ def parse_value(formula, ref):
236
272
 
237
273
  is_formula = (num_open == num_close) and (num_open > 0)
238
274
 
239
- return parsed.strip(), is_formula
275
+ return parsed.strip(), is_formula, param_num
240
276
 
241
277
 
242
278
  def try_date_format(date, date_format):
@@ -291,12 +327,13 @@ def format_property_list(properties, comparison_operator = ':', boolean_operator
291
327
  return res
292
328
 
293
329
 
294
- def format(properties, property_ref=''):
330
+ def format(properties, property_ref='', query_manager = None, section='DEFAULT'):
295
331
  # Reformat using identified data types
296
332
  pairs = []
297
333
  for p in properties.keys():
298
334
  pairs.append(f'{properties[p].key}:{properties[p].get_value(property_ref)}')
299
- return '{' + ','.join(pairs) + '}'
335
+ pair_data = '{' + ','.join(pairs) + '}'
336
+ return QueryManager.parameterise(query_manager, pair_data, section)
300
337
 
301
338
 
302
339
  def to_str(properties, comparison_operator: str = ':', boolean_operator: str = ',', property_ref='', key_ref='') -> str:
@@ -0,0 +1,98 @@
1
+ import copy
2
+
3
+ class QueryManager():
4
+
5
+ def __init__(self, parameters):
6
+ self.parameters = parameters
7
+
8
+ def parameterise(self, query_text, section):
9
+ if self.parameters:
10
+ query_list = []
11
+
12
+ for parm, values in self.parameters[section].items():
13
+ parm_name = '${'+str(parm)+'}'
14
+ if parm_name in query_text:
15
+ for v in values:
16
+ new_query = query_text.replace(parm_name, v)
17
+ query_list.append(new_query)
18
+
19
+ if query_list == []:
20
+ query_list = [query_text]
21
+
22
+ else:
23
+ query_list = [query_text]
24
+
25
+ return query_list
26
+
27
+ def parameterise_dict(self, data, section):
28
+ if self.parameters:
29
+
30
+ params = self.parameters[section]
31
+ params_found = []
32
+ param_num = -1
33
+
34
+ for d in data:
35
+ if data[d].parameter_number != -1:
36
+ params_found.append(d)
37
+ param_num = data[d].parameter_number
38
+
39
+ if params_found and param_num in params:
40
+ params_to_use = params[param_num]
41
+ num_params = len(params_to_use)
42
+ param_id = '${'+param_num+'}'
43
+
44
+ new_data = []
45
+ for count in range(num_params):
46
+ this_one = {}
47
+ for k, v in data.items():
48
+ if k in params_found:
49
+ new_value = data[k].value.replace(param_id, params_to_use[count])
50
+ new_prop = copy.deepcopy(data[k])
51
+ new_prop.set_value(new_value)
52
+ this_one[k] = new_prop
53
+ else:
54
+ this_one[k] = copy.deepcopy(data[k])
55
+ new_data += [this_one]
56
+ else:
57
+ new_data = [data]
58
+ else:
59
+ new_data = [data]
60
+
61
+ return new_data
62
+
63
+
64
+ def parameterise_list(self, prop_data, section):
65
+ if self.parameters:
66
+
67
+ params = self.parameters[section]
68
+ params_found = []
69
+ param_num = -1
70
+
71
+ for prop in prop_data:
72
+ if prop.parameter_number != -1:
73
+ params_found.append(prop.key)
74
+ param_num = prop.parameter_number
75
+
76
+ if params_found:
77
+ params_to_use = params[param_num]
78
+ num_params = len(params_to_use)
79
+ param_id = '{$' + param_num + '}'
80
+
81
+ new_data = []
82
+ for count in range(num_params):
83
+ this_one = []
84
+ for prop in prop_data:
85
+ if prop.key in params_found:
86
+ new_value = prop.value.replace(param_id, params_to_use[count])
87
+ new_prop = copy.deepcopy(prop)
88
+ new_prop.set_value(new_value)
89
+ this_one.append(new_prop)
90
+ else:
91
+ this_one.append(copy.deepcopy(prop))
92
+ new_data.append(this_one[0])
93
+ else:
94
+ new_data = prop_data
95
+ else:
96
+ new_data = prop_data
97
+
98
+ return new_data
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-eigen-ingenuity-nocli
3
- Version: 0.5.27
3
+ Version: 0.5.28
4
4
  Summary: A python library used to query data from the Eigen Ingenuity system
5
5
  Home-page: https://www.eigen.co/
6
6
  Author: Murray Callander
@@ -37,16 +37,17 @@ local-tests/historianmulti/test_tagManagement.py,sha256=oXrzHH2RFodqMYjGu6tu-pMj
37
37
  local-tests/historianmulti/test_writePoints.py,sha256=AW6n5Qsqffkpd21MViqJnUPhcZ3EVLEDODT5CvwIrGQ,2794
38
38
  modelbuilder/__init__.py,sha256=HSsHItu5BbGQiHYTG00QPMNDbC3RkRUaaN50YpksIUA,171
39
39
  modelbuilder/src/__init__.py,sha256=bMvb-E_plw2dz9_TYIPevQuvDNmKtW0dmBgnQE9ylwc,57
40
- modelbuilder/src/assetmodelbuilder.py,sha256=JgeO0tTCIvT5p2d2U7q4KNO4Yw9LGu4H37aeCTfP3Xw,8737
40
+ modelbuilder/src/assetmodelbuilder.py,sha256=92Yu9CvmObPYDdqCpn8eBCaZ_KGBhm307YsFt6cg2Eg,8886
41
41
  modelbuilder/src/assetmodelcsvwriter.py,sha256=GKNi_fw7AlY-UG2XhwFIS34Ff3XiVRss-o5MUzyJSV0,1071
42
42
  modelbuilder/src/assetmodelutilities.py,sha256=S_q5F7mVulk13zCeC1A8cLkJDXj_BR5_yFi3vTw3xUQ,1746
43
- modelbuilder/src/configmanager.py,sha256=6PwreBt0NjqC7dYF3I_1OwwKDVXXgqpyTB7Zw6dxEvo,29346
44
- modelbuilder/src/csvcontentsmanager.py,sha256=R2SofLHDpCsn8hA82KWYFUPWjGSUfwteXJeUoDcnmoE,7878
43
+ modelbuilder/src/configmanager.py,sha256=ewMueJsbr87jPvkPHqDPdXFQgAN83MIw8PtJ4naieAo,30173
44
+ modelbuilder/src/csvcontentsmanager.py,sha256=rVJmR6cPZMS851GeCsRgKzY7b6E_wdbM24rvS0c2feA,7838
45
45
  modelbuilder/src/csvwriter.py,sha256=2Xc6kdV6cYwCjrVF6WaZfS6tVp8-oc0ksIHSOx6iqj8,14132
46
46
  modelbuilder/src/fileanalyser.py,sha256=L7x44NmOaD0spXO9GLAWrGTp-npM8T0xCqCYesMGHgU,4301
47
- modelbuilder/src/filemanager.py,sha256=Jzopuov8g7VLNOe0CHKDbbyExyzNTJA4N3oTJ71oaVI,23346
47
+ modelbuilder/src/filemanager.py,sha256=JZOjiBTs_yLqEsb7LutPqYClsgyte6dW_YVWHqRBZOQ,23667
48
48
  modelbuilder/src/messages.py,sha256=6JnW-ke6nHGUA4hTEBvo_kVlNJTXoV4LWw8mNwMpBCQ,1325
49
- modelbuilder/src/property.py,sha256=r5VMJ4IVJ3efQEzDLmJQ8PEB_qoQcSh98mIJJaXAn_4,12703
49
+ modelbuilder/src/property.py,sha256=MQ2jY3EKvPAIF-bWKrkrXj55I3AW1eujAnY4pkw_4IE,11441
50
+ modelbuilder/src/querymanager.py,sha256=Wr0LcY7iCwmLyeSx8LcdbQT2xt1viltp6XFvP3Bg5v8,3270
50
51
  modelbuilder/src/versionmanager.py,sha256=B8mrYY5Der0sWi1GQjduyVGZ6BuAb6rTNVAZzQlP4k4,19148
51
52
  modelbuilder/src/connectors/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
52
53
  modelbuilder/src/connectors/boltconnector.py,sha256=9mFpYUqYzf--o_8gLw00BjPOmOqo1X1KsdxjFkzYRaQ,4885
@@ -54,11 +55,11 @@ modelbuilder/src/connectors/dbconnectors.py,sha256=rgakGoU2acsMv6N6D6ecqJMld2ZMi
54
55
  modelbuilder/src/connectors/genericconnector.py,sha256=bMfnbrOWq97BC9oM7RIA58bNdC4kR3q3XDOiOVvYNkU,861
55
56
  modelbuilder/src/connectors/httpsconnector.py,sha256=DOZyxRW3JQcaiaYtnx0_Jq2dBEhgSUIubnx5jj7OY_g,6078
56
57
  modelbuilder/src/processors/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
57
- modelbuilder/src/processors/cypherfileprocessor.py,sha256=egf46Jh9qux4hPSqtPDTz8mXOcD65Vxa-znOHgWX2nU,2916
58
+ modelbuilder/src/processors/cypherfileprocessor.py,sha256=EmaLsBhC6gWQwvhyY7Ks2HEbGEzDoGAZfu2nBkh2hOs,2941
58
59
  modelbuilder/src/processors/labelmanager.py,sha256=b2xkIqMd2hptplm5Sp10zoc7LGOKTVZH2jDKN7brvYU,6619
59
- modelbuilder/src/processors/nodefileprocessor.py,sha256=4W74Daydx1jLwkp50dW3qpzpL9T5Nd9dYzDzdXFfBLE,13722
60
+ modelbuilder/src/processors/nodefileprocessor.py,sha256=-9vH1trZuYY6OFxfABCimJ2eEKCwGUnby-1ExDraQug,14561
60
61
  modelbuilder/src/processors/propertymanager.py,sha256=zLr8S0HPZMXeUp1RUzVXWyNa64MxLufXrOqh5uL1mwU,6978
61
- modelbuilder/src/processors/relationshipfileprocessor.py,sha256=sZqPDKOPC84hUHM3woL4lsniER9m0t6qt4aIxZke95A,17651
62
+ modelbuilder/src/processors/relationshipfileprocessor.py,sha256=1osOMAaSKkVZTDZlk_XiZQyp8mGPAsmWgCMYm59ccdo,19143
62
63
  modelbuilder/src/processors/relationshipmanager.py,sha256=lDtE_5AdKzL3boq7VD8Gmpai8Uscq79vRxkzYQL8A9A,1105
63
64
  modelbuilder/src/queries/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
64
65
  modelbuilder/src/queries/cypherbuilder.py,sha256=VpUGuPo-Ba3skjCVBFjmxm4ORQBGgF5cDiQYnK67hLA,10418
@@ -87,7 +88,7 @@ regressiontests/eigeningenuity/historian-multi/test_getRawDatapoints.py,sha256=f
87
88
  regressiontests/eigeningenuity/historian-multi/test_listDataTags.py,sha256=TcceNSjCKoiK5SJcgTH2JXfKLYxIHdQdwZWlkpGnEVM,2006
88
89
  regressiontests/eigeningenuity/historian-multi/test_tagManagement.py,sha256=ylInBt453d1RaSih1eTTxGPZmb60UK4vMwI3UW-U1JY,4830
89
90
  regressiontests/eigeningenuity/historian-multi/test_writePoints.py,sha256=51tfUSLUqLKcCKJ1EyhjfzoC_4OP6n1oL3zgTSkXu4s,2696
90
- python_eigen_ingenuity_nocli-0.5.27.dist-info/METADATA,sha256=57JxHq7PQBlaKoyZPrxzhU5mOm_bVwFT1DvS848Fttc,1434
91
- python_eigen_ingenuity_nocli-0.5.27.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
92
- python_eigen_ingenuity_nocli-0.5.27.dist-info/top_level.txt,sha256=oDWOSmlNPKNBlIEKP8_JaV01O60jTcUIt2tDkq3OD18,56
93
- python_eigen_ingenuity_nocli-0.5.27.dist-info/RECORD,,
91
+ python_eigen_ingenuity_nocli-0.5.28.dist-info/METADATA,sha256=cU-HrBFuA9xtju79mnZy-pkHhBqrDYMrAYZCuVoH8tw,1434
92
+ python_eigen_ingenuity_nocli-0.5.28.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
93
+ python_eigen_ingenuity_nocli-0.5.28.dist-info/top_level.txt,sha256=oDWOSmlNPKNBlIEKP8_JaV01O60jTcUIt2tDkq3OD18,56
94
+ python_eigen_ingenuity_nocli-0.5.28.dist-info/RECORD,,