lamindb_setup 1.14.1__tar.gz → 1.15.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/.gitignore +2 -0
  2. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/.pre-commit-config.yaml +3 -1
  3. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/PKG-INFO +3 -2
  4. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/__init__.py +2 -2
  5. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/_connect_instance.py +1 -7
  6. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/_init_instance.py +4 -2
  7. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/_setup_user.py +5 -0
  8. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/__init__.py +15 -0
  9. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/_aws_options.py +9 -0
  10. lamindb_setup-1.15.1/lamindb_setup/io.py +354 -0
  11. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/noxfile.py +1 -1
  12. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/pyproject.toml +2 -0
  13. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/hub-local/test_update_schema_in_hub.py +1 -1
  14. lamindb_setup-1.15.1/tests/storage/conftest.py +10 -0
  15. lamindb_setup-1.15.1/tests/storage/test_db_import_export.py +215 -0
  16. lamindb_setup-1.14.1/lamindb_setup/_exportdb.py +0 -68
  17. lamindb_setup-1.14.1/lamindb_setup/_importdb.py +0 -50
  18. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/.github/workflows/build.yml +0 -0
  19. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/.github/workflows/doc-changes.yml +0 -0
  20. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/LICENSE +0 -0
  21. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/README.md +0 -0
  22. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/docs/changelog.md +0 -0
  23. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/docs/hub-cloud/01-init-local-instance.ipynb +0 -0
  24. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/docs/hub-cloud/02-connect-local-instance.ipynb +0 -0
  25. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/docs/hub-cloud/03-add-managed-storage.ipynb +0 -0
  26. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/docs/hub-cloud/04-test-bionty.ipynb +0 -0
  27. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/docs/hub-cloud/05-init-hosted-instance.ipynb +0 -0
  28. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/docs/hub-cloud/06-connect-hosted-instance.ipynb +0 -0
  29. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/docs/hub-cloud/07-keep-artifacts-local.ipynb +0 -0
  30. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/docs/hub-cloud/08-test-multi-session.ipynb +0 -0
  31. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/docs/hub-cloud/09-test-migrate.ipynb +0 -0
  32. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/docs/hub-cloud/test_notebooks.py +0 -0
  33. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/docs/hub-prod/test-cache-management.ipynb +0 -0
  34. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/docs/hub-prod/test-cloud-sync.ipynb +0 -0
  35. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/docs/hub-prod/test-connect-anonymously.ipynb +0 -0
  36. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/docs/hub-prod/test-empty-init.ipynb +0 -0
  37. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/docs/hub-prod/test-import-schema.ipynb +0 -0
  38. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/docs/hub-prod/test-init-load-local-anonymously.ipynb +0 -0
  39. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/docs/hub-prod/test-insufficient-user-info.ipynb +0 -0
  40. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/docs/hub-prod/test-invalid-schema.ipynb +0 -0
  41. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/docs/hub-prod/test-sqlite-lock.ipynb +0 -0
  42. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/docs/hub-prod/test_notebooks2.py +0 -0
  43. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/docs/index.md +0 -0
  44. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/docs/notebooks.md +0 -0
  45. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/docs/reference.md +0 -0
  46. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/_cache.py +0 -0
  47. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/_check.py +0 -0
  48. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/_check_setup.py +0 -0
  49. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/_delete.py +0 -0
  50. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/_disconnect.py +0 -0
  51. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/_django.py +0 -0
  52. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/_entry_points.py +0 -0
  53. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/_migrate.py +0 -0
  54. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/_register_instance.py +0 -0
  55. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/_schema.py +0 -0
  56. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/_schema_metadata.py +0 -0
  57. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/_set_managed_storage.py +0 -0
  58. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/_silence_loggers.py +0 -0
  59. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/_aws_storage.py +0 -0
  60. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/_clone.py +0 -0
  61. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/_deprecated.py +0 -0
  62. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/_docs.py +0 -0
  63. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/_hub_client.py +0 -0
  64. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/_hub_core.py +0 -0
  65. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/_hub_crud.py +0 -0
  66. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/_hub_utils.py +0 -0
  67. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/_private_django_api.py +0 -0
  68. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/_settings.py +0 -0
  69. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/_settings_instance.py +0 -0
  70. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/_settings_load.py +0 -0
  71. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/_settings_save.py +0 -0
  72. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/_settings_storage.py +0 -0
  73. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/_settings_store.py +0 -0
  74. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/_settings_user.py +0 -0
  75. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/_setup_bionty_sources.py +0 -0
  76. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/cloud_sqlite_locker.py +0 -0
  77. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/django.py +0 -0
  78. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/exceptions.py +0 -0
  79. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/hashing.py +0 -0
  80. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/types.py +0 -0
  81. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/core/upath.py +0 -0
  82. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/errors.py +0 -0
  83. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/py.typed +0 -0
  84. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/lamindb_setup/types.py +0 -0
  85. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/hub-cloud/scripts/script-init-pass-user-no-writes.py +0 -0
  86. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/hub-cloud/scripts/script-to-fail-managed-storage.py +0 -0
  87. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/hub-cloud/test_clone_instance.py +0 -0
  88. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/hub-cloud/test_connect_instance.py +0 -0
  89. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/hub-cloud/test_delete_instance.py +0 -0
  90. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/hub-cloud/test_edge_request.py +0 -0
  91. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/hub-cloud/test_fail_managed_storage.py +0 -0
  92. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/hub-cloud/test_init_instance.py +0 -0
  93. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/hub-cloud/test_init_pass_user_no_writes.py +0 -0
  94. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/hub-cloud/test_login.py +0 -0
  95. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/hub-cloud/test_set_storage.py +0 -0
  96. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/hub-local/README.md +0 -0
  97. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/hub-local/conftest.py +0 -0
  98. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/hub-local/scripts/script-connect-fine-grained-access.py +0 -0
  99. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/hub-local/test_all.py +0 -0
  100. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/hub-prod/conftest.py +0 -0
  101. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/hub-prod/test_aws_options_manager.py +0 -0
  102. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/hub-prod/test_django.py +0 -0
  103. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/hub-prod/test_global_settings.py +0 -0
  104. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/hub-prod/test_migrate.py +0 -0
  105. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/hub-prod/test_switch_and_fallback_env.py +0 -0
  106. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/hub-prod/test_upath.py +0 -0
  107. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/storage/test_entry_point.py +0 -0
  108. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/storage/test_hashing.py +0 -0
  109. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/storage/test_storage_access.py +0 -0
  110. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/storage/test_storage_basis.py +0 -0
  111. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/storage/test_storage_settings.py +0 -0
  112. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/storage/test_storage_stats.py +0 -0
  113. {lamindb_setup-1.14.1 → lamindb_setup-1.15.1}/tests/storage/test_to_url.py +0 -0
