|
| 1 | +import random |
| 2 | +from typing import * |
| 3 | +from objectbox.logger import logger |
| 4 | +from objectbox.model import Model |
| 5 | +from objectbox.model.entity import _Entity |
| 6 | +from objectbox.model.properties import Property, Index, HnswIndex |
| 7 | +from objectbox.model.iduid import IdUid |
| 8 | + |
| 9 | +MODEL_PARSER_VERSION = 5 |
| 10 | + |
| 11 | + |
| 12 | +class IdSync: |
| 13 | + def __init__(self, model: Model, model_json_filepath: str): |
| 14 | + self.model = model |
| 15 | + |
| 16 | + self.model_filepath = model_json_filepath |
| 17 | + self.model_json = None |
| 18 | + self._load_model_json() |
| 19 | + |
| 20 | + def _load_model_json(self): |
| 21 | + import json |
| 22 | + from os import path |
| 23 | + |
| 24 | + if not path.exists(self.model_filepath): |
| 25 | + logger.debug(f"Model file not found: {self.model_filepath}") |
| 26 | + return |
| 27 | + |
| 28 | + with open(self.model_filepath, "rt") as model_file: |
| 29 | + self.model_json = json.load(model_file) |
| 30 | + logger.debug(f"Syncing model with model file: {self.model_filepath}") |
| 31 | + |
| 32 | + def _save_model_json(self): |
| 33 | + """ Replaces model JSON with the serialized model whose ID/UIDs are assigned. """ |
| 34 | + |
| 35 | + # model.validate_ids_assigned() |
| 36 | + |
| 37 | + model_json = { |
| 38 | + "_note1": "KEEP THIS FILE! Check it into a version control system (VCS) like git.", |
| 39 | + "_note2": "ObjectBox manages crucial IDs for your object model. See docs for details.", |
| 40 | + "_note3": "If you have VCS merge conflicts, you must resolve them according to ObjectBox docs.", |
| 41 | + "modelVersionParserMinimum": MODEL_PARSER_VERSION, |
| 42 | + "entities": [], |
| 43 | + "lastEntityId": str(self.model.last_entity_iduid), |
| 44 | + "lastIndexId": str(self.model.last_index_iduid) |
| 45 | + } |
| 46 | + # TODO lastRelationId |
| 47 | + # TODO modelVersion |
| 48 | + # TODO retiredEntityUids |
| 49 | + # TODO retiredIndexUids |
| 50 | + # TODO retiredPropertyUids |
| 51 | + # TODO retiredRelationUids |
| 52 | + # TODO version |
| 53 | + |
| 54 | + for entity in self.model.entities: |
| 55 | + entity_json = { |
| 56 | + "id": str(entity.iduid), |
| 57 | + "name": entity.name, |
| 58 | + "lastPropertyId": str(entity.last_property_iduid), |
| 59 | + "properties": [] |
| 60 | + } |
| 61 | + for prop in entity.properties: |
| 62 | + prop_json = { |
| 63 | + "id": str(prop.iduid), |
| 64 | + "name": prop.name, |
| 65 | + "type": prop._ob_type, |
| 66 | + "flags": prop._flags |
| 67 | + } |
| 68 | + if prop.index is not None: |
| 69 | + prop_json["indexId"] = str(prop.index.iduid) |
| 70 | + entity_json["properties"].append(prop_json) |
| 71 | + model_json["entities"].append(entity_json) |
| 72 | + |
| 73 | + import json |
| 74 | + with open(self.model_filepath, "w") as model_file: |
| 75 | + model_file.write(json.dumps(model_json, indent=2)) # Pretty |
| 76 | + |
| 77 | + # *** Sync *** |
| 78 | + |
| 79 | + def _find_entity_json_by_name(self, entity_name: str) -> Optional[Dict[str, Any]]: |
| 80 | + """ Finds the entity data by name in the model JSON file. """ |
| 81 | + if self.model_json is None: |
| 82 | + return None |
| 83 | + for entity_json in self.model_json["entities"]: |
| 84 | + if entity_json["name"] == entity_name: |
| 85 | + return entity_json |
| 86 | + return None |
| 87 | + |
| 88 | + def _find_property_json_by_name(self, entity_name: str, prop_name: str) -> Optional[Dict[str, Any]]: |
| 89 | + """ Finds the entity property data by name in the model JSON file. """ |
| 90 | + entity_json = self._find_entity_json_by_name(entity_name) |
| 91 | + if entity_json is None: |
| 92 | + return None |
| 93 | + for prop_json in entity_json["properties"]: |
| 94 | + if prop_json["name"] == prop_name: |
| 95 | + return prop_json |
| 96 | + return None |
| 97 | + |
| 98 | + @staticmethod |
| 99 | + def _generate_uid() -> int: |
| 100 | + return random.getrandbits(63) + 1 # 0 would be invalid |
| 101 | + |
| 102 | + def _validate_uid_unassigned(self, uid: int): |
| 103 | + """ Validates that the UID is not assigned for any other entity/property/index. """ |
| 104 | + pass # TODO |
| 105 | + |
| 106 | + def _sync_index_id(self, entity: _Entity, prop: Property, index: Union[Index, HnswIndex]) -> None: |
| 107 | + """ Given an index, syncs its ID/UID with the JSON file. """ |
| 108 | + iduid_json = None |
| 109 | + prop_json = self._find_property_json_by_name(entity.name, prop.name) |
| 110 | + if prop_json is not None and "indexId" in prop_json: |
| 111 | + iduid_json = IdUid.from_str(prop_json["indexId"]) |
| 112 | + if iduid_json is None: # Index not present in JSON |
| 113 | + if index.has_uid(): |
| 114 | + self._validate_uid_unassigned(index.uid) |
| 115 | + else: |
| 116 | + gen_uid = self._generate_uid() |
| 117 | + index.iduid.uid = gen_uid |
| 118 | + index.iduid = IdUid(self.model.last_index_iduid.id + 1, index.uid) |
| 119 | + else: # Index present in JSON |
| 120 | + if index.has_uid() and index.uid != iduid_json.uid: |
| 121 | + self._validate_uid_unassigned(index.uid) |
| 122 | + index.iduid = IdUid(self.model.last_index_iduid.id + 1, index.uid) # Assign ID |
| 123 | + else: # not index.has_uid() or index.uid != iduid_json.uid |
| 124 | + index.iduid = iduid_json |
| 125 | + |
| 126 | + def _validate_matching_prop(self, entity: _Entity, prop: Property, prop_json: Dict[str, Any]): |
| 127 | + """ Validates that the given property matches the JSON property. """ |
| 128 | + assert prop.name == prop_json["name"], \ |
| 129 | + f"Property {entity.name}.{prop.name} mismatches property found in JSON file " \ |
| 130 | + f"(name {prop.name} != type {prop_json['name']})" # Shouldn't happen (JSON property is got by name) |
| 131 | + assert prop._ob_type == prop_json["type"], \ |
| 132 | + f"Property {entity.name}.{prop.name} mismatches property found in JSON file " \ |
| 133 | + f"(type {prop._ob_type} != type {prop_json['type']})" |
| 134 | + assert prop._flags == prop_json["flags"], \ |
| 135 | + f"Property {entity.name}.{prop.name} mismatches property found in JSON file " \ |
| 136 | + f"(flags {prop._flags} != type {prop_json['flags']})" |
| 137 | + |
| 138 | + def _sync_property_id(self, entity: _Entity, prop: Property) -> None: |
| 139 | + """ Given an entity's property, syncs its ID/UID with the JSON file. """ |
| 140 | + prop_json = self._find_property_json_by_name(entity.name, prop.name) |
| 141 | + if prop_json is None: # Property not present in JSON |
| 142 | + if prop.has_uid(): |
| 143 | + self._validate_uid_unassigned(prop.uid) |
| 144 | + else: |
| 145 | + prop.iduid.uid = self._generate_uid() |
| 146 | + prop.iduid = IdUid(entity.last_property_iduid.id + 1, prop.uid) # Assign ID |
| 147 | + else: # Property present in JSON |
| 148 | + iduid_json = IdUid.from_str(prop_json["id"]) |
| 149 | + if prop.has_uid() and prop.uid != iduid_json.uid: # New property |
| 150 | + self._validate_uid_unassigned(prop.uid) |
| 151 | + prop.iduid = IdUid(entity.last_property_iduid.id + 1, prop.uid) # Assign ID |
| 152 | + else: # not prop.has_uid() or prop.uid == iduid_json.uid |
| 153 | + self._validate_matching_prop(entity, prop, prop_json) |
| 154 | + prop.iduid = iduid_json |
| 155 | + |
| 156 | + def _validate_matching_entity(self, entity: _Entity, entity_json: Dict[str, Any]): |
| 157 | + """ Validates that the given entity matches the JSON entity. """ |
| 158 | + assert entity.name == entity_json["name"], \ |
| 159 | + f"Entity {entity.name} mismatches property found in JSON file " \ |
| 160 | + f"(name {entity.name} != type {entity_json['name']})" # Shouldn't happen (JSON entity is got by name) |
| 161 | + assert len(entity.properties) == len(entity_json["properties"]), \ |
| 162 | + f"Entity {entity.name} mismatches entity found in JSON file " \ |
| 163 | + f"({len(entity.properties)} properties != {len(entity_json['properties'])} properties)" |
| 164 | + # TODO check relations count |
| 165 | + pass # TODO check properties' fields? |
| 166 | + |
| 167 | + def _sync_entity_id(self, entity: _Entity) -> None: |
| 168 | + """ Given an entity, syncs its ID/UID with the JSON file. """ |
| 169 | + entity_json = self._find_entity_json_by_name(entity.name) |
| 170 | + if entity_json is None: # Entity not present in JSON file |
| 171 | + if entity.has_uid(): |
| 172 | + self._validate_uid_unassigned(entity.uid) |
| 173 | + else: |
| 174 | + entity.iduid.uid = self._generate_uid() |
| 175 | + entity.iduid = IdUid(self.model.last_entity_iduid.id + 1, entity.uid) # Assign ID |
| 176 | + else: # Entity present in JSON file |
| 177 | + iduid_json = IdUid.from_str(entity_json["id"]) |
| 178 | + if entity.has_uid() and entity.uid != iduid_json.uid: # New entity |
| 179 | + self._validate_uid_unassigned(entity.uid) |
| 180 | + entity.iduid = IdUid(self.model.last_entity_iduid.id + 1, entity.uid) # Assign ID |
| 181 | + else: # not entity.has_uid() or entity.uid == iduid_json.uid |
| 182 | + self._validate_matching_entity(entity, entity_json) |
| 183 | + entity.iduid = iduid_json |
| 184 | + |
| 185 | + def sync(self): |
| 186 | + """ Syncs the provided model with the model JSON file. """ |
| 187 | + |
| 188 | + # Sync entities ID/UID |
| 189 | + if self.model_json is not None: |
| 190 | + self.model.last_entity_iduid = IdUid.from_str(self.model_json["lastEntityId"]) |
| 191 | + else: |
| 192 | + self.model.last_entity_iduid = IdUid(0, 0) |
| 193 | + for entity in self.model.entities: |
| 194 | + self._sync_entity_id(entity) |
| 195 | + if entity.id > self.model.last_entity_iduid.id: # If assignment occurred, update last_entity_iduid |
| 196 | + self.model.last_entity_iduid = entity.iduid |
| 197 | + |
| 198 | + # Sync properties ID/UID |
| 199 | + for entity in self.model.entities: |
| 200 | + entity_json = self._find_entity_json_by_name(entity.name) |
| 201 | + if entity_json is not None: |
| 202 | + entity.last_property_iduid = IdUid.from_str(entity_json["lastPropertyId"]) |
| 203 | + else: |
| 204 | + entity.last_property_iduid = IdUid(0, 0) |
| 205 | + for prop in entity.properties: |
| 206 | + self._sync_property_id(entity, prop) |
| 207 | + if prop.id > entity.last_property_iduid.id: # If assignment occurred, update last_property_iduid |
| 208 | + entity.last_property_iduid = prop.iduid |
| 209 | + |
| 210 | + # Sync indexes ID/UID |
| 211 | + if self.model_json is not None: |
| 212 | + self.model.last_index_iduid = IdUid.from_str(self.model_json["lastIndexId"]) |
| 213 | + else: |
| 214 | + self.model.last_index_iduid = IdUid(0, 0) |
| 215 | + for entity in self.model.entities: |
| 216 | + for prop in entity.properties: |
| 217 | + if prop.index is not None: |
| 218 | + index = prop.index |
| 219 | + self._sync_index_id(entity, prop, index) |
| 220 | + if index.id > self.model.last_index_iduid.id: # If assignment occurred, update last_index_iduid |
| 221 | + self.model.last_index_iduid = index.iduid |
| 222 | + |
| 223 | + # TODO Sync relations ID/UID(s) |
| 224 | + |
| 225 | + self._save_model_json() |
| 226 | + |
| 227 | + |
| 228 | +def sync_model(model: Model, model_filepath: str = "obx-model.json"): |
| 229 | + """ Syncs the provided model with the model JSON file. """ |
| 230 | + |
| 231 | + id_sync = IdSync(model, model_filepath) |
| 232 | + id_sync.sync() |
0 commit comments