python-eigen-ingenuity 0.5.11b1__tar.gz → 0.5.12__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/PKG-INFO +10 -2
  2. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/eigeningenuity/historianmulti.py +154 -0
  3. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/assetmodelbuilder.py +2 -1
  4. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/configmanager.py +37 -3
  5. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/connectors/boltconnector.py +6 -0
  6. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/csvcontentsmanager.py +23 -8
  7. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/csvwriter.py +14 -13
  8. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/fileanalyser.py +11 -4
  9. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/processors/labelmanager.py +1 -1
  10. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/processors/nodefileprocessor.py +4 -4
  11. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/processors/propertymanager.py +7 -2
  12. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/processors/relationshipfileprocessor.py +27 -6
  13. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/property.py +15 -5
  14. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/queries/cypherbuilder.py +20 -22
  15. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/versionmanager.py +5 -7
  16. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/python_eigen_ingenuity.egg-info/PKG-INFO +10 -2
  17. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/python_eigen_ingenuity.egg-info/SOURCES.txt +0 -1
  18. python_eigen_ingenuity-0.5.11b1/modelbuilder/src/queries/typedefs.py +0 -235
  19. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/MANIFEST.in +0 -0
  20. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/README-nocli.md +0 -0
  21. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/README.md +0 -0
  22. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/eigeningenuity/__init__.py +0 -0
  23. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/eigeningenuity/assetmodel.py +0 -0
  24. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/eigeningenuity/auth.py +0 -0
  25. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/eigeningenuity/core/__init__.py +0 -0
  26. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/eigeningenuity/elastic.py +0 -0
  27. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/eigeningenuity/events.py +0 -0
  28. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/eigeningenuity/historian.py +0 -0
  29. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/eigeningenuity/settings.py +0 -0
  30. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/eigeningenuity/smartdash.py +0 -0
  31. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/eigeningenuity/sql.py +0 -0
  32. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/eigeningenuity/util.py +0 -0
  33. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/__init__.py +0 -0
  34. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/__init__.py +0 -0
  35. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/assetmodelcsvwriter.py +0 -0
  36. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/assetmodelutilities.py +0 -0
  37. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/connectors/__init__.py +0 -0
  38. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/connectors/dbconnectors.py +0 -0
  39. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/connectors/genericconnector.py +0 -0
  40. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/connectors/httpsconnector.py +0 -0
  41. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/filemanager.py +0 -0
  42. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/messages.py +0 -0
  43. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/processors/__init__.py +0 -0
  44. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/processors/cypherfileprocessor.py +0 -0
  45. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/processors/relationshipmanager.py +0 -0
  46. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/queries/__init__.py +0 -0
  47. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/modelbuilder/src/queries/query.py +0 -0
  48. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/pyproject.toml +0 -0
  49. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/python_eigen_ingenuity.egg-info/dependency_links.txt +0 -0
  50. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/python_eigen_ingenuity.egg-info/entry_points.txt +0 -0
  51. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/python_eigen_ingenuity.egg-info/requires.txt +0 -0
  52. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/python_eigen_ingenuity.egg-info/top_level.txt +0 -0
  53. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/requirements.txt +0 -0
  54. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/setup.cfg +0 -0
  55. {python_eigen_ingenuity-0.5.11b1 → python_eigen_ingenuity-0.5.12}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.2
2
2
  Name: python-eigen-ingenuity
3
- Version: 0.5.11b1
3
+ Version: 0.5.12
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
@@ -19,6 +19,14 @@ Requires-Dist: pyarrow
19
19
  Requires-Dist: neo4j>=5.17.0
20
20
  Requires-Dist: requests>=2.31.0
21
21
  Requires-Dist: dateparser
22
+ Dynamic: author
23
+ Dynamic: author-email
24
+ Dynamic: description
25
+ Dynamic: description-content-type
26
+ Dynamic: home-page
27
+ Dynamic: license
28
+ Dynamic: requires-dist
29
+ Dynamic: summary
22
30
 
23
31
  CONTENTS <!-- omit in toc -->
24
32
  ============
@@ -37,6 +37,7 @@ class HistorianMulti (object):
37
37
  self.baseurl = baseurl
38
38
  self.serverurl = baseurl + "multi/"
39
39
  self.writeurl = baseurl + "write/points"
40
+ self.metaurl = baseurl + "metadata"
40
41
  self.listurl = baseurl + "list"
41
42
  self.searchurl = baseurl + "search"
42
43
 
@@ -55,6 +56,9 @@ class HistorianMulti (object):
55
56
  except (URLError, ConnectionError):
56
57
  raise ConnectionError ("Failed to connect to ingenuity instance at " + self.serverurl + ". Please check the url is correct and the instance is up.")
57
58
 
59
+
60
+ #SECTION Read Requests
61
+
58
62
  def getCurrentDataPoints(self,tags: Union[str, list], output: str = "json"):
59
63
  tags = force_list(tags)
