django-compose 0.1.0.dev2__py3-none-any.whl → 0.1.0.dev5__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.
@@ -22,6 +22,7 @@ def atomic_write(path: Path, content: bytes, *, exclusive: bool = False, mode: i
22
22
 
23
23
  Exclusive publication fails atomically if the destination already exists.
24
24
  An explicit mode also restores permissions when recreating a deleted file.
25
+ New files use ordinary creation permissions filtered by the process umask.
25
26
  """
26
27
  # Native loaders may otherwise accept same-second, same-size stale bytecode.
27
28
  caches: tuple[Path, ...] = ()
@@ -38,9 +39,11 @@ def atomic_write(path: Path, content: bytes, *, exclusive: bool = False, mode: i
38
39
  except FileNotFoundError:
39
40
  pass
40
41
  path.parent.mkdir(parents=True, exist_ok=True)
41
- descriptor, temporary = tempfile.mkstemp(prefix=".compose-", dir=path.parent)
42
- try:
43
- with os.fdopen(descriptor, "wb") as stream:
42
+ # The private directory protects incomplete bytes while native exclusive
43
+ # creation applies the umask, without changing process-wide permissions.
44
+ with tempfile.TemporaryDirectory(prefix=".compose-", dir=path.parent) as directory:
45
+ temporary = Path(directory) / path.name
46
+ with temporary.open("xb") as stream:
44
47
  stream.write(content)
45
48
  stream.flush()
46
49
  if mode is not None:
@@ -52,9 +55,6 @@ def atomic_write(path: Path, content: bytes, *, exclusive: bool = False, mode: i
52
55
  os.replace(temporary, path)
53
56
  for cache in caches:
54
57
  cache.unlink(missing_ok=True)
55
- finally:
56
- if os.path.exists(temporary):
57
- os.unlink(temporary)
58
58
 
59
59
 
60
60
  @dataclass
django_compose/build.py CHANGED
@@ -162,7 +162,7 @@ class BuildPlan:
162
162
  importlib.invalidate_caches()
163
163
  for label in self.labels:
164
164
  importlib.import_module(f"{self.output_module}.{label}.models")
165
- self.composition.validate_generated(apps)
165
+ self.composition.validate_generated(apps, declarations)
166
166
  return self
167
167
  except BaseException:
168
168
  self.close()
@@ -1,4 +1,4 @@
1
- """Resolve installed component metadata into an ordered selection of native Django apps."""
1
+ """Index native component metadata and resolve ordered selections of Django apps."""
2
2
 
3
3
  from __future__ import annotations
4
4
 
@@ -7,7 +7,7 @@ import math
7
7
  import os
8
8
  import subprocess
9
9
  import sys
10
- from collections.abc import Iterable, Mapping
10
+ from collections.abc import Iterable, Iterator, Mapping
11
11
  from dataclasses import asdict, dataclass, field
12
12
  from graphlib import CycleError, TopologicalSorter
13
13
  from importlib import metadata
@@ -178,23 +178,29 @@ def active_requirements(requirements: Iterable[str]) -> tuple[Requirement, ...]:
178
178
  )
179
179
 
180
180
 
181
- def installed_components(group: str) -> InstalledComponents:
182
- """Index group declarations and declared app-key collisions without imports.
181
+ def index_components(distributions: Iterable[metadata.Distribution], *, group: str) -> InstalledComponents:
182
+ """Index supplied native metadata without discovering or importing apps.
183
183
 
184
184
  Each participating distribution must declare exactly one group entry point.
185
185
  Its value remains a native app/config string, never a loaded entry point.
186
- Native metadata.distribution selects the winner for same-name installations.
186
+ Canonical distribution names must be unique, including library-only inputs.
187
+ Containers are immutable and sorted by distribution name; values retain
188
+ their supplied native Distribution and EntryPoint APIs. Indexing neither
189
+ validates app paths nor resolves requirements.
187
190
  """
188
191
  if not isinstance(group, str) or not group:
189
192
  raise ImproperlyConfigured("An explicit non-empty component entry-point group is required")
190
- distributions: dict[str, metadata.Distribution] = {}
193
+ indexed: dict[str, metadata.Distribution] = {}
194
+ for distribution in distributions:
195
+ name: str = canonicalize_name(distribution.metadata["Name"])
196
+ if name in indexed:
197
+ raise ImproperlyConfigured(f"Duplicate component distribution name {name!r}")
198
+ indexed[name] = distribution
199
+ indexed = dict(sorted(indexed.items()))
191
200
  points: dict[str, metadata.EntryPoint] = {}
192
201
  app_providers: dict[str, str] = {}
193
- names = {canonicalize_name(dist.metadata["Name"]) for dist in metadata.distributions()}
194
- for name in sorted(names):
195
- distribution = metadata.distribution(name)
202
+ for name, distribution in indexed.items():
196
203
  entries = distribution.entry_points.select(group=group)
197
- distributions[name] = distribution
198
204
  if not entries:
199
205
  continue
200
206
  if len(entries) != 1:
@@ -207,10 +213,21 @@ def installed_components(group: str) -> InstalledComponents:
207
213
  app_providers[point.name] = name
208
214
  points[name] = point
209
215
  return InstalledComponents(
210
- MappingProxyType(distributions), MappingProxyType(points), MappingProxyType(app_providers)
216
+ MappingProxyType(indexed), MappingProxyType(points), MappingProxyType(app_providers)
211
217
  )
212
218
 
213
219
 
220
+ def installed_components(group: str) -> InstalledComponents:
221
+ """Index installed metadata using native same-name installation precedence."""
222
+
223
+ def distributions() -> Iterator[metadata.Distribution]:
224
+ names = {canonicalize_name(dist.metadata["Name"]) for dist in metadata.distributions()}
225
+ for name in sorted(names):
226
+ yield metadata.distribution(name)
227
+
228
+ return index_components(distributions(), group=group)
229
+
230
+
214
231
  def enabled_apps(roots: Iterable[str], *, group: str | None = None) -> Closure:
215
232
  """Expand explicit roots using installed providers and selected requires_apps.
216
233
 
@@ -223,12 +240,20 @@ def enabled_apps(roots: Iterable[str], *, group: str | None = None) -> Closure:
223
240
 
224
241
  Root configs are preselected and override dependency/default config choices.
225
242
  Conflicting dependency configs, duplicate native labels and cycles fail.
243
+ Each exact app/config string resolves to one native instance per call.
226
244
  """
227
245
  installed = installed_components(group) if group is not None else None
228
246
  root_entries = tuple(roots)
229
247
  if any(not isinstance(entry, str) for entry in root_entries):
230
248
  raise ImproperlyConfigured("Root INSTALLED_APPS entries must be native app strings")
231
- root_configs = tuple((entry, AppConfig.create(entry)) for entry in root_entries)
249
+ resolved: dict[str, AppConfig] = {}
250
+
251
+ def resolve(entry: str) -> AppConfig:
252
+ if entry not in resolved:
253
+ resolved[entry] = AppConfig.create(entry)
254
+ return resolved[entry]
255
+
256
+ root_configs = tuple((entry, resolve(entry)) for entry in root_entries)
232
257
  normalized_roots = app_entries(Entry.from_config(config, entry) for entry, config in root_configs)
233
258
  root_names = tuple(entry.name for entry in normalized_roots)
234
259
  root_set = frozenset(root_names)
@@ -239,7 +264,7 @@ def enabled_apps(roots: Iterable[str], *, group: str | None = None) -> Closure:
239
264
  def component_entry(provider: str) -> str:
240
265
  assert installed is not None
241
266
  point = installed.entry_points[provider]
242
- config = AppConfig.create(point.value)
267
+ config = resolve(point.value)
243
268
  if config.name != point.name:
244
269
  raise ImproperlyConfigured(
245
270
  f"Entry point {point.name!r} from {provider!r} selects app {config.name!r}"
@@ -247,7 +272,7 @@ def enabled_apps(roots: Iterable[str], *, group: str | None = None) -> Closure:
247
272
  return point.value
248
273
 
249
274
  def choose(entry: str) -> str:
250
- config = AppConfig.create(entry)
275
+ config = resolve(entry)
251
276
  previous = selected.get(config.name)
252
277
  if previous is None:
253
278
  selected[config.name] = (entry, config)
@@ -100,7 +100,7 @@ def _fallback_inputs() -> None:
100
100
  from django_compose.sources import SourceResolver
101
101
 
102
102
  try:
103
- location = SourceResolver(()).resolve(module)
103
+ location = SourceResolver().locate(module)
104
104
  if location.path is not None:
105
105
  report_inputs(files=[location.path])
106
106
  except ImportError, ImproperlyConfigured, ValueError:
@@ -5,7 +5,6 @@ from __future__ import annotations
5
5
  import ast
6
6
  import importlib.util
7
7
  import pkgutil
8
- import re
9
8
  import symtable
10
9
  from collections.abc import Iterable
11
10
  from dataclasses import dataclass
@@ -14,6 +13,7 @@ from pathlib import Path
14
13
 
15
14
  from django.apps import apps
16
15
  from django.conf import settings
16
+ from packaging.utils import canonicalize_name
17
17
 
18
18
  from django_compose.sources import ModuleSource, SourceResolver
19
19
 
@@ -29,10 +29,6 @@ class HistoricalImport:
29
29
  detail: str = ""
30
30
 
31
31
 
32
- def _distribution_key(name: str) -> str:
33
- return re.sub(r"[-_.]+", "-", name).lower()
34
-
35
-
36
32
  class _ImportCalls(ast.NodeVisitor):
37
33
  """Let Python's symbol tables own import bindings across lexical scopes.
38
34
 
@@ -441,7 +437,7 @@ class MigrationImportReport:
441
437
 
442
438
  def removal_refusals(self, removing: Iterable[str]) -> tuple[str, ...]:
443
439
  """Refuse enabled providers, retained imports and unprovable dependencies."""
444
- selected = {_distribution_key(name) for name in removing}
440
+ selected = {canonicalize_name(name) for name in removing}
445
441
  refusals = []
446
442
  for config in apps.get_app_configs():
447
443
  source = self.resolver.resolve(config.name)
@@ -449,14 +445,14 @@ class MigrationImportReport:
449
445
  config_source = self.resolver.resolve(type(config).__module__)
450
446
  providers.update(config_source.distributions)
451
447
  for name in sorted(providers):
452
- if _distribution_key(name) in selected:
448
+ if canonicalize_name(name) in selected:
453
449
  refusals.append(f"{name} provides enabled app {config.name}")
454
450
  for item in self.items:
455
451
  if item.kind in {"unsupported", "unresolved"}:
456
452
  refusals.append(f"{item.path}: {item.kind} {item.module}: {item.detail}")
457
453
  if item.kind == "namespace":
458
454
  if item.distributions and all(
459
- _distribution_key(name) in selected for name in item.distributions
455
+ canonicalize_name(name) in selected for name in item.distributions
460
456
  ):
461
457
  refusals.append(
462
458
  f"{item.path}: retained namespace import {item.module} needs at least one of "
@@ -464,7 +460,7 @@ class MigrationImportReport:
464
460
  )
465
461
  continue
466
462
  for name in item.distributions:
467
- if _distribution_key(name) in selected:
463
+ if canonicalize_name(name) in selected:
468
464
  refusals.append(f"{item.path}: retained import {item.module} requires {name}")
469
465
  return tuple(sorted(set(refusals)))
470
466
 
@@ -23,6 +23,8 @@ from django.conf import settings
23
23
  from django.core.exceptions import ImproperlyConfigured
24
24
  from django.core.management.base import CommandError
25
25
  from django.db import DEFAULT_DB_ALIAS, DatabaseError, connections, router, transaction
26
+ from django.db.backends.base.base import BaseDatabaseWrapper
27
+ from django.db.backends.utils import split_identifier
26
28
  from django.db.migrations import Migration
27
29
  from django.db.migrations.autodetector import MigrationAutodetector
28
30
  from django.db.migrations.executor import MigrationExecutor
@@ -488,26 +490,162 @@ class TransitionBinding:
488
490
  return tuple(written)
489
491
 
490
492
 
493
+ def _storage_identifier(connection: BaseDatabaseWrapper, identifier: str) -> tuple[str, str]:
494
+ """Interpret only native Django's simple or double-quoted identifiers.
495
+
496
+ split_identifier() is not a SQL parser. Reject spellings it cannot represent
497
+ faithfully rather than silently turn quoted storage into an absent object.
498
+ """
499
+ namespace, name = split_identifier(identifier)
500
+ convert = connection.introspection.identifier_converter
501
+ limit = connection.ops.max_name_length()
502
+ if (
503
+ not name
504
+ or (limit is not None and max(len(namespace.encode()), len(name.encode())) > limit)
505
+ or '"' in namespace + name
506
+ or identifier.startswith(("`", "["))
507
+ or (namespace and connection.vendor != "postgresql")
508
+ or (
509
+ identifier != name
510
+ and convert(connection.ops.quote_name(identifier)) != convert(connection.ops.quote_name(name))
511
+ and not (namespace and identifier == f'"{namespace}"."{name}"')
512
+ )
513
+ ):
514
+ raise ImproperlyConfigured(
515
+ f"cannot resolve storage identifier {identifier!r} on {connection.alias!r}; "
516
+ "use a reviewed explicit migration for unsupported identifier syntax, length or namespace"
517
+ )
518
+ return convert(namespace), convert(name)
519
+
520
+
521
+ def _storage_identity(connection: BaseDatabaseWrapper, table: str, cursor: Any) -> tuple[str, str] | None:
522
+ """Resolve physical storage through the backend's native catalog semantics."""
523
+ namespace, name = _storage_identifier(connection, table)
524
+ if connection.vendor == "postgresql":
525
+ cursor.execute(
526
+ "SELECT n.nspname, c.relname FROM pg_catalog.pg_class c "
527
+ "JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "
528
+ "WHERE c.oid = pg_catalog.to_regclass(%s)",
529
+ [connection.ops.quote_name(table)],
530
+ )
531
+ row = cursor.fetchone()
532
+ return (row[0], row[1]) if row else None
533
+ if connection.vendor == "sqlite":
534
+ # SQLite resolves temp before main, and identifiers with native NOCASE.
535
+ # Do not substitute Python's broader Unicode case folding for that rule.
536
+ cursor.execute("PRAGMA database_list")
537
+ if any(row[1] not in {"main", "temp"} for row in cursor.fetchall()):
538
+ raise ImproperlyConfigured("cannot resolve storage across attached SQLite database namespaces")
539
+ cursor.execute(
540
+ "SELECT 'temp', name, 0 FROM sqlite_temp_master WHERE name = %s COLLATE NOCASE "
541
+ "UNION ALL SELECT 'main', name, 1 FROM sqlite_master WHERE name = %s COLLATE NOCASE "
542
+ "ORDER BY 3 LIMIT 1",
543
+ [name, name],
544
+ )
545
+ row = cursor.fetchone()
546
+ return (row[0], row[1]) if row else None
547
+ convert = connection.introspection.identifier_converter
548
+ tables = {convert(item) for item in connection.introspection.table_names(cursor)}
549
+ if name in tables:
550
+ return namespace, name
551
+ if connection.features.ignores_table_name_case:
552
+ raise ImproperlyConfigured(f"cannot prove case-sensitive storage identity for {table!r}")
553
+ return None
554
+
555
+
556
+ def _allows_migrate_model(operation: Operation, alias: str, model: Any, *, offline: bool) -> bool:
557
+ # Feature properties can connect (e.g. MySQL server metadata). Offline
558
+ # planning must conservatively retain an alias instead of probing it.
559
+ if offline and model._meta.required_db_features and not model._meta.required_db_vendor:
560
+ return router.allow_migrate_model(alias, model)
561
+ return operation.allow_migrate_model(alias, model)
562
+
563
+
564
+ def _model_storage(model: Any, *, removed_field: str | None = None) -> Iterator[Any]:
565
+ """Tables deleted by native model deletion or implicit M2M field removal."""
566
+ # Django intentionally creates no implicit through classes for swapped models.
567
+ if model._meta.swapped:
568
+ return
569
+ if removed_field is None:
570
+ yield model
571
+ fields = model._meta.local_many_to_many
572
+ else:
573
+ field = model._meta.get_field(removed_field)
574
+ fields = (field,) if field.many_to_many else ()
575
+ for field in fields:
576
+ through = field.remote_field.through
577
+ if through._meta.auto_created:
578
+ yield through
579
+
580
+
491
581
  def _shared_table_drops(
492
582
  before: ProjectState,
493
583
  after: ProjectState,
494
584
  changes: dict[str, list[Migration]],
585
+ *,
586
+ database: bool = False,
495
587
  ) -> None:
496
- owners: dict[str, set[str]] = {}
497
- for model in after.apps.get_models(include_swapped=True):
498
- if model._meta.managed and not model._meta.proxy:
499
- owners.setdefault(model._meta.db_table, set()).add(model._meta.label_lower)
588
+ owners = tuple(
589
+ (owner, storage)
590
+ for owner in after.apps.get_models(include_swapped=True)
591
+ for storage in _model_storage(owner)
592
+ )
500
593
  for label, migrations in sorted(changes.items()):
501
594
  for migration in migrations:
502
595
  for operation in migration.operations:
503
596
  if isinstance(operation, DeleteModel):
504
597
  model = before.apps.get_model(label, operation.name)
505
- remaining = owners.get(model._meta.db_table, set()) - {model._meta.label_lower}
506
- if model._meta.managed and not model._meta.proxy and remaining:
598
+ dropped = tuple(_model_storage(model))
599
+ elif isinstance(operation, RemoveField):
600
+ model = before.apps.get_model(label, operation.model_name)
601
+ dropped = tuple(_model_storage(model, removed_field=operation.name))
602
+ else:
603
+ continue
604
+ if not dropped:
605
+ continue
606
+ for alias in sorted(connections):
607
+ connection = connections[alias]
608
+ try:
609
+ if not _allows_migrate_model(operation, alias, model, offline=not database):
610
+ continue
611
+ for storage in dropped:
612
+ table = storage._meta.db_table
613
+ identity = _storage_identifier(connection, table)
614
+ remaining = set()
615
+ for owner, active_storage in owners:
616
+ if (
617
+ isinstance(operation, DeleteModel)
618
+ and owner._meta.label_lower == model._meta.label_lower
619
+ ) or not _allows_migrate_model(operation, alias, owner, offline=not database):
620
+ continue
621
+ active_table = active_storage._meta.db_table
622
+ other = _storage_identifier(connection, active_table)
623
+ if identity == other:
624
+ remaining.add(active_storage._meta.label_lower)
625
+ elif identity[1] == other[1] or (
626
+ connection.vendor in {"sqlite", "mysql"}
627
+ and identity[1].casefold() == other[1].casefold()
628
+ ):
629
+ if not database:
630
+ raise ImproperlyConfigured(
631
+ f"cannot resolve shared storage {table!r} and "
632
+ f"{active_table!r} offline; use a reviewed explicit migration"
633
+ )
634
+ with connection.cursor() as cursor:
635
+ physical = _storage_identity(connection, table, cursor)
636
+ if physical is not None and physical == _storage_identity(
637
+ connection, active_table, cursor
638
+ ):
639
+ remaining.add(active_storage._meta.label_lower)
640
+ if remaining:
641
+ raise CommandError(
642
+ f"unsafe autodetected table deletion: table {table!r} "
643
+ f"is still owned by {', '.join(sorted(remaining))} on {alias!r}"
644
+ )
645
+ except (DatabaseError, ImproperlyConfigured) as error:
507
646
  raise CommandError(
508
- f"unsafe autodetected model deletion: table {model._meta.db_table!r} "
509
- f"is still owned by {', '.join(sorted(remaining))}"
510
- )
647
+ f"cannot prove shared storage safe on {alias!r}: {error}"
648
+ ) from error
511
649
 
512
650
 
513
651
  class DropGuardAutodetector(MigrationAutodetector):
@@ -531,7 +669,7 @@ class DropGuardAutodetector(MigrationAutodetector):
531
669
  migration_name: str | None = None,
532
670
  ) -> dict[str, list[Migration]]:
