lamindb_setup 0.76.5__py2.py3-none-any.whl → 0.76.7__py2.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.
Files changed (47) hide show
  1. lamindb_setup/__init__.py +1 -1
  2. lamindb_setup/_cache.py +34 -34
  3. lamindb_setup/_check.py +7 -7
  4. lamindb_setup/_check_setup.py +79 -79
  5. lamindb_setup/_close.py +35 -35
  6. lamindb_setup/_connect_instance.py +433 -433
  7. lamindb_setup/_delete.py +137 -137
  8. lamindb_setup/_django.py +41 -41
  9. lamindb_setup/_exportdb.py +68 -68
  10. lamindb_setup/_importdb.py +50 -50
  11. lamindb_setup/_init_instance.py +374 -374
  12. lamindb_setup/_migrate.py +239 -236
  13. lamindb_setup/_register_instance.py +36 -36
  14. lamindb_setup/_schema.py +27 -27
  15. lamindb_setup/_schema_metadata.py +391 -391
  16. lamindb_setup/_set_managed_storage.py +55 -55
  17. lamindb_setup/_setup_user.py +118 -118
  18. lamindb_setup/_silence_loggers.py +44 -44
  19. lamindb_setup/core/__init__.py +21 -21
  20. lamindb_setup/core/_aws_credentials.py +151 -151
  21. lamindb_setup/core/_aws_storage.py +48 -48
  22. lamindb_setup/core/_deprecated.py +55 -55
  23. lamindb_setup/core/_docs.py +14 -14
  24. lamindb_setup/core/_hub_client.py +164 -161
  25. lamindb_setup/core/_hub_core.py +473 -473
  26. lamindb_setup/core/_hub_crud.py +211 -211
  27. lamindb_setup/core/_hub_utils.py +109 -109
  28. lamindb_setup/core/_private_django_api.py +88 -88
  29. lamindb_setup/core/_settings.py +138 -138
  30. lamindb_setup/core/_settings_instance.py +461 -460
  31. lamindb_setup/core/_settings_load.py +100 -100
  32. lamindb_setup/core/_settings_save.py +81 -81
  33. lamindb_setup/core/_settings_storage.py +393 -389
  34. lamindb_setup/core/_settings_store.py +72 -72
  35. lamindb_setup/core/_settings_user.py +51 -51
  36. lamindb_setup/core/_setup_bionty_sources.py +99 -99
  37. lamindb_setup/core/cloud_sqlite_locker.py +232 -232
  38. lamindb_setup/core/django.py +113 -113
  39. lamindb_setup/core/exceptions.py +12 -12
  40. lamindb_setup/core/hashing.py +114 -114
  41. lamindb_setup/core/types.py +19 -19
  42. lamindb_setup/core/upath.py +779 -779
  43. {lamindb_setup-0.76.5.dist-info → lamindb_setup-0.76.7.dist-info}/METADATA +4 -3
  44. lamindb_setup-0.76.7.dist-info/RECORD +46 -0
  45. {lamindb_setup-0.76.5.dist-info → lamindb_setup-0.76.7.dist-info}/WHEEL +1 -1
  46. lamindb_setup-0.76.5.dist-info/RECORD +0 -46
  47. {lamindb_setup-0.76.5.dist-info → lamindb_setup-0.76.7.dist-info}/LICENSE +0 -0