60
64
  body = {
@@ -346,6 +350,155 @@ class HistorianMulti (object):
346
350
 
347
351
  return metadata
348
352
 
353
+ #SECTION - Tag Metadata Requests
354
+
355
+ def createTag(self, tag:str, description:str=None, units:str=None, stepped:bool=False, update_existing:bool=False):
356
+ """Create a Tag With Metadata - Writing points to a new tag directly will also create it, but will not create metadata
357
+
358
+ Args:
359
+ tag: Name of the tag to create, either including datasource, or using datasource defined when instantiating historian multi object
360
+ description (Optional): A concise summary of the tags purpose/usage. Defaults to blank/null
361
+ units (Optional): The engineering unit recorded by the value. Defaults to blank/null
362
+ stepped (Optional): Classify whether the measurement is continuous or discrete. Defaults to false
363
+ update_existing (Optional): Whether this function should overwrite metadata of any existing tags referenced. Defaults to false
364
+
365
+ Returns:
366
+ A dict with keys "success" containing a bool, and "errors" that present any tags that failed to be created with metadata
367
+
368
+ Raises:
369
+ URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
370
+ RemoteServerException: When the provided historian could not be found, or the API response contains an error
371
+ RunTimeError/HTTPError: No response from the API
372
+ """
373
+ url = self.metaurl + "/create"
374
+
375
+ if "/" not in tag:
376
+ tag = self.historian + tag
377
+
378
+ metadata = {}
379
+
380
+ for key, value in [("description", description), ("units", units), ("stepped", stepped)]:
381
+ if value is not None:
382
+ metadata[key] = value
383
+
384
+ body = {
385
+ "entries": {
386
+ f"{tag}": metadata
387
+ },
388
+ "updateIfExists": update_existing
389
+ }
390
+
391
+ resp = _do_historian_multi_request(url,body,self.auth)
392
+
393
+ if len(resp["errors"].keys()):
394
+ success = False
395
+ else:
396
+ success = True
397
+
398
+ return {"success": success, "errors": resp["errors"]}
399
+
400
+ def updateTag(self, tag:str, description:str=None, units:str=None, stepped:bool=False, create_missing:bool=False):
401
+ """Update or Create Metadata for an existing tag
402
+
403
+ Args:
404
+ tag: Name of the tag to amend, either including datasource, or using datasource defined when instantiating historian multi object
405
+ description (Optional): A concise summary of the tags purpose/usage. Defaults to blank/null
406
+ units (Optional): The engineering unit recorded by the value. Defaults to blank/null
407
+ stepped (Optional): Classify whether the measurement is continuous or discrete. Defaults to false
408
+ create_missing (Optional): Whether this function should create any non-existent tags referenced. Defaults to false
409
+
410
+ Returns:
411
+ A dict with keys "success" containing a bool, and "errors" that present any tags that failed to be created with metadata
412
+
413
+ Raises:
414
+ URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
415
+ RemoteServerException: When the provided historian could not be found, or the API response contains an error
416
+ RunTimeError/HTTPError: No response from the API
417
+ """
418
+ url = self.metaurl + "/update"
419
+
420
+ if "/" not in tag:
421
+ tag = self.historian + tag
422
+
423
+ metadata = {}
424
+
425
+ for key, value in [("description", description), ("units", units), ("stepped", stepped)]:
426
+ if value is not None:
427
+ metadata[key] = value
428
+
429
+ body = {
430
+ "entries": {
431
+ f"{tag}": metadata
432
+ },
433
+ "createIfMissing": create_missing
434
+ }
435
+
436
+ resp = _do_historian_multi_request(url,body,self.auth)
437
+
438
+ if len(resp["errors"].keys()):
439
+ success = False
440
+ else:
441
+ success = True
442
+
443
+ return {"success": success, "errors": resp["errors"]}
444
+
445
+ def createAndPopulateTag(self, tag:str, points: Union[dict, list], description:str=None, units:str=None, stepped:bool=False, update_existing:bool=True):
446
+ """Create a Tag With Metadata, and batch import points in a single function
447
+
448
+ Args:
449
+ tag: Name of the tag to create, either including datasource, or using datasource defined when instantiating historian multi object
450
+ points: A dict, or list of dicts of the form {"value": x, "timestamp": y}. Where x is an int/double and y is a python datetime, iso datetime string, or epoch timestamp
451
+ description (Optional): A concise summary of the tags purpose/usage. Defaults to blank/null
452
+ units (Optional): The engineering unit recorded by the value. Defaults to blank/null
453
+ stepped (Optional): Classify whether the measurement is continuous or discrete. Defaults to false
454
+ update_existing (Optional): Whether this function should overwrite metadata of any existing tags referenced. Defaults to True
455
+
456
+ Returns:
457
+ A dict with keys "success" containing a bool, and "errors" that present any tags that failed to be created with metadata
458
+
459
+ Raises:
460
+ URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
461
+ RemoteServerException: When the provided historian could not be found, or the API response contains an error
462
+ RunTimeError/HTTPError: No response from the API
463
+ """
464
+ url = self.metaurl + "/create"
465
+
466
+ if "/" not in tag:
467
+ tag = self.historian + tag
468
+
469
+ metadata = {}
470
+
471
+ for key, value in [("description", description), ("units", units), ("stepped", stepped)]:
472
+ if value is not None:
473
+ metadata[key] = value
474
+
475
+ body = {
476
+ "entries": {
477
+ f"{tag}": metadata
478
+ },
479
+ "updateIfExists": update_existing
480
+ }
481
+
482
+ createResp = _do_historian_multi_request(url,body,self.auth)
483
+
484
+ if len(createResp["errors"].keys()):
485
+ createSuccess = False
486
+ else:
487
+ createSuccess = True
488
+
489
+ message = _do_historian_multi_request(self.writeurl,body,self.auth,True)
490
+
491
+ if message == 'All points written!':
492
+ writeSuccess = True
493
+ else:
494
+ ret = writeSuccess = True
495
+
496
+ return {"success": createSuccess and writeSuccess, "createTag": {"success": createSuccess, "errors": createResp["errors"]}, "writePoints": {"success": writeSuccess, "message": message}}
497
+
498
+
499
+ #SECTION - Write Requests
500
+
501
+
349
502
  def writePoints(self, tag:str, points: Union[dict, list]):
350
503
  """Write one or more points to a single tag
351
504
 
@@ -436,6 +589,7 @@ class HistorianMulti (object):
436
589
 
437
590
  return ret
438
591
 
592
+ #SECTION - Utility Functions
439
593
 
440
594
  def createPoint(value:Union[int,float],timestamp:Union[int,str,datetime],status:str="OK"):
441
595
  """Quickly Create a dict of the format required to push data to historians
@@ -64,7 +64,7 @@ def _convert_sys_argv_(func):
64
64
  def build(path:str='.', config:str='config.ini', configsection:str='', file:str='', query:list=[], preprocess:list=[], postprocess:list=[], delete_all:list=[], separator:str=';',
65
65
  start_from:int=1, end_at:int=1, no_versions:bool=False, no_system_properties:bool=False, ignore_nodes:bool=False, skip_duplicates:bool=False,
66
66
  no_duplicates:bool=False, allow_blanks:list=[], replace_blanks:str='', batch:int=0, auth:bool=False, order:str='qnrc', filetypes:str='qnrc', primary_property:str='',
67
- required_labels:list=[], required_properties:list=[], database:str='0', verify:bool=False, summarise:bool=False, show_queries:bool=False, show_returns:bool=False,
67
+ required_labels:list=[], required_properties:list=[], required_relationship_properties:list=[], database:str='0', verify:bool=False, summarise:bool=False, show_queries:bool=False, show_returns:bool=False,
68
68
  write_queries:str='', write_returns:str='', display_rate='auto', create_node_csv_file:bool=False, node_labels:list=[], node_properties:list=[],
69
69
  csv_file_suffix:str='', create_relationship_csv_file:bool=False, csv_to_labels:list=[], csv_to_properties:str=''):
70
70
  """The main model builder tools, features a suite of options that allow for importing, exporting, building and updating neo4j data models
@@ -100,6 +100,7 @@ def build(path:str='.', config:str='config.ini', configsection:str='', file:str=
100
100
  primary_property: Primary property
101
101
  required_labels: Required labels - appended to contents of config; use !Label to remove
102
102
  required_properties: Required properties - appended to contents of config; use !property to remove
103
+ required_relationship_properties: Required relationship properties - appended to contents of config; use !property to remove
103
104
 
104
105
  # What output is required
105
106
  verify: Display the generated queries, but do not process them
@@ -50,7 +50,8 @@ class ConfigManager:
50
50
  # Overrides... used to override values in the config file
51
51
  parser.add_argument('-pp', '--primaryproperty', default='', help='Primary node_key')
52
52
  parser.add_argument('-rl', '--requiredlabels', default='', help='Required labels - appended to contents of config; use !Label to remove')
53
- parser.add_argument('-rp', '--requiredproperties', default='', help='Required properties - appended to contents of config; use !node_key to remove')
53
+ parser.add_argument('-rp', '--requiredproperties', default='', help='Required properties - appended to contents of config; use !property to remove')
54
+ parser.add_argument('-rrp', '--requiredrelationshipproperties', default='', help='Required relationship properties - appended to contents of config; use !property to remove')
54
55
 
55
56
  # And finally specify what output is required
56
57
  parser.add_argument('-v', '--verify', action='store_true', help='Display the generated queries, but do not process them')
@@ -106,6 +107,7 @@ class ConfigManager:
106
107
  self.primary_property_override = args.primaryproperty
107
108
  self.required_labels_override = args.requiredlabels
108
109
  self.required_properties_override = args.requiredproperties
110
+ self.required_relationship_properties_override = args.requiredrelationshipproperties
109
111
 
110
112
  self.db_name = args.database
111
113
  self.validation_mode = args.verify
@@ -148,8 +150,6 @@ class ConfigManager:
148
150
 
149
151
  if self.auth:
150
152
  settings.disable_azure_auth(False)
151
- ## settings.set_azure_client_id('74efa022-e6d6-42ad-bc15-edc76c525bdd')
152
- ## settings.set_azure_tenant_id('74efa022-e6d6-42ad-bc15-edc76c525bdf')
153
153
  else:
154
154
  settings.disable_azure_auth(True)
155
155
 
@@ -270,6 +270,10 @@ class ConfigManager:
270
270
  self.required_properties_dict = {}
271
271
  self.unrequired_properties_list = {}
272
272
 
273
+ self.required_relationship_properties_dict = {}
274
+ self.unrequired_relationship_properties_list = {}
275
+ self.required_relationships_dict = {}
276
+
273
277
  self.no_system_properties = self.get_config_value(self.common_section, "SystemProperties", "on").lower() != 'on' or self.no_system_properties
274
278
  if self.no_system_properties:
275
279
  self.no_version = True
@@ -281,6 +285,8 @@ class ConfigManager:
281
285
 
282
286
  for s in self.available_sections:
283
287
  self.required_properties_dict[s], self.unrequired_properties_list[s] = pm.combine_required_properties(self.get_config_value_list(s, "RequiredProperties", ""), [self.required_properties_override], self.default_data_type[s])
288
+ self.required_relationship_properties_dict[s], self.unrequired_relationship_properties_list[s] = pm.combine_required_properties(self.get_config_value_list(s, "RequiredRelationshipProperties", ""), [self.required_relationship_properties_override], self.default_data_type[s])
289
+ self.required_relationships_dict[s] = self.get_config_value_dict(s, "RequiredRelationships", "")
284
290
 
285
291
  try:
286
292
  self.header_mappings_dict[s] = {i.replace('=', '->').split('->')[0].rstrip(): i.replace('=', '->').split('->')[1].lstrip() for i in header_mappings[s]}
@@ -312,6 +318,25 @@ class ConfigManager:
312
318
  else:
313
319
  return []
314
320
 
321
+ def get_config_value_dict(self, section, option, default=None):
322
+ # Get a node_value from the settings file, reporting an error if it's missing
323
+ try:
324
+ raw_value = self.config[section][option] or default
325
+ except:
326
+ if default is not None:
327
+ raw_value = default
328
+ else:
329
+ self.error_list += [f'No value found for {option} in the configuration file']
330
+ raw_value = ''
331
+ # Reformat from a single string of comma separated values to a Dictionary
332
+ # removing leading and trailing spaces while we're at it
333
+ if raw_value:
334
+ values = [(i.strip()+':').split(':') for i in raw_value.split(',')]
335
+ # If v[1] is blank, it means no key was provided, only a value (in v[0]), so use it for both key and value
336
+ return {v[0]: v[1] if v[1] != '' else v[0] for v in values}
337
+ else:
338
+ return {}
339
+
315
340
  def get_config_value(self, section, option, default=None):
316
341
  # Get a node_value from the settings file, reporting an error if it's missing
317
342
  value_list = self.get_config_value_list(section, option, default)
@@ -417,6 +442,15 @@ class ConfigManager:
417
442
  def get_unrequired_properties_list(self):
418
443
  return self.unrequired_properties_list
419
444
 
445
+ def get_required_relationship_properties_dict(self):
446
+ return self.required_relationship_properties_dict
447
+
448
+ def get_unrequired_relationship_properties_list(self):
449
+ return self.unrequired_relationship_properties_list
450
+
451
+ def get_required_relationships_dict(self):
452
+ return self.required_relationships_dict
453
+
420
454
  def get_unique_id_property(self):
421
455
  return self.unique_id_property
422
456
 
@@ -63,11 +63,14 @@ class BoltConnector(GenericConnector):
63
63
  try_count = 0
64
64
  all_good = False
65
65
  while not all_good and try_count < 3 and not cypher_error:
66
+ # with session.begin_transaction() as tx:
66
67
  try:
67
68
  result = session.run(query_text)
69
+ # result = tx.run(query_text)
68
70
  converted_result = self.convert_result(result)
69
71
  all_good = True
70
72
  except Exception as e:
73
+ ## print(f'Query failed: {e}')
71
74
  if str(type(e)) == "<class 'neo4j.exceptions.ServiceUnavailable'>" or str(type(e)) == "<class 'neo4j.exceptions.SessionExpired'>":
72
75
  info_message(f'Query {self.query_id} failed at {assetmodelutilities.get_formatted_time_now_noms()}: Service unavailable, retrying...')
73
76
  try_count += 1
@@ -78,6 +81,9 @@ class BoltConnector(GenericConnector):
78
81
  info_message(f'Query {self.query_id} failed at {assetmodelutilities.get_formatted_time_now_noms()} with error type {type(e)}, retrying...')
79
82
  try_count += 1
80
83
  sleep(1)
84
+ # finally:
85
+ # if not tx.closed():
86
+ # tx.rollback()
81
87
 
82
88
  if not all_good:
83
89
  if cypher_error:
@@ -9,7 +9,8 @@ class CSVContentsManager:
9
9
 
10
10
  def __init__(self, csv_data, header_mappings, alias_mappings, default_data_type):
11
11
  file_headers = next(csv_data)
12
- self.data_list = list(csv_data)
12
+ data_list = list(csv_data)
13
+ self.data_list = [i for i in data_list if len(i) > 0 and not i[0].startswith('#')]
13
14
  unmapped_keys = []
14
15
  mapped_keys = []
15
16
  self.formats = []
@@ -88,7 +89,7 @@ class CSVContentsManager:
88
89
  name_list = [column_name]
89
90
  else:
90
91
  name_list = column_name
91
- 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)]
92
+ column_list = [i for i, j in enumerate(self.mapped_keys) if ((j in name_list and self.types[i] == '') or self.types[i] in type_list)]
92
93
  return column_list
93
94
 
94
95
  def get_other_column_numbers_list(self, column_name, type_list=[]):
@@ -97,7 +98,7 @@ class CSVContentsManager:
97
98
  name_list = [column_name]
98
99
  else:
99
100
  name_list = column_name
100
- 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)]
101
+ column_list = [i for i, j in enumerate(self.mapped_keys) if not ((j in name_list and self.types[i] == '') or self.types[i] in type_list)]
101
102
  return column_list
102
103
 
103
104
  def get_incomplete_rows(self):
@@ -117,6 +118,13 @@ class CSVContentsManager:
117
118
  columns_list = [this_row[i] for i in column_numbers if len(this_row[i]) > 0]
118
119
  return columns_list
119
120
 
121
+ def get_column_values_dict(self, row_number, column_numbers):
122
+ # Return the values in the given row, for the columns in the provided list (skips empty values)
123
+ # Returned as a List (of strings)
124
+ this_row = self.data_list[row_number]
125
+ columns_list = {self.mapped_keys[i]: this_row[i] for i in column_numbers if len(this_row[i]) > 0}
126
+ return columns_list
127
+
120
128
  def get_column_values_list_with_formatted_keys(self, row_number, column_numbers):
121
129
  # Return the values in the given row, for the columns in the provided list (skips empty values)
122
130
  # Returned as a List (of strings)
@@ -124,16 +132,23 @@ class CSVContentsManager:
124
132
  properties_list = [Neo4jProperty(self.mapped_keys[column], this_row[column], self.formats[column]) for column in column_numbers if len(this_row[column])]
125
133
  return properties_list
126
134
 
127
- def get_property_values_dict(self, row_number, column_numbers, allow_blank_property_list, default_key='', prefix='', blank_override=''):
135
+ def get_property_values_dict(self, row_number, column_numbers, allow_blank_property_list, default_key='', prefix='', blank_override='', allow_split=True):
128
136
  this_row = self.data_list[row_number]
129
- split_values = [this_row[column].split('::') for column in column_numbers]
137
+ if allow_split:
138
+ split_values = [this_row[column].split('::') for column in column_numbers]
139
+ else:
140
+ split_values = [[this_row[column]] for column in column_numbers]
130
141
  split_keys = [(split_values[count][0] + ':').split(':') for count, column in enumerate(column_numbers)]
131
142
  this_list = {prefix + (self.mapped_keys[column] or default_key): Neo4jProperty(prefix + (self.mapped_keys[column] or default_key), this_row[column], self.formats[column], blank_override=blank_override) if len(split_values[count]) == 1 else {prefix + (split_keys[count][0] or default_key): Neo4jProperty(prefix + (split_keys[count][0] or default_key), split_values[count][1], split_keys[count][1] or self.formats[column], blank_override=blank_override)} 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 == []}
132
143
  return this_list
133
144
 
134
- def get_property_values_list(self, row_number, column_numbers, default_key='', override_key=''):
145
+ def get_property_values_list(self, row_number, column_numbers, default_key='', override_key='', allow_split=True):
135
146
  this_row = self.data_list[row_number]
136
- split_values = [this_row[column].split('::') for column in column_numbers]
147
+ if allow_split:
148
+ split_values = [this_row[column].split('::') for column in column_numbers]
149
+ else:
150
+ split_values = [[this_row[column]] for column in column_numbers]
137
151
  split_keys = [(split_values[count][0]+':').split(':') for count, column in enumerate(column_numbers)]
138
- this_list = [Neo4jProperty((override_key or self.mapped_keys[column] or default_key), this_row[column], self.formats[column]) if len(split_values[count]) == 1 else Neo4jProperty(split_keys[count][0] or default_key, split_values[count][1], split_keys[count][1] or self.formats[column]) for count, column in enumerate(column_numbers) if this_row[column]]
152
+ these_keys = [override_key or self.mapped_keys[column] if self.types[column] == '' else self.mapped_keys[column] or default_key for count, column in enumerate(column_numbers)]
153
+ this_list = [Neo4jProperty(these_keys[count], this_row[column], self.formats[column]) if len(split_values[count]) == 1 else Neo4jProperty(split_values[count][0] or default_key, split_values[count][1], split_keys[count][1] or self.formats[column]) for count, column in enumerate(column_numbers) if this_row[column]]
139
154
  return this_list
@@ -1,7 +1,7 @@
1
1
  import csv
2
2
  from queries.query import Neo4jQuery
3
3
  from queries.cypherbuilder import QueryBuilder, ValidAfterWhere
4
- from queries.typedefs import *
4
+ #from queries.typedefs import *
5
5
  from messages import *
6
6
  import assetmodelutilities as amu
7
7
  from processors import labelmanager as lm
@@ -14,11 +14,12 @@ class CSVFileWriter:
14
14
 
15
15
  self.write_node_file = config_manager.get_node_csvfile_requested()
16
16
  self.node_labels = config_manager.get_node_csv_labels()
17
- self.csv_node_primary_property = config_manager.get_csv_node_property_list()
17
+ self.csv_node_primary_property = config_manager.get_csv_node_property_list()['DEFAULT']
18
+
18
19
  self.file_suffix = config_manager.get_csv_file_suffix()
19
20
  self.write_relationship_file = config_manager.get_relationship_csvfile_requested()
20
21
  self.to_labels = config_manager.get_to_csv_labels()
21
- self.csv_to_primary_property = config_manager.get_csv_to_property_list()
22
+ self.csv_to_primary_property = config_manager.get_csv_to_property_list()['DEFAULT']
22
23
  if self.csv_to_primary_property != self.csv_node_primary_property:
23
24
  self.to_prefix = self.csv_to_primary_property + '::'
24
25
  else:
@@ -29,16 +30,16 @@ class CSVFileWriter:
29
30
  self.batch_size = 100
30
31
 
31
32
  self.required_labels = config_manager.get_required_labels()
32
- self.primary_property = config_manager.get_primary_property()
33
+ self.primary_property = config_manager.get_primary_property()['DEFAULT'][0]
33
34
  self.unique_id_property = config_manager.get_unique_id_property()
34
35
  self.version_labels = config_manager.get_version_labels_list()
35
36
 
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]
37
+ self.relationship_alias = config_manager.get_relationship_alias()['DEFAULT'][0]
38
+ self.from_alias = config_manager.get_from_alias()['DEFAULT'][0]
39
+ self.to_alias = config_manager.get_to_alias()['DEFAULT'][0]
40
+ self.node_label = config_manager.get_label_alias()['DEFAULT'][0]
41
+ self.from_label = config_manager.get_from_label_alias()['DEFAULT'][0]
42
+ self.to_label = config_manager.get_to_label_alias()['DEFAULT'][0]
42
43
 
43
44
  self.all_keys = [self.node_label]
44
45
  self.all_nodes = []
@@ -249,9 +250,9 @@ class CSVFileWriter:
249
250
  where_tests = {'cn.' + self.csv_node_primary_property: this_batch}
250
251
 
251
252
  if 'WHERE' in node_query.toStr():
252
- this_query = node_query.where_additional(Properties(where_tests), ' IN ', ' AND ')
253
+ this_query = node_query.where_additional(where_tests, ' IN ', ' AND ')
253
254
  else:
254
- this_query = node_query.where_multiple(Properties(where_tests), ' IN ', ' AND ')
255
+ this_query = node_query.where_multiple(where_tests, ' IN ', ' AND ')
255
256
 
256
257
  if self.write_node_file:
257
258
  this_query_text = this_query.return_literal(node_response_text).toStr().replace('\\"', '"')
@@ -283,7 +284,7 @@ class CSVFileWriter:
283
284
  try:
284
285
  nodes_found = [i[list_name] for i in response]
285
286
  except:
286
- nodes_found = 0
287
+ nodes_found = []
287
288
 
288
289
  return nodes_found
289
290
 
@@ -21,6 +21,8 @@ class FileAnalyser():
21
21
  self.relationship_alias = config.get_relationship_alias()[section]
22
22
  self.ignore_nodes = config.get_ignore_nodes()
23
23
 
24
+ self.num_required_relationships = len(config.get_required_relationships_dict()[section])
25
+
24
26
  self.node_types = amu.node_types
25
27
  self.from_types = amu.from_types
26
28
  self.to_types = amu.to_types
@@ -39,16 +41,21 @@ class FileAnalyser():
39
41
  match file_format:
40
42
  case 'csv':
41
43
  try:
42
- with open(file_name, encoding='utf8') as csv_file:
44
+ with open(file_name) as csv_file:
43
45
  csv_data = csv.reader(csv_file, delimiter=self.separator)
44
46
  contents = CSVContentsManager(csv_data, self.header_mappings, self.alias_mappings, self.default_data_type)
45
47
  except:
46
48
  try:
47
- with open(file_name) as csv_file:
49
+ with open(file_name, encoding='utf-8') as csv_file:
48
50
  csv_data = csv.reader(csv_file, delimiter=self.separator)
49
51
  contents = CSVContentsManager(csv_data, self.header_mappings, self.alias_mappings, self.default_data_type)
50
52
  except:
51
- return 'incorrect file format', contents, []
53
+ try:
54
+ with open(file_name, encoding='iso-8859-1') as csv_file:
55
+ csv_data = csv.reader(csv_file, delimiter=self.separator)
56
+ contents = CSVContentsManager(csv_data, self.header_mappings, self.alias_mappings, self.default_data_type)
57
+ except:
58
+ return 'incorrect file format', contents, []
52
59
  case _:
53
60
  pass
54
61
 
@@ -71,7 +78,7 @@ class FileAnalyser():
71
78
 
72
79
  # Check if there are at least one each of From, To and Relationship (including aliases) columns
73
80
  # If so, this could be a Relationship file
74
- if num_from_columns > 0 and num_to_columns > 0 and num_relation_columns > 0:
81
+ if num_from_columns > 0 and num_to_columns > 0 and num_relation_columns + self.num_required_relationships > 0:
75
82
  could_be_relations = True
76
83
  else:
77
84
  could_be_relations = False
@@ -93,7 +93,7 @@ def sort_relationship_labels(required_labels, input_labels):
93
93
  # Labels used in the relationship MATCH queries
94
94
  relationship_labels = [i for i in required_labels + wanted_label_list if (not ('!' + i in unwanted_label_list) and not (i in remove_label_list) and not (i.startswith('!')))]
95
95
 
96
- return relationship_labels
96
+ return list(set(relationship_labels))
97
97
 
98
98
  def sort_output_labels(node_labels, version_labels):
99
99
  # We need the specifed node labels, but not any version labels
@@ -71,7 +71,7 @@ class NodeFileProcessor:
71
71
  while this_row < last_row:
72
72
  validated_csv_labels = lm.validate_labels(self.contents.get_column_values_list(this_row, label_columns))
73
73
  merge_labels, new_labels, remove_labels = lm.sort_node_labels(self.required_labels, validated_csv_labels)
74
- row_properties = self.contents.get_property_values_dict(this_row, property_columns, self.blank_property_list, blank_override=self.blank_property_override)
74
+ row_properties = self.contents.get_property_values_dict(this_row, property_columns, self.blank_property_list, blank_override=self.blank_property_override, allow_split=False)
75
75
  properties = pm.combine_properties(self.required_properties, row_properties)
76
76
  # Remove any properties we don't want
77
77
  for unwanted in self.unrequired_properties:
@@ -80,7 +80,7 @@ class NodeFileProcessor:
80
80
  # Split out those properties that are dependent on others, so that we can add them in the right order
81
81
  explicit_properties, calculated_properties = pm.split_out_functional_properties(properties)
82
82
 
83
- for primary_property in self.contents.get_property_values_list(this_row, node_columns, self.primary_property):
83
+ for primary_property in self.contents.get_property_values_list(this_row, node_columns, self.primary_property, allow_split=False):
84
84
  time_now = amu.get_formatted_time_now()
85
85
 
86
86
  # Build a simple MERGE query using queries
@@ -158,9 +158,9 @@ class NodeFileProcessor:
158
158
  while this_row < last_row:
159
159
  validated_csv_labels = lm.validate_labels(self.contents.get_column_values_list(this_row, label_columns))
160
160
  merge_labels, new_labels, remove_labels = lm.sort_node_labels(self.required_labels, validated_csv_labels)
161
- row_properties = self.contents.get_property_values_dict(this_row, property_columns, self.blank_property_list, blank_override=self.blank_property_override)
161
+ row_properties = self.contents.get_property_values_dict(this_row, property_columns, self.blank_property_list, blank_override=self.blank_property_override, allow_split=False)
162
162
 
163
- for primary_property in self.contents.get_property_values_list(this_row, node_columns, self.primary_property):
163
+ for primary_property in self.contents.get_property_values_list(this_row, node_columns, self.primary_property, allow_split=False):
164
164
  properties = pm.combine_properties(self.required_properties, row_properties)
165
165
  # Remove any properties we don't want
166
166
  for unwanted in self.unrequired_properties:
@@ -98,8 +98,13 @@ def sort_properties(properties, default_type):
98
98
  else:
99
99
  # If we have a format and/or value we have a new property to add
100
100
  # ...unless it starts with ! in which case it belongs in the unwanted list (format/value are ignored)
101
- if num_fields > 1 and not key.startswith('!'):
102
- validated[valid_key] = Neo4jProperty(valid_key, prop_value, prop_type)
101
+ if not key.startswith('!'):
102
+ if num_fields > 1:
103
+ validated[valid_key] = Neo4jProperty(valid_key, prop_value, prop_type)
104
+ else:
105
+ # We have a property with no value field (as opposed to a blank/empty value) i.e. "key", so we ignore it
106
+ # If a blank value is needed, the property should end with a ':' to specify so i.e. "key:"
107
+ pass
103
108
  else:
104
109
  # Add to the unwanted list
105
110
  unwanted.append(valid_key)
@@ -19,6 +19,9 @@ class RelationshipFileProcessor:
19
19
  self.add_system_properties = not config.get_no_system_properties()
20
20
 
21
21
  self.required_labels = config.get_required_labels()[section]
22
+ self.required_properties = config.get_required_relationship_properties_dict()[section]
23
+ self.unrequired_properties = config.get_unrequired_relationship_properties_list()[section]
24
+ self.required_relationships = config.get_required_relationships_dict()[section]
22
25
  self.creation_time_property = config.get_creation_time_property()[section]
23
26
  self.update_time_property = config.get_update_time_property()[section]
24
27
 
@@ -76,9 +79,17 @@ class RelationshipFileProcessor:
76
79
  last_row = self.get_last_row(num_data_rows)
77
80
  while this_row < last_row:
78
81
 
79
- relationships = rm.validate_relationships(self.contents.get_column_values_list(this_row, relation_columns))
82
+ combined_relationships = {**self.required_relationships, **self.contents.get_column_values_dict(this_row, relation_columns)}
83
+ relationships = rm.validate_relationships(list(combined_relationships.values()))
84
+
85
+ row_properties = self.contents.get_property_values_dict(this_row, property_columns, self.blank_property_list, blank_override=self.blank_property_override)
86
+ properties = pm.combine_properties(self.required_properties, row_properties)
87
+ for unwanted in self.unrequired_properties:
88
+ temp = properties.pop(unwanted, None)
89
+
90
+ # Split out those properties that are dependent on others, so that we can add them in the right order
91
+ explicit_properties, calculated_properties = pm.split_out_functional_properties(properties)
80
92
 
81
- properties = self.contents.get_property_values_dict(this_row, property_columns, self.blank_property_list, blank_override=self.blank_property_override)
82
93
  # If there are multiple From or To nodes, create a relationship query for each combination
83
94
  for from_node in self.contents.get_property_values_list(this_row, from_columns, self.primary_property, self.primary_property):
84
95
  validated_csv_from_labels = lm.validate_labels(self.contents.get_column_values_list(this_row, from_label_columns))
@@ -110,8 +121,11 @@ class RelationshipFileProcessor:
110
121
  update_time = relation_ref_dot + self.update_time_property + '=datetime("' + time_now + '")'
111
122
  query_text = query_text.on_create().set_literal(create_time).set_literal(update_time)
112
123
 
113
- if len(properties) > 0:
114
- query_text = query_text.set(properties=properties, property_ref=relation_ref_dot)
124
+ if len(explicit_properties) > 0:
125
+ query_text = query_text.set(properties=explicit_properties, property_ref=relation_ref_dot)
126
+ if len(calculated_properties) > 0:
127
+ query_text = query_text.set(properties=calculated_properties, property_ref=relation_ref_dot)
128
+
115
129
  query_text = query_text.toStr()
116
130
  query = Neo4jQuery('relationship', query_text, time_now)
117
131
 
@@ -164,8 +178,15 @@ class RelationshipFileProcessor:
164
178
  this_row = self.start_from-1
165
179
  last_row = self.get_last_row(num_data_rows)
166
180
  while this_row < last_row:
167
- relationships = rm.validate_relationships(self.contents.get_column_values_list(this_row, relation_columns))
168
- properties = self.contents.get_property_values_dict(this_row, property_columns, self.blank_property_list, blank_override=self.blank_property_override)
181
+
182
+ combined_relationships = {**self.required_relationships, **self.contents.get_column_values_dict(this_row, relation_columns)}
183
+ relationships = rm.validate_relationships(list(combined_relationships.values()))
184
+
185
+ row_properties = self.contents.get_property_values_dict(this_row, property_columns, self.blank_property_list, blank_override=self.blank_property_override)
186
+ properties = pm.combine_properties(self.required_properties, row_properties)
187
+ for unwanted in self.unrequired_properties:
188
+ temp = properties.pop(unwanted, None)
189
+
169
190
  # If there are multiple From or To nodes, create a relationship query for each combination
170
191
  for from_node in self.contents.get_property_values_list(this_row, from_columns, self.primary_property, self.primary_property):
171
192
  validated_csv_from_labels = lm.validate_labels(self.contents.get_column_values_list(this_row, from_label_columns))