533
671
  changes = super().changes(graph, trim_to_apps, convert_apps, migration_name)
534
- _shared_table_drops(self.from_state, self.to_state, changes)
672
+ _shared_table_drops(self.from_state, self.to_state, changes, database=True)
535
673
  refusals: list[str] = []
536
674
  rows: Callable[[str], Any]
537
675
  for label, migrations in sorted(changes.items()):
@@ -541,8 +679,8 @@ class DropGuardAutodetector(MigrationAutodetector):
541
679
  model = self.from_state.apps.get_model(label, operation.model_name)
542
680
  field = model._meta.get_field(operation.name)
543
681
  if field.many_to_many:
544
- through = field.remote_field.through
545
- if not through._meta.auto_created:
682
+ through = next(_model_storage(model, removed_field=operation.name), None)
683
+ if through is None:
546
684
  continue
547
685
  table, column = through._meta.db_table, None
548
686
 
@@ -565,11 +703,9 @@ class DropGuardAutodetector(MigrationAutodetector):
565
703
  rows = column_rows
566
704
  else:
567
705
  continue
568
- refusals.extend(self._holding(model, rows, table, column))
706
+ refusals.extend(self._holding(operation, model, rows, table, column))
569
707
  elif isinstance(operation, DeleteModel):
570
708
  model = self.from_state.apps.get_model(label, operation.name)