@@ -1,391 +1,391 @@
1
- from __future__ import annotations
2
-
3
- import hashlib
4
- import importlib
5
- import json
6
- from typing import TYPE_CHECKING, Literal
7
- from uuid import UUID
8
-
9
- from django.db.models import (
10
- Field,
11
- ForeignKey,
12
- ForeignObjectRel,
13
- ManyToManyField,
14
- ManyToManyRel,
15
- ManyToOneRel,
16
- OneToOneField,
17
- OneToOneRel,
18
- )
19
- from pydantic import BaseModel
20
-
21
- from lamindb_setup import settings
22
- from lamindb_setup._init_instance import get_schema_module_name
23
- from lamindb_setup.core._hub_client import call_with_fallback_auth
24
-
25
- # surpress pydantic warning about `model_` namespace
26
- try:
27
- BaseModel.model_config["protected_namespaces"] = ()
28
- except Exception:
29
- pass
30
-
31
-
32
- if TYPE_CHECKING:
33
- from supabase import Client
34
-
35
-
36
- def update_schema_in_hub() -> tuple[bool, UUID, dict]:
37
- return call_with_fallback_auth(_synchronize_schema)
38
-
39
-
40
- def _synchronize_schema(client: Client) -> tuple[bool, UUID, dict]:
41
- schema_metadata = _SchemaHandler()
42
- schema_metadata_dict = schema_metadata.to_json()
43
- schema_uuid = _dict_to_uuid(schema_metadata_dict)
44
- schema = _get_schema_by_id(schema_uuid, client)
45
-
46
- is_new = schema is None
47
- if is_new:
48
- module_set_info = schema_metadata._get_module_set_info()
49
- module_ids = "-".join(str(module_info["id"]) for module_info in module_set_info)
50
- schema = (
51
- client.table("schema")
52
- .insert(
53
- {
54
- "id": schema_uuid.hex,
55
- "module_ids": module_ids,
56
- "module_set_info": module_set_info,
57
- "schema_json": schema_metadata_dict,
58
- }
59
- )
60
- .execute()
61
- .data[0]
62
- )
63
-
64
- instance_response = (
65
- client.table("instance")
66
- .update({"schema_id": schema_uuid.hex})
67
- .eq("id", settings.instance._id.hex)
68
- .execute()
69
- )
70
- assert (
71
- len(instance_response.data) == 1
72
- ), f"schema of instance {settings.instance._id.hex} could not be updated with schema {schema_uuid.hex}"
73
-
74
- return is_new, schema_uuid, schema
75
-
76
-
77
- def get_schema_by_id(id: UUID):
78
- return call_with_fallback_auth(_get_schema_by_id, id=id)
79
-
80
-
81
- def _get_schema_by_id(id: UUID, client: Client):
82
- response = client.table("schema").select("*").eq("id", id.hex).execute()
83
- if len(response.data) == 0:
84
- return None
85
- return response.data[0]
86
-
87
-
88
- def _dict_to_uuid(dict: dict):
89
- encoded = json.dumps(dict, sort_keys=True).encode("utf-8")
90
- hash = hashlib.md5(encoded).digest()
91
- uuid = UUID(bytes=hash[:16])
92
- return uuid
93
-
94
-
95
- RelationType = Literal["many-to-one", "one-to-many", "many-to-many", "one-to-one"]
96
- Type = Literal[
97
- "ForeignKey",
98
- "CharField",
99
- "DateTimeField",
100
- "AutoField",
101
- "BooleanField",
102
- "BigIntegerField",
103
- "SmallIntegerField",
104
- "TextField",
105
- "BigAutoField",
106
- "ManyToManyField",
107
- "IntegerField",
108
- "OneToOneField",
109
- "JSONField",
110
- "DateField",
111
- "FloatField",
112
- "PositiveIntegerField",
113
- "PositiveBigIntegerField",
114
- ]
115
-
116
-
117
- class Through(BaseModel):
118
- left_key: str
119
- right_key: str
120
- link_table_name: str | None = None
121
-
122
-
123
- class FieldMetadata(BaseModel):
124
- type: Type
125
- column_name: str | None = None
126
- through: Through | None = None
127
- field_name: str
128
- model_name: str
129
- schema_name: str
130
- is_link_table: bool
131
- relation_type: RelationType | None = None
132
- related_field_name: str | None = None
133
- related_model_name: str | None = None
134
- related_schema_name: str | None = None
135
-
136
-
137
- class _ModelHandler:
138
- def __init__(self, model, module_name: str, included_modules: list[str]) -> None:
139
- self.model = model
140
- self.class_name = model.__name__
141
- self.module_name = module_name
142
- self.model_name = model._meta.model_name
143
- self.table_name = model._meta.db_table
144
- self.included_modules = included_modules
145
- self.fields = self._get_fields_metadata(self.model)
146
-
147
- def to_dict(self, include_django_objects: bool = True):
148
- _dict = {
149
- "fields": self.fields.copy(),
150
- "class_name": self.class_name,
151
- "table_name": self.table_name,
152
- }
153
-
154
- for field_name in self.fields.keys():
155
- _dict["fields"][field_name] = _dict["fields"][field_name].__dict__
156
- through = _dict["fields"][field_name]["through"]
157
- if through is not None:
158
- _dict["fields"][field_name]["through"] = through.__dict__
159
-
160
- if include_django_objects:
161
- _dict.update({"model": self.model})
162
-
163
- return _dict
164
-
165
- def _get_fields_metadata(self, model):
166
- related_fields = []
167
- fields_metadata: dict[str, FieldMetadata] = {}
168
-
169
- for field in model._meta.get_fields():
170
- field_metadata = self._get_field_metadata(model, field)
171
- if field_metadata.related_schema_name is None:
172
- fields_metadata.update({field.name: field_metadata})
173
-
174
- if (
175
- field_metadata.related_schema_name in self.included_modules
176
- and field_metadata.schema_name in self.included_modules
177
- ):
178
- related_fields.append(field)
179
-
180
- related_fields_metadata = self._get_related_fields_metadata(
181
- model, related_fields
182
- )
183
-
184
- fields_metadata = {**fields_metadata, **related_fields_metadata}
185
-
186
- return fields_metadata
187
-
188
- def _get_related_fields_metadata(self, model, fields: list[ForeignObjectRel]):
189
- related_fields: dict[str, FieldMetadata] = {}
190
-
191
- for field in fields:
192
- if field.many_to_one:
193
- related_fields.update(
194
- {f"{field.name}": self._get_field_metadata(model, field)}
195
- )
196
- elif field.one_to_many:
197
- # exclude self reference as it is already included in the many to one
198
- if field.related_model == model:
199
- continue
200
- related_fields.update(
201
- {f"{field.name}": self._get_field_metadata(model, field.field)}
202
- )
203
- elif field.many_to_many:
204
- related_fields.update(
205
- {f"{field.name}": self._get_field_metadata(model, field)}
206
- )
207
- elif field.one_to_one:
208
- related_fields.update(
209
- {f"{field.name}": self._get_field_metadata(model, field)}
210
- )
211
-
212
- return related_fields
213
-
214
- def _get_field_metadata(self, model, field: Field):
215
- from lnschema_core.models import LinkORM
216
-
217
- internal_type = field.get_internal_type()
218
- model_name = field.model._meta.model_name
219
- relation_type = self._get_relation_type(model, field)
220
- if field.related_model is None:
221
- schema_name = field.model.__get_schema_name__()
222
- related_model_name = None
223
- related_schema_name = None
224
- related_field_name = None
225
- field_name = field.name
226
- else:
227
- related_model_name = field.related_model._meta.model_name
228
- related_schema_name = field.related_model.__get_schema_name__()
229
- schema_name = field.model.__get_schema_name__()
230
- related_field_name = field.remote_field.name
231
- field_name = field.name
232
-
233
- if relation_type in ["one-to-many"]:
234
- # For a one-to-many relation, the field belong
235
- # to the other model as a foreign key.
236
- # To make usage similar to other relation types
237
- # we need to invert model and related model.
238
- schema_name, related_schema_name = related_schema_name, schema_name
239
- model_name, related_model_name = related_model_name, model_name
240
- field_name, related_field_name = related_field_name, field_name
241
- pass
242
-
243
- column = None
244
- if relation_type not in ["many-to-many", "one-to-many"]:
245
- if not isinstance(field, ForeignObjectRel):
246
- column = field.column
247
-
248
- if relation_type is None:
249
- through = None
250
- elif relation_type == "many-to-many":
251
- through = self._get_through_many_to_many(field)
252
- else:
253
- through = self._get_through(field)
254
-
255
- return FieldMetadata(
256
- schema_name=schema_name,
257
- model_name=model_name,
258
- field_name=field_name,
259
- type=internal_type,
260
- is_link_table=issubclass(field.model, LinkORM),
261
- column_name=column,
262
- relation_type=relation_type,
263
- related_schema_name=related_schema_name,
264
- related_model_name=related_model_name,
265
- related_field_name=related_field_name,
266
- through=through,
267
- )
268
-
269
- @staticmethod
270
- def _get_through_many_to_many(field_or_rel: ManyToManyField | ManyToManyRel):
271
- from lnschema_core.models import Registry
272
-
273
- if isinstance(field_or_rel, ManyToManyField):
274
- if field_or_rel.model != Registry:
275
- return Through(
276
- left_key=field_or_rel.m2m_column_name(),
277
- right_key=field_or_rel.m2m_reverse_name(),
278
- link_table_name=field_or_rel.remote_field.through._meta.db_table,
279
- )
280
- else:
281
- return Through(
282
- left_key=field_or_rel.m2m_reverse_name(),
283
- right_key=field_or_rel.m2m_column_name(),
284
- link_table_name=field_or_rel.remote_field.through._meta.db_table,
285
- )
286
-
287
- if isinstance(field_or_rel, ManyToManyRel):
288
- if field_or_rel.model != Registry:
289
- return Through(
290
- left_key=field_or_rel.field.m2m_reverse_name(),
291
- right_key=field_or_rel.field.m2m_column_name(),
292
- link_table_name=field_or_rel.through._meta.db_table,
293
- )
294
- else:
295
- return Through(
296
- left_key=field_or_rel.field.m2m_column_name(),
297
- right_key=field_or_rel.field.m2m_reverse_name(),
298
- link_table_name=field_or_rel.through._meta.db_table,
299
- )
300
-
301
- def _get_through(
302
- self, field_or_rel: ForeignKey | OneToOneField | ManyToOneRel | OneToOneRel
303
- ):
304
- if isinstance(field_or_rel, ForeignObjectRel):
305
- rel_1 = field_or_rel.field.related_fields[0][0]
306
- rel_2 = field_or_rel.field.related_fields[0][1]
307
- else:
308
- rel_1 = field_or_rel.related_fields[0][0]
309
- rel_2 = field_or_rel.related_fields[0][1]
310
-
311
- if rel_1.model._meta.model_name == self.model._meta.model_name:
312
- return Through(
313
- left_key=rel_1.column,
314
- right_key=rel_2.column,
315
- )
316
- else:
317
- return Through(
318
- left_key=rel_2.column,
319
- right_key=rel_1.column,
320
- )
321
-
322
- @staticmethod
323
- def _get_relation_type(model, field: Field):
324
- if field.many_to_one:
325
- # defined in the model
326
- if model == field.model:
327
- return "many-to-one"
328
- # defined in the related model
329
- else:
330
- return "one-to-many"
331
- elif field.one_to_many:
332
- return "one-to-many"
333
- elif field.many_to_many:
334
- return "many-to-many"
335
- elif field.one_to_one:
336
- return "one-to-one"
337
- else:
338
- return None
339
-
340
-
341
- class _SchemaHandler:
342
- def __init__(self) -> None:
343
- self.included_modules = ["core"] + list(settings.instance.schema)
344
- self.modules = self._get_modules_metadata()
345
-
346
- def to_dict(self, include_django_objects: bool = True):
347
- return {
348
- module_name: {
349
- model_name: model.to_dict(include_django_objects)
350
- for model_name, model in module.items()
351
- }
352
- for module_name, module in self.modules.items()
353
- }
354
-
355
- def to_json(self):
356
- return self.to_dict(include_django_objects=False)
357
-
358
- def _get_modules_metadata(self):
359
- from lnschema_core.models import Record, Registry
360
-
361
- all_models = {
362
- module_name: {
363
- model._meta.model_name: _ModelHandler(
364
- model, module_name, self.included_modules
365
- )
366
- for model in self._get_schema_module(
367
- module_name
368
- ).models.__dict__.values()
369
- if model.__class__ is Registry
370
- and model is not Record
371
- and not model._meta.abstract
372
- and model.__get_schema_name__() == module_name
373
- }
374
- for module_name in self.included_modules
375
- }
376
- assert all_models
377
- return all_models
378
-
379
- def _get_module_set_info(self):
380
- # TODO: rely on schemamodule table for this
381
- module_set_info = []
382
- for module_name in self.included_modules:
383
- module = self._get_schema_module(module_name)
384
- module_set_info.append(
385
- {"id": 0, "name": module_name, "version": module.__version__}
386
- )
387
- return module_set_info
388
-
389
- @staticmethod
390
- def _get_schema_module(module_name):
391
- return importlib.import_module(get_schema_module_name(module_name))
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import importlib
5
+ import json
6
+ from typing import TYPE_CHECKING, Literal
7
+ from uuid import UUID
8
+
9
+ from django.db.models import (
10
+ Field,
11
+ ForeignKey,
12
+ ForeignObjectRel,
13
+ ManyToManyField,
14
+ ManyToManyRel,
15
+ ManyToOneRel,
16
+ OneToOneField,
17
+ OneToOneRel,
18
+ )
19
+ from pydantic import BaseModel
20
+
21
+ from lamindb_setup import settings
22
+ from lamindb_setup._init_instance import get_schema_module_name
23
+ from lamindb_setup.core._hub_client import call_with_fallback_auth
24
+
25
+ # surpress pydantic warning about `model_` namespace
26
+ try:
27
+ BaseModel.model_config["protected_namespaces"] = ()
28
+ except Exception:
29
+ pass
30
+
31
+
32
+ if TYPE_CHECKING:
33
+ from supabase import Client
34
+
35
+
36
+ def update_schema_in_hub() -> tuple[bool, UUID, dict]:
37
+ return call_with_fallback_auth(_synchronize_schema)
38
+
39
+
40
+ def _synchronize_schema(client: Client) -> tuple[bool, UUID, dict]:
41
+ schema_metadata = _SchemaHandler()
42
+ schema_metadata_dict = schema_metadata.to_json()
43
+ schema_uuid = _dict_to_uuid(schema_metadata_dict)
44
+ schema = _get_schema_by_id(schema_uuid, client)
45
+
46
+ is_new = schema is None
47
+ if is_new:
48
+ module_set_info = schema_metadata._get_module_set_info()
49
+ module_ids = "-".join(str(module_info["id"]) for module_info in module_set_info)
50
+ schema = (
51
+ client.table("schema")
52
+ .insert(
53
+ {
54
+ "id": schema_uuid.hex,
55
+ "module_ids": module_ids,
56
+ "module_set_info": module_set_info,
57
+ "schema_json": schema_metadata_dict,
58
+ }
59
+ )
60
+ .execute()
61
+ .data[0]
62
+ )
63
+
64
+ instance_response = (
65
+ client.table("instance")
66
+ .update({"schema_id": schema_uuid.hex})
67
+ .eq("id", settings.instance._id.hex)
68
+ .execute()
69
+ )
70
+ assert (
71
+ len(instance_response.data) == 1
72
+ ), f"schema of instance {settings.instance._id.hex} could not be updated with schema {schema_uuid.hex}"
73
+
74
+ return is_new, schema_uuid, schema
75
+
76
+
77
+ def get_schema_by_id(id: UUID):
78
+ return call_with_fallback_auth(_get_schema_by_id, id=id)
79
+
80
+
81
+ def _get_schema_by_id(id: UUID, client: Client):
82
+ response = client.table("schema").select("*").eq("id", id.hex).execute()
83
+ if len(response.data) == 0:
84
+ return None
85
+ return response.data[0]
86
+
87
+
88
+ def _dict_to_uuid(dict: dict):
89
+ encoded = json.dumps(dict, sort_keys=True).encode("utf-8")
90
+ hash = hashlib.md5(encoded).digest()
91
+ uuid = UUID(bytes=hash[:16])
92
+ return uuid
93
+
94
+
95
+ RelationType = Literal["many-to-one", "one-to-many", "many-to-many", "one-to-one"]
96
+ Type = Literal[
97
+ "ForeignKey",
98
+ "CharField",
99
+ "DateTimeField",
100
+ "AutoField",
101
+ "BooleanField",
102
+ "BigIntegerField",
103
+ "SmallIntegerField",
104
+ "TextField",
105
+ "BigAutoField",
106
+ "ManyToManyField",
107
+ "IntegerField",
108
+ "OneToOneField",
109
+ "JSONField",
110
+ "DateField",
111
+ "FloatField",
112
+ "PositiveIntegerField",
113
+ "PositiveBigIntegerField",
114
+ ]
115
+
116
+
117
+ class Through(BaseModel):
118
+ left_key: str
119
+ right_key: str
120
+ link_table_name: str | None = None
121
+
122
+
123
+ class FieldMetadata(BaseModel):
124
+ type: Type
125
+ column_name: str | None = None
126
+ through: Through | None = None
127
+ field_name: str
128
+ model_name: str
129
+ schema_name: str
130
+ is_link_table: bool
131
+ relation_type: RelationType | None = None
132
+ related_field_name: str | None = None
133
+ related_model_name: str | None = None
134
+ related_schema_name: str | None = None
135
+
136
+
137
+ class _ModelHandler:
138
+ def __init__(self, model, module_name: str, included_modules: list[str]) -> None:
139
+ self.model = model
140
+ self.class_name = model.__name__
141
+ self.module_name = module_name
142
+ self.model_name = model._meta.model_name
143
+ self.table_name = model._meta.db_table
144
+ self.included_modules = included_modules
145
+ self.fields = self._get_fields_metadata(self.model)
146
+
147
+ def to_dict(self, include_django_objects: bool = True):
148
+ _dict = {
149
+ "fields": self.fields.copy(),
150
+ "class_name": self.class_name,
151
+ "table_name": self.table_name,
152
+ }
153
+
154
+ for field_name in self.fields.keys():
155
+ _dict["fields"][field_name] = _dict["fields"][field_name].__dict__
156
+ through = _dict["fields"][field_name]["through"]
157
+ if through is not None:
158
+ _dict["fields"][field_name]["through"] = through.__dict__
159
+
160
+ if include_django_objects:
161
+ _dict.update({"model": self.model})
162
+
163
+ return _dict
164
+
165
+ def _get_fields_metadata(self, model):
166
+ related_fields = []
167
+ fields_metadata: dict[str, FieldMetadata] = {}
168
+
169
+ for field in model._meta.get_fields():
170
+ field_metadata = self._get_field_metadata(model, field)
171
+ if field_metadata.related_schema_name is None:
172
+ fields_metadata.update({field.name: field_metadata})
173
+
174
+ if (
175
+ field_metadata.related_schema_name in self.included_modules
176
+ and field_metadata.schema_name in self.included_modules
177
+ ):
178
+ related_fields.append(field)
179
+
180
+ related_fields_metadata = self._get_related_fields_metadata(
181
+ model, related_fields
182
+ )
183
+
184
+ fields_metadata = {**fields_metadata, **related_fields_metadata}
185
+
186
+ return fields_metadata
187
+
188
+ def _get_related_fields_metadata(self, model, fields: list[ForeignObjectRel]):
189
+ related_fields: dict[str, FieldMetadata] = {}
190
+
191
+ for field in fields:
192
+ if field.many_to_one:
193
+ related_fields.update(
194
+ {f"{field.name}": self._get_field_metadata(model, field)}
195
+ )
196
+ elif field.one_to_many:
197
+ # exclude self reference as it is already included in the many to one
198
+ if field.related_model == model:
199
+ continue
200
+ related_fields.update(
201
+ {f"{field.name}": self._get_field_metadata(model, field.field)}
202
+ )
203
+ elif field.many_to_many:
204
+ related_fields.update(
205
+ {f"{field.name}": self._get_field_metadata(model, field)}
206
+ )
207
+ elif field.one_to_one:
208
+ related_fields.update(
209
+ {f"{field.name}": self._get_field_metadata(model, field)}
210
+ )
211
+
212
+ return related_fields
213
+
214
+ def _get_field_metadata(self, model, field: Field):
215
+ from lnschema_core.models import LinkORM
216
+
217
+ internal_type = field.get_internal_type()
218
+ model_name = field.model._meta.model_name
219
+ relation_type = self._get_relation_type(model, field)
220
+ if field.related_model is None:
221
+ schema_name = field.model.__get_schema_name__()
222
+ related_model_name = None
223
+ related_schema_name = None
224
+ related_field_name = None
225
+ field_name = field.name
226
+ else:
227
+ related_model_name = field.related_model._meta.model_name
228
+ related_schema_name = field.related_model.__get_schema_name__()
229
+ schema_name = field.model.__get_schema_name__()
230
+ related_field_name = field.remote_field.name
231
+ field_name = field.name
232
+
233
+ if relation_type in ["one-to-many"]:
234
+ # For a one-to-many relation, the field belong
235
+ # to the other model as a foreign key.
236
+ # To make usage similar to other relation types
237
+ # we need to invert model and related model.
238
+ schema_name, related_schema_name = related_schema_name, schema_name
239
+ model_name, related_model_name = related_model_name, model_name
240
+ field_name, related_field_name = related_field_name, field_name
241
+ pass
242
+
243
+ column = None
244
+ if relation_type not in ["many-to-many", "one-to-many"]:
245
+ if not isinstance(field, ForeignObjectRel):
246
+ column = field.column
247
+
248
+ if relation_type is None:
249
+ through = None
250
+ elif relation_type == "many-to-many":
251
+ through = self._get_through_many_to_many(field)
252
+ else:
253
+ through = self._get_through(field)
254
+
255
+ return FieldMetadata(
256
+ schema_name=schema_name,
257
+ model_name=model_name,
258
+ field_name=field_name,
259
+ type=internal_type,
260
+ is_link_table=issubclass(field.model, LinkORM),
261
+ column_name=column,
262
+ relation_type=relation_type,
263
+ related_schema_name=related_schema_name,
264
+ related_model_name=related_model_name,
265
+ related_field_name=related_field_name,
266
+ through=through,
267
+ )
268
+
269
+ @staticmethod
270
+ def _get_through_many_to_many(field_or_rel: ManyToManyField | ManyToManyRel):
271
+ from lnschema_core.models import Registry
272
+
273
+ if isinstance(field_or_rel, ManyToManyField):
274
+ if field_or_rel.model != Registry:
275
+ return Through(
276
+ left_key=field_or_rel.m2m_column_name(),
277
+ right_key=field_or_rel.m2m_reverse_name(),
278
+ link_table_name=field_or_rel.remote_field.through._meta.db_table,
279
+ )
280
+ else:
281
+ return Through(
282
+ left_key=field_or_rel.m2m_reverse_name(),
283
+ right_key=field_or_rel.m2m_column_name(),
284
+ link_table_name=field_or_rel.remote_field.through._meta.db_table,
285
+ )
286
+
287
+ if isinstance(field_or_rel, ManyToManyRel):
288
+ if field_or_rel.model != Registry:
289
+ return Through(
290
+ left_key=field_or_rel.field.m2m_reverse_name(),
291
+ right_key=field_or_rel.field.m2m_column_name(),
292
+ link_table_name=field_or_rel.through._meta.db_table,
293
+ )
294
+ else:
295
+ return Through(
296
+ left_key=field_or_rel.field.m2m_column_name(),
297
+ right_key=field_or_rel.field.m2m_reverse_name(),
298
+ link_table_name=field_or_rel.through._meta.db_table,
299
+ )
300
+
301
+ def _get_through(
302
+ self, field_or_rel: ForeignKey | OneToOneField | ManyToOneRel | OneToOneRel
303
+ ):
304
+ if isinstance(field_or_rel, ForeignObjectRel):
305
+ rel_1 = field_or_rel.field.related_fields[0][0]
306
+ rel_2 = field_or_rel.field.related_fields[0][1]
307
+ else:
308
+ rel_1 = field_or_rel.related_fields[0][0]
309
+ rel_2 = field_or_rel.related_fields[0][1]
310
+
311
+ if rel_1.model._meta.model_name == self.model._meta.model_name:
312
+ return Through(
313
+ left_key=rel_1.column,
314
+ right_key=rel_2.column,
315
+ )
316
+ else:
317
+ return Through(
318
+ left_key=rel_2.column,
319
+ right_key=rel_1.column,
320
+ )
321
+
322
+ @staticmethod
323
+ def _get_relation_type(model, field: Field):
324
+ if field.many_to_one:
325
+ # defined in the model
326
+ if model == field.model:
327
+ return "many-to-one"
328
+ # defined in the related model
329
+ else:
330
+ return "one-to-many"
331
+ elif field.one_to_many:
332
+ return "one-to-many"
333
+ elif field.many_to_many:
334
+ return "many-to-many"
335
+ elif field.one_to_one:
336
+ return "one-to-one"
337
+ else:
338
+ return None
339
+
340
+
341
+ class _SchemaHandler:
342
+ def __init__(self) -> None:
343
+ self.included_modules = ["core"] + list(settings.instance.schema)
344
+ self.modules = self._get_modules_metadata()
345
+
346
+ def to_dict(self, include_django_objects: bool = True):
347
+ return {
348
+ module_name: {
349
+ model_name: model.to_dict(include_django_objects)
350
+ for model_name, model in module.items()
351
+ }
352
+ for module_name, module in self.modules.items()
353
+ }
354
+
355
+ def to_json(self):
356
+ return self.to_dict(include_django_objects=False)
357
+
358
+ def _get_modules_metadata(self):
359
+ from lnschema_core.models import Record, Registry
360
+
361
+ all_models = {
362
+ module_name: {
363
+ model._meta.model_name: _ModelHandler(
364
+ model, module_name, self.included_modules
365
+ )
366
+ for model in self._get_schema_module(
367
+ module_name
368
+ ).models.__dict__.values()
369
+ if model.__class__ is Registry
370
+ and model is not Record
371
+ and not model._meta.abstract
372
+ and model.__get_schema_name__() == module_name
373
+ }
374
+ for module_name in self.included_modules
375
+ }
376
+ assert all_models
377
+ return all_models
378
+
379
+ def _get_module_set_info(self):
380
+ # TODO: rely on schemamodule table for this
381
+ module_set_info = []
382
+ for module_name in self.included_modules:
383
+ module = self._get_schema_module(module_name)
384
+ module_set_info.append(
385
+ {"id": 0, "name": module_name, "version": module.__version__}
386
+ )
387
+ return module_set_info
388
+
389
+ @staticmethod
390
+ def _get_schema_module(module_name):
391
+ return importlib.import_module(get_schema_module_name(module_name))