half-orm-dev 1.2.0a1__tar.gz → 2.0.0a1__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 (86) hide show
  1. {half_orm_dev-1.2.0a1/half_orm_dev.egg-info → half_orm_dev-2.0.0a1}/PKG-INFO +6 -9
  2. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/README.md +2 -2
  3. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/cli/commands/migrate.py +54 -36
  4. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/cli/main.py +41 -4
  5. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/file_executor.py +7 -0
  6. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/migration_manager.py +52 -33
  7. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/migrations/0/17/4/00_toml_dict_format.py +1 -4
  8. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/modules.py +133 -11
  9. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/release_file.py +1 -5
  10. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/release_manager.py +103 -0
  11. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/repo.py +9 -3
  12. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/templates/pyproject.toml +2 -3
  13. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/utils.py +24 -0
  14. half_orm_dev-2.0.0a1/half_orm_dev/version.txt +1 -0
  15. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1/half_orm_dev.egg-info}/PKG-INFO +6 -9
  16. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev.egg-info/SOURCES.txt +0 -1
  17. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev.egg-info/requires.txt +1 -4
  18. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/pyproject.toml +16 -4
  19. half_orm_dev-1.2.0a1/half_orm_dev/version.txt +0 -1
  20. half_orm_dev-1.2.0a1/setup.py +0 -84
  21. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/AUTHORS +0 -0
  22. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/LICENSE +0 -0
  23. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/__init__.py +0 -0
  24. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/_bootstrap_runner.py +0 -0
  25. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/cli/__init__.py +0 -0
  26. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/cli/commands/__init__.py +0 -0
  27. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/cli/commands/apply.py +0 -0
  28. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/cli/commands/check.py +0 -0
  29. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/cli/commands/clone.py +0 -0
  30. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/cli/commands/init.py +0 -0
  31. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/cli/commands/patch.py +0 -0
  32. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/cli/commands/recover.py +0 -0
  33. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/cli/commands/release.py +0 -0
  34. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/cli/commands/restore.py +0 -0
  35. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/cli/commands/revert_migration.py +0 -0
  36. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/cli/commands/rollback.py +0 -0
  37. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/cli/commands/set_git_origin.py +0 -0
  38. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/cli/commands/sync.py +0 -0
  39. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/cli/commands/todo.py +0 -0
  40. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/cli/commands/undo.py +0 -0
  41. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/cli/commands/upgrade.py +0 -0
  42. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/cli_extension.py +0 -0
  43. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/database.py +0 -0
  44. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/decorators.py +0 -0
  45. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/hgit.py +0 -0
  46. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/migrations/0/17/1/00_move_to_hop.py +0 -0
  47. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/migrations/0/17/1/01_txt_to_toml.py +0 -0
  48. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/migrations/0/17/4/02_move_patches_to_subdirs.py +0 -0
  49. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/migrations/0/17/5/01_update_pyproject_dependency.py +0 -0
  50. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/migrations/0/18/0/00_add_async_support.py +0 -0
  51. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/migrations/0/18/0/01_update_default_tests.py +0 -0
  52. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/migrations/1/0/0/a20/01_update_gitignore.py +0 -0
  53. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/migrations/1/0/0/a33/00_metadata_to_data_sql.py +0 -0
  54. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/migrations/1/0/0/a35/00_drop_stale_release_schemas.py +0 -0
  55. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/migrations/1/0/0/a36/00_drop_release_schemas.py +0 -0
  56. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/migrations/hop/BREAKING_CHANGES-1.0.0.md +0 -0
  57. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/patch_manager.py +0 -0
  58. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/patch_validator.py +0 -0
  59. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/patches/0/1/0/00_half_orm_meta.database.sql +0 -0
  60. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/patches/0/1/0/01_alter_half_orm_meta.hop_release.sql +0 -0
  61. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/patches/0/1/0/02_half_orm_meta.view.hop_penultimate_release.sql +0 -0
  62. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/patches/log +0 -0
  63. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/patches/sql/half_orm_meta.sql +0 -0
  64. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/py.typed +0 -0
  65. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/scripts/repair-metadata.py +0 -0
  66. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/templates/.gitignore +0 -0
  67. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/templates/MANIFEST.in +0 -0
  68. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/templates/README +0 -0
  69. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/templates/conftest_template +0 -0
  70. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/templates/git-hooks/pre-commit +0 -0
  71. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/templates/git-hooks/pre-push +0 -0
  72. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/templates/git-hooks/prepare-commit-msg +0 -0
  73. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/templates/git-hooks/reference-transaction +0 -0
  74. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/templates/init_module_template +0 -0
  75. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/templates/module_template_1 +0 -0
  76. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/templates/module_template_2 +0 -0
  77. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/templates/module_template_3 +0 -0
  78. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/templates/relation_test +0 -0
  79. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/templates/sql_adapter +0 -0
  80. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/templates/warning +0 -0
  81. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev/venv_setup.py +0 -0
  82. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev.egg-info/dependency_links.txt +0 -0
  83. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev.egg-info/entry_points.txt +0 -0
  84. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/half_orm_dev.egg-info/top_level.txt +0 -0
  85. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/setup.cfg +0 -0
  86. {half_orm_dev-1.2.0a1 → half_orm_dev-2.0.0a1}/tests/test_bootstrap_runner.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: half_orm_dev