@@ -113,3 +113,5 @@ _docs_tmp*
113
113
  *.db
114
114
  storage_uid.txt
115
115
  test.ipynb
116
+ test2.ipynb
117
+ *_export
@@ -42,5 +42,7 @@ repos:
42
42
  - id: mypy
43
43
  exclude: |
44
44
  (?x)(
45
- tests/hub-local/conftest.py
45
+ tests/hub-local/conftest.py|
46
+ tests/hub-prod/conftest.py|
47
+ tests/storage/conftest.py
46
48
  )
@@ -1,10 +1,11 @@
1
- Metadata-Version: 2.3
1
+ Metadata-Version: 2.4
2
2
  Name: lamindb_setup
3
- Version: 1.14.1
3
+ Version: 1.15.1
4
4
  Summary: Setup & configure LaminDB.
5
5
  Author-email: Lamin Labs <open-source@lamin.ai>
6
6
  Requires-Python: >=3.10
7
7
  Description-Content-Type: text/markdown
8
+ License-File: LICENSE
8
9
  Requires-Dist: lamin_utils>=0.3.3
9
10
  Requires-Dist: django>=5.2,<5.3
10
11
  Requires-Dist: dj_database_url>=1.3.0,<3.0.0
@@ -35,7 +35,7 @@ Migration management
35
35
 
