lamindb 1.1.0__py3-none-any.whl → 1.2a2__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 (72) hide show
  1. lamindb/__init__.py +31 -26
  2. lamindb/_finish.py +9 -1
  3. lamindb/_tracked.py +26 -3
  4. lamindb/_view.py +2 -3
  5. lamindb/base/__init__.py +1 -1
  6. lamindb/base/ids.py +1 -10
  7. lamindb/base/users.py +1 -4
  8. lamindb/core/__init__.py +7 -65
  9. lamindb/core/_context.py +41 -10
  10. lamindb/core/_mapped_collection.py +4 -2
  11. lamindb/core/_settings.py +6 -6
  12. lamindb/core/_sync_git.py +1 -1
  13. lamindb/core/_track_environment.py +2 -1
  14. lamindb/core/datasets/_small.py +3 -3
  15. lamindb/core/loaders.py +22 -9
  16. lamindb/core/storage/_anndata_accessor.py +8 -3
  17. lamindb/core/storage/_backed_access.py +14 -7
  18. lamindb/core/storage/_pyarrow_dataset.py +24 -9
  19. lamindb/core/storage/_tiledbsoma.py +6 -4
  20. lamindb/core/storage/_zarr.py +32 -11
  21. lamindb/core/storage/objects.py +59 -26
  22. lamindb/core/storage/paths.py +16 -13
  23. lamindb/curators/__init__.py +173 -145
  24. lamindb/errors.py +1 -1
  25. lamindb/integrations/_vitessce.py +4 -4
  26. lamindb/migrations/0089_subsequent_runs.py +159 -0
  27. lamindb/migrations/0090_runproject_project_runs.py +73 -0
  28. lamindb/migrations/{0088_squashed.py → 0090_squashed.py} +245 -177
  29. lamindb/models/__init__.py +79 -0
  30. lamindb/{core → models}/_describe.py +3 -3
  31. lamindb/{core → models}/_django.py +8 -5
  32. lamindb/{core → models}/_feature_manager.py +103 -87
  33. lamindb/{_from_values.py → models/_from_values.py} +5 -2
  34. lamindb/{core/versioning.py → models/_is_versioned.py} +94 -6
  35. lamindb/{core → models}/_label_manager.py +10 -17
  36. lamindb/{core/relations.py → models/_relations.py} +8 -1
  37. lamindb/models/artifact.py +2601 -0
  38. lamindb/{_can_curate.py → models/can_curate.py} +349 -180
  39. lamindb/models/collection.py +683 -0
  40. lamindb/models/core.py +135 -0
  41. lamindb/models/feature.py +643 -0
  42. lamindb/models/flextable.py +163 -0
  43. lamindb/{_parents.py → models/has_parents.py} +55 -49
  44. lamindb/models/project.py +384 -0
  45. lamindb/{_query_manager.py → models/query_manager.py} +10 -8
  46. lamindb/{_query_set.py → models/query_set.py} +52 -30
  47. lamindb/models/record.py +1757 -0
  48. lamindb/models/run.py +563 -0
  49. lamindb/{_save.py → models/save.py} +18 -8
  50. lamindb/models/schema.py +732 -0
  51. lamindb/models/transform.py +360 -0
  52. lamindb/models/ulabel.py +249 -0
  53. {lamindb-1.1.0.dist-info → lamindb-1.2a2.dist-info}/METADATA +5 -5
  54. lamindb-1.2a2.dist-info/RECORD +94 -0
  55. lamindb/_artifact.py +0 -1361
  56. lamindb/_collection.py +0 -440
  57. lamindb/_feature.py +0 -316
  58. lamindb/_is_versioned.py +0 -40
  59. lamindb/_record.py +0 -1065
  60. lamindb/_run.py +0 -60
  61. lamindb/_schema.py +0 -347
  62. lamindb/_storage.py +0 -15
  63. lamindb/_transform.py +0 -170
  64. lamindb/_ulabel.py +0 -56
  65. lamindb/_utils.py +0 -9
  66. lamindb/base/validation.py +0 -63
  67. lamindb/core/_data.py +0 -491
  68. lamindb/core/fields.py +0 -12
  69. lamindb/models.py +0 -4435
  70. lamindb-1.1.0.dist-info/RECORD +0 -95
  71. {lamindb-1.1.0.dist-info → lamindb-1.2a2.dist-info}/LICENSE +0 -0
  72. {lamindb-1.1.0.dist-info → lamindb-1.2a2.dist-info}/WHEEL +0 -0