3
- Version: 1.2.0a1
3
+ Version: 2.0.0a1
4
4
  Summary: half_orm development Framework.
5
5
  Author-email: Joël Maïzi <joel.maizi@collorg.org>
6
6
  License-Expression: GPL-3.0-or-later
@@ -9,13 +9,12 @@ Keywords: postgres,relation-object mapping
9
9
  Classifier: Development Status :: 3 - Alpha
10
10
  Classifier: Intended Audience :: Developers
11
11
  Classifier: Topic :: Software Development :: Build Tools
12
- Classifier: Programming Language :: Python :: 3.9
13
- Classifier: Programming Language :: Python :: 3.10
14
12
  Classifier: Programming Language :: Python :: 3.11
15
13
  Classifier: Programming Language :: Python :: 3.12
16
14
  Classifier: Programming Language :: Python :: 3.13
17
15
  Classifier: Programming Language :: Python :: 3.14
18
- Requires-Python: >=3.9
16
+ Classifier: Programming Language :: Python :: 3.15
17
+ Requires-Python: >=3.11
19
18
  Description-Content-Type: text/markdown
20
19
  License-File: LICENSE
21
20
  License-File: AUTHORS
@@ -25,11 +24,9 @@ Requires-Dist: packaging
25
24
  Requires-Dist: pydash
26
25
  Requires-Dist: pytest
27
26
  Requires-Dist: pytest-asyncio
28
- Requires-Dist: half_orm<1.3.0,>=1.2.0a1
29
- Requires-Dist: tomli>=2.0.0; python_version < "3.11"
27
+ Requires-Dist: half-orm<3,>=2.0.0
30
28
  Requires-Dist: tomli_w>=1.0.0
31
29
  Dynamic: license-file
32
- Dynamic: requires-dist
33
30
 
34
31
  # half-orm-dev
35
32
 
@@ -39,7 +36,7 @@ Dynamic: requires-dist
39
36
 
40
37
  **Git-centric patch management and PostgreSQL database versioning for half-orm projects**
41
38
 