571
- if model._meta.proxy or not model._meta.managed or model._meta.swapped:
572
- continue
573
709
  integrations = tuple(
574
710
  integration
575
711
  for integration in resolve_integrations(
@@ -590,7 +726,9 @@ class DropGuardAutodetector(MigrationAutodetector):
590
726
  }
591
727
  return model._base_manager.exclude(pk__in=retired)
592
728
 
593
- refusals.extend(self._holding(model, remaining_rows, model._meta.db_table, None))
729
+ refusals.extend(
730
+ self._holding(operation, model, remaining_rows, model._meta.db_table, None)
731
+ )
594
732
  if refusals:
595
733
  raise CommandError(
596
734
  "unsafe autodetected drop: "
@@ -601,22 +739,47 @@ class DropGuardAutodetector(MigrationAutodetector):
601
739
 
602
740
  @staticmethod
603
741
  def _holding(
742
+ operation: Operation,
604
743
  model: type[Any],
605
744
  rows: Callable[[str], Any],
606
745
  table: str,
607
746
  column: str | None,
608
747
  ) -> Iterator[str]:
609
748
  for alias in sorted(connections):
610
- if not router.allow_migrate_model(alias, model):
611
- continue
612
749
  connection = connections[alias]
613
750
  try:
751
+ if not operation.allow_migrate_model(alias, model):
752
+ continue
614
753
  with connection.cursor() as cursor:
615
- present = table in connection.introspection.table_names(cursor)
754
+ present = _storage_identity(connection, table, cursor) is not None
616
755
  if present and column is not None:
617
- present = column in {
618
- f.name for f in connection.introspection.get_table_description(cursor, table)
619
- }
756
+ namespace, name = _storage_identifier(connection, column)
757
+ if namespace:
758
+ raise ImproperlyConfigured(f"column {column!r} cannot have a namespace")
759
+ if connection.vendor == "sqlite":
760
+ cursor.execute(
761
+ "SELECT name FROM pragma_table_xinfo(%s) WHERE name = %s COLLATE NOCASE",
762
+ [split_identifier(table)[1], name],
763
+ )
764
+ present = cursor.fetchone() is not None
765
+ else:
766
+ convert = connection.introspection.identifier_converter
767
+ if connection.vendor == "postgresql":
768
+ # Native PostgreSQL introspection only describes
769
+ # visible unqualified tables; the cursor owns the
770
+ # actual columns of this fully quoted relation.
771
+ cursor.execute(f"SELECT * FROM {connection.ops.quote_name(table)} LIMIT 0")
772
+ columns = {convert(field[0]) for field in cursor.description}
773
+ else:
774
+ columns = {
775
+ convert(field.name)
776
+ for field in connection.introspection.get_table_description(
777
+ cursor, split_identifier(table)[1]
778
+ )
779
+ }
780
+ present = name in columns
781
+ if not present and connection.vendor == "mysql":
782
+ raise ImproperlyConfigured(f"cannot prove column identity for {column!r}")
620
783
  count = rows(alias).using(alias).count() if present else 0
621
784
  except (DatabaseError, ImproperlyConfigured) as error:
622
785
  yield (
@@ -745,7 +908,9 @@ def _history_aliases(loader: MigrationLoader, labels: set[str]) -> tuple[str, ..
745
908
  for model in state.apps.get_models():
746
909
  if model._meta.app_label in labels:
747
910
  model_labels.add(model._meta.app_label)
748
- aliases.update(alias for alias in connections if router.allow_migrate_model(alias, model))
911
+ aliases.update(
912
+ alias for alias in connections if Operation().allow_migrate_model(alias, model)
913
+ )
749
914
 
750
915
  def include_operations(operations: Iterable[Operation], label: str, state: ProjectState) -> None:
751
916
  include(state)
@@ -841,7 +1006,7 @@ def retire_history(label: str, *, purge: bool = False) -> None:
841
1006
  changes = MigrationAutodetector(before, after).changes(
842
1007
  graph=loader.graph, trim_to_apps={label}, migration_name="compose_purge"
843
1008
  )
844
- _shared_table_drops(before, after, changes)
1009
+ _shared_table_drops(before, after, changes, database=True)
845
1010
  for migration in changes.get(label, ()):
846
1011
  writer = MigrationWriter(migration, include_header=False)
847
1012
  path = Path(writer.path)
@@ -7,7 +7,7 @@ import keyword
7
7
  import sys
8
8
  from collections.abc import Iterable, Mapping
9
9
  from graphlib import CycleError, TopologicalSorter
10
- from typing import Any
10
+ from typing import TYPE_CHECKING, Any
11
11
 
12
12
  from django.apps import AppConfig
13
13
  from django.apps.registry import Apps
@@ -16,6 +16,9 @@ from django.db import models
16
16
 
17
17
  from django_compose.models import Composable
18
18
 
19
+ if TYPE_CHECKING:
20
+ from django_compose.declarations import ModelDeclaration
21
+
19
22
 
20
23
  def _ordered(graph: Mapping[str, Iterable[str]], description: str) -> tuple[str, ...]:
21
24
  try:
@@ -170,21 +173,27 @@ class ModelComposition:
170
173
  """Return one native declaration per constraint, preserving shared ancestry."""
171
174
  return self._constraints[source]
172
175
 
173
- def validate_generated(self, registry: Apps) -> None:
174
- """Check constructed native namespaces, including automatically created managers."""
176
+ def validate_generated(
177
+ self,
178
+ registry: Apps,
179
+ declarations: Mapping[type[models.Model], ModelDeclaration] | None = None,
180
+ ) -> None:
181
+ """Check native structural namespaces, including implicit fields and managers."""
175
182
  for source in self.ordered_models:
176
183
  model = registry.get_model(source._meta.app_label, source.__name__, require_ready=False)
184
+ fields = (
185
+ *model._meta.fields,
186
+ *model._meta.many_to_many,
187
+ *model._meta.private_fields,
188
+ *(field for field in model._meta.parents.values() if field is not None),
189
+ )
190
+ field_names = {name for native in fields for name in (native.name, native.get_attname())}
191
+ if declaration := (declarations or {}).get(source):
192
+ for name in sorted(field_names & declaration.attributes.keys()):
193
+ raise ImproperlyConfigured(f"{model._meta.label}: cannot declare {name!r}")
177
194
  self._validate_field_managers(
178
195
  model,
179
- (
180
- name
181
- for native in (
182
- *model._meta.fields,
183
- *model._meta.many_to_many,
184
- *model._meta.private_fields,
185
- )
186
- for name in (native.name, native.attname)
187
- ),
196
+ field_names,
188
197
  (manager.name for manager in model._meta.managers),
189
198
  )
190
199
 
django_compose/serving.py CHANGED
@@ -186,7 +186,7 @@ def read_receipt(output_module: Path | str) -> Receipt | None:
186
186
 
187
187
 
188
188
  def output_directory(output_module: str) -> Path:
189
- source = SourceResolver().resolve(output_module)
189
+ source = SourceResolver().locate(output_module)
190
190
  if len(source.search_locations) != 1:
191
191
  raise ImproperlyConfigured(f"Missing generated package {output_module!r}; run compose")
192
192
  root = source.search_locations[0]
@@ -235,7 +235,7 @@ def _fingerprints(
235
235
  ) -> tuple[tuple[str, str], ...]:
236
236
  result = []
237
237
  for declaration in records:
238
- location = resolver.resolve(declaration["module"])
238
+ location = resolver.locate(declaration["module"])
239
239
  if location.path is not None:
240
240
  report_inputs(files=[location.path])
241
241
  if location.path is None or not location.path.is_file():
@@ -388,7 +388,7 @@ def snapshot(
388
388
  if owner is not object:
389
389
  modules[f"config:{owner.__module__}"] = owner.__module__
390
390
  for key, module in sorted(modules.items()):
391
- location = resolver.resolve(module)
391
+ location = resolver.locate(module)
392
392
  if location.path is not None:
393
393
  report_inputs(files=[location.path])
394
394
  if location.kind in {"builtin", "frozen"}:
django_compose/sources.py CHANGED
@@ -6,7 +6,7 @@ import json
6
6
  import sys
7
7
  import sysconfig
8
8
  from collections.abc import Iterable
9
- from dataclasses import dataclass
9
+ from dataclasses import dataclass, replace
10
10
  from importlib import metadata
11
11
  from importlib.machinery import BuiltinImporter, FrozenImporter, ModuleSpec, PathFinder
12
12
  from pathlib import Path
@@ -93,12 +93,12 @@ class SourceResolver:
93
93
  search = list(spec.submodule_search_locations)
94
94
  return None
95
95
 
96
- def resolve(self, module: str) -> ModuleSource:
96
+ def _locate(self, module: str) -> tuple[ModuleSource, tuple[Path, ...]]:
97
97
  if not module or not all(part and ("_" + part).isidentifier() for part in module.split(".")):
98
- return ModuleSource(module, None, "unresolved")
98
+ return ModuleSource(module, None, "unresolved"), ()
99
99
  for finder, kind in ((BuiltinImporter, "builtin"), (FrozenImporter, "frozen")):
100
100
  if finder.find_spec(module) is not None:
101
- return ModuleSource(module, None, kind)
101
+ return ModuleSource(module, None, kind), ()
102
102
  spec = None
103
103
  for entry in self.entries:
104
104
  if module == entry.name:
@@ -114,11 +114,11 @@ class SourceResolver:
114
114
  if spec is None:
115
115
  spec = self._find(module.split("."))
116
116
  if spec is None:
117
- return ModuleSource(module, None, "unresolved")
117
+ return ModuleSource(module, None, "unresolved"), ()
118
118
  locations = tuple(Path(path).resolve() for path in spec.submodule_search_locations or ())
119
119
  path = Path(spec.origin).resolve() if spec.origin else next(iter(locations), None)
120
120
  if path is None:
121
- return ModuleSource(module, None, "unresolved")
121
+ return ModuleSource(module, None, "unresolved"), ()
122
122
  paths = sysconfig.get_paths()
123
123
  site_roots = {Path(paths[key]).resolve() for key in ("purelib", "platlib")}
124
124
  if (
@@ -126,18 +126,26 @@ class SourceResolver:
126
126
  and path.is_relative_to(Path(paths["stdlib"]).resolve())
127
127
  and not any(path.is_relative_to(root) for root in site_roots)
128
128
  ):
129
- return ModuleSource(module, path, "stdlib")
129
+ return ModuleSource(module, path, "stdlib"), ()
130
130
  ownership_paths = (path,) if spec.origin else locations
131
- names = tuple(
132
- sorted({name for source in ownership_paths for name in self.distribution_names(source)})
133
- )
134
131
  app = next(
135
132
  (entry.name for entry in self.entries if path.is_relative_to(Path(entry.path).resolve())), None
136
133
  )
137
- return ModuleSource(
138
- module, path, "distribution" if names else "app" if app else "project", names, app, locations
134
+ return (
135
+ ModuleSource(module, path, "app" if app else "project", app=app, search_locations=locations),
136
+ ownership_paths,
139
137
  )
140
138
 
139
+ def locate(self, module: str) -> ModuleSource:
140
+ """Locate without imports or distribution metadata; kind excludes installed ownership."""
141
+ return self._locate(module)[0]
142
+
143
+ def resolve(self, module: str) -> ModuleSource:
144
+ """Locate and attribute exact installed ownership, indexing metadata once per resolver."""
145
+ source, ownership_paths = self._locate(module)
146
+ names = tuple(sorted({name for path in ownership_paths for name in self.distribution_names(path)}))
147
+ return replace(source, kind="distribution", distributions=names) if names else source
148
+
141
149
 
142
150
  def resolve_module(module: str, entries: Iterable[AppSource] = ()) -> ModuleSource:
143
151
  return SourceResolver(entries).resolve(module)
django_compose/typing.py CHANGED
@@ -16,9 +16,13 @@ from typing import TYPE_CHECKING, Literal
16
16
 
17
17
  from django.core.exceptions import FieldDoesNotExist
18
18
  from django.db import models
19
+ from mypy.checkmember import analyze_member_access
20
+ from mypy.expandtype import expand_type, expand_type_by_instance
21
+ from mypy.maptype import map_instance_to_supertype
19
22
  from mypy.mro import calculate_mro
20
23
  from mypy.nodes import (
21
24
  MDEF,
25
+ CallExpr,
22
26
  ClassDef,
23
27
  Decorator,
24
28
  FuncDef,
@@ -26,6 +30,7 @@ from mypy.nodes import (
26
30
  MypyFile,
27
31
  OverloadedFuncDef,
28
32
  PlaceholderNode,
33
+ SymbolTable,
29
34
  SymbolTableNode,
30
35
  TypeInfo,
31
36
  Var,
@@ -34,7 +39,8 @@ from mypy.options import Options
34
39
  from mypy.plugin import AttributeContext, ClassDefContext, DynamicClassDefContext, ReportConfigContext
35
40
  from mypy.semanal_shared import PRIORITY_FALLBACKS, has_placeholder
36
41
  from mypy.server.trigger import make_trigger
37
- from mypy.types import CallableType, Instance, Overloaded, TypeType, get_proper_type
42
+ from mypy.typeops import erase_to_bound, make_simplified_union
43
+ from mypy.types import CallableType, Instance, Overloaded, TypeType, UnionType, get_proper_type
38
44
  from mypy.types import Type as MypyType
39
45
  from mypy.typevars import fill_typevars, fill_typevars_with_any
40
46
  from mypy_django_plugin.django.context import DjangoContext
@@ -119,7 +125,10 @@ class CompositionContext(DjangoContext):
119
125
  selected: dict[str, _Member] = {}
120
126
  self.members[name] = selected
121
127
  donor_ancestors = {base for donor in donors for base in donor.__mro__}
122
- for owner in concrete.__mro__:
128
+ seen = set(vars(concrete))
129
+ for owner in concrete.__mro__[1:]:
130
+ attributes = set(vars(owner)) - seen
131
+ seen.update(vars(owner))
123
132
  if owner in source.__mro__ or owner not in donor_ancestors:
124
133
  continue
125
134
  receiver = next(
@@ -127,7 +136,7 @@ class CompositionContext(DjangoContext):
127
136
  )
128
137
  member = _Member(helpers.get_class_fullname(owner), helpers.get_class_fullname(receiver))
129
138
  self.dependencies.setdefault(source.__module__, set()).add(owner.__module__)
130
- for attribute in vars(owner):
139
+ for attribute in sorted(attributes):
131
140
  selected.setdefault(attribute, member)
132
141
  for source, parent in self.required_ancestors.items():
133
142
  self.parents.setdefault(helpers.get_class_fullname(source), helpers.get_class_fullname(parent))
@@ -175,6 +184,7 @@ class CompositionPlugin(NewSemanalDjangoPlugin):
175
184
 
176
185
  django_context: CompositionContext
177
186
  context_class: type[CompositionContext] = CompositionContext
187
+ _projecting_access = False
178
188
 
179
189
  def __init__(self, options: Options) -> None:
180
190
  with _compose_mode():
@@ -191,13 +201,105 @@ class CompositionPlugin(NewSemanalDjangoPlugin):
191
201
  }
192
202
 
193
203
  def get_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], MypyType] | None:
194
- """Expose configure's derived facts through native Django settings lookup."""
204
+ """Project effective member access and configure's native settings facts."""
195
205
 
196
206
  native = super().get_attribute_hook(fullname)
207
+ if projection := self._member_access_hook(fullname):
208
+ return projection
197
209
  if fullname.rpartition(".")[0] == fullnames.DUMMY_SETTINGS_BASE_CLASS and native is not None:
198
210
  return partial(self._derived_setting, native=native)
199
211
  return native
200
212
 
213
+ def get_class_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], MypyType] | None:
214
+ return self._member_access_hook(fullname) or super().get_class_attribute_hook(fullname)
215
+
216
+ def _member_access_hook(self, fullname: str) -> Callable[[AttributeContext], MypyType] | None:
217
+ if self._projecting_access:
218
+ return None
219
+ owner, _, name = fullname.rpartition(".")
220
+ if name not in self.django_context.members.get(owner, {}):
221
+ symbol = self.lookup_fully_qualified(owner)
222
+ if symbol and isinstance(symbol.node, TypeInfo):
223
+ inherited = symbol.node.get_containing_type_info(name)
224
+ if inherited is not None:
225
+ owner = inherited.fullname
226
+ if name in self.django_context.members.get(owner, {}):
227
+ return partial(self._member_access, target_name=owner, name=name)
228
+ return None
229
+
230
+ def _member_access(self, ctx: AttributeContext, *, target_name: str, name: str) -> MypyType:
231
+ # Native override checks also use member access with a declaration as
232
+ # context; those must continue to compare the authored signatures. The
233
+ # native union call checker rechecks member access with the CallExpr.
234
+ if not isinstance(ctx.context, MemberExpr) and not (
235
+ isinstance(ctx.context, CallExpr) and isinstance(ctx.context.callee, MemberExpr)
236
+ ):
237
+ return ctx.default_attr_type
238
+ target_symbol = self.lookup_fully_qualified(target_name)
239
+ assert target_symbol and isinstance(target_symbol.node, TypeInfo)
240
+ target = target_symbol.node
241
+ if name not in target.metadata.get("compose_overrides", {}):
242
+ return ctx.default_attr_type
243
+ member = self.django_context.members[target.fullname][name]
244
+ origin = self.lookup_fully_qualified(member.owner)
245
+ receiver = self.lookup_fully_qualified(member.receiver)
246
+ assert origin and isinstance(origin.node, TypeInfo)
247
+ assert receiver and isinstance(receiver.node, TypeInfo)
248
+ symbol = origin.node.names.get(name)
249
+ declaration = _member_variable(symbol.node) if symbol is not None else None
250
+ if declaration is None or declaration.type is None:
251
+ return ctx.default_attr_type
252
+ checker = helpers.get_typechecker_api(ctx)
253
+ projected = self._specialize_member(
254
+ name, declaration, target, origin.node, receiver.node, checker.named_type("builtins.function")
255
+ )
256
+ # A native lookup view keeps authored signatures available to override
257
+ # and method-body analysis. Only expression access sees the donor.
258
+ view = TypeInfo(
259
+ SymbolTable({name: SymbolTableNode(MDEF, projected)}), target.defn, target.module_name
260
+ )
261
+ view._fullname = target.fullname
262
+ view.mro = [view, *target.mro[1:]]
263
+ receivers: list[MypyType] = [ctx.type]
264
+ bounded = get_proper_type(erase_to_bound(ctx.type))
265
+ if isinstance(bounded, UnionType):
266
+ # Native union lookup invokes this hook for each owning member but
267
+ # exposes the original union. Keep only that owner's receivers;
268
+ # the outer native lookup handles the other arms independently.
269
+ receivers = []
270
+ for item in bounded.relevant_items():
271
+ instance = get_proper_type(item)
272
+ if isinstance(instance, TypeType):
273
+ instance = get_proper_type(instance.item)
274
+ elif isinstance(instance, CallableType | Overloaded) and instance.is_type_obj():
275
+ instance = get_proper_type(instance.items[0].ret_type)
276
+ if isinstance(instance, Instance) and instance.type.get_containing_type_info(name) is target:
277
+ receivers.append(item)
278
+ if not receivers:
279
+ return ctx.default_attr_type
280
+ self._projecting_access = True
281
+ try:
282
+ return make_simplified_union(
283
+ [
284
+ analyze_member_access(
285
+ name,
286
+ TypeType.make_normalized(receiver.items[0].ret_type)
287
+ if isinstance(receiver, CallableType | Overloaded) and receiver.is_type_obj()
288
+ else receiver,
289
+ ctx.context,
290
+ is_lvalue=ctx.is_lvalue,
291
+ is_super=False,
292
+ is_operator=False,
293
+ original_type=receiver,
294
+ chk=checker,
295
+ override_info=view,
296
+ )
297
+ for receiver in receivers
298
+ ]
299
+ )
300
+ finally:
301
+ self._projecting_access = False
302
+
201
303
  def _derived_setting(
202
304
  self, ctx: AttributeContext, *, native: Callable[[AttributeContext], MypyType]
203
305
  ) -> MypyType:
@@ -476,8 +578,10 @@ class CompositionPlugin(NewSemanalDjangoPlugin):
476
578
  if symbol and symbol.plugin_generated and isinstance(symbol.node, Var):
477
579
  del target.names[name]
478
580
  emitted = target.metadata.setdefault("compose_members", {})
581
+ overrides = target.metadata.setdefault("compose_overrides", {})
479
582
  for name, member in self.django_context.members.get(target.fullname, {}).items():
480
- if target.get(name) is not None:
583
+ existing = target.get(name)
584
+ if existing is not None and existing.plugin_generated:
481
585
  continue
482
586
  origin = self.lookup_fully_qualified(member.owner)
483
587
  receiver = self.lookup_fully_qualified(member.receiver)
@@ -495,6 +599,17 @@ class CompositionPlugin(NewSemanalDjangoPlugin):
495
599
  projected = self._specialize_member(
496
600
  name, declaration, target, origin.node, receiver.node, function_type
497
601
  )
602
+ if existing is not None:
603
+ original = _member_variable(existing.node)
604
+ if original is not None and original.type is not None:
605
+ owner = target.get_containing_type_info(name)
606
+ assert owner is not None
607
+ target.names[name] = SymbolTableNode(
608
+ MDEF,
609
+ self._specialize_member(name, original, target, owner, target, function_type),
610
+ )
611
+ overrides[name] = True
612
+ continue
498
613
  target.names[name] = SymbolTableNode(MDEF, projected, plugin_generated=True)
499
614
  emitted[name] = member.owner
500
615
 
@@ -507,11 +622,6 @@ class CompositionPlugin(NewSemanalDjangoPlugin):
507
622
  receiver: TypeInfo,
508
623
  function_type: Instance,
509
624
  ) -> Var:
510
- # Load this native owner after mypy.types: its standalone import cycle
511
- # otherwise prevents importing CompositionContext outside mypy's CLI.
512
- from mypy.expandtype import expand_type, expand_type_by_instance
513
- from mypy.maptype import map_instance_to_supertype
514
-
515
625
  assert declaration.type is not None
516
626
  instance = fill_typevars(receiver)
517
627
  assert isinstance(instance, Instance)
django_compose/urls.py CHANGED
@@ -2,12 +2,14 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- import re
6
5
  from collections.abc import Iterator
7
6
 
8
7
  from django.apps import apps
9
8
  from django.core.checks import Error
10
9
  from django.urls import URLPattern, URLResolver, include, path
10
+ from django.urls.resolvers import RegexPattern, RoutePattern
11
+
12
+ type _Route = tuple[tuple[object, ...], ...]
11
13
 
12
14
 
13
15
  def _patterns() -> Iterator[tuple[str, URLResolver]]:
@@ -26,29 +28,48 @@ def _patterns() -> Iterator[tuple[str, URLResolver]]:
26
28
  )
27
29
 
28
30
 
29
- def _routes(pattern: URLPattern | URLResolver, prefix: str = "") -> Iterator[str]:
30
- # Compare native effective regular expressions, including nested includes.
31
- expression = pattern.pattern.regex.pattern.removeprefix("^")
32
- route = prefix + expression
31
+ def _routes(pattern: URLPattern | URLResolver, prefix: _Route = ()) -> Iterator[_Route]:
32
+ native = pattern.pattern
33
+ if type(pattern) not in (URLPattern, URLResolver) or type(native) not in (RoutePattern, RegexPattern):
34
+ return
35
+ # Each include matches independently. Preserve native boundaries, anchors,
36
+ # flags and converter identity instead of approximating one combined regex.
37
+ route = prefix + (
38
+ (
39
+ type(native),
40
+ native.regex.pattern,
41
+ native.regex.flags,
42
+ native._is_endpoint, # type: ignore[union-attr] # Native attribute omitted by django-stubs.
43
+ tuple((name, id(converter)) for name, converter in native.converters.items()),
44
+ ),
45
+ )
33
46
  if isinstance(pattern, URLResolver):
34
47
  for child in pattern.url_patterns:
35
48
  yield from _routes(child, route)
36
49
  else:
37
- yield re.sub(r"\(\?P<[^>]+>", "(?:", route)
50
+ yield route
38
51
 
39
52
 
40
53
  def check_url_collisions(**kwargs: object) -> list[Error]:
41
- """Report competing effective routes, regardless of reverse namespace."""
42
- owners: dict[str, str] = {}
54
+ """Report identical native matching chains, regardless of reverse namespace.
55
+
56
+ Pattern type, regex text/flags, endpoint behavior and converter instances
57
+ must agree at every include boundary. Differently expressed chains and
58
+ custom pattern types retain Django's ordered resolution without a proof.
59
+ No converter is executed by this check.
60
+ """
61
+ owners: dict[_Route, str] = {}
43
62
  errors = []
44
- for owner, resolver in _patterns():
63
+ # Retain native resolvers throughout the proof so converter IDs stay live.
64
+ for owner, resolver in tuple(_patterns()):
45
65
  for route in _routes(resolver):
46
66
  previous = owners.get(route)
47
67
  owners[route] = owner
48
68
  if previous is not None:
49
69
  errors.append(
50
70
  Error(
51
- f"URL route {route!r} is claimed by {previous} and {owner}",
71
+ f"URL pattern chain {tuple(part[1] for part in route)!r} "
72
+ f"is claimed by {previous} and {owner}",
52
73
  id="django_compose.E001",
53
74
  )
54
75
  )
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.5
2
+ Name: django-compose
3
+ Version: 0.1.0.dev5
4
+ Summary: Compose reusable Django apps into a runnable project.
5
+ Project-URL: Source, https://github.com/ang-ee/django-compose
6
+ Project-URL: Documentation, https://github.com/ang-ee/django-compose/tree/main/docs
7
+ Project-URL: Issues, https://github.com/ang-ee/django-compose/issues
8
+ Author-email: "Angee, Inc." <hi@angee.ai>
9
+ License-Expression: LGPL-3.0-or-later
10
+ License-File: COPYING
11
+ License-File: LICENSE
12
+ License-File: NOTICE
13
+ Requires-Python: >=3.14
14
+ Requires-Dist: django-yamlconf>=1.5
15
+ Requires-Dist: django<6.2,>=6.1.2
16
+ Requires-Dist: packaging>=26
17
+ Provides-Extra: typing
18
+ Requires-Dist: angee-django-stubs-ext==6.1.2; extra == 'typing'
19
+ Requires-Dist: angee-django-stubs[compatible-mypy]==6.1.2.post3; extra == 'typing'
20
+ Requires-Dist: angee-mypy==2.1.0; extra == 'typing'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # django-compose
24
+
25
+ Compose reusable Django apps into a runnable project.
26
+
27
+ django-compose resolves the apps selected by your project's `INSTALLED_APPS`,
28
+ combines their model declarations and settings contributions, and generates
29
+ ordinary Django models and app configurations before startup.
30
+
31
+ Use it when several projects share reusable apps but need different combinations
32
+ of fields and behavior. You author the project settings and launcher; Django
33
+ continues to own the app registry, ORM, managers, querysets and migrations.
34
+
35
+ ```text
36
+ installed apps + project settings → compose → generated Django package
37
+ ```
38
+
39
+ ## What it provides
40
+
41
+ - **App selection:** expand explicit roots through declared app dependencies and
42
+ optional installed-package metadata.
43
+ - **Model composition:** add fields and methods to another app's model, create
44
+ concrete models, or declare native multi-table inheritance.
45
+ - **Project configuration:** combine app settings and optionally collect URL,
46
+ ASGI and database-preparation contributions.
47
+ - **Build output:** generate model/configuration modules and declared artifacts;
48
+ verify that they match the selected inputs before serving.
49
+
50
+ Packages remain installed at runtime because generated classes import their
51
+ source declarations. `compose` writes files; Django's migration commands change
52
+ the database.
53
+
54
+ ## One model, two apps
55
+
56
+ ```python
57
+ # catalog/models.py
58
+ from django.db import models
59
+ from django_compose.models import Composable
60
+
61
+ class Item(Composable, concrete=True):
62
+ title = models.CharField(max_length=100)
63
+
64
+ class Meta:
65
+ abstract = True
66
+ ```
67
+
68
+ ```python
69
+ # reviews/models.py
70
+ from django.db import models
71
+ from django_compose.models import Composable
72
+
73
+ class Rating(Composable, extends="catalog.Item"):
74
+ rating = models.PositiveSmallIntegerField(default=0)
75
+
76
+ class Meta:
77
+ abstract = True
78
+ ```
79
+
80
+ With both apps selected, the generated `catalog.Item` has `title` and `rating` in
81
+ one table. `Rating` adds no table of its own. After composition, migrations and
82
+ Django setup, use `apps.get_model("catalog", "Item")` to obtain the concrete model.
83
+ The [model guide](https://github.com/ang-ee/django-compose/blob/main/docs/models.md)
84
+ explains all four declaration keywords and lazy relations.
85
+
86
+ ## Get started
87
+
88
+ This is a development preview. See [compatibility and platform requirements](https://github.com/ang-ee/django-compose/blob/main/docs/dependencies.md)
89
+ and [installation](https://github.com/ang-ee/django-compose/blob/main/docs/packaging.md).
90
+
91
+ 1. [Run the quick start](https://github.com/ang-ee/django-compose/blob/main/docs/quickstart.md)
92
+ to compose the checked-in SQLite project and query the result.
93
+ 2. [Configure your project](https://github.com/ang-ee/django-compose/blob/main/docs/configuration.md)
94
+ with `configure(globals())` and the command launcher.
95
+ 3. [Browse the APIs](https://github.com/ang-ee/django-compose/blob/main/docs/README.md)
96
+ for commands, Python entry points and app extension hooks.
97
+
98
+ Licensed under [LGPL-3.0-or-later](https://github.com/ang-ee/django-compose/blob/main/LICENSE).
@@ -1,29 +1,29 @@
1
1
  django_compose/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
2
  django_compose/__main__.py,sha256=3UMaUz10MyIX8O46BUiU269LnvxdKfjImI2j2Jnl3us,135
3
3
  django_compose/apps.py,sha256=thorhTqeNu2fw6Kx4oguoPqsyYwvkiKnvQbAGeLKB6c,4157
4
- django_compose/artifacts.py,sha256=GHLrzCMU00scL9712TLaQPbTY8cdk3l5gv3QQ1DWZb8,9859
4
+ django_compose/artifacts.py,sha256=JIwTpHDB6dahVpOOrS9M8bHWV1356nGCjCo45Sds5vg,10046
5
5
  django_compose/asgi.py,sha256=EllgrrF3fMEQXNd3YR5JvijKaKFHqPI2Lv2PtmQ4ZKA,5151
6
6
  django_compose/autoreload.py,sha256=Obguzio30T42nIjSX9HVmrU-CqtTrm7moU0Wd271Egg,4128
7
- django_compose/build.py,sha256=QexC6r-yPcWrQ-WBfT2iI1xW1b1iMiYwDCXR-YzLmyw,11752
7
+ django_compose/build.py,sha256=hxLad46ZIU5QdD0f6e6TUtk3W9XQEXXgHyZQXeMhfFU,11766
8
8
  django_compose/checks.py,sha256=68mO4E6_UPYhya9wjO-SsQ2YFnDSl0q_fI8r-DnSTZ0,366
9
9
  django_compose/cli.py,sha256=9YlvZY7-qPVtuTXpMA5KxtAZd-TzTVCrg-2F4cNodUM,1209
10
- django_compose/components.py,sha256=jtjaK2gDBWDMV0H05bT0aG3ruIYkjKyallDHLfnhscA,13450
10
+ django_compose/components.py,sha256=jNMkWm0Q15dbmVkK3jBdM_ldgqilFitvrfGaRHxmXx0,14518
11
11
  django_compose/conf.py,sha256=Y6wEhxZh2gT_XjooEjc_5Ry0MOEIaPH4yCOf6UlZo-U,15838
12
12
  django_compose/declarations.py,sha256=JJ09haPmgua4h2P9T8-fMos3CWHdQMpWkw15gXlL1nM,6900
13
13
  django_compose/history.py,sha256=-D9jT-2EvKH6HDo3EfDeTD6lxUirgQOxeDh4cJKLoAU,1291
14
- django_compose/migration_imports.py,sha256=AuK2HdfesyuN55_-eQ_lROnxLqh6z_BZ36vRJP-KFoE,22066
15
- django_compose/migrations.py,sha256=q-oOLgDX2lEjK9qDzSUMwnCWpawusvhhzBn75-O-BDU,40613
16
- django_compose/model_composition.py,sha256=6LxdVnpDxkmbfYKG99fqPX-D-QK4PiH7Eg96ggK5x9o,16057
14
+ django_compose/migration_imports.py,sha256=vyg8NdUCl977HrdfBkz642x0ra_btaRdCqZEfQs4V2o,22011
15
+ django_compose/migrations.py,sha256=oHkVHiYk-iq64cDio6zDSBNMEFwZax2Cfk8UommYzxw,49469
16
+ django_compose/model_composition.py,sha256=470nEltv-x6JYl_AWaQxK6cUOnOQe7e63y-Ehi_WrnM,16547
17
17
  django_compose/models.py,sha256=hM0ed-sotXh2vdI0zNESYnX_qS_39_IHwAk4jZnpYXU,2512
18
18
  django_compose/provision.py,sha256=ufGuc1jesX6gid-s1a-rNwQbKvKcgnOjvSPwVdUrHF4,15321
19
19
  django_compose/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
20
20
  django_compose/rendering.py,sha256=1OFZU7lLMO2rD4S9K1-g8wvdn8RKBnUuQTFPHnDWsHY,3647
21
- django_compose/serving.py,sha256=kOEKik7Oe0CLDmGviHjtP3z3ZUn8xnjdG0z53WMM0KY,15499
22
- django_compose/snapshot.py,sha256=V7oxltGssttISZ7zPtIjuPA5fBOvzWbD2e4UdkEnPus,17732
23
- django_compose/sources.py,sha256=zusV-sFM9KnW6zyb05Dvag1APU_ABZlqL47W1xwvssI,6094
24
- django_compose/typing.py,sha256=J929_NrnmRWEpANDAhT3pivNE_Cas5sHEDCSENf9O_c,30405
25
- django_compose/urls.py,sha256=pIWRJ2stsL7Cf29S0ET9yBs161hGWdUy7LeYIXB1f_o,1987
26
- django_compose/management/__init__.py,sha256=p9ZFdX92SHN9RHeSN4dTgt6Oe3DhKq0LbiTaPRz7tSY,8727
21
+ django_compose/serving.py,sha256=FoS3TNNpgPGLpfCHtGrW0JVJVT9DyI7sxJ5U4x0oVLU,15498
22
+ django_compose/snapshot.py,sha256=115gi4SRkYUu2JFf_GC8kORPUWGy9z0BGlTyhNZxZYg,17730
23
+ django_compose/sources.py,sha256=fLBGSHtAInnoTM1Z2Wdt74P_cbLUUP4MWD1l2uS_zAI,6629
24
+ django_compose/typing.py,sha256=13pd3JfIoBV8v4AHK-QgAg9J8C4Miz_D0dmHFEwUG4I,36089
25
+ django_compose/urls.py,sha256=PZLa-pGe5JgzpUgu9sOEUbO2FgLGPkZZSOhRD1ZLgUk,2969
26
+ django_compose/management/__init__.py,sha256=wBX58M8MHUEvl9M57wVNNDAq4lsCSLjPtM3Copabs2w,8724
27
27
  django_compose/management/commands/__init__.py,sha256=_mgOwmIp5-GhgJd6tY4Wc89G0EJDiHF9tYo8F63ytm8,40
28
28
  django_compose/management/commands/check_migrations.py,sha256=CIGGQCq-01Cm0_ZR7Exl4EtM_-qnFfhzfMsLxhl8P5A,2918
29
29
  django_compose/management/commands/compose.py,sha256=UuNjIgNwYOYE_1aKIcEvh3C1fMjP9tdN_-SDDwVQjIc,1860
@@ -32,10 +32,10 @@ django_compose/management/commands/migrate.py,sha256=_MkiQRjQRwIr9dEUnKk4WEjLgz5
32
32
  django_compose/management/commands/provision.py,sha256=4GTPwH1Pp1V_YkztDZxeHuyAjDUHjZxhkdvFlrgDBfU,1035
33
33
  django_compose/management/commands/reset_migration_history.py,sha256=PD3baeH1jQHIXXLaEYyxZXfhVYfJLzTXnv-XF1ySULQ,1489
34
34
  django_compose/management/commands/retire_history.py,sha256=3RV1-w5Niij0svr0gB_gAjBgskxCYtdg5pPfsGN287s,886
35
- django_compose-0.1.0.dev2.dist-info/METADATA,sha256=n-5jP3W_nMDISvjGOxNZK9J0fgN8DrtBie9tCebUniA,4897
36
- django_compose-0.1.0.dev2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
37
- django_compose-0.1.0.dev2.dist-info/entry_points.txt,sha256=-Iw1c8YAegCC53YCKgPXjIZn4aPS3MmEKbcMrCpUMFU,59
38
- django_compose-0.1.0.dev2.dist-info/licenses/COPYING,sha256=jOtLnuWt7d5Hsx6XXB2QxzrSe2sWWh3NgMfFRetluQM,35147
39
- django_compose-0.1.0.dev2.dist-info/licenses/LICENSE,sha256=46mU2C5kSwOnkqkw9XQAJlhBL2JAf1_uCD8lVcXyMRg,7652
40
- django_compose-0.1.0.dev2.dist-info/licenses/NOTICE,sha256=C4fEGI9_-a1GCPfAH9bC0ZvmZFS71b9Z4v6rjrT5dxA,450
41
- django_compose-0.1.0.dev2.dist-info/RECORD,,
35
+ django_compose-0.1.0.dev5.dist-info/METADATA,sha256=Pc9V5woPKK6K8UEae8GhJ-jq7rcjA8aGAurtGFfCvzM,3939
36
+ django_compose-0.1.0.dev5.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
37
+ django_compose-0.1.0.dev5.dist-info/entry_points.txt,sha256=-Iw1c8YAegCC53YCKgPXjIZn4aPS3MmEKbcMrCpUMFU,59
38
+ django_compose-0.1.0.dev5.dist-info/licenses/COPYING,sha256=jOtLnuWt7d5Hsx6XXB2QxzrSe2sWWh3NgMfFRetluQM,35147
39
+ django_compose-0.1.0.dev5.dist-info/licenses/LICENSE,sha256=46mU2C5kSwOnkqkw9XQAJlhBL2JAf1_uCD8lVcXyMRg,7652
40
+ django_compose-0.1.0.dev5.dist-info/licenses/NOTICE,sha256=C4fEGI9_-a1GCPfAH9bC0ZvmZFS71b9Z4v6rjrT5dxA,450
41
+ django_compose-0.1.0.dev5.dist-info/RECORD,,
@@ -1,111 +0,0 @@
1
- Metadata-Version: 2.5
2
- Name: django-compose
3
- Version: 0.1.0.dev2
4
- Summary: Compose reusable Django apps into a runnable project.
5
- Project-URL: Source, https://github.com/ang-ee/django-compose
6
- Project-URL: Documentation, https://github.com/ang-ee/django-compose/tree/main/docs
7
- Project-URL: Issues, https://github.com/ang-ee/django-compose/issues
8
- Author-email: "Angee, Inc." <hi@angee.ai>
9
- License-Expression: LGPL-3.0-or-later
10
- License-File: COPYING
11
- License-File: LICENSE
12
- License-File: NOTICE
13
- Requires-Python: >=3.14
14
- Requires-Dist: django-yamlconf>=1.5
15
- Requires-Dist: django<6.2,>=6.1.2
16
- Requires-Dist: packaging>=26
17
- Provides-Extra: typing
18
- Requires-Dist: angee-django-stubs-ext==6.1.2; extra == 'typing'
19
- Requires-Dist: angee-django-stubs[compatible-mypy]==6.1.2.post3; extra == 'typing'
20
- Requires-Dist: angee-mypy==2.1.0; extra == 'typing'
21
- Description-Content-Type: text/markdown
22
-
23
- # django-compose
24
-
25
- Compose reusable Django apps into a runnable project.
26
-
27
- Installed Python distributions participate as **components**, each providing one
28
- Django app. Native package metadata supplies dependencies; `INSTALLED_APPS`
29
- selects the project's roots. Components can provide models, settings or resources.
30
-
31
- One app can define a model and another can add fields and behavior to it. The
32
- result is an ordinary concrete Django model, with Django's ORM and migrations.
33
-
34
- For example, `catalog` defines an item and `reviews` adds a rating:
35
-
36
- ```text
37
- catalog.Item (title) + reviews.Rating (rating, is_recommended)
38
- → concrete catalog.Item → one catalog_item table
39
- ```
40
-
41
- The reusable declarations are abstract models. An explicit `compose` command
42
- writes the concrete classes into a Python package before the project runs.
43
- Select the apps you need; the generated models reflect that selection. You
44
- write ordinary project settings and a command launcher; django-compose supplies
45
- the generated models and app configuration.
46
-
47
- This is useful when several projects share a model but need different optional
48
- capabilities. For a single project with a fixed model structure, ordinary Django
49
- models and abstract bases may already be sufficient.
50
-
51
- **Status:** development preview `0.1.0.dev2`; Python 3.14 and Django 6.1 are supported.
52
- The base dependencies are Django, packaging and django-yamlconf.
53
-
54
- ```sh
55
- python -m pip install django-compose==0.1.0.dev2
56
- ```
57
-
58
- For advanced composed-model analysis, install `django-compose[typing]==0.1.0.dev2`;
59
- see [typing dependencies](https://github.com/ang-ee/django-compose/blob/main/docs/dependencies.md#advanced-typing). The example below
60
- uses this checkout and does not require another framework.
61
-
62
- ## Try the example
63
-
64
- Install [uv](https://docs.astral.sh/uv/) and run these commands from the checkout
65
- root. The example uses a local SQLite database.
66
-
67
- ```sh
68
- uv sync --frozen --no-dev
69
- uv pip install --no-deps ./examples/shop/catalog ./examples/shop/reviews
70
- cd examples/shop
71
- uv run --project ../.. --no-sync python manage.py compose
72
- uv run --project ../.. --no-sync python manage.py makemigrations catalog auth contenttypes
73
- uv run --project ../.. --no-sync python manage.py migrate
74
- uv run --project ../.. --no-sync python manage.py compose --check
75
- uv run --project ../.. --no-sync python verify.py
76
- uv run --project ../.. --no-sync python manage.py shell
77
- ```
78
-
79
- In the Django shell:
80
-
81
- ```python
82
- from django.apps import apps
83
-
84
- Item = apps.get_model("catalog", "Item")
85
- item = Item.objects.create(title="A book", rating=5)
86
- assert item.is_recommended()
87
- assert Item.objects.get(pk=item.pk).rating == 5
88
- ```
89
-
90
- The two apps now contribute to the same model and table. `compose` generated the
91
- classes; `makemigrations` and `migrate` created and applied ordinary Django
92
- history. Source apps remain installed when the generated project runs.
93
-
94
- Projects with database preparation hooks can use
95
- [`provision`](https://github.com/ang-ee/django-compose/blob/main/docs/provisioning.md)
96
- after composing and authoring migrations. It applies migrations, runs optional
97
- app hooks and records readiness for the verified composition. `compose` itself
98
- performs no database preparation.
99
-
100
- ## Where to go next
101
-
102
- - [Quick start](https://github.com/ang-ee/django-compose/blob/main/docs/quickstart.md): walk through the source, generated files,
103
- commands and ORM result.
104
- - [Model declarations](https://github.com/ang-ee/django-compose/blob/main/docs/models.md): add fields to one model or declare
105
- native multi-table inheritance.
106
- - [Project configuration](https://github.com/ang-ee/django-compose/blob/main/docs/configuration.md): use django-compose in your own
107
- project with the current settings and `manage.py` integration.
108
- - [Documentation](https://github.com/ang-ee/django-compose/blob/main/docs/README.md): optional component selection, integrations,
109
- migrations, packaging, API reference and current limitations.
110
-
111
- The source is licensed under [LGPL-3.0-or-later](https://github.com/ang-ee/django-compose/blob/main/LICENSE).