@@ -0,0 +1,1757 @@
1
+ from __future__ import annotations
2
+
3
+ import builtins
4
+ import inspect
5
+ import re
6
+ import sys
7
+ from collections import defaultdict
8
+ from functools import reduce
9
+ from itertools import chain
10
+ from pathlib import PurePosixPath
11
+ from typing import (
12
+ TYPE_CHECKING,
13
+ Any,
14
+ Literal,
15
+ NamedTuple,
16
+ Union,
17
+ )
18
+
19
+ import dj_database_url
20
+ import lamindb_setup as ln_setup
21
+ from django.core.exceptions import ValidationError as DjangoValidationError
22
+ from django.db import IntegrityError, connections, models, transaction
23
+ from django.db.models import (
24
+ CASCADE,
25
+ PROTECT,
26
+ Field,
27
+ IntegerField,
28
+ Manager,
29
+ Q,
30
+ QuerySet,
31
+ Value,
32
+ )
33
+ from django.db.models.base import ModelBase
34
+ from django.db.models.fields.related import (
35
+ ManyToManyField,
36
+ ManyToManyRel,
37
+ ManyToOneRel,
38
+ )
39
+ from django.db.models.functions import Cast, Coalesce
40
+ from django.db.models.lookups import (
41
+ Contains,
42
+ Exact,
43
+ IContains,
44
+ IExact,
45
+ IRegex,
46
+ IStartsWith,
47
+ Regex,
48
+ StartsWith,
49
+ )
50
+ from lamin_utils import colors, logger
51
+ from lamin_utils._lookup import Lookup
52
+ from lamindb_setup._connect_instance import (
53
+ get_owner_name_from_identifier,
54
+ load_instance_settings,
55
+ update_db_using_local,
56
+ )
57
+ from lamindb_setup.core._docs import doc_args
58
+ from lamindb_setup.core._hub_core import connect_instance_hub
59
+ from lamindb_setup.core._settings_store import instance_settings_file
60
+ from lamindb_setup.core.upath import extract_suffix_from_path
61
+
62
+ from lamindb.base import deprecated
63
+ from lamindb.base.fields import (
64
+ CharField,
65
+ DateTimeField,
66
+ ForeignKey,
67
+ JSONField,
68
+ TextField,
69
+ )
70
+ from lamindb.base.types import FieldAttr, StrField
71
+ from lamindb.errors import FieldValidationError
72
+
73
+ from ..errors import (
74
+ InvalidArgument,
75
+ RecordNameChangeIntegrityError,
76
+ ValidationError,
77
+ )
78
+ from ._is_versioned import IsVersioned
79
+
80
+ if TYPE_CHECKING:
81
+ from datetime import datetime
82
+
83
+ import pandas as pd
84
+
85
+ from .artifact import Artifact
86
+ from .run import Run, User
87
+ from .transform import Transform
88
+
89
+
90
+ IPYTHON = getattr(builtins, "__IPYTHON__", False)
91
+
92
+
93
+ # -------------------------------------------------------------------------------------
94
+ # A note on required fields at the Record level
95
+ #
96
+ # As Django does most of its validation on the Form-level, it doesn't offer functionality
97
+ # for validating the integrity of an Record object upon instantation (similar to pydantic)
98
+ #
99
+ # For required fields, we define them as commonly done on the SQL level together
100
+ # with a validator in Record (validate_required_fields)
101
+ #
102
+ # This goes against the Django convention, but goes with the SQLModel convention
103
+ # (Optional fields can be null on the SQL level, non-optional fields cannot)
104
+ #
105
+ # Due to Django's convention where CharFieldAttr has pre-configured (null=False, default=""), marking
106
+ # a required field necessitates passing `default=None`. Without the validator it would trigger
107
+ # an error at the SQL-level, with it, it triggers it at instantiation
108
+
109
+ # -------------------------------------------------------------------------------------
110
+ # A note on class and instance methods of core Record
111
+ #
112
+ # All of these are defined and tested within lamindb, in files starting with _{orm_name}.py
113
+
114
+ # -------------------------------------------------------------------------------------
115
+ # A note on maximal lengths of char fields
116
+ #
117
+ # 100 characters:
118
+ # "Raindrops pitter-pattered on the windowpane, blurring the"
119
+ # "city lights outside, curled up with a mug."
120
+ # A good maximal length for a name (title).
121
+ #
122
+ # 150 characters: We choose this for name maximal length because some users like long names.
123
+ #
124
+ # 255 characters:
125
+ # "In creating a precise 255-character paragraph, one engages in"
126
+ # "a dance of words, where clarity meets brevity. Every syllable counts,"
127
+ # "illustrating the skill in compact expression, ensuring the essence of the"
128
+ # "message shines through within the exacting limit."
129
+ # This is a good maximal length for a description field.
130
+
131
+
132
+ class LinkORM:
133
+ pass
134
+
135
+
136
+ def deferred_attribute__repr__(self):
137
+ return f"FieldAttr({self.field.model.__name__}.{self.field.name})"
138
+
139
+
140
+ FieldAttr.__repr__ = deferred_attribute__repr__ # type: ignore
141
+
142
+
143
+ class ValidateFields:
144
+ pass
145
+
146
+
147
+ def is_approx_pascal_case(s):
148
+ """Check if the last component of a dotted string is in PascalCase.
149
+
150
+ Args:
151
+ s (str): The string to check
152
+
153
+ Returns:
154
+ bool: True if the last component is in PascalCase
155
+
156
+ Raises:
157
+ ValueError: If the last component doesn't start with a capital letter
158
+ """
159
+ if "[" in s: # this is because we allow types of form 'script[test_script.py]'
160
+ return True
161
+ last_component = s.split(".")[-1]
162
+
163
+ if not last_component[0].isupper():
164
+ raise ValueError(
165
+ f"'{last_component}' should start with a capital letter given you're defining a type"
166
+ )
167
+
168
+ return True
169
+
170
+
171
+ def init_self_from_db(self: Record, existing_record: Record):
172
+ new_args = [
173
+ getattr(existing_record, field.attname) for field in self._meta.concrete_fields
174
+ ]
175
+ super(self.__class__, self).__init__(*new_args)
176
+ self._state.adding = False # mimic from_db
177
+ self._state.db = "default"
178
+
179
+
180
+ def update_attributes(record: Record, attributes: dict[str, str]):
181
+ for key, value in attributes.items():
182
+ if (
183
+ getattr(record, key) != value
184
+ and value is not None
185
+ and key != "dtype"
186
+ and key != "_aux"
187
+ ):
188
+ logger.warning(f"updated {key} from {getattr(record, key)} to {value}")
189
+ setattr(record, key, value)
190
+
191
+
192
+ def validate_literal_fields(record: Record, kwargs) -> None:
193
+ """Validate all Literal type fields in a record.
194
+
195
+ Args:
196
+ record: record being validated
197
+
198
+ Raises:
199
+ ValidationError: If any field value is not in its Literal's allowed values
200
+ """
201
+ if isinstance(record, LinkORM):
202
+ return None
203
+ if record.__class__.__name__ in "Feature":
204
+ return None
205
+ from lamindb.base.types import FeatureDtype, TransformType
206
+
207
+ types = {
208
+ "TransformType": TransformType,
209
+ "ArtifactKind": FeatureDtype,
210
+ "FeatureDtype": FeatureDtype,
211
+ }
212
+ errors = {}
213
+ annotations = getattr(record.__class__, "__annotations__", {})
214
+ for field_name, annotation in annotations.items():
215
+ if field_name not in kwargs or kwargs[field_name] is None:
216
+ continue
217
+ value = kwargs[field_name]
218
+ if str(annotation) in types:
219
+ annotation = types[annotation]
220
+ if not hasattr(annotation, "__origin__"):
221
+ continue
222
+ literal_type = annotation if annotation.__origin__ is Literal else None
223
+ if literal_type is None:
224
+ continue
225
+ valid_values = set(literal_type.__args__)
226
+ if value not in valid_values:
227
+ errors[field_name] = (
228
+ f"{field_name}: {colors.yellow(value)} is not a valid value"
229
+ f"\n → Valid values are: {colors.green(', '.join(sorted(valid_values)))}"
230
+ )
231
+ if errors:
232
+ message = "\n "
233
+ for _, error in errors.items():
234
+ message += error + "\n "
235
+ raise FieldValidationError(message)
236
+
237
+
238
+ def validate_fields(record: Record, kwargs):
239
+ from lamindb.models import (
240
+ Artifact,
241
+ Collection,
242
+ Feature,
243
+ Param,
244
+ Run,
245
+ Schema,
246
+ Transform,
247
+ ULabel,
248
+ )
249
+
250
+ # validate required fields
251
+ # a "required field" is a Django field that has `null=False, default=None`
252
+ required_fields = {
253
+ k.name for k in record._meta.fields if not k.null and k.default is None
254
+ }
255
+ required_fields_not_passed = {k: None for k in required_fields if k not in kwargs}
256
+ kwargs.update(required_fields_not_passed)
257
+ missing_fields = [
258
+ k for k, v in kwargs.items() if v is None and k in required_fields
259
+ ]
260
+ if missing_fields:
261
+ raise FieldValidationError(f"{missing_fields} are required.")
262
+ # ensure the exact length of the internal uid for core entities
263
+ if "uid" in kwargs and record.__class__ in {
264
+ Artifact,
265
+ Collection,
266
+ Transform,
267
+ Run,
268
+ ULabel,
269
+ Feature,
270
+ Schema,
271
+ Param,
272
+ }:
273
+ uid_max_length = record.__class__._meta.get_field(
274
+ "uid"
275
+ ).max_length # triggers FieldDoesNotExist
276
+ if len(kwargs["uid"]) != uid_max_length: # triggers KeyError
277
+ raise ValidationError(
278
+ f"`uid` must be exactly {uid_max_length} characters long, got {len(kwargs['uid'])}."
279
+ )
280
+ # validate is_type
281
+ if "is_type" in kwargs and "name" in kwargs and kwargs["is_type"]:
282
+ if kwargs["name"].endswith("s"):
283
+ logger.warning(
284
+ f"name '{kwargs['name']}' for type ends with 's', in case you're naming with plural, consider the singular for a type name"
285
+ )
286
+ is_approx_pascal_case(kwargs["name"])
287
+ # validate literals
288
+ validate_literal_fields(record, kwargs)
289
+
290
+
291
+ def suggest_records_with_similar_names(
292
+ record: Record, name_field: str, kwargs
293
+ ) -> Record | None:
294
+ """Returns True if found exact match, otherwise False.
295
+
296
+ Logs similar matches if found.
297
+ """
298
+ if kwargs.get(name_field) is None or not isinstance(kwargs.get(name_field), str):
299
+ return None
300
+ # need to perform an additional request to find the exact match
301
+ # previously, this was inferred from the truncated/fuzzy search below
302
+ # but this isn't reliable: https://laminlabs.slack.com/archives/C04FPE8V01W/p1737812808563409
303
+ # the below needs to be .first() because there might be multiple records with the same
304
+ # name field in case the record is versioned (e.g. for Transform key)
305
+ exact_match = record.__class__.filter(**{name_field: kwargs[name_field]}).first()
306
+ if exact_match is not None:
307
+ return exact_match
308
+ queryset = _search(
309
+ record.__class__,
310
+ kwargs[name_field],
311
+ field=name_field,
312
+ truncate_string=True,
313
+ limit=3,
314
+ )
315
+ if not queryset.exists(): # empty queryset
316
+ return None
317
+ s, it, nots = ("", "it", "s") if len(queryset) == 1 else ("s", "one of them", "")
318
+ msg = f"record{s} with similar {name_field}{s} exist{nots}! did you mean to load {it}?"
319
+ if IPYTHON:
320
+ from IPython.display import display
321
+
322
+ from lamindb import settings
323
+
324
+ logger.warning(f"{msg}")
325
+ if settings._verbosity_int >= 1:
326
+ display(queryset.df())
327
+ else:
328
+ logger.warning(f"{msg}\n{queryset}")
329
+ return None
330
+
331
+
332
+ RECORD_REGISTRY_EXAMPLE = """Example::
333
+
334
+ from lamindb import Record, fields
335
+
336
+ # sub-classing `Record` creates a new registry
337
+ class Experiment(Record):
338
+ name: str = fields.CharField()
339
+
340
+ # instantiating `Experiment` creates a record `experiment`
341
+ experiment = Experiment(name="my experiment")
342
+
343
+ # you can save the record to the database
344
+ experiment.save()
345
+
346
+ # `Experiment` refers to the registry, which you can query
347
+ df = Experiment.filter(name__startswith="my ").df()
348
+ """
349
+
350
+
351
+ # this is the metaclass for Record
352
+ @doc_args(RECORD_REGISTRY_EXAMPLE)
353
+ class Registry(ModelBase):
354
+ """Metaclass for :class:`~lamindb.models.Record`.
355
+
356
+ Each `Registry` *object* is a `Record` *class* and corresponds to a table in the metadata SQL database.
357
+
358
+ You work with `Registry` objects whenever you use *class methods* of `Record`.
359
+
360
+ You call any subclass of `Record` a "registry" and their objects "records". A `Record` object corresponds to a row in the SQL table.
361
+
362
+ If you want to create a new registry, you sub-class `Record`.
363
+
364
+ {}
365
+
366
+ Note: `Registry` inherits from Django's `ModelBase`.
367
+ """
368
+
369
+ def __new__(cls, name, bases, attrs, **kwargs):
370
+ new_class = super().__new__(cls, name, bases, attrs, **kwargs)
371
+ return new_class
372
+
373
+ # below creates a sensible auto-complete behavior that differs across the
374
+ # class and instance level in Jupyter Editors it doesn't have any effect for
375
+ # static type analyzer like pylance used in VSCode
376
+ def __dir__(cls):
377
+ # this is needed to bring auto-complete on the class-level back
378
+ # https://laminlabs.slack.com/archives/C04FPE8V01W/p1717535625268849
379
+ # Filter class attributes, excluding instance methods
380
+ exclude_instance_methods = "sphinx" not in sys.modules
381
+ # https://laminlabs.slack.com/archives/C04FPE8V01W/p1721134595920959
382
+
383
+ def include_attribute(attr_name, attr_value):
384
+ if attr_name.startswith("__"):
385
+ return False
386
+ if exclude_instance_methods and callable(attr_value):
387
+ return isinstance(attr_value, (classmethod, staticmethod, type))
388
+ return True
389
+
390
+ # check also inherited attributes
391
+ if hasattr(cls, "mro"):
392
+ attrs = chain(*(c.__dict__.items() for c in cls.mro()))
393
+ else:
394
+ attrs = cls.__dict__.items()
395
+
396
+ result = []
397
+ for attr_name, attr_value in attrs:
398
+ if attr_name not in result and include_attribute(attr_name, attr_value):
399
+ result.append(attr_name)
400
+
401
+ # Add non-dunder attributes from Registry
402
+ for attr in dir(Registry):
403
+ if not attr.startswith("__") and attr not in result:
404
+ result.append(attr)
405
+ return result
406
+
407
+ def __repr__(cls) -> str:
408
+ return registry_repr(cls)
409
+
410
+ def lookup(
411
+ cls,
412
+ field: StrField | None = None,
413
+ return_field: StrField | None = None,
414
+ ) -> NamedTuple:
415
+ """Return an auto-complete object for a field.
416
+
417
+ Args:
418
+ field: The field to look up the values for. Defaults to first string field.
419
+ return_field: The field to return. If `None`, returns the whole record.
420
+
421
+ Returns:
422
+ A `NamedTuple` of lookup information of the field values with a
423
+ dictionary converter.
424
+
425
+ See Also:
426
+ :meth:`~lamindb.models.Record.search`
427
+
428
+ Examples:
429
+ >>> import bionty as bt
430
+ >>> bt.settings.organism = "human"
431
+ >>> bt.Gene.from_source(symbol="ADGB-DT").save()
432
+ >>> lookup = bt.Gene.lookup()
433
+ >>> lookup.adgb_dt
434
+ >>> lookup_dict = lookup.dict()
435
+ >>> lookup_dict['ADGB-DT']
436
+ >>> lookup_by_ensembl_id = bt.Gene.lookup(field="ensembl_gene_id")
437
+ >>> genes.ensg00000002745
438
+ >>> lookup_return_symbols = bt.Gene.lookup(field="ensembl_gene_id", return_field="symbol")
439
+ """
440
+ return _lookup(cls=cls, field=field, return_field=return_field)
441
+
442
+ def filter(cls, *queries, **expressions) -> QuerySet:
443
+ """Query records.
444
+
445
+ Args:
446
+ queries: One or multiple `Q` objects.
447
+ expressions: Fields and values passed as Django query expressions.
448
+
449
+ Returns:
450
+ A :class:`~lamindb.models.QuerySet`.
451
+
452
+ See Also:
453
+ - Guide: :doc:`docs:registries`
454
+ - Django documentation: `Queries <https://docs.djangoproject.com/en/stable/topics/db/queries/>`__
455
+
456
+ Examples:
457
+ >>> ln.ULabel(name="my label").save()
458
+ >>> ln.ULabel.filter(name__startswith="my").df()
459
+ """
460
+ from .query_set import QuerySet
461
+
462
+ _using_key = None
463
+ if "_using_key" in expressions:
464
+ _using_key = expressions.pop("_using_key")
465
+
466
+ return QuerySet(model=cls, using=_using_key).filter(*queries, **expressions)
467
+
468
+ def get(
469
+ cls,
470
+ idlike: int | str | None = None,
471
+ **expressions,
472
+ ) -> Record:
473
+ """Get a single record.
474
+
475
+ Args:
476
+ idlike: Either a uid stub, uid or an integer id.
477
+ expressions: Fields and values passed as Django query expressions.
478
+
479
+ Returns:
480
+ A record.
481
+
482
+ Raises:
483
+ :exc:`docs:lamindb.errors.DoesNotExist`: In case no matching record is found.
484
+
485
+ See Also:
486
+ - Guide: :doc:`docs:registries`
487
+ - Django documentation: `Queries <https://docs.djangoproject.com/en/stable/topics/db/queries/>`__
488
+
489
+ Examples:
490
+ >>> ulabel = ln.ULabel.get("FvtpPJLJ")
491
+ >>> ulabel = ln.ULabel.get(name="my-label")
492
+ """
493
+ from .query_set import QuerySet
494
+
495
+ return QuerySet(model=cls).get(idlike, **expressions)
496
+
497
+ def df(
498
+ cls,
499
+ include: str | list[str] | None = None,
500
+ features: bool | list[str] = False,
501
+ limit: int = 100,
502
+ ) -> pd.DataFrame:
503
+ """Convert to `pd.DataFrame`.
504
+
505
+ By default, shows all direct fields, except `updated_at`.
506
+
507
+ Use arguments `include` or `feature` to include other data.
508
+
509
+ Args:
510
+ include: Related fields to include as columns. Takes strings of
511
+ form `"ulabels__name"`, `"cell_types__name"`, etc. or a list
512
+ of such strings.
513
+ features: If `True`, map all features of the
514
+ :class:`~lamindb.Feature` registry onto the resulting
515
+ `DataFrame`. Only available for `Artifact`.
516
+ limit: Maximum number of rows to display from a Pandas DataFrame.
517
+ Defaults to 100 to reduce database load.
518
+
519
+ Examples:
520
+
521
+ Include the name of the creator in the `DataFrame`:
522
+
523
+ >>> ln.ULabel.df(include="created_by__name"])
524
+
525
+ Include display of features for `Artifact`:
526
+
527
+ >>> df = ln.Artifact.df(features=True)
528
+ >>> ln.view(df) # visualize with type annotations
529
+
530
+ Only include select features:
531
+
532
+ >>> df = ln.Artifact.df(features=["cell_type_by_expert", "cell_type_by_model"])
533
+ """
534
+ query_set = cls.filter()
535
+ if hasattr(cls, "updated_at"):
536
+ query_set = query_set.order_by("-updated_at")
537
+ return query_set[:limit].df(include=include, features=features)
538
+
539
+ def search(
540
+ cls,
541
+ string: str,
542
+ *,
543
+ field: StrField | None = None,
544
+ limit: int | None = 20,
545
+ case_sensitive: bool = False,
546
+ ) -> QuerySet:
547
+ """Search.
548
+
549
+ Args:
550
+ string: The input string to match against the field ontology values.
551
+ field: The field or fields to search. Search all string fields by default.
552
+ limit: Maximum amount of top results to return.
553
+ case_sensitive: Whether the match is case sensitive.
554
+
555
+ Returns:
556
+ A sorted `DataFrame` of search results with a score in column `score`.
557
+ If `return_queryset` is `True`. `QuerySet`.
558
+
559
+ See Also:
560
+ :meth:`~lamindb.models.Record.filter`
561
+ :meth:`~lamindb.models.Record.lookup`
562
+
563
+ Examples:
564
+ >>> ulabels = ln.ULabel.from_values(["ULabel1", "ULabel2", "ULabel3"], field="name")
565
+ >>> ln.save(ulabels)
566
+ >>> ln.ULabel.search("ULabel2")
567
+ """
568
+ return _search(
569
+ cls=cls,
570
+ string=string,
571
+ field=field,
572
+ limit=limit,
573
+ case_sensitive=case_sensitive,
574
+ )
575
+
576
+ def using(
577
+ cls,
578
+ instance: str | None,
579
+ ) -> QuerySet:
580
+ """Use a non-default LaminDB instance.
581
+
582
+ Args:
583
+ instance: An instance identifier of form "account_handle/instance_name".
584
+
585
+ Examples:
586
+ >>> ln.ULabel.using("account_handle/instance_name").search("ULabel7", field="name")
587
+ uid score
588
+ name
589
+ ULabel7 g7Hk9b2v 100.0
590
+ ULabel5 t4Jm6s0q 75.0
591
+ ULabel6 r2Xw8p1z 75.0
592
+ """
593
+ from .query_set import QuerySet
594
+
595
+ if instance is None:
596
+ return QuerySet(model=cls, using=None)
597
+ owner, name = get_owner_name_from_identifier(instance)
598
+ settings_file = instance_settings_file(name, owner)
599
+ cache_filepath = (
600
+ ln_setup.settings.cache_dir / f"instance--{owner}--{name}--uid.txt"
601
+ )
602
+ if not settings_file.exists():
603
+ result = connect_instance_hub(owner=owner, name=name)
604
+ if isinstance(result, str):
605
+ raise RuntimeError(
606
+ f"Failed to load instance {instance}, please check your permissions!"
607
+ )
608
+ iresult, _ = result
609
+ source_module = {
610
+ modules for modules in iresult["schema_str"].split(",") if modules != ""
611
+ } # type: ignore
612
+ target_module = ln_setup.settings.instance.modules
613
+ if not source_module.issubset(target_module):
614
+ missing_members = source_module - target_module
615
+ logger.warning(
616
+ f"source modules has additional modules: {missing_members}\nconsider mounting these registry modules to transfer all metadata"
617
+ )
618
+ cache_filepath.write_text(f"{iresult['lnid']}\n{iresult['schema_str']}") # type: ignore
619
+ settings_file = instance_settings_file(name, owner)
620
+ db = update_db_using_local(iresult, settings_file)
621
+ else:
622
+ isettings = load_instance_settings(settings_file)
623
+ db = isettings.db
624
+ cache_filepath.write_text(f"{isettings.uid}\n{','.join(isettings.modules)}") # type: ignore
625
+ add_db_connection(db, instance)
626
+ return QuerySet(model=cls, using=instance)
627
+
628
+ def __get_module_name__(cls) -> str:
629
+ schema_module_name = cls.__module__.split(".")[0]
630
+ module_name = schema_module_name.replace("lnschema_", "")
631
+ if module_name == "lamindb":
632
+ module_name = "core"
633
+ return module_name
634
+
635
+ @deprecated("__get_module_name__")
636
+ def __get_schema_name__(cls) -> str:
637
+ return cls.__get_module_name__()
638
+
639
+ def __get_name_with_module__(cls) -> str:
640
+ module_name = cls.__get_module_name__()
641
+ if module_name == "core":
642
+ module_prefix = ""
643
+ else:
644
+ module_prefix = f"{module_name}."
645
+ return f"{module_prefix}{cls.__name__}"
646
+
647
+ @deprecated("__get_name_with_module__")
648
+ def __get_name_with_schema__(cls) -> str:
649
+ return cls.__get_name_with_module__()
650
+
651
+
652
+ class BasicRecord(models.Model, metaclass=Registry):
653
+ """Basic metadata record.
654
+
655
+ It has the same methods as Record, but doesn't have the additional fields.
656
+
657
+ It's mainly used for LinkORMs and similar.
658
+ """
659
+
660
+ class Meta:
661
+ abstract = True
662
+
663
+ def __init__(self, *args, **kwargs):
664
+ skip_validation = kwargs.pop("_skip_validation", False)
665
+ if not args and skip_validation:
666
+ super().__init__(**kwargs)
667
+ elif not args and not skip_validation:
668
+ from ..core._settings import settings
669
+ from .can_curate import CanCurate
670
+ from .collection import Collection
671
+ from .schema import Schema
672
+ from .transform import Transform
673
+
674
+ validate_fields(self, kwargs)
675
+
676
+ # do not search for names if an id is passed; this is important
677
+ # e.g. when synching ids from the notebook store to lamindb
678
+ has_consciously_provided_uid = False
679
+ if "_has_consciously_provided_uid" in kwargs:
680
+ has_consciously_provided_uid = kwargs.pop(
681
+ "_has_consciously_provided_uid"
682
+ )
683
+ if (
684
+ isinstance(self, (CanCurate, Collection, Transform))
685
+ and settings.creation.search_names
686
+ and not has_consciously_provided_uid
687
+ ):
688
+ name_field = getattr(self, "_name_field", "name")
689
+ exact_match = suggest_records_with_similar_names(
690
+ self, name_field, kwargs
691
+ )
692
+ if exact_match is not None:
693
+ if "version" in kwargs:
694
+ if kwargs["version"] is not None:
695
+ version_comment = " and version"
696
+ existing_record = self.__class__.filter(
697
+ **{
698
+ name_field: kwargs[name_field],
699
+ "version": kwargs["version"],
700
+ }
701
+ ).one_or_none()
702
+ else:
703
+ # for a versioned record, an exact name match is not a criterion
704
+ # for retrieving a record in case `version` isn't passed -
705
+ # we'd always pull out many records with exactly the same name
706
+ existing_record = None
707
+ else:
708
+ version_comment = ""
709
+ existing_record = exact_match
710
+ if existing_record is not None:
711
+ logger.important(
712
+ f"returning existing {self.__class__.__name__} record with same"
713
+ f" {name_field}{version_comment}: '{kwargs[name_field]}'"
714
+ )
715
+ if isinstance(self, Schema):
716
+ if existing_record.hash != kwargs["hash"]:
717
+ raise ValueError(
718
+ f"Schema name is already in use by schema with uid '{existing_record.uid}', please choose a different name."
719
+ )
720
+ init_self_from_db(self, existing_record)
721
+ update_attributes(self, kwargs)
722
+ return None
723
+ super().__init__(**kwargs)
724
+ if isinstance(self, ValidateFields):
725
+ # this will trigger validation against django validators
726
+ try:
727
+ if hasattr(self, "clean_fields"):
728
+ self.clean_fields()
729
+ else:
730
+ self._Model__clean_fields()
731
+ except DjangoValidationError as e:
732
+ message = _format_django_validation_error(self, e)
733
+ raise FieldValidationError(message) from e
734
+ elif len(args) != len(self._meta.concrete_fields):
735
+ raise FieldValidationError(
736
+ f"Use keyword arguments instead of positional arguments, e.g.: {self.__class__.__name__}(name='...')."
737
+ )
738
+ else:
739
+ super().__init__(*args)
740
+ _store_record_old_name(self)
741
+ _store_record_old_key(self)
742
+
743
+ def save(self, *args, **kwargs) -> Record:
744
+ """Save.
745
+
746
+ Always saves to the default database.
747
+ """
748
+ using_key = None
749
+ if "using" in kwargs:
750
+ using_key = kwargs["using"]
751
+ db = self._state.db
752
+ pk_on_db = self.pk
753
+ artifacts: list = []
754
+ if self.__class__.__name__ == "Collection" and self.id is not None:
755
+ # when creating a new collection without being able to access artifacts
756
+ artifacts = self.ordered_artifacts.list()
757
+ pre_existing_record = None
758
+ # consider records that are being transferred from other databases
759
+ transfer_logs: dict[str, list[str]] = {
760
+ "mapped": [],
761
+ "transferred": [],
762
+ "run": None,
763
+ }
764
+ if db is not None and db != "default" and using_key is None:
765
+ if isinstance(self, IsVersioned):
766
+ if not self.is_latest:
767
+ raise NotImplementedError(
768
+ "You are attempting to transfer a record that's not the latest in its version history. This is currently not supported."
769
+ )
770
+ pre_existing_record = transfer_to_default_db(
771
+ self, using_key, transfer_logs=transfer_logs
772
+ )
773
+ self._revises: IsVersioned
774
+ if pre_existing_record is not None:
775
+ init_self_from_db(self, pre_existing_record)
776
+ else:
777
+ check_key_change(self)
778
+ check_name_change(self)
779
+ try:
780
+ # save versioned record in presence of self._revises
781
+ if isinstance(self, IsVersioned) and self._revises is not None:
782
+ assert self._revises.is_latest # noqa: S101
783
+ revises = self._revises
784
+ revises.is_latest = False
785
+ with transaction.atomic():
786
+ revises._revises = None # ensure we don't start a recursion
787
+ revises.save()
788
+ super().save(*args, **kwargs) # type: ignore
789
+ self._revises = None
790
+ # save unversioned record
791
+ else:
792
+ super().save(*args, **kwargs)
793
+ except IntegrityError as e:
794
+ error_msg = str(e)
795
+ # two possible error messages for hash duplication
796
+ # "duplicate key value violates unique constraint"
797
+ # "UNIQUE constraint failed"
798
+ if (
799
+ "UNIQUE constraint failed" in error_msg
800
+ or "duplicate key value violates unique constraint" in error_msg
801
+ ) and "hash" in error_msg:
802
+ pre_existing_record = self.__class__.get(hash=self.hash)
803
+ logger.warning(
804
+ f"returning {self.__class__.__name__.lower()} with same hash: {pre_existing_record}"
805
+ )
806
+ init_self_from_db(self, pre_existing_record)
807
+ else:
808
+ raise
809
+ _store_record_old_name(self)
810
+ _store_record_old_key(self)
811
+ # perform transfer of many-to-many fields
812
+ # only supported for Artifact and Collection records
813
+ if db is not None and db != "default" and using_key is None:
814
+ if self.__class__.__name__ == "Collection":
815
+ if len(artifacts) > 0:
816
+ logger.info("transfer artifacts")
817
+ for artifact in artifacts:
818
+ artifact.save()
819
+ self.artifacts.add(*artifacts)
820
+ if hasattr(self, "labels"):
821
+ from copy import copy
822
+
823
+ from lamindb.models._feature_manager import FeatureManager
824
+
825
+ # here we go back to original record on the source database
826
+ self_on_db = copy(self)
827
+ self_on_db._state.db = db
828
+ self_on_db.pk = pk_on_db # manually set the primary key
829
+ self_on_db.features = FeatureManager(self_on_db) # type: ignore
830
+ self.features._add_from(self_on_db, transfer_logs=transfer_logs)
831
+ self.labels.add_from(self_on_db, transfer_logs=transfer_logs)
832
+ for k, v in transfer_logs.items():
833
+ if k != "run":
834
+ logger.important(f"{k} records: {', '.join(v)}")
835
+
836
+ if self.__class__.__name__ in {
837
+ "Artifact",
838
+ "Transform",
839
+ "Run",
840
+ "ULabel",
841
+ "Feature",
842
+ "Schema",
843
+ "Collection",
844
+ "Reference",
845
+ }:
846
+ import lamindb as ln
847
+
848
+ if ln.context.project is not None:
849
+ self.projects.add(ln.context.project)
850
+ return self
851
+
852
+ def delete(self) -> None:
853
+ """Delete."""
854
+ # note that the logic below does not fire if a record is moved to the trash
855
+ # the idea is that moving a record to the trash should move its entire version family
856
+ # to the trash, whereas permanently deleting should default to only deleting a single record
857
+ # of a version family
858
+ # we can consider making it easy to permanently delete entire version families as well,
859
+ # but that's for another time
860
+ if isinstance(self, IsVersioned) and self.is_latest:
861
+ new_latest = (
862
+ self.__class__.objects.using(self._state.db)
863
+ .filter(is_latest=False, uid__startswith=self.stem_uid)
864
+ .order_by("-created_at")
865
+ .first()
866
+ )
867
+ if new_latest is not None:
868
+ new_latest.is_latest = True
869
+ with transaction.atomic():
870
+ new_latest.save()
871
+ super().delete() # type: ignore
872
+ logger.warning(f"new latest version is {new_latest}")
873
+ return None
874
+ super().delete()
875
+
876
+
877
+ class Space(BasicRecord):
878
+ """Spaces."""
879
+
880
+ id: int = models.SmallAutoField(primary_key=True)
881
+ """Internal id, valid only in one DB instance."""
882
+ name: str = models.CharField(max_length=100, db_index=True)
883
+ """Name of space."""
884
+ uid: str = CharField(
885
+ editable=False,
886
+ unique=True,
887
+ max_length=12,
888
+ default="00000000",
889
+ db_default="00000000",
890
+ db_index=True,
891
+ )
892
+ """Universal id."""
893
+ description: str | None = CharField(null=True)
894
+ """Description of space."""
895
+ created_at: datetime = DateTimeField(
896
+ editable=False, db_default=models.functions.Now(), db_index=True
897
+ )
898
+ """Time of creation of record."""
899
+ created_by: User = ForeignKey(
900
+ "User", CASCADE, default=None, related_name="+", null=True
901
+ )
902
+ """Creator of run."""
903
+
904
+
905
+ @doc_args(RECORD_REGISTRY_EXAMPLE)
906
+ class Record(BasicRecord, metaclass=Registry):
907
+ """Metadata record.
908
+
909
+ Every `Record` is a data model that comes with a registry in form of a SQL
910
+ table in your database.
911
+
912
+ Sub-classing `Record` creates a new registry while instantiating a `Record`
913
+ creates a new record.
914
+
915
+ {}
916
+
917
+ `Record`'s metaclass is :class:`~lamindb.models.Registry`.
918
+
919
+ `Record` inherits from Django's `Model` class. Why does LaminDB call it `Record`
920
+ and not `Model`? The term `Record` can't lead to confusion with statistical,
921
+ machine learning or biological models.
922
+ """
923
+
924
+ _branch_code: int = models.SmallIntegerField(db_index=True, default=1, db_default=1)
925
+ """Whether record is on a branch, in archive or in trash.
926
+
927
+ This dictates whether a record appears in queries & searches.
928
+
929
+ Coding is as follows:
930
+
931
+ - 3: template (hidden in queries & searches)
932
+ - 2: draft (hidden in queries & searches)
933
+ - 1: default (visible in queries & searches)
934
+ - 0: archive (hidden, meant to be kept)
935
+ - -1: trash (hidden, scheduled for deletion)
936
+
937
+ Any integer higher than >3 codes a branch that's involved in a pull request.
938
+ """
939
+ space: Space = ForeignKey(Space, PROTECT, default=1, db_default=1)
940
+ """The space in which the record lives."""
941
+ _aux: dict[str, Any] | None = JSONField(default=None, db_default=None, null=True)
942
+ """Auxiliary field for dictionary-like metadata."""
943
+
944
+ class Meta:
945
+ abstract = True
946
+
947
+
948
+ def _format_django_validation_error(record: Record, e: DjangoValidationError):
949
+ """Pretty print Django validation errors."""
950
+ errors = {}
951
+ if hasattr(e, "error_dict"):
952
+ error_dict = e.error_dict
953
+ else:
954
+ error_dict = {"__all__": e.error_list}
955
+
956
+ for field_name, error_list in error_dict.items():
957
+ for error in error_list:
958
+ if hasattr(error, "message"):
959
+ msg = error.message
960
+ else:
961
+ msg = str(error)
962
+
963
+ if field_name == "__all__":
964
+ errors[field_name] = f"{colors.yellow(msg)}"
965
+ else:
966
+ current_value = getattr(record, field_name, None)
967
+ errors[field_name] = (
968
+ f"{field_name}: {colors.yellow(current_value)} is not valid\n → {msg}"
969
+ )
970
+
971
+ if errors:
972
+ message = "\n "
973
+ for _, error in errors.items():
974
+ message += error + "\n "
975
+
976
+ return message
977
+
978
+
979
+ def _get_record_kwargs(record_class) -> list[tuple[str, str]]:
980
+ """Gets the parameters of a Record from the overloaded signature.
981
+
982
+ Example:
983
+ >>> get_record_params(bt.Organism)
984
+ >>> [('name', 'str'), ('taxon_id', 'str | None'), ('scientific_name', 'str | None')]
985
+ """
986
+ source = inspect.getsource(record_class)
987
+
988
+ # Find first overload that's not *db_args
989
+ pattern = r"@overload\s+def __init__\s*\(([\s\S]*?)\):\s*\.{3}"
990
+ overloads = re.finditer(pattern, source)
991
+
992
+ for overload in overloads:
993
+ params_block = overload.group(1)
994
+ # This is an additional safety measure if the overloaded signature that we're
995
+ # looking for is not at the top but a "db_args" constructor
996
+ if "*db_args" in params_block:
997
+ continue
998
+
999
+ params = []
1000
+ for line in params_block.split("\n"):
1001
+ line = line.strip()
1002
+ if not line or "self" in line:
1003
+ continue
1004
+
1005
+ # Extract name and type annotation
1006
+ # The regex pattern finds parameter definitions like:
1007
+ # Simple: name: str
1008
+ # With default: age: int = 0
1009
+ # With complex types: items: List[str] = []
1010
+ param_pattern = (
1011
+ r"(\w+)" # Parameter name
1012
+ r"\s*:\s*" # Colon with optional whitespace
1013
+ r"((?:[^=,]|" # Type hint: either non-equals/comma chars
1014
+ r"(?<=\[)[^[\]]*" # or contents within square brackets
1015
+ r"(?=\]))+)" # looking ahead for closing bracket
1016
+ r"(?:\s*=\s*" # Optional default value part
1017
+ r"([^,]+))?" # Default value: anything but comma
1018
+ )
1019
+ match = re.match(param_pattern, line)
1020
+ if not match:
1021
+ continue
1022
+
1023
+ name, type_str = match.group(1), match.group(2).strip()
1024
+
1025
+ # Keep type as string instead of evaluating
1026
+ params.append((name, type_str))
1027
+
1028
+ return params
1029
+
1030
+ return []
1031
+
1032
+
1033
+ def _search(
1034
+ cls,
1035
+ string: str,
1036
+ *,
1037
+ field: StrField | list[StrField] | None = None,
1038
+ limit: int | None = 20,
1039
+ case_sensitive: bool = False,
1040
+ using_key: str | None = None,
1041
+ truncate_string: bool = False,
1042
+ ) -> QuerySet:
1043
+ if string is None:
1044
+ raise ValueError("Cannot search for None value! Please pass a valid string.")
1045
+
1046
+ input_queryset = _queryset(cls, using_key=using_key)
1047
+ registry = input_queryset.model
1048
+ name_field = getattr(registry, "_name_field", "name")
1049
+ if field is None:
1050
+ fields = [
1051
+ field.name
1052
+ for field in registry._meta.fields
1053
+ if field.get_internal_type() in {"CharField", "TextField"}
1054
+ ]
1055
+ else:
1056
+ if not isinstance(field, list):
1057
+ fields_input = [field]
1058
+ else:
1059
+ fields_input = field
1060
+ fields = []
1061
+ for field in fields_input:
1062
+ if not isinstance(field, str):
1063
+ try:
1064
+ fields.append(field.field.name)
1065
+ except AttributeError as error:
1066
+ raise TypeError(
1067
+ "Please pass a Record string field, e.g., `CellType.name`!"
1068
+ ) from error
1069
+ else:
1070
+ fields.append(field)
1071
+
1072
+ if truncate_string:
1073
+ if (len_string := len(string)) > 5:
1074
+ n_80_pct = int(len_string * 0.8)
1075
+ string = string[:n_80_pct]
1076
+
1077
+ string = string.strip()
1078
+ string_escape = re.escape(string)
1079
+
1080
+ exact_lookup = Exact if case_sensitive else IExact
1081
+ regex_lookup = Regex if case_sensitive else IRegex
1082
+ contains_lookup = Contains if case_sensitive else IContains
1083
+
1084
+ ranks = []
1085
+ contains_filters = []
1086
+ for field in fields:
1087
+ field_expr = Coalesce(
1088
+ Cast(field, output_field=TextField()),
1089
+ Value(""),
1090
+ output_field=TextField(),
1091
+ )
1092
+ # exact rank
1093
+ exact_expr = exact_lookup(field_expr, string)
1094
+ exact_rank = Cast(exact_expr, output_field=IntegerField()) * 200
1095
+ ranks.append(exact_rank)
1096
+ # exact synonym
1097
+ synonym_expr = regex_lookup(field_expr, rf"(?:^|.*\|){string_escape}(?:\|.*|$)")
1098
+ synonym_rank = Cast(synonym_expr, output_field=IntegerField()) * 200
1099
+ ranks.append(synonym_rank)
1100
+ # match as sub-phrase
1101
+ sub_expr = regex_lookup(
1102
+ field_expr, rf"(?:^|.*[ \|\.,;:]){string_escape}(?:[ \|\.,;:].*|$)"
1103
+ )
1104
+ sub_rank = Cast(sub_expr, output_field=IntegerField()) * 10
1105
+ ranks.append(sub_rank)
1106
+ # startswith and avoid matching string with " " on the right
1107
+ # mostly for truncated
1108
+ startswith_expr = regex_lookup(
1109
+ field_expr, rf"(?:^|.*\|){string_escape}[^ ]*(?:\|.*|$)"
1110
+ )
1111
+ startswith_rank = Cast(startswith_expr, output_field=IntegerField()) * 8
1112
+ ranks.append(startswith_rank)
1113
+ # match as sub-phrase from the left, mostly for truncated
1114
+ right_expr = regex_lookup(field_expr, rf"(?:^|.*[ \|]){string_escape}.*")
1115
+ right_rank = Cast(right_expr, output_field=IntegerField()) * 2
1116
+ ranks.append(right_rank)
1117
+ # match as sub-phrase from the right
1118
+ left_expr = regex_lookup(field_expr, rf".*{string_escape}(?:$|[ \|\.,;:].*)")
1119
+ left_rank = Cast(left_expr, output_field=IntegerField()) * 2
1120
+ ranks.append(left_rank)
1121
+ # simple contains filter
1122
+ contains_expr = contains_lookup(field_expr, string)
1123
+ contains_filter = Q(contains_expr)
1124
+ contains_filters.append(contains_filter)
1125
+ # also rank by contains
1126
+ contains_rank = Cast(contains_expr, output_field=IntegerField())
1127
+ ranks.append(contains_rank)
1128
+ # additional rule for truncated strings
1129
+ # weight matches from the beginning of the string higher
1130
+ # sometimes whole words get truncated and startswith_expr is not enough
1131
+ if truncate_string and field == name_field:
1132
+ startswith_lookup = StartsWith if case_sensitive else IStartsWith
1133
+ name_startswith_expr = startswith_lookup(field_expr, string)
1134
+ name_startswith_rank = (
1135
+ Cast(name_startswith_expr, output_field=IntegerField()) * 2
1136
+ )
1137
+ ranks.append(name_startswith_rank)
1138
+
1139
+ ranked_queryset = (
1140
+ input_queryset.filter(reduce(lambda a, b: a | b, contains_filters))
1141
+ .alias(rank=sum(ranks))
1142
+ .order_by("-rank")
1143
+ )
1144
+
1145
+ return ranked_queryset[:limit]
1146
+
1147
+
1148
+ def _lookup(
1149
+ cls,
1150
+ field: StrField | None = None,
1151
+ return_field: StrField | None = None,
1152
+ using_key: str | None = None,
1153
+ ) -> NamedTuple:
1154
+ """{}""" # noqa: D415
1155
+ queryset = _queryset(cls, using_key=using_key)
1156
+ field = get_name_field(registry=queryset.model, field=field)
1157
+
1158
+ return Lookup(
1159
+ records=queryset,
1160
+ values=[i.get(field) for i in queryset.values()],
1161
+ tuple_name=cls.__class__.__name__,
1162
+ prefix="ln",
1163
+ ).lookup(
1164
+ return_field=(
1165
+ get_name_field(registry=queryset.model, field=return_field)
1166
+ if return_field is not None
1167
+ else None
1168
+ )
1169
+ )
1170
+
1171
+
1172
+ def get_name_field(
1173
+ registry: type[Record] | QuerySet | Manager,
1174
+ *,
1175
+ field: str | StrField | None = None,
1176
+ ) -> str:
1177
+ """Get the 1st char or text field from the registry."""
1178
+ if isinstance(registry, (QuerySet, Manager)):
1179
+ registry = registry.model
1180
+ model_field_names = [i.name for i in registry._meta.fields]
1181
+
1182
+ # set to default name field
1183
+ if field is None:
1184
+ if hasattr(registry, "_name_field"):
1185
+ field = registry._meta.get_field(registry._name_field)
1186
+ elif "name" in model_field_names:
1187
+ field = registry._meta.get_field("name")
1188
+ else:
1189
+ # first char or text field that doesn't contain "id"
1190
+ for i in registry._meta.fields:
1191
+ if "id" in i.name:
1192
+ continue
1193
+ if i.get_internal_type() in {"CharField", "TextField"}:
1194
+ field = i
1195
+ break
1196
+
1197
+ # no default name field can be found
1198
+ if field is None:
1199
+ raise ValueError(
1200
+ "please pass a Record string field, e.g., `CellType.name`!"
1201
+ )
1202
+ else:
1203
+ field = field.name # type:ignore
1204
+ if not isinstance(field, str):
1205
+ try:
1206
+ field = field.field.name
1207
+ except AttributeError:
1208
+ raise TypeError(
1209
+ "please pass a Record string field, e.g., `CellType.name`!"
1210
+ ) from None
1211
+
1212
+ return field
1213
+
1214
+
1215
+ def _queryset(cls: Record | QuerySet | Manager, using_key: str) -> QuerySet:
1216
+ if isinstance(cls, (QuerySet, Manager)):
1217
+ return cls.all()
1218
+ elif using_key is None or using_key == "default":
1219
+ return cls.objects.all()
1220
+ else:
1221
+ # using must be called on cls, otherwise the connection isn't found
1222
+ return cls.using(using_key).all()
1223
+
1224
+
1225
+ def add_db_connection(db: str, using: str):
1226
+ db_config = dj_database_url.config(
1227
+ default=db, conn_max_age=600, conn_health_checks=True
1228
+ )
1229
+ db_config["TIME_ZONE"] = "UTC"
1230
+ db_config["OPTIONS"] = {}
1231
+ db_config["AUTOCOMMIT"] = True
1232
+ connections.settings[using] = db_config
1233
+
1234
+
1235
+ REGISTRY_UNIQUE_FIELD = {
1236
+ "storage": "root",
1237
+ "feature": "name",
1238
+ "ulabel": "name",
1239
+ "space": "name", # TODO: this should be updated with the currently used space instead during transfer
1240
+ }
1241
+
1242
+
1243
+ def update_fk_to_default_db(
1244
+ records: Record | list[Record] | QuerySet,
1245
+ fk: str,
1246
+ using_key: str | None,
1247
+ transfer_logs: dict,
1248
+ ):
1249
+ record = records[0] if isinstance(records, (list, QuerySet)) else records
1250
+ if hasattr(record, f"{fk}_id") and getattr(record, f"{fk}_id") is not None:
1251
+ fk_record = getattr(record, fk)
1252
+ field = REGISTRY_UNIQUE_FIELD.get(fk, "uid")
1253
+ fk_record_default = fk_record.__class__.filter(
1254
+ **{field: getattr(fk_record, field)}
1255
+ ).one_or_none()
1256
+ if fk_record_default is None:
1257
+ from copy import copy
1258
+
1259
+ fk_record_default = copy(fk_record)
1260
+ transfer_to_default_db(
1261
+ fk_record_default, using_key, save=True, transfer_logs=transfer_logs
1262
+ )
1263
+ if isinstance(records, (list, QuerySet)):
1264
+ for r in records:
1265
+ setattr(r, f"{fk}", None)
1266
+ setattr(r, f"{fk}_id", fk_record_default.id)
1267
+ else:
1268
+ setattr(records, f"{fk}", None)
1269
+ setattr(records, f"{fk}_id", fk_record_default.id)
1270
+
1271
+
1272
+ FKBULK = [
1273
+ "organism",
1274
+ "source",
1275
+ "report", # Run
1276
+ ]
1277
+
1278
+
1279
+ def transfer_fk_to_default_db_bulk(
1280
+ records: list | QuerySet, using_key: str | None, transfer_logs: dict
1281
+ ):
1282
+ for fk in FKBULK:
1283
+ update_fk_to_default_db(records, fk, using_key, transfer_logs=transfer_logs)
1284
+
1285
+
1286
+ def get_transfer_run(record) -> Run:
1287
+ from lamindb import settings
1288
+ from lamindb.core._context import context
1289
+ from lamindb.models import Run, Transform
1290
+ from lamindb.models.artifact import WARNING_RUN_TRANSFORM
1291
+
1292
+ slug = record._state.db
1293
+ owner, name = get_owner_name_from_identifier(slug)
1294
+ cache_filepath = ln_setup.settings.cache_dir / f"instance--{owner}--{name}--uid.txt"
1295
+ if not cache_filepath.exists():
1296
+ raise SystemExit("Need to call .using() before")
1297
+ instance_uid = cache_filepath.read_text().split("\n")[0]
1298
+ key = f"transfers/{instance_uid}"
1299
+ uid = instance_uid + "0000"
1300
+ transform = Transform.filter(uid=uid).one_or_none()
1301
+ if transform is None:
1302
+ search_names = settings.creation.search_names
1303
+ settings.creation.search_names = False
1304
+ transform = Transform( # type: ignore
1305
+ uid=uid, description=f"Transfer from `{slug}`", key=key, type="function"
1306
+ ).save()
1307
+ settings.creation.search_names = search_names
1308
+ # use the global run context to get the initiated_by_run run id
1309
+ if context.run is not None:
1310
+ initiated_by_run = context.run
1311
+ else:
1312
+ if not settings.creation.artifact_silence_missing_run_warning:
1313
+ logger.warning(WARNING_RUN_TRANSFORM)
1314
+ initiated_by_run = None
1315
+ # it doesn't seem to make sense to create new runs for every transfer
1316
+ run = Run.filter(
1317
+ transform=transform, initiated_by_run=initiated_by_run
1318
+ ).one_or_none()
1319
+ if run is None:
1320
+ run = Run(transform=transform, initiated_by_run=initiated_by_run).save() # type: ignore
1321
+ run.initiated_by_run = initiated_by_run # so that it's available in memory
1322
+ return run
1323
+
1324
+
1325
+ def transfer_to_default_db(
1326
+ record: Record,
1327
+ using_key: str | None,
1328
+ *,
1329
+ transfer_logs: dict,
1330
+ save: bool = False,
1331
+ transfer_fk: bool = True,
1332
+ ) -> Record | None:
1333
+ if record._state.db is None or record._state.db == "default":
1334
+ return None
1335
+ registry = record.__class__
1336
+ record_on_default = registry.objects.filter(uid=record.uid).one_or_none()
1337
+ record_str = f"{record.__class__.__name__}(uid='{record.uid}')"
1338
+ if transfer_logs["run"] is None:
1339
+ transfer_logs["run"] = get_transfer_run(record)
1340
+ if record_on_default is not None:
1341
+ transfer_logs["mapped"].append(record_str)
1342
+ return record_on_default
1343
+ else:
1344
+ transfer_logs["transferred"].append(record_str)
1345
+
1346
+ if hasattr(record, "created_by_id"):
1347
+ record.created_by = None
1348
+ record.created_by_id = ln_setup.settings.user.id
1349
+ # run & transform
1350
+ run = transfer_logs["run"]
1351
+ if hasattr(record, "run_id"):
1352
+ record.run = None
1353
+ record.run_id = run.id
1354
+ # deal with denormalized transform FK on artifact and collection
1355
+ if hasattr(record, "transform_id"):
1356
+ record.transform = None
1357
+ record.transform_id = run.transform_id
1358
+ # transfer other foreign key fields
1359
+ fk_fields = [
1360
+ i.name
1361
+ for i in record._meta.fields
1362
+ if i.get_internal_type() == "ForeignKey"
1363
+ if i.name not in {"created_by", "run", "transform"}
1364
+ ]
1365
+ if not transfer_fk:
1366
+ # don't transfer fk fields that are already bulk transferred
1367
+ fk_fields = [fk for fk in fk_fields if fk not in FKBULK]
1368
+ for fk in fk_fields:
1369
+ update_fk_to_default_db(record, fk, using_key, transfer_logs=transfer_logs)
1370
+ record.id = None
1371
+ record._state.db = "default"
1372
+ if save:
1373
+ record.save()
1374
+ return None
1375
+
1376
+
1377
+ def _store_record_old_name(record: Record):
1378
+ # writes the name to the _name attribute, so we can detect renaming upon save
1379
+ if hasattr(record, "_name_field"):
1380
+ record._old_name = getattr(record, record._name_field)
1381
+
1382
+
1383
+ def _store_record_old_key(record: Record):
1384
+ from lamindb.models import Artifact, Transform
1385
+
1386
+ # writes the key to the _old_key attribute, so we can detect key changes upon save
1387
+ if isinstance(record, (Artifact, Transform)):
1388
+ record._old_key = record.key
1389
+
1390
+
1391
+ def check_name_change(record: Record):
1392
+ """Warns if a record's name has changed."""
1393
+ from lamindb.models import Artifact, Collection, Feature, Schema, Transform
1394
+
1395
+ if (
1396
+ not record.pk
1397
+ or not hasattr(record, "_old_name")
1398
+ or not hasattr(record, "_name_field")
1399
+ ):
1400
+ return
1401
+
1402
+ # checked in check_key_change or not checked at all
1403
+ if isinstance(record, (Artifact, Collection, Transform)):
1404
+ return
1405
+
1406
+ # renaming feature sets is not checked
1407
+ if isinstance(record, Schema):
1408
+ return
1409
+
1410
+ old_name = record._old_name
1411
+ new_name = getattr(record, record._name_field)
1412
+ registry = record.__class__.__name__
1413
+
1414
+ if old_name != new_name:
1415
+ # when a label is renamed, only raise a warning if it has a feature
1416
+ if hasattr(record, "artifacts"):
1417
+ linked_records = (
1418
+ record.artifacts.through.filter(
1419
+ label_ref_is_name=True, **{f"{registry.lower()}_id": record.pk}
1420
+ )
1421
+ .exclude(feature_id=None) # must have a feature
1422
+ .exclude(
1423
+ feature_ref_is_name=None
1424
+ ) # must be linked via Curator and therefore part of a schema
1425
+ .distinct()
1426
+ )
1427
+ artifact_ids = linked_records.list("artifact__uid")
1428
+ n = len(artifact_ids)
1429
+ if n > 0:
1430
+ s = "s" if n > 1 else ""
1431
+ logger.error(
1432
+ f"You are trying to {colors.red('rename label')} from '{old_name}' to '{new_name}'!\n"
1433
+ f" → The following {n} artifact{s} {colors.red('will no longer be validated')}: {artifact_ids}\n\n"
1434
+ f"{colors.bold('To rename this label')}, make it external:\n"
1435
+ f" → run `artifact.labels.make_external(label)`\n\n"
1436
+ f"After renaming, consider re-curating the above artifact{s}:\n"
1437
+ f' → in each dataset, manually modify label "{old_name}" to "{new_name}"\n'
1438
+ f" → run `ln.Curator`\n"
1439
+ )
1440
+ raise RecordNameChangeIntegrityError
1441
+
1442
+ # when a feature is renamed
1443
+ elif isinstance(record, Feature):
1444
+ # only internal features are associated with schemas
1445
+ linked_artifacts = Artifact.filter(feature_sets__features=record).list(
1446
+ "uid"
1447
+ )
1448
+ n = len(linked_artifacts)
1449
+ if n > 0:
1450
+ s = "s" if n > 1 else ""
1451
+ logger.error(
1452
+ f"You are trying to {colors.red('rename feature')} from '{old_name}' to '{new_name}'!\n"
1453
+ f" → The following {n} artifact{s} {colors.red('will no longer be validated')}: {linked_artifacts}\n\n"
1454
+ f"{colors.bold('To rename this feature')}, make it external:\n"
1455
+ " → run `artifact.features.make_external(feature)`\n\n"
1456
+ f"After renaming, consider re-curating the above artifact{s}:\n"
1457
+ f" → in each dataset, manually modify feature '{old_name}' to '{new_name}'\n"
1458
+ f" → run `ln.Curator`\n"
1459
+ )
1460
+ raise RecordNameChangeIntegrityError
1461
+
1462
+
1463
+ def check_key_change(record: Union[Artifact, Transform]):
1464
+ """Errors if a record's key has falsely changed."""
1465
+ from .artifact import Artifact
1466
+
1467
+ if not isinstance(record, Artifact) or not hasattr(record, "_old_key"):
1468
+ return
1469
+
1470
+ old_key = record._old_key or ""
1471
+ new_key = record.key or ""
1472
+
1473
+ if old_key != new_key:
1474
+ if not record._key_is_virtual:
1475
+ raise InvalidArgument(
1476
+ f"Changing a non-virtual key of an artifact is not allowed! Tried to change key from '{old_key}' to '{new_key}'."
1477
+ )
1478
+ old_key_suffix = (
1479
+ record.suffix
1480
+ if record.suffix
1481
+ else extract_suffix_from_path(PurePosixPath(old_key), arg_name="key")
1482
+ )
1483
+ new_key_suffix = extract_suffix_from_path(
1484
+ PurePosixPath(new_key), arg_name="key"
1485
+ )
1486
+ if old_key_suffix != new_key_suffix:
1487
+ raise InvalidArgument(
1488
+ f"The suffix '{new_key_suffix}' of the provided key is incorrect, it should be '{old_key_suffix}'."
1489
+ )
1490
+
1491
+
1492
+ def format_field_value(value: datetime | str | Any) -> Any:
1493
+ from datetime import datetime
1494
+
1495
+ if isinstance(value, datetime):
1496
+ return value.strftime("%Y-%m-%d %H:%M:%S %Z")
1497
+
1498
+ if isinstance(value, str):
1499
+ try:
1500
+ value = datetime.fromisoformat(value)
1501
+ value = value.strftime("%Y-%m-%d %H:%M:%S %Z")
1502
+ except ValueError:
1503
+ pass
1504
+ return f"'{value}'"
1505
+ else:
1506
+ return value
1507
+
1508
+
1509
+ class RecordInfo:
1510
+ def __init__(self, registry: Registry):
1511
+ self.registry = registry
1512
+
1513
+ def _get_type_for_field(self, field_name: str) -> str:
1514
+ field = self.registry._meta.get_field(field_name)
1515
+ related_model_name = (
1516
+ field.related_model.__name__
1517
+ if hasattr(field, "related_model") and field.related_model
1518
+ else None
1519
+ )
1520
+ return related_model_name if related_model_name else field.get_internal_type()
1521
+
1522
+ def _get_base_class_fields(self) -> list[str]:
1523
+ return [
1524
+ field.name
1525
+ for base in self.registry.__bases__
1526
+ if hasattr(base, "_meta")
1527
+ for field in base._meta.get_fields()
1528
+ ]
1529
+
1530
+ def _reorder_fields_by_class(self, fields_to_order: list[Field]) -> list[Field]:
1531
+ """Reorders the fields so that base class fields come last."""
1532
+ non_base_class_fields = [
1533
+ field
1534
+ for field in fields_to_order
1535
+ if field.name not in self._get_base_class_fields()
1536
+ ]
1537
+ found_base_class_fields = [
1538
+ field
1539
+ for field in fields_to_order
1540
+ if field.name in self._get_base_class_fields()
1541
+ ]
1542
+ return non_base_class_fields + found_base_class_fields
1543
+
1544
+ def get_simple_fields(self, return_str: bool = False) -> Any:
1545
+ simple_fields = [
1546
+ field
1547
+ for field in self.registry._meta.get_fields()
1548
+ if not (
1549
+ isinstance(field, ManyToOneRel)
1550
+ or isinstance(field, ManyToManyRel)
1551
+ or isinstance(field, ManyToManyField)
1552
+ or isinstance(field, ForeignKey)
1553
+ or field.name.startswith("_")
1554
+ or field.name == "id"
1555
+ )
1556
+ ]
1557
+ simple_fields = self._reorder_fields_by_class(simple_fields)
1558
+ if not return_str:
1559
+ return simple_fields
1560
+ else:
1561
+ repr_str = f" {colors.italic('Simple fields')}\n"
1562
+ if simple_fields:
1563
+ repr_str += "".join(
1564
+ [
1565
+ f" .{field_name.name}: {self._get_type_for_field(field_name.name)}\n"
1566
+ for field_name in simple_fields
1567
+ ]
1568
+ )
1569
+ return repr_str
1570
+
1571
+ def get_relational_fields(self, return_str: bool = False):
1572
+ # we ignore ManyToOneRel because it leads to so much clutter in the API
1573
+ # also note that our general guideline is to have related_name="+"
1574
+ # for ForeignKey fields
1575
+ relational_fields = (ManyToOneRel, ManyToManyRel, ManyToManyField, ForeignKey)
1576
+
1577
+ class_specific_relational_fields = [
1578
+ field
1579
+ for field in self.registry._meta.fields + self.registry._meta.many_to_many
1580
+ if isinstance(field, relational_fields)
1581
+ and not field.name.startswith(("links_", "_"))
1582
+ ]
1583
+
1584
+ non_class_specific_relational_fields = [
1585
+ field
1586
+ for field in self.registry._meta.get_fields()
1587
+ if isinstance(field, relational_fields)
1588
+ and not field.name.startswith(("links_", "_"))
1589
+ ]
1590
+ non_class_specific_relational_fields = self._reorder_fields_by_class(
1591
+ non_class_specific_relational_fields
1592
+ )
1593
+
1594
+ # Ensure that class specific fields (e.g. Artifact) come before non-class specific fields (e.g. collection)
1595
+ filtered_non_class_specific = [
1596
+ field
1597
+ for field in non_class_specific_relational_fields
1598
+ if field not in class_specific_relational_fields
1599
+ ]
1600
+ ordered_relational_fields = (
1601
+ class_specific_relational_fields + filtered_non_class_specific
1602
+ )
1603
+
1604
+ core_module_fields = []
1605
+ external_modules_fields = []
1606
+ for field in ordered_relational_fields:
1607
+ field_name = repr(field).split(": ")[1][:-1]
1608
+ if field_name.count(".") == 1 and "lamindb" not in field_name:
1609
+ external_modules_fields.append(field)
1610
+ else:
1611
+ core_module_fields.append(field)
1612
+
1613
+ def _get_related_field_type(field) -> str:
1614
+ field_type = (
1615
+ field.related_model.__get_name_with_module__()
1616
+ .replace(
1617
+ "Artifact", ""
1618
+ ) # some fields have an unnecessary 'Artifact' in their name
1619
+ .replace(
1620
+ "Collection", ""
1621
+ ) # some fields have an unnecessary 'Collection' in their name
1622
+ )
1623
+ return (
1624
+ self._get_type_for_field(field.name)
1625
+ if not field_type.strip()
1626
+ else field_type
1627
+ )
1628
+
1629
+ core_module_fields_formatted = [
1630
+ f" .{field.name}: {_get_related_field_type(field)}\n"
1631
+ for field in core_module_fields
1632
+ ]
1633
+ external_modules_fields_formatted = [
1634
+ f" .{field.name}: {_get_related_field_type(field)}\n"
1635
+ for field in external_modules_fields
1636
+ ]
1637
+
1638
+ if not return_str:
1639
+ external_modules_fields_by_modules = defaultdict(list)
1640
+ for field_str, field in zip(
1641
+ external_modules_fields_formatted, external_modules_fields
1642
+ ):
1643
+ field_type = field_str.split(":")[1].split()[0]
1644
+ module_name = field_type.split(".")[0]
1645
+ external_modules_fields_by_modules[module_name].append(field)
1646
+ return core_module_fields, external_modules_fields_by_modules
1647
+ else:
1648
+ repr_str = ""
1649
+
1650
+ # Non-external relational fields
1651
+ if core_module_fields:
1652
+ repr_str += f" {colors.italic('Relational fields')}\n"
1653
+ repr_str += "".join(core_module_fields_formatted)
1654
+
1655
+ # External relational fields
1656
+ external_modules = set()
1657
+ for field in external_modules_fields_formatted:
1658
+ field_type = field.split(":")[1].split()[0]
1659
+ external_modules.add(field_type.split(".")[0])
1660
+
1661
+ if external_modules:
1662
+ # We want Bionty to show up before other modules
1663
+ external_modules = (
1664
+ ["bionty"] + sorted(external_modules - {"bionty"}) # type: ignore
1665
+ if "bionty" in external_modules
1666
+ else sorted(external_modules)
1667
+ )
1668
+ for ext_module in external_modules:
1669
+ ext_module_fields = [
1670
+ field
1671
+ for field in external_modules_fields_formatted
1672
+ if ext_module in field
1673
+ ]
1674
+
1675
+ if ext_module_fields:
1676
+ repr_str += (
1677
+ f" {colors.italic(f'{ext_module.capitalize()} fields')}\n"
1678
+ )
1679
+ repr_str += "".join(ext_module_fields)
1680
+
1681
+ return repr_str
1682
+
1683
+
1684
+ def registry_repr(cls):
1685
+ """Shows fields."""
1686
+ repr_str = f"{colors.green(cls.__name__)}\n"
1687
+ info = RecordInfo(cls)
1688
+ repr_str += info.get_simple_fields(return_str=True)
1689
+ repr_str += info.get_relational_fields(return_str=True)
1690
+ repr_str = repr_str.rstrip("\n")
1691
+ return repr_str
1692
+
1693
+
1694
+ def record_repr(
1695
+ self: Record, include_foreign_keys: bool = True, exclude_field_names=None
1696
+ ) -> str:
1697
+ if exclude_field_names is None:
1698
+ exclude_field_names = ["id", "updated_at", "source_code"]
1699
+ field_names = [
1700
+ field.name
1701
+ for field in self._meta.fields
1702
+ if (not isinstance(field, ForeignKey) and field.name not in exclude_field_names)
1703
+ ]
1704
+ if include_foreign_keys:
1705
+ field_names += [
1706
+ f"{field.name}_id"
1707
+ for field in self._meta.fields
1708
+ if isinstance(field, ForeignKey)
1709
+ ]
1710
+ if "created_at" in field_names:
1711
+ field_names.remove("created_at")
1712
+ field_names.append("created_at")
1713
+ if field_names[0] != "uid" and "uid" in field_names:
1714
+ field_names.remove("uid")
1715
+ field_names.insert(0, "uid")
1716
+ fields_str = {}
1717
+ for k in field_names:
1718
+ if not k.startswith("_") and hasattr(self, k):
1719
+ value = getattr(self, k)
1720
+ # Force strip the time component of the version
1721
+ if k == "version" and value:
1722
+ fields_str[k] = f"'{str(value).split()[0]}'"
1723
+ else:
1724
+ fields_str[k] = format_field_value(value)
1725
+ fields_joined_str = ", ".join(
1726
+ [f"{k}={fields_str[k]}" for k in fields_str if fields_str[k] is not None]
1727
+ )
1728
+ return f"{self.__class__.__name__}({fields_joined_str})"
1729
+
1730
+
1731
+ # below is code to further format the repr of a record
1732
+ #
1733
+ # def format_repr(
1734
+ # record: Record, exclude_field_names: str | list[str] | None = None
1735
+ # ) -> str:
1736
+ # if isinstance(exclude_field_names, str):
1737
+ # exclude_field_names = [exclude_field_names]
1738
+ # exclude_field_names_init = ["id", "created_at", "updated_at"]
1739
+ # if exclude_field_names is not None:
1740
+ # exclude_field_names_init += exclude_field_names
1741
+ # return record.__repr__(
1742
+ # include_foreign_keys=False, exclude_field_names=exclude_field_names_init
1743
+ # )
1744
+
1745
+
1746
+ Record.__repr__ = record_repr # type: ignore
1747
+ Record.__str__ = record_repr # type: ignore
1748
+
1749
+
1750
+ class Migration(BasicRecord):
1751
+ app = CharField(max_length=255)
1752
+ name = CharField(max_length=255)
1753
+ applied: datetime = DateTimeField()
1754
+
1755
+ class Meta:
1756
+ db_table = "django_migrations"
1757
+ managed = False