42
- [![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
39
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
43
40
  [![License: GPLv3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
44
41
  [![half-orm](https://img.shields.io/badge/halfORM-compatible-green.svg)](https://github.com/half-orm/half-orm)
45
42
  [![PyPI Downloads](https://static.pepy.tech/personalized-badge/half-orm-dev?period=total&units=INTERNATIONAL_SYSTEM&left_color=BLACK&right_color=GREEN&left_text=downloads)](https://pepy.tech/projects/half-orm-dev)
@@ -120,7 +117,7 @@ half_orm dev patch merge
120
117
 
121
118
  ### Prerequisites
122
119
 
123
- - **Python**: [Active versions](https://devguide.python.org/versions/) (currently 3.9+)
120
+ - **Python**: [Active versions](https://devguide.python.org/versions/) (currently 3.11+)
124
121
  - **PostgreSQL**: [Supported versions](https://www.postgresql.org/support/versioning/) (currently 13+)
125
122
  - **Git** for version control
126
123
 
@@ -6,7 +6,7 @@
6
6
 
7
7
  **Git-centric patch management and PostgreSQL database versioning for half-orm projects**
8
8
 
9
- [![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
9
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
10
10
  [![License: GPLv3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
11
11
  [![half-orm](https://img.shields.io/badge/halfORM-compatible-green.svg)](https://github.com/half-orm/half-orm)
12
12
  [![PyPI Downloads](https://static.pepy.tech/personalized-badge/half-orm-dev?period=total&units=INTERNATIONAL_SYSTEM&left_color=BLACK&right_color=GREEN&left_text=downloads)](https://pepy.tech/projects/half-orm-dev)
@@ -87,7 +87,7 @@ half_orm dev patch merge
87
87
 
88
88
  ### Prerequisites
89
89
 
90
- - **Python**: [Active versions](https://devguide.python.org/versions/) (currently 3.9+)
90
+ - **Python**: [Active versions](https://devguide.python.org/versions/) (currently 3.11+)
91
91
  - **PostgreSQL**: [Supported versions](https://www.postgresql.org/support/versioning/) (currently 13+)
92
92
  - **Git** for version control
93
93
 
@@ -7,10 +7,61 @@ is newer than the repository's hop_version in .hop/config.
7
7
 
8
8
  import click
9
9
  from half_orm_dev.repo import Repo, RepoError
10
- from half_orm_dev.migration_manager import MigrationManager
10
+ from half_orm_dev.migration_manager import (
11
+ MigrationManager, HALF_ORM_BREAKING_CHANGES_URL)
11
12
  from half_orm import utils
12
13
 
13
14
 
15
+ def announce_breaking_changes(repo, config_version: str, installed_version: str) -> bool:
16
+ """Say what a migration breaks, before it is confirmed.
17
+
18
+ Two kinds of breaking change, shown differently:
19
+
20
+ * half-orm's, when its major version changes: what the application's
21
+ code must change. They are documented on half-orm's site, so a link
22
+ is enough -- migrating happens on a development machine.
23
+ * half_orm_dev's: what the migration about to run does to the
24
+ repository. Shown in full, since that is what is being confirmed.
25
+
26
+ Returns:
27
+ True when there was something to announce, and the migration calls
28
+ for an explicit "yes" rather than a y/n.
29
+ """
30
+ mgr = MigrationManager(repo)
31
+ major_change = mgr.half_orm_major_change(config_version, installed_version)
32
+ notes = mgr.get_breaking_changes(config_version, installed_version)
33
+
34
+ if major_change:
35
+ from_major, to_major = major_change
36
+ click.echo(utils.Color.bold(
37
+ f"⚠️ half-orm {from_major}.x → {to_major}.x: a major release, "
38
+ "which may require changes to your code."))
39
+ click.echo(" Read what changed, and what to write instead, before going on:")
40
+ click.echo(f" {HALF_ORM_BREAKING_CHANGES_URL.format(major=to_major)}")
41
+ click.echo()
42
+
43
+ if notes:
44
+ width = 70
45
+ label = 'half-orm-dev'
46
+ lines = ['━' * width, " ⚠️ BREAKING CHANGES", '━' * width]
47
+ for note in notes:
48
+ lines.append(
49
+ f"\n ━━━ {label} {installed_version} "
50
+ f"{'━' * max(0, width - len(label) - len(installed_version) - 7)}")
51
+ lines.extend(f" {line}" for line in note['content'].splitlines())
52
+ lines.append(f"\n{'━' * width}")
53
+ click.echo_via_pager('\n'.join(lines) + '\n')
54
+
55
+ return bool(major_change or notes)
56
+
57
+
58
+ def confirm_breaking_migration() -> bool:
59
+ "Ask for the explicit \"yes\" a breaking migration calls for."
60
+ click.echo("Type \"yes\" to confirm you have read the breaking changes and want to proceed.")
61
+ answer = click.prompt("Proceed?", default="no")
62
+ return answer.strip().lower() == "yes"
63
+
64
+
14
65
  @click.command()
15
66
  @click.option(
16
67
  '--verbose', '-v',
@@ -77,41 +128,8 @@ def migrate(verbose: bool) -> None:
77
128
  click.echo()
78
129
 
79
130
  # Check for breaking changes between current and target version
80
- mgr = MigrationManager(repo)
81
- breaking_changes = mgr.get_breaking_changes(config_version, installed_version)
82
-
83
- needs_explicit_confirm = False
84
- if breaking_changes:
85
- import importlib.metadata
86
- try:
87
- half_orm_installed = importlib.metadata.version('half-orm')
88
- except importlib.metadata.PackageNotFoundError:
89
- half_orm_installed = None
90
-
91
- width = 70
92
- lines = []
93
- lines.append('━' * width)
94
- lines.append(f" ⚠️ BREAKING CHANGES")
95
- lines.append('━' * width)
96
- for bc in breaking_changes:
97
- if bc['component'] == 'hop':
98
- label = 'half-orm-dev'
99
- display_version = installed_version
100
- else:
101
- label = 'half-orm'
102
- display_version = half_orm_installed or bc['version']
103
- lines.append(f"\n ━━━ {label} {display_version} {'━' * max(0, width - len(label) - len(display_version) - 7)}")
104
- for line in bc['content'].splitlines():
105
- lines.append(f" {line}")
106
- lines.append(f"\n{'━' * width}")
107
- click.echo_via_pager('\n'.join(lines) + '\n')
108
- needs_explicit_confirm = True
109
-
110
- # Run migrations
111
- if needs_explicit_confirm:
112
- click.echo("Type \"yes\" to confirm you have read the breaking changes and want to proceed.")
113
- answer = click.prompt("Proceed?", default="no")
114
- confirmed = answer.strip().lower() == "yes"
131
+ if announce_breaking_changes(repo, config_version, installed_version):
132
+ confirmed = confirm_breaking_migration()
115
133
  else:
116
134
  confirmed = click.confirm("Do you want to proceed?", default=False)
117
135
 
@@ -10,7 +10,7 @@ import sys
10
10
  from pathlib import Path
11
11
 
12
12
  import half_orm_dev as _half_orm_dev
13
- from half_orm_dev.utils import hop_version
13
+ from half_orm_dev.utils import hop_version, is_production_checkout
14
14
  from half_orm_dev.repo import Repo, OutdatedHalfORMDevError
15
15
  from half_orm import utils
16
16
  from .commands import ALL_COMMANDS
@@ -141,10 +141,27 @@ def create_cli_group():
141
141
  cmd = super().get_command(ctx, cmd_name)
142
142
  if cmd is not None:
143
143
  return cmd
144
+ if hop.needs_hop_upgrade:
145
+ # No command is registered while half_orm_dev is too old, so
146
+ # `half_orm dev upgrade` answered "No such command 'upgrade'"
147
+ # before the group callback could say why -- and install the
148
+ # right version, or refuse to on a production server. Resolve
149
+ # the name to a placeholder, and let the callback speak.
150
+ @click.command(
151
+ cmd_name,
152
+ context_settings={
153
+ 'allow_extra_args': True,
154
+ 'ignore_unknown_options': True,
155
+ },
156
+ )
157
+ def _outdated():
158
+ sys.exit(1) # not reached: the callback exits or restarts
159
+
160
+ return _outdated
144
161
  # Unknown command — show a specific message when migration is needed.
145
162
  if hop.repo_checked and hop._Hop__repo.needs_migration():
146
163
  installed_version = hop_version()
147
- config_version = hop._Hop__repo.repo.config.hop_version
164
+ config_version = hop._Hop__repo.config.hop_version
148
165
 
149
166
  @click.command(
150
167
  cmd_name,
@@ -193,6 +210,16 @@ def create_cli_group():
193
210
  error = hop.hop_upgrade_error
194
211
  required = error.required_version
195
212
  installed = error.installed_version
213
+ if error.base_dir and is_production_checkout(error.base_dir):
214
+ # Nothing is installed behind an operator's back on a
215
+ # production server: the version is a decision.
216
+ click.echo(utils.Color.red(
217
+ f"\n This repository requires half-orm-dev {required} "
218
+ f"(installed: {installed})."), err=True)
219
+ click.echo(" Production server: nothing is installed automatically.", err=True)
220
+ click.echo(" Install it, then run the command again:", err=True)
221
+ click.echo(f" pip install half-orm-dev=={required}", err=True)
222
+ sys.exit(1)
196
223
  click.echo(f"\n This repository requires half-orm-dev {required} "
197
224
  f"(installed: {installed}).")
198
225
  click.echo(f" Installing the required version...")
@@ -217,7 +244,7 @@ def create_cli_group():
217
244
  # Propose automatic migration
218
245
  from half_orm_dev.repo import RepoError
219
246
  installed_version = hop_version()
220
- config_version = hop._Hop__repo.repo.config.hop_version
247
+ config_version = hop._Hop__repo.config.hop_version
221
248
  current_branch = hop._Hop__repo.hgit.branch if hop._Hop__repo.hgit else 'unknown'
222
249
 
223
250
  click.echo(f"\n{'='*70}")
@@ -234,8 +261,18 @@ def create_cli_group():
234
261
  click.echo(f"\n 💡 You can interrupt (Ctrl+C) to backup .git/ if needed.")
235
262
  click.echo(f"\n{'='*70}\n")
236
263
 
264
+ # What the migration breaks, if anything: this path used
265
+ # to migrate without showing any breaking change at all.
266
+ from half_orm_dev.cli.commands.migrate import (
267
+ announce_breaking_changes, confirm_breaking_migration)
268
+ if announce_breaking_changes(
269
+ hop._Hop__repo, config_version, installed_version):
270
+ apply = confirm_breaking_migration()
271
+ else:
272
+ apply = click.confirm("Apply migration now?", default=True)
273
+
237
274
  # Ask for confirmation
238
- if click.confirm("Apply migration now?", default=True):
275
+ if apply:
239
276
  click.echo()
240
277
 
241
278
  # Switch to ho-prod if needed
@@ -107,6 +107,11 @@ def execute_python_file(
107
107
  text=True,
108
108
  check=True
109
109
  )
110
+ # A script that succeeds can still have something to say - notably
111
+ # the generated package logging a relation missing from the database.
112
+ # Dropping its stderr would make that warning unobservable.
113
+ if result.stderr:
114
+ sys.stderr.write(result.stderr)
110
115
  return result.stdout.strip()
111
116
 
112
117
  except subprocess.CalledProcessError as e:
@@ -170,6 +175,8 @@ def _execute_via_venv_runner(
170
175
  text=True,
171
176
  check=True
172
177
  )
178
+ if result.stderr:
179
+ sys.stderr.write(result.stderr)
173
180
  return result.stdout.strip()
174
181
  except subprocess.CalledProcessError as e:
175
182
  error_msg = f"Python execution failed in {file_path.name}"
@@ -34,10 +34,9 @@ from typing import List, Dict, Optional, Tuple
34
34
  from half_orm import utils
35
35
  from half_orm_dev.decorators import with_dynamic_branch_lock
36
36
 
37
- try:
38
- from half_orm.migrations import get_breaking_changes_dir
39
- except (ImportError, AttributeError):
40
- get_breaking_changes_dir = None # type: ignore[assignment]
37
+ # Where half-orm documents what a major release requires of the code.
38
+ HALF_ORM_BREAKING_CHANGES_URL = (
39
+ 'https://half-orm.github.io/half-orm/latest/breaking-changes/#breaking-{major}-0-0')
41
40
 
42
41
 
43
42
  class MigrationManagerError(Exception):
@@ -721,13 +720,14 @@ class MigrationManager:
721
720
 
722
721
  def get_breaking_changes(self, current_version: str, target_version: str) -> List[Dict]:
723
722
  """
724
- Collect breaking-changes documents for all versions in ]current, target].
723
+ Collect half_orm_dev's breaking-changes notes for ]current, target].
725
724
 
726
- Looks in two subdirectories of the migrations root:
727
- - hop/ BREAKING_CHANGES-X.Y.Z.md (half-orm-dev changes)
728
- - half_orm/ BREAKING_CHANGES-X.Y.Z.md (half-orm library changes)
725
+ These describe what the migration about to run does to the
726
+ repository -- the .hop/ layout, a command, the generated code -- and
727
+ are shown in full before it runs. half-orm's own notes are not
728
+ collected: see half_orm_major_change().
729
729
 
730
- Both are keyed by hop version (same major.minor family).
730
+ Files live in migrations/hop/ as BREAKING_CHANGES-X.Y.Z.md.
731
731
 
732
732
  Args:
733
733
  current_version: Current hop version (exclusive lower bound)
@@ -735,7 +735,7 @@ class MigrationManager:
735
735
 
736
736
  Returns:
737
737
  List of dicts ordered by version, each with keys:
738
- - component: 'hop' or 'half_orm'
738
+ - component: 'hop'
739
739
  - version: version string from filename
740
740
  - content: file content
741
741
  """
@@ -751,30 +751,49 @@ class MigrationManager:
751
751
  except Exception:
752
752
  return results
753
753
 
754
- component_dirs = {'hop': self._migrations_root / 'hop'}
755
- if get_breaking_changes_dir is not None:
754
+ bc_dir = self._migrations_root / 'hop'
755
+ if not bc_dir.is_dir():
756
+ return results
757
+ for bc_file in sorted(bc_dir.glob('BREAKING_CHANGES-*.md')):
758
+ # filename: BREAKING_CHANGES-X.Y.Z.md (hyphens in pre-release OK)
759
+ raw = bc_file.stem[len('BREAKING_CHANGES-'):] # e.g. '1.0.0' or '1.0.0-rc1'
756
760
  try:
757
- component_dirs['half_orm'] = get_breaking_changes_dir()
761
+ file_version = version.parse(raw)
758
762
  except Exception:
759
- pass # older half-orm — ignore silently
760
-
761
- for component, bc_dir in component_dirs.items():
762
- if not bc_dir.is_dir():
763
763
  continue
764
- for bc_file in sorted(bc_dir.glob('BREAKING_CHANGES-*.md')):
765
- # filename: BREAKING_CHANGES-X.Y.Z.md (hyphens in pre-release OK)
766
- raw = bc_file.stem[len('BREAKING_CHANGES-'):] # e.g. '1.0.0' or '1.0.0-rc1'
767
- try:
768
- file_version = version.parse(raw)
769
- except Exception:
770
- continue
771
- if current_base < file_version <= target_base:
772
- results.append({
773
- 'component': component,
774
- 'version': raw,
775
- 'content': bc_file.read_text(encoding='utf-8'),
776
- })
777
-
778
- # Sort by version, then by component for a stable display order
779
- results.sort(key=lambda r: (version.parse(r['version']), r['component']))
764
+ if current_base < file_version <= target_base:
765
+ results.append({
766
+ 'component': 'hop',
767
+ 'version': raw,
768
+ 'content': bc_file.read_text(encoding='utf-8'),
769
+ })
770
+
771
+ results.sort(key=lambda r: version.parse(r['version']))
780
772
  return results
773
+
774
+ @staticmethod
775
+ def half_orm_major_change(current_version: str, target_version: str) -> Optional[Tuple[int, int]]:
776
+ """
777
+ The half-orm major versions a migration moves between, if it does.
778
+
779
+ half-orm follows Semantic Versioning: only a major release requires
780
+ changes to the application's code, and its notes are on half-orm's
781
+ documentation, where a developer -- the one running this, on a
782
+ machine with a browser -- is pointed. half_orm_dev's major version
783
+ is half-orm's (its CLI loads nothing else), so a change of
784
+ half_orm_dev's major version is a change of half-orm's.
785
+
786
+ Args:
787
+ current_version: Current hop version
788
+ target_version: Target hop version
789
+
790
+ Returns:
791
+ ``(from_major, to_major)``, or None when the major version does
792
+ not move forward or a version cannot be read.
793
+ """
794
+ try:
795
+ current = version.parse(current_version).major
796
+ target = version.parse(target_version).major
797
+ except Exception:
798
+ return None
799
+ return (current, target) if target > current else None
@@ -18,10 +18,7 @@ from pathlib import Path
18
18
  import subprocess
19
19
  import sys
20
20
 
21
- if sys.version_info >= (3, 11):
22
- import tomllib as tomli
23
- else:
24
- import tomli
21
+ import tomllib as tomli
25
22
 
26
23
  try:
27
24
  import tomli_w
@@ -93,6 +93,37 @@ def _to_valid_identifier(name: str) -> str:
93
93
  return sanitized
94
94
 
95
95
 
96
+ def _safe_identifier(name: str) -> str:
97
+ """Return `name` if it can be written as a Python identifier, else a
98
+ sanitized form of it.
99
+
100
+ Schema, relation and constraint names are read from the database, and
101
+ PostgreSQL accepts anything in a quoted name -- a quote, a slash, a
102
+ newline. Written as they are into a class statement, an attribute or a
103
+ path, they are code or a directory of the database's choosing rather than
104
+ a name. A name that already is an identifier is returned untouched, so
105
+ what is generated for an ordinary schema does not change.
106
+ """
107
+ name = str(name)
108
+ if name.isidentifier() and not iskeyword(name):
109
+ return name
110
+ return _to_valid_identifier(name) or '_'
111
+
112
+
113
+ def _docstring_safe(text: str) -> str:
114
+ """Escape `text` so that it can only ever be the content of a
115
+ triple-quoted docstring.
116
+
117
+ Relation and column comments end up in the docstring of the generated
118
+ class. A comment holding three quotes used to close it, and the rest of
119
+ the comment became statements of the class body, run at import. The
120
+ backslash is escaped first: it would otherwise undo the escaping of the
121
+ quotes -- and was already turning a comment such as `C:\new` into a
122
+ line break.
123
+ """
124
+ return str(text).replace('\\', '\\\\').replace('"""', '\\"\\"\\"')
125
+
126
+
96
127
  def __get_test_directory_path(schema_name, table_name, base_dir):
97
128
  """
98
129
  Calculate the test directory path for a given schema and table.
@@ -153,7 +184,29 @@ def __get_test_file_path(schema_name, table_name, base_dir, package_name):
153
184
  def __get_full_class_name(schemaname, relationname):
154
185
  schemaname = ''.join([elt.capitalize() for elt in schemaname.split('.')])
155
186
  relationname = ''.join([elt.capitalize() for elt in relationname.split('_')])
156
- return f'{schemaname}{relationname}'
187
+ # Every generated class name is built on this one: DC_*, BC_*, *Dict.
188
+ return _safe_identifier(f'{schemaname}{relationname}')
189
+
190
+
191
+ def __get_dataclass_name(relation) -> str:
192
+ """Name of the DC_* class of `relation`.
193
+
194
+ Same formula as Relation._ho_dataclass_name(), through
195
+ __get_full_class_name so that the result is always an identifier.
196
+ """
197
+ return f'DC_{__get_full_class_name(*list(relation._t_fqrn)[1:])}'
198
+
199
+
200
+ def __attribute_line(indent: str, attr_name: str, statement: str) -> str:
201
+ """Return `statement`, or a comment in its place when `attr_name` cannot
202
+ be an attribute.
203
+
204
+ The name is shown through repr(): a name holding a line break must not
205
+ get to end the comment it is quoted in.
206
+ """
207
+ if attr_name.isidentifier() and not iskeyword(attr_name):
208
+ return f'{indent}{statement}'
209
+ return f'{indent}# FIX ME! {attr_name!r} is not a valid identifier in Python.'
157
210
 
158
211
 
159
212
  def __get_field_desc(field_name, field):
@@ -188,7 +241,7 @@ def __get_field_desc(field_name, field):
188
241
 
189
242
  def __gen_dataclass(relation, fkeys):
190
243
  rel = relation()
191
- dc_name = relation._ho_dataclass_name()
244
+ dc_name = __get_dataclass_name(relation)
192
245
  fields = []
193
246
  post_init = [' def __post_init__(self) -> None:']
194
247
  for field_name, field in rel._ho_fields.items():
@@ -209,7 +262,9 @@ def __gen_dataclass(relation, fkeys):
209
262
  fdc_name = f'DC_{__get_full_class_name(fk_fqrn[1], fk_fqrn[2])}'
210
263
  except Exception:
211
264
  fdc_name = dc_name # fallback: host class
212
- post_init.append(f" self.{attr_name} = {fdc_name}")
265
+ # A constraint may be named anything, and so may an alias.
266
+ post_init.append(__attribute_line(
267
+ ' ', attr_name, f"self.{attr_name} = {fdc_name}"))
213
268
  return '\n'.join([f'@dataclasses.dataclass\nclass {dc_name}(DC_Relation):'] + fields + post_init)
214
269
 
215
270
 
@@ -273,6 +328,13 @@ def __gen_json_typedicts(name_prefix: str, schema) -> tuple:
273
328
  fields = []
274
329
 
275
330
  for key, val in schema.items():
331
+ # The keys come from a column comment. One that is not an identifier
332
+ # cannot be a TypedDict field, and written as it is would be a
333
+ # statement of the class body.
334
+ if not isinstance(key, str) or not key.isidentifier() or iskeyword(key):
335
+ fields.append(
336
+ f" # FIX ME! {key!r} is not a valid identifier in Python.")
337
+ continue
276
338
  if isinstance(val, str):
277
339
  type_str = __json_scalar_type(val)
278
340
  fields.append(f" {key}: Optional[{type_str}]")
@@ -297,7 +359,10 @@ def __gen_json_typedicts(name_prefix: str, schema) -> tuple:
297
359
  fields.append(f" {key}: Optional[Any]")
298
360
 
299
361
  class_name = f'{name_prefix}Dict'
300
- body = '\n'.join(fields) if fields else ' pass'
362
+ if not any(not line.lstrip().startswith('#') for line in fields):
363
+ # Nothing but comments, or nothing at all: a class needs a statement.
364
+ fields.append(' pass')
365
+ body = '\n'.join(fields)
301
366
  classes.append(f'class {class_name}(TypedDict, total=False):\n{body}')
302
367
  return classes, class_name
303
368
 
@@ -449,9 +514,11 @@ def __apply_fkey_aliases_to_doc(documentation: str, rel, existing_fkeys: dict) -
449
514
  lines.append(" }")
450
515
  new_block = '\n'.join(lines)
451
516
 
517
+ # A function, not the string: in a replacement string a backslash is an
518
+ # escape, and constraint names are not ours to vouch for.
452
519
  return re.sub(
453
520
  r' Fkeys = \{[^}]*\}',
454
- new_block,
521
+ lambda _match: new_block,
455
522
  documentation,
456
523
  flags=re.DOTALL,
457
524
  )
@@ -524,7 +591,10 @@ def __update_this_module(
524
591
  arg_names = ", ".join(arg_names)
525
592
 
526
593
  path[0] = package_dir
527
- path[1] = path[1].replace('.', os.sep)
594
+ # One directory per dotted part of the schema name, each of them a name
595
+ # and nothing else: left as it was, a schema called `/tmp/x` sent the
596
+ # module there, os.path.join dropping everything before an absolute part.
597
+ path[1] = os.sep.join(_safe_identifier(part) for part in path[1].split('.'))
528
598
 
529
599
  path = [_to_valid_identifier(elt).lower() if i >= 2 else elt for i, elt in enumerate(path)]
530
600
  class_name = camel_case(path[-1])
@@ -552,11 +622,13 @@ def __update_this_module(
552
622
  file_.write(
553
623
  module_template.format(
554
624
  hop_release = hop_version(),
555
- module=f"{package_name}.{fqtn}",
625
+ # Both land inside a docstring, and both are database text:
626
+ # the relation's comment, and its qualified name.
627
+ module=_docstring_safe(f"{package_name}.{fqtn}"),
556
628
  package_name=package_name,
557
- documentation=documentation,
629
+ documentation=_docstring_safe(documentation),
558
630
  class_name=class_name,
559
- dc_name=rel._ho_dataclass_name(),
631
+ dc_name=__get_dataclass_name(rel),
560
632
  dict_class_name=dict_class_name,
561
633
  bc_name=bc_name,
562
634
  fqtn=fqtn,
@@ -703,6 +775,51 @@ def _bc_override(name: str, return_annotation: str, override_ignore: bool) -> st
703
775
  ])
704
776
 
705
777
 
778
+ # Emitted near the top of every generated ho_baseclasses.py.
779
+ #
780
+ # ho_baseclasses.py builds one base class per relation *at import time*, from
781
+ # the schema as it stood at the last generation — and the database does not
782
+ # always match. `patch apply` rebuilds it from the production baseline and
783
+ # replays the staged patches one by one, so a table created by a later patch
784
+ # is still missing while an earlier patch's Python script imports the package.
785
+ # Resolving that base eagerly aborted the whole apply with UnknownRelation.
786
+ #
787
+ # A missing relation now degrades to a placeholder that raises only if
788
+ # something actually instantiates it, and every occurrence is logged, so the
789
+ # drift is never silent.
790
+ BC_BASE_HELPER = '''def _bc_base(fqrn: str):
791
+ """Base class for *fqrn*, or a placeholder when it is not in the database.
792
+
793
+ The generated code describes the schema as of the last generation; the
794
+ database it runs against may be older (mid-migration, or rebuilt from the
795
+ production baseline by `half_orm dev patch apply`).
796
+ """
797
+ try:
798
+ return MODEL.get_relation_class(fqrn, fields_aliases=None)
799
+ except UnknownRelation as exc:
800
+ # Bind it under a name that survives the except block, so the
801
+ # placeholder below can re-raise it from its closure.
802
+ error = exc
803
+ sys.stderr.write(
804
+ f"half-orm: relation '{fqrn}' is not in the database - generated code "
805
+ f"is ahead of the schema. Using a placeholder base class.\\n")
806
+
807
+ class _MissingRelation:
808
+ """Stands in for a relation absent from the database.
809
+
810
+ Importing the module keeps working; using the class does not.
811
+ """
812
+ _ho_missing_fqrn = fqrn
813
+
814
+ def __init__(self, *args, **kwargs):
815
+ # Re-raise half_orm's own error: it carries the message
816
+ # built from the (dbname, schema, relation) triple.
817
+ raise error
818
+
819
+ return _MissingRelation
820
+ '''
821
+
822
+
706
823
  def __gen_baseclass(relation, fkeys) -> str:
707
824
  """Generate a BC_* base class string with TypedDict-typed method overrides."""
708
825
  rel = relation()
@@ -710,13 +827,14 @@ def __gen_baseclass(relation, fkeys) -> str:
710
827
  full_name = __get_full_class_name(*t_qrn)
711
828
  fqtn = '.'.join(t_qrn)
712
829
  bc_name = f'BC_{full_name}'
713
- dc_name = rel._ho_dataclass_name()
830
+ dc_name = __get_dataclass_name(rel)
714
831
  d = f'{full_name}Dict'
715
832
  HO_BASECLASSES_DICT_NAMES.add(d)
716
833
 
717
834
  header = [
718
835
  f"class {bc_name}(",
719
- f" MODEL.get_relation_class('{fqtn}', fields_aliases=None), # type: ignore[misc]",
836
+ # repr(): a quote in a schema or relation name closed the literal.
837
+ f" _bc_base({fqtn!r}), # type: ignore[misc]",
720
838
  f" {dc_name}",
721
839
  f"):",
722
840
  ]
@@ -751,7 +869,9 @@ def __gen_baseclasses(package_dir, package_name):
751
869
  typing_names = sorted(dc_typing | {'Iterator', 'List', 'Optional', 'TYPE_CHECKING'})
752
870
  file_.write(f"from typing import {', '.join(typing_names)}\n")
753
871
  file_.write("import dataclasses\n")
872
+ file_.write("import sys\n")
754
873
  file_.write("from half_orm.field import Field # type: ignore[import-not-found]\n")
874
+ file_.write("from half_orm.model_errors import UnknownRelation # type: ignore[import-not-found]\n")
755
875
  for mod in sorted(HO_DATACLASSES_IMPORTS):
756
876
  file_.write(f"import {mod}\n")
757
877
  file_.write(f"from {package_name} import MODEL # type: ignore[import-not-found]\n")
@@ -762,6 +882,8 @@ def __gen_baseclasses(package_dir, package_name):
762
882
  file_.write(f" {name},\n")
763
883
  file_.write(" )\n")
764
884
  file_.write("\n\n")
885
+ file_.write(BC_BASE_HELPER)
886
+ file_.write("\n")
765
887
  file_.write(dc_relation_str)
766
888
  for dc in HO_DATACLASSES:
767
889
  file_.write(f"\n\n{dc}\n")
@@ -7,12 +7,8 @@ during development (candidate and staged status).
7
7
 
8
8
  from pathlib import Path
9
9
  from typing import List, Optional, Dict
10
- import sys
11
10
 
12
- if sys.version_info >= (3, 11):
13
- import tomllib as tomli
14
- else:
15
- import tomli
11
+ import tomllib as tomli
16
12
 
17
13
  try:
18
14
  import tomli_w