36
36
  """
37
37
 
38
- __version__ = "1.14.1" # denote a release candidate for 0.1.0 with 0.1rc1
38
+ __version__ = "1.15.1" # denote a release candidate for 0.1.0 with 0.1rc1
39
39
 
40
40
  import os
41
41
  import warnings
@@ -47,7 +47,7 @@ warnings.filterwarnings("ignore", category=DeprecationWarning, module="postgrest
47
47
 
48
48
  from packaging import version as packaging_version
49
49
 
50
- from . import core, errors, types
50
+ from . import core, errors, io, types
51
51
  from ._check_setup import _check_instance_setup
52
52
  from ._connect_instance import connect
53
53
  from ._delete import delete
@@ -204,18 +204,12 @@ def reset_django_module_variables():
204
204
  app_names = {app.name for app in apps.get_app_configs()}
205
205
  # always copy before iterations over sys.modules
206
206
  # see https://docs.python.org/3/library/sys.html#sys.modules
207
+ # this whole thing runs about 50ms in a big env
207
208
  for name, module in sys.modules.copy().items():
208
209
  if (
209
210
  module is not None
210
211
  and (not name.startswith("__") or name == "__main__")
211
212
  and name not in sys.builtin_module_names
212
- and not (
213
- hasattr(module, "__file__")
214
- and module.__file__
215
- and any(
216
- path in module.__file__ for path in ["/lib/python", "\\lib\\python"]
217
- )
218
- )
219
213
  ):
220
214
  try:
221
215
  for k, v in vars(module).items():
@@ -7,8 +7,6 @@ from typing import TYPE_CHECKING, Literal
7
7
  from uuid import UUID
8
8
 
9
9
  import click
10
- from django.core.exceptions import FieldError
11
- from django.db.utils import IntegrityError, OperationalError, ProgrammingError
12
10
  from lamin_utils import logger
13
11
 
14
12
  from ._disconnect import disconnect
@@ -71,6 +69,10 @@ def register_storage_in_instance(ssettings: StorageSettings) -> Storage:
71
69
 
72
70
 
73
71
  def register_user(usettings: UserSettings, update_user: bool = True) -> None:
72
+ # we have to import this here dynamically because otherwise
73
+ # the except below will fail on re-connect due to reset
74
+ from django.core.exceptions import FieldError
75
+ from django.db.utils import IntegrityError, OperationalError, ProgrammingError
74
76
  from lamindb.models import User
75
77
 
76
78
  if not update_user and User.objects.filter(uid=usettings.uid).exists():
@@ -7,6 +7,7 @@ from lamin_utils import logger
7
7
 
8
8
  from ._check_setup import _check_instance_setup
9
9
  from ._init_instance import register_user
10
+ from .core._aws_options import reset_aws_options_cache
10
11
  from .core._settings import settings
11
12
  from .core._settings_load import load_user_settings
12
13
  from .core._settings_save import save_user_settings
@@ -147,6 +148,8 @@ def login(
147
148
  register_user(user_settings)
148
149
 
149
150
  settings._user_settings = None
151
+ # aws s3 credentials are scoped to the user
152
+ reset_aws_options_cache()
150
153
  return user_settings
151
154
 
152
155
 
@@ -163,6 +166,8 @@ def logout():
163
166
  if current_user_settings_file().exists():
164
167
  current_user_settings_file().unlink()
165
168
  settings._user_settings = None
169
+ # aws s3 credentials are scoped to the user
170
+ reset_aws_options_cache()
166
171
  logger.success("logged out")
167
172
  else:
168
173
  logger.important("already logged out")
@@ -1,8 +1,23 @@
1
1
  """Core setup library.
2
2
 
3
+ General
4
+ -------
5
+
3
6
  .. autoclass:: SetupSettings
7
+
8
+ User
9
+ ----
10
+
4
11
  .. autoclass:: UserSettings
12
+
13
+ Instance
14
+ --------
15
+
5
16
  .. autoclass:: InstanceSettings
17
+
18
+ Storage
19
+ -------
20
+
6
21
  .. autoclass:: StorageSettings
7
22
 
8
23
  """
@@ -20,6 +20,7 @@ lamin_env = os.getenv("LAMIN_ENV")
20
20
  if lamin_env is None or lamin_env == "prod":
21
21
  HOSTED_BUCKETS = tuple([f"s3://lamin-{region}" for region in HOSTED_REGIONS])
22
22
  else:
23
+ logger.warning("loaded LAMIN_ENV: staging")
23
24
  HOSTED_BUCKETS = ("s3://lamin-hosted-test",) # type: ignore
24
25
 
25
26
 
@@ -245,3 +246,11 @@ def get_aws_options_manager() -> AWSOptionsManager:
245
246
  _aws_options_manager = AWSOptionsManager()
246
247
 
247
248
  return _aws_options_manager
249
+
250
+
251
+ def reset_aws_options_cache():
252
+ global _aws_options_manager
253
+
254
+ if _aws_options_manager is not None:
255
+ _aws_options_manager._credentials_cache = {}
256
+ _aws_options_manager._parameters_cache = {}
@@ -0,0 +1,354 @@
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import json
5
+ import warnings
6
+ from concurrent.futures import ProcessPoolExecutor, as_completed
7
+ from importlib import import_module
8
+ from pathlib import Path
9
+ from typing import TYPE_CHECKING
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+ from django.db import models, transaction
14
+ from rich.progress import Progress
15
+
16
+ if TYPE_CHECKING:
17
+ from collections.abc import Sequence
18
+ from typing import Literal
19
+
20
+
21
+ def _get_registries(module_name: str) -> list[str]:
22
+ """Get registry class names from a module."""
23
+ schema_module = import_module(module_name)
24
+ exclude = {"SQLRecord", "BaseSQLRecord"}
25
+
26
+ if module_name == "lamindb":
27
+ module_filter = lambda cls, name: cls.__module__.startswith(
28
+ f"{module_name}.models."
29
+ ) and name in dir(schema_module)
30
+ else:
31
+ module_filter = (
32
+ lambda cls, name: cls.__module__ == f"{module_name}.models"
33
+ and name in dir(schema_module)
34
+ )
35
+
36
+ return [
37
+ name
38
+ for name in dir(schema_module.models)
39
+ if (
40
+ name[0].isupper()
41
+ and isinstance(cls := getattr(schema_module.models, name, None), type)
42
+ and issubclass(cls, models.Model)
43
+ and module_filter(cls, name)
44
+ and name not in exclude
45
+ )
46
+ ]
47
+
48
+
49
+ def _export_full_table(
50
+ registry_info: tuple[str, str, str | None],
51
+ directory: Path,
52
+ chunk_size: int,
53
+ ) -> list[tuple[str, Path]] | str:
54
+ """Export a registry table to parquet.
55
+
56
+ For PostgreSQL, uses COPY TO which streams the table directly to CSV format,
57
+ bypassing query planner overhead and row-by-row conversion (10-50x faster than SELECT).
58
+
59
+ For SQLite with large tables, reads in chunks to avoid memory issues when tables exceed available RAM.
60
+
61
+ Args:
62
+ registry_info: Tuple of (module_name, model_name, field_name) where field_name
63
+ is None for regular tables or the field name for M2M link tables.
64
+ directory: Output directory for parquet files.
65
+ chunk_size: Maximum rows per chunk for SQLite large tables.
66
+
67
+ Returns:
68
+ String identifier for single-file exports, or list of (table_name, chunk_path) tuples for chunked exports that need merging.
69
+ """
70
+ from django.db import connection
71
+
72
+ import lamindb_setup as ln_setup
73
+
74
+ module_name, model_name, field_name = registry_info
75
+ schema_module = import_module(module_name)
76
+ registry = getattr(schema_module, model_name)
77
+
78
+ if field_name:
79
+ registry = getattr(registry, field_name).through
80
+
81
+ table_name = registry._meta.db_table
82
+
83
+ try:
84
+ if ln_setup.settings.instance.dialect == "postgresql":
85
+ buffer = io.StringIO()
86
+ with connection.cursor() as cursor:
87
+ cursor.copy_expert(
88
+ f'COPY "{table_name}" TO STDOUT WITH (FORMAT CSV, HEADER TRUE)',
89
+ buffer,
90
+ )
91
+ buffer.seek(0)
92
+ df = pd.read_csv(buffer)
93
+ df.to_parquet(directory / f"{table_name}.parquet", compression=None)
94
+ return (
95
+ f"{module_name}.{model_name}.{field_name}"
96
+ if field_name
97
+ else f"{module_name}.{model_name}"
98
+ )
99
+ else:
100
+ with warnings.catch_warnings():
101
+ warnings.filterwarnings(
102
+ "ignore", message="Skipped unsupported reflection"
103
+ )
104
+ row_count = pd.read_sql(
105
+ f"SELECT COUNT(*) as count FROM {table_name}",
106
+ ln_setup.settings.instance.db,
107
+ ).iloc[0]["count"]
108
+
109
+ if row_count > chunk_size:
110
+ chunk_files = []
111
+ num_chunks = (row_count + chunk_size - 1) // chunk_size
112
+ for chunk_id in range(num_chunks):
113
+ offset = chunk_id * chunk_size
114
+ df = pd.read_sql(
115
+ f"SELECT * FROM {table_name} LIMIT {chunk_size} OFFSET {offset}",
116
+ ln_setup.settings.instance.db,
117
+ )
118
+ chunk_file = (
119
+ directory / f"{table_name}_chunk_{chunk_id}.parquet"
120
+ )
121
+ df.to_parquet(chunk_file, compression=None)
122
+ chunk_files.append((table_name, chunk_file))
123
+ return chunk_files
124
+ else:
125
+ df = pd.read_sql_table(table_name, ln_setup.settings.instance.db)
126
+ df.to_parquet(directory / f"{table_name}.parquet", compression=None)
127
+ return (
128
+ f"{module_name}.{model_name}.{field_name}"
129
+ if field_name
130
+ else f"{module_name}.{model_name}"
131
+ )
132
+ except (ValueError, pd.errors.DatabaseError):
133
+ raise ValueError(
134
+ f"Table '{table_name}' was not found. The instance might need to be migrated."
135
+ ) from None
136
+
137
+
138
+ def export_db(
139
+ module_names: Sequence[str] | None = None,
140
+ *,
141
+ output_dir: str | Path = "./lamindb_export/",
142
+ max_workers: int = 8,
143
+ chunk_size: int = 500_000,
144
+ ) -> None:
145
+ """Export registry tables and many-to-many link tables to parquet files.
146
+
147
+ Ensure that you connect to postgres instances using `use_root_db_user=True`.
148
+
149
+ Args:
150
+ module_names: Module names to export (e.g., ["lamindb", "bionty", "wetlab"]).
151
+ Defaults to "lamindb" if not provided.
152
+ output_dir: Directory path for exported parquet files.
153
+ max_workers: Number of parallel processes.
154
+ chunk_size: Number of rows per chunk for large tables.
155
+ """
156
+ directory = Path(output_dir)
157
+ directory.mkdir(parents=True, exist_ok=True)
158
+
159
+ module_names = module_names or ["lamindb"]
160
+ modules = {name: _get_registries(name) for name in module_names}
161
+
162
+ tasks = []
163
+ for module_name, model_names in modules.items():
164
+ schema_module = import_module(module_name)
165
+ for model_name in model_names:
166
+ registry = getattr(schema_module, model_name)
167
+ tasks.append((module_name, model_name, None))
168
+ for field in registry._meta.many_to_many:
169
+ tasks.append((module_name, model_name, field.name))
170
+
171
+ chunk_files_by_table: dict[str, list[Path]] = {}
172
+
173
+ with Progress() as progress:
174
+ task_id = progress.add_task("Exporting", total=len(tasks))
175
+ with ProcessPoolExecutor(max_workers=max_workers) as executor:
176
+ futures = {
177
+ executor.submit(_export_full_table, task, directory, chunk_size): task
178
+ for task in tasks
179
+ }
180
+
181
+ for future in as_completed(futures):
182
+ result = future.result()
183
+ if isinstance(result, list):
184
+ for table_name, chunk_file in result:
185
+ chunk_files_by_table.setdefault(table_name, []).append(
186
+ chunk_file
187
+ )
188
+ progress.advance(task_id)
189
+
190
+ for table_name, chunk_files in chunk_files_by_table.items():
191
+ merged_df = pd.concat([pd.read_parquet(f) for f in sorted(chunk_files)])
192
+ merged_df.to_parquet(directory / f"{table_name}.parquet", compression=None)
193
+ for chunk_file in chunk_files:
194
+ chunk_file.unlink()
195
+
196
+
197
+ def _serialize_value(val):
198
+ """Convert value to JSON string if it's a dict, list, or numpy array, otherwise return as-is."""
199
+ if isinstance(val, (dict, list, np.ndarray)):
200
+ return json.dumps(
201
+ val, default=lambda o: o.tolist() if isinstance(o, np.ndarray) else None
202
+ )
203
+ return val
204
+
205
+
206
+ def _import_registry(
207
+ registry: type[models.Model],
208
+ directory: Path,
209
+ if_exists: Literal["fail", "replace", "append"] = "replace",
210
+ ) -> None:
211
+ """Import a single registry table from parquet.
212
+
213
+ For PostgreSQL, uses COPY FROM which bypasses SQL parsing and writes directly to
214
+ table pages (20-50x faster than multi-row INSERTs).
215
+
216
+ For SQLite, uses multi-row INSERTs with dynamic chunking to stay under the 999
217
+ variable limit (2-5x faster than single-row INSERTs).
218
+ """
219
+ from django.db import connection
220
+
221
+ table_name = registry._meta.db_table
222
+ parquet_file = directory / f"{table_name}.parquet"
223
+
224
+ if not parquet_file.exists():
225
+ print(f"Skipped {table_name} (file not found)")
226
+ return
227
+
228
+ df = pd.read_parquet(parquet_file)
229
+
230
+ old_foreign_key_columns = [col for col in df.columns if col.endswith("_old")]
231
+ if old_foreign_key_columns:
232
+ df = df.drop(columns=old_foreign_key_columns)
233
+
234
+ for col in df.columns:
235
+ if df[col].dtype == "object":
236
+ mask = df[col].apply(lambda x: isinstance(x, (dict, list, np.ndarray)))
237
+ if mask.any():
238
+ df.loc[mask, col] = df.loc[mask, col].map(_serialize_value)
239
+
240
+ if df.empty:
241
+ return
242
+
243
+ if connection.vendor == "postgresql":
244
+ columns = df.columns.tolist()
245
+ column_names = ", ".join(f'"{col}"' for col in columns)
246
+
247
+ buffer = io.StringIO()
248
+ df.to_csv(buffer, index=False, header=False, sep="\t", na_rep="\\N")
249
+ buffer.seek(0)
250
+
251
+ with connection.cursor() as cursor:
252
+ if if_exists == "replace":
253
+ cursor.execute(f'DELETE FROM "{table_name}"')
254
+ elif if_exists == "fail":
255
+ cursor.execute(f'SELECT COUNT(*) FROM "{table_name}"')
256
+ if cursor.fetchone()[0] > 0:
257
+ raise ValueError(f"Table {table_name} already contains data")
258
+
259
+ cursor.copy_expert(
260
+ f"COPY \"{table_name}\" ({column_names}) FROM STDIN WITH (FORMAT CSV, DELIMITER E'\\t', NULL '\\N')",
261
+ buffer,
262
+ )
263
+ else:
264
+ num_cols = len(df.columns)
265
+ max_vars = 900 # SQLite has a limit of 999 variables per statement
266
+ chunksize = max(1, max_vars // num_cols)
267
+
268
+ df.to_sql(
269
+ table_name,
270
+ connection.connection,
271
+ if_exists=if_exists,
272
+ index=False,
273
+ method="multi",
274
+ chunksize=chunksize,
275
+ )
276
+
277
+
278
+ def import_db(
279
+ module_names: Sequence[str] | None = None,
280
+ *,
281
+ input_dir: str | Path = "./lamindb_export/",
282
+ if_exists: Literal["fail", "replace", "append"] = "replace",
283
+ ) -> None:
284
+ """Import registry and link tables from parquet files.
285
+
286
+ Temporarily disables FK constraints to allow insertion in arbitrary order.
287
+ Requires superuser/RDS admin privileges for postgres databases.
288
+
289
+ Args:
290
+ input_dir: Directory containing parquet files to import.
291
+ module_names: Module names to import (e.g., ["lamindb", "bionty", "wetlab"]).
292
+ if_exists: How to behave if table exists: 'fail', 'replace', or 'append'.
293
+ """
294
+ from django.db import connection
295
+
296
+ import lamindb_setup as ln_setup
297
+
298
+ directory = Path(input_dir)
299
+
300
+ if not directory.exists():
301
+ raise ValueError(f"Directory does not exist: {directory}")
302
+
303
+ if module_names is None:
304
+ parquet_files = list(directory.glob("*.parquet"))
305
+ detected_modules = {
306
+ f.name.split("_")[0] for f in parquet_files if "_" in f.name
307
+ }
308
+ module_names = sorted(detected_modules)
309
+
310
+ modules = {name: _get_registries(name) for name in module_names}
311
+ total_models = sum(len(models) for models in modules.values())
312
+
313
+ is_sqlite = ln_setup.settings.instance.dialect == "sqlite"
314
+
315
+ try:
316
+ with connection.cursor() as cursor:
317
+ if ln_setup.settings.instance.dialect == "postgresql":
318
+ cursor.execute("SET session_replication_role = 'replica'")
319
+ elif is_sqlite:
320
+ cursor.execute("PRAGMA foreign_keys = OFF")
321
+ # Disables fsync - OS buffers writes to disk, 10-50x faster but can corrupt DB on crash
322
+ cursor.execute("PRAGMA synchronous = OFF")
323
+ # Keeps rollback journal in RAM - 2-5x faster but cannot rollback on crash
324
+ cursor.execute("PRAGMA journal_mode = MEMORY")
325
+ # 64MB page cache for better performance on large imports
326
+ cursor.execute("PRAGMA cache_size = -64000")
327
+
328
+ with transaction.atomic():
329
+ if ln_setup.settings.instance.dialect == "postgresql":
330
+ with connection.cursor() as cursor:
331
+ cursor.execute("SET CONSTRAINTS ALL DEFERRED")
332
+
333
+ with Progress() as progress:
334
+ task = progress.add_task("Importing", total=total_models)
335
+ for module_name, model_names in modules.items():
336
+ schema_module = import_module(module_name)
337
+ for model_name in model_names:
338
+ progress.update(
339
+ task, description=f"[cyan]{module_name}.{model_name}"
340
+ )
341
+ registry = getattr(schema_module, model_name)
342
+ _import_registry(registry, directory, if_exists=if_exists)
343
+ for field in registry._meta.many_to_many:
344
+ link_orm = getattr(registry, field.name).through
345
+ _import_registry(link_orm, directory, if_exists=if_exists)
346
+ progress.advance(task)
347
+ finally:
348
+ with connection.cursor() as cursor:
349
+ if ln_setup.settings.instance.dialect == "postgresql":
350
+ cursor.execute("SET session_replication_role = 'origin'")
351
+ elif is_sqlite:
352
+ cursor.execute("PRAGMA synchronous = FULL")
353
+ cursor.execute("PRAGMA journal_mode = DELETE")
354
+ cursor.execute("PRAGMA foreign_keys = ON")
@@ -40,7 +40,7 @@ uv pip install --system git+https://github.com/laminlabs/bionty
40
40
  elif group == "docs":
41
41
  cmds = modules_deps.strip()
42
42
  elif group == "storage":
43
- cmds = modules_deps + "uv pip install --system gcsfs huggingface_hub"
43
+ cmds = modules_deps + "uv pip install --system gcsfs huggingface_hub sqlalchemy"
44
44
  elif group == "hub-prod":
45
45
  # cmds = "git clone --depth 1 https://github.com/django/django\n"
46
46
  # cmds += "uv pip install --system -e ./django\n"
@@ -158,4 +158,6 @@ filterwarnings = [
158
158
  "ignore:Jupyter is migrating its paths to use standard platformdirs:DeprecationWarning",
159
159
  "ignore:The 'timeout' parameter is deprecated. Please configure it in the http client instead.:DeprecationWarning",
160
160
  "ignore:The 'verify' parameter is deprecated. Please configure it in the http client instead.:DeprecationWarning",
161
+ "ignore:There is no current event loop:DeprecationWarning",
162
+ "ignore:DateTimeField.*received a naive datetime.*while time zone support is active:RuntimeWarning",
161
163
  ]
@@ -44,7 +44,7 @@ def test_update_schema_in_hub(setup_instance):
44
44
  assert not schema["schema_json"]["core"]["artifact"]["is_link_table"]
45
45
  assert schema["schema_json"]["core"]["artifactulabel"]["is_link_table"]
46
46
 
47
- assert schema["schema_json"]["core"]["artifact"]["name_field"] is None
47
+ assert schema["schema_json"]["core"]["artifact"]["name_field"] == "key"
48
48
  assert schema["schema_json"]["core"]["artifact"]["ontology_id_field"] is None
49
49
  assert schema["schema_json"]["bionty"]["gene"]["name_field"] == "symbol"
50
50
  assert (
@@ -0,0 +1,10 @@
1
+ import pytest
2
+
3
+
4
+ @pytest.fixture(scope="session")
5
+ def simple_instance():
6
+ import lamindb_setup as ln_setup
7
+
8
+ ln_setup.init(storage="./testdb", modules="bionty,wetlab")
9
+ yield
10
+ ln_setup.delete("testdb", force=True)