half-orm 1.2.1__tar.gz → 2.0.0__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 (44) hide show
  1. {half_orm-1.2.1/half_orm.egg-info → half_orm-2.0.0}/PKG-INFO +1 -38
  2. {half_orm-1.2.1 → half_orm-2.0.0}/README.md +0 -37
  3. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm/__main__.py +5 -2
  4. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm/cli.py +25 -12
  5. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm/fkey.py +8 -2
  6. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm/migrations/BREAKING_CHANGES-1.0.0.md +29 -0
  7. half_orm-2.0.0/half_orm/migrations/BREAKING_CHANGES-2.0.0.md +123 -0
  8. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm/model.py +64 -7
  9. half_orm-2.0.0/half_orm/model_errors.py +91 -0
  10. half_orm-2.0.0/half_orm/naming.py +179 -0
  11. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm/pg_meta.py +229 -37
  12. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm/relation.py +155 -48
  13. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm/relation_factory.py +6 -3
  14. half_orm-2.0.0/half_orm/version.txt +1 -0
  15. {half_orm-1.2.1 → half_orm-2.0.0/half_orm.egg-info}/PKG-INFO +1 -38
  16. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm.egg-info/SOURCES.txt +2 -0
  17. {half_orm-1.2.1 → half_orm-2.0.0}/pyproject.toml +1 -1
  18. {half_orm-1.2.1 → half_orm-2.0.0}/test/test_cli.py +20 -16
  19. half_orm-1.2.1/half_orm/model_errors.py +0 -31
  20. half_orm-1.2.1/half_orm/version.txt +0 -1
  21. {half_orm-1.2.1 → half_orm-2.0.0}/AUTHORS +0 -0
  22. {half_orm-1.2.1 → half_orm-2.0.0}/LICENSE +0 -0
  23. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm/__init__.py +0 -0
  24. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm/_predicate.py +0 -0
  25. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm/cli_utils.py +0 -0
  26. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm/field.py +0 -0
  27. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm/field_errors.py +0 -0
  28. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm/hotest.py +0 -0
  29. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm/migrations/__init__.py +0 -0
  30. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm/null.py +0 -0
  31. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm/py.typed +0 -0
  32. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm/relation_errors.py +0 -0
  33. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm/sql_adapter.py +0 -0
  34. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm/sql_ast.py +0 -0
  35. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm/testing.py +0 -0
  36. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm/transaction.py +0 -0
  37. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm/utils.py +0 -0
  38. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm.egg-info/dependency_links.txt +0 -0
  39. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm.egg-info/entry_points.txt +0 -0
  40. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm.egg-info/requires.txt +0 -0
  41. {half_orm-1.2.1 → half_orm-2.0.0}/half_orm.egg-info/top_level.txt +0 -0
  42. {half_orm-1.2.1 → half_orm-2.0.0}/setup.cfg +0 -0
  43. {half_orm-1.2.1 → half_orm-2.0.0}/test/test_main.py +0 -0
  44. {half_orm-1.2.1 → half_orm-2.0.0}/test/test_sql_ast.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: half_orm
3
- Version: 1.2.1
3
+ Version: 2.0.0
4
4
  Summary: A database-first ORM for PostgreSQL
5
5
  Author-email: Joël Maïzi <joel.maizi@collorg.org>
6
6
  License-Expression: GPL-3.0-or-later
@@ -37,43 +37,6 @@ Dynamic: license-file
37
37
  [![Coverage](https://coveralls.io/repos/github/half-orm/half-orm/badge.svg?branch=main)](https://coveralls.io/github/half-orm/half-orm?branch=main)
38
38
  [![Downloads](https://static.pepy.tech/badge/half_orm)](https://pepy.tech/project/half_orm)
39
39
 
40
- > ## ⚠️ BREAKING CHANGES in v1.0.0
41
- >
42
- > **Legacy unprefixed API removed** — the pre-`ho_` method names, deprecated
43
- > since 0.x, no longer exist: `select`, `insert`, `update`, `delete`, `get`,
44
- > `count`, `is_empty`, `unaccent`, `order_by`, `limit`, `offset`, `_mogrify`.
45
- > Use their `ho_`-prefixed equivalents (`ho_select`, `ho_insert`, `ho_update`,
46
- > `ho_delete`, `ho_get`, `ho_count`, `ho_is_empty`, `ho_unaccent`, `ho_mogrify`,
47
- > passing `order_by`/`limit`/`offset` as `ho_select()` keyword arguments).
48
- >
49
- > **`DC_Relation`** removed from `half_orm.relation` — this IDE type-checking
50
- > stub is now generated per-project by `half-orm-dev` instead of shipped in
51
- > the library.
52
- >
53
- > **`ho_get()`** is now public and returns a `dict` directly. It raises
54
- > `NotFoundError` (0 rows) or `MultipleRowsError` (> 1 row) instead of
55
- > counting first.
56
- >
57
- > **Deprecated query-builder setters removed** — `ho_limit`, `ho_offset`,
58
- > `ho_order_by`, `ho_distinct` no longer exist as setters. Pass these as
59
- > keyword arguments to `ho_select()`:
60
- > ```python
61
- > # Before (0.x)
62
- > rel.ho_limit = 10
63
- > rel.ho_order_by = 'name'
64
- > list(rel)
65
- >
66
- > # After (1.0)
67
- > list(rel.ho_select(limit=10, order_by='name'))
68
- > ```
69
- >
70
- > **`FKEYS_PROPERTIES` / `FKEYS`** class attributes removed — use `Fkeys` only.
71
- >
72
- > **`ho_cast()`** now raises `CastError` if the target is not in the
73
- > PostgreSQL inheritance hierarchy of the relation.
74
- >
75
- > See [CHANGELOG.md](CHANGELOG.md) for the full list of changes.
76
-
77
40
  halfORM is a database-first ORM for PostgreSQL. Your schema lives in the
78
41
  database; halfORM introspects it at runtime and gives you Python objects to work
79
42
  with your data. No migrations, no code generation.
@@ -8,43 +8,6 @@
8
8
  [![Coverage](https://coveralls.io/repos/github/half-orm/half-orm/badge.svg?branch=main)](https://coveralls.io/github/half-orm/half-orm?branch=main)
9
9
  [![Downloads](https://static.pepy.tech/badge/half_orm)](https://pepy.tech/project/half_orm)
10
10
 
11
- > ## ⚠️ BREAKING CHANGES in v1.0.0
12
- >
13
- > **Legacy unprefixed API removed** — the pre-`ho_` method names, deprecated
14
- > since 0.x, no longer exist: `select`, `insert`, `update`, `delete`, `get`,
15
- > `count`, `is_empty`, `unaccent`, `order_by`, `limit`, `offset`, `_mogrify`.
16
- > Use their `ho_`-prefixed equivalents (`ho_select`, `ho_insert`, `ho_update`,
17
- > `ho_delete`, `ho_get`, `ho_count`, `ho_is_empty`, `ho_unaccent`, `ho_mogrify`,
18
- > passing `order_by`/`limit`/`offset` as `ho_select()` keyword arguments).
19
- >
20
- > **`DC_Relation`** removed from `half_orm.relation` — this IDE type-checking
21
- > stub is now generated per-project by `half-orm-dev` instead of shipped in
22
- > the library.
23
- >
24
- > **`ho_get()`** is now public and returns a `dict` directly. It raises
25
- > `NotFoundError` (0 rows) or `MultipleRowsError` (> 1 row) instead of
26
- > counting first.
27
- >
28
- > **Deprecated query-builder setters removed** — `ho_limit`, `ho_offset`,
29
- > `ho_order_by`, `ho_distinct` no longer exist as setters. Pass these as
30
- > keyword arguments to `ho_select()`:
31
- > ```python
32
- > # Before (0.x)
33
- > rel.ho_limit = 10
34
- > rel.ho_order_by = 'name'
35
- > list(rel)
36
- >
37
- > # After (1.0)
38
- > list(rel.ho_select(limit=10, order_by='name'))
39
- > ```
40
- >
41
- > **`FKEYS_PROPERTIES` / `FKEYS`** class attributes removed — use `Fkeys` only.
42
- >
43
- > **`ho_cast()`** now raises `CastError` if the target is not in the
44
- > PostgreSQL inheritance hierarchy of the relation.
45
- >
46
- > See [CHANGELOG.md](CHANGELOG.md) for the full list of changes.
47
-
48
11
  halfORM is a database-first ORM for PostgreSQL. Your schema lives in the
49
12
  database; halfORM introspects it at runtime and gives you Python objects to work
50
13
  with your data. No migrations, no code generation.
@@ -40,7 +40,8 @@ def check_databases_access():
40
40
  try:
41
41
  model = Model(cnx_file)
42
42
  print(f"✅ {cnx_file}")
43
- except (psycopg.Error, model_errors.MalformedConfigFile, ValueError) as exc:
43
+ except (psycopg.Error, model_errors.MalformedConfigFile,
44
+ model_errors.NamingError, ValueError) as exc:
44
45
  sys.stderr.write(f'❌ {cnx_file}: {exc}\n')
45
46
  else:
46
47
  print("💡 No database configuration files found.")
@@ -81,7 +82,8 @@ def main():
81
82
  try:
82
83
  model = Model(database)
83
84
  print(model)
84
- except (psycopg.Error, model_errors.MalformedConfigFile, ValueError) as exc:
85
+ except (psycopg.Error, model_errors.MalformedConfigFile,
86
+ model_errors.NamingError, ValueError) as exc:
85
87
  sys.stderr.write(f"❌ Error connecting to database '{database}': {exc}\n")
86
88
  sys.stderr.write(f"💡 Use 'python -m half_orm --help' for usage information\n")
87
89
  sys.exit(1)
@@ -103,6 +105,7 @@ def main():
103
105
  relation_class = model.get_relation_class(relation)
104
106
  print(relation_class())
105
107
  except (psycopg.Error, model_errors.MalformedConfigFile, ValueError,
108
+ model_errors.NamingError,
106
109
  model_errors.UnknownRelation, model_errors.MissingSchemaInName) as exc:
107
110
  sys.stderr.write(f"❌ Error accessing relation '{relation}' in database '{database}': {exc}\n")
108
111
  sys.stderr.write(f"💡 Use 'python -m half_orm --help' for usage information\n")
@@ -247,26 +247,39 @@ def save_cli_config(config):
247
247
  except OSError:
248
248
  return False
249
249
 
250
+ # The start of a version string: 2.1 in '2.1.0', '2.1.0rc1', '2.1.0-a1'.
251
+ _VERSION_RE = re.compile(r'^(\d+)\.(\d+)')
252
+
253
+
254
+ def _major(version):
255
+ "The major version number, or None when `version` is not a version."
256
+ match = _VERSION_RE.match(str(version))
257
+ return int(match.group(1)) if match else None
258
+
259
+
250
260
  def check_version_compatibility(extension_version: str, core_version: str) -> bool:
251
- """Check if extension version is compatible with core version (major.minor must match)."""
252
- try:
253
- ext_parts = extension_version.split('.')
254
- core_parts = core_version.split('.')
261
+ """Whether an extension can run on this version of the core.
255
262
 
256
- if len(ext_parts) < 2 or len(core_parts) < 2:
257
- return False
263
+ halfORM follows Semantic Versioning from 2.0.0: within a major version a
264
+ release adds and fixes, and breaks nothing. An extension built for 2.1
265
+ therefore runs on 2.4, and only the major versions have to match.
258
266
 
259
- # Major.minor must match exactly, patch can differ
260
- return ext_parts[0] == core_parts[0] and ext_parts[1] == core_parts[1]
261
- except (ValueError, IndexError):
262
- return False
267
+ A finer bound is the extension's own business, stated where pip enforces
268
+ it: one that needs something added in 2.3 declares ``half_orm>=2.3,<3``.
269
+
270
+ Until 2.0.0 a minor release could break the API, and major.minor had to
271
+ match. That rule ships with the 1.x cores, which are the only ones it
272
+ applies to.
273
+ """
274
+ ext_major = _major(extension_version)
275
+ return ext_major is not None and ext_major == _major(core_version)
263
276
 
264
277
  def warn_version_incompatibility(package_name: str, ext_version: str, core_version: str):
265
278
  """Warn about version incompatibility."""
266
279
  click.echo(f"❌ ERROR: '{package_name}' v{ext_version} is incompatible", err=True)
267
280
  click.echo(f" halfORM core: v{core_version}", err=True)
268
- click.echo(f" Extension must have same major.minor version", err=True)
269
- click.echo(f" Expected: {'.'.join(core_version.split('.')[:2])}.x", err=True)
281
+ click.echo(" An extension must be built for the core's major version", err=True)
282
+ click.echo(f" Expected: {_major(core_version)}.x", err=True)
270
283
  sys.exit(1)
271
284
 
272
285
  def is_official_extension(package_name):
@@ -127,7 +127,10 @@ class FKey:
127
127
  return f_relation
128
128
 
129
129
  def values(self):
130
- return [list(elt.values()) for elt in self.__to_relation.ho_select(*self.__fk_names)]
130
+ # fk_names are database names; ho_select takes Python ones.
131
+ to_relation = self.__to_relation
132
+ return [list(elt.values())
133
+ for elt in to_relation.ho_select(*to_relation._ho_py_names(self.__fk_names))]
131
134
 
132
135
  def set(self, ho_to_rel=None, **kwargs):
133
136
  """Bind this foreign key to a relation, adding a JOIN condition.
@@ -236,7 +239,10 @@ class FKey:
236
239
 
237
240
  #@utils.trace
238
241
  def _fkey_prep_select(self):
239
- return (self.__fields, self.__fk_to._ho_prep_select(*self.fk_names)) if self.__is_set else None
242
+ if not self.__is_set:
243
+ return None
244
+ return (self.__fields,
245
+ self.__fk_to._ho_prep_select(*self.__fk_to._ho_py_names(self.fk_names)))
240
246
 
241
247
  @property
242
248
  def name(self):
@@ -1,5 +1,34 @@
1
1
  # half-orm 1.0.0 — Breaking Changes
2
2
 
3
+ ## Legacy unprefixed API removed
4
+
5
+ The method names without the `ho_` prefix, deprecated since 0.x, no longer
6
+ exist: `select`, `insert`, `update`, `delete`, `get`, `count`, `is_empty`,
7
+ `unaccent`, `order_by`, `limit`, `offset`, `_mogrify`.
8
+
9
+ **Before:**
10
+ ```python
11
+ for row in Author(last_name='Martin').select('id'):
12
+ ...
13
+ Author(id=1).update(email='a@example.com')
14
+ ```
15
+
16
+ **After:**
17
+ ```python
18
+ for row in Author(last_name='Martin').ho_select('id'):
19
+ ...
20
+ Author(id=1).ho_update(email='a@example.com')
21
+ ```
22
+
23
+ `order_by`, `limit` and `offset` are keyword arguments of `ho_select()`, see
24
+ below.
25
+
26
+ ## `DC_Relation` removed from `half_orm.relation`
27
+
28
+ This IDE type-checking stub is no longer shipped with the library. It is
29
+ generated for each project by `half-orm-dev`, in the package's
30
+ `ho_baseclasses.py`.
31
+
3
32
  ## `ho_get()` returns a `dict` and raises on 0 or >1 rows
4
33
 
5
34
  `ho_get()` now returns a plain `dict` directly (no longer a Relation
@@ -0,0 +1,123 @@
1
+ # half-orm 2.0.0 — Breaking Changes
2
+
3
+ ## A Model refuses a database whose derived names collide
4
+
5
+ `Model(...)` and `reconnect(reload=True)` now raise `NamingError` when two
6
+ things end up under one Python name. Before, one of them was silently
7
+ dropped, so an application may have been running on such a database without
8
+ knowing it. The error lists every problem.
9
+
10
+ The usual case is two foreign keys that spell the same reverse name:
11
+
12
+ ```sql
13
+ create table post (id int primary key, author_id int references author);
14
+ create table post_author (pk int primary key, id int references author);
15
+ -- both: _reverse_fkey_<db>_public_post_author_id
16
+ ```
17
+
18
+ Also refused: a column named like a foreign-key attribute (`fk_owner` next
19
+ to a constraint `owner`), a column named like something `Relation` uses
20
+ (`ho_*`, `_ho_*`, `Fkeys`), a column that cannot be an attribute and is
21
+ exposed as `column<N>` next to a real `column<N>`, and two relations that
22
+ read the same without quotes (`"a.b".c` and `a."b.c"`).
23
+
24
+ **To settle one**, give one side a name of its own.
25
+
26
+ In the database:
27
+ ```sql
28
+ COMMENT ON CONSTRAINT post_author_id_fkey ON post IS '@ho_reverse_name posts';
29
+ COMMENT ON COLUMN orders.fk_owner IS '@ho_name owner_ref';
30
+ ```
31
+
32
+ Or on the Model, when the database cannot be written to:
33
+ ```python
34
+ Model('legacy',
35
+ reverse_names={('public.post', 'post_author_id_fkey'): 'posts'},
36
+ field_names={'public.orders': {'fk_owner': 'owner_ref'}},
37
+ ignore=['old.*']) # or leave relations out altogether
38
+ ```
39
+
40
+ A reverse key named this way is `_reverse_fkey_posts` in `Fkeys` and
41
+ `rfk_posts` on the relation. Renaming the constraint, the column or the
42
+ table settles it too.
43
+
44
+ **To find out before upgrading**, open the Model with 2.0.0 in a shell:
45
+ `python -m half_orm <config>` prints the list.
46
+
47
+ ## Rows are keyed by Python names
48
+
49
+ This only concerns relations with a column known in Python under another
50
+ name than its own: one whose name is not a valid identifier (`"a = 1"`,
51
+ exposed as `column<N>`), or one renamed with `fields_aliases`, `@ho_name` or
52
+ `Model(field_names=...)`.
53
+
54
+ A row returned whole — `ho_select()`, `ho_get()`, `ho_insert()`, `RETURNING
55
+ *`, iterating a relation — was keyed by the SQL name. It is now keyed by the
56
+ Python name, as a row returned by `ho_select('column5')` already was.
57
+
58
+ **Before:**
59
+ ```python
60
+ row = Comment(id=1).ho_get()
61
+ row['a = 1']
62
+ ```
63
+
64
+ **After:**
65
+ ```python
66
+ row = Comment(id=1).ho_get()
67
+ row['column5']
68
+ ```
69
+
70
+ In `order_by`, `ho_copy()` (dict keys, CSV header, `columns=`) and the field
71
+ lists of `json_agg`, a column is named by its Python name. These did not work
72
+ with such columns before; if you worked around it with raw SQL, you can drop
73
+ the workaround.
74
+
75
+ **To find out whether you are affected**, look for the warning halfORM prints
76
+ when it exposes a column under another name (`"a = 1" is not a valid
77
+ identifier in Python`), and for `fields_aliases` in your code.
78
+
79
+ ## A relation is no longer a mapping
80
+
81
+ `Relation.keys()`, `Relation.items()` and `rel['col']` are removed, and with
82
+ them `Other(**rel)`. `dict(rel)` no longer means anything either — and does
83
+ not necessarily fail: a relation is still iterable, over its rows, so the
84
+ call now runs the query and tries to build a dict out of them.
85
+
86
+ They returned the *predicate* — the constraint set on each column, `None`
87
+ for the columns left unconstrained — not a row. Rows are the `dict`s that
88
+ `ho_get()` and `ho_select()` return, and those are unchanged.
89
+
90
+ **Before:**
91
+ ```python
92
+ person = Person(last_name='Lagaffe')
93
+
94
+ person['last_name'] # 'Lagaffe'
95
+ list(person.keys()) # every column name
96
+ dict(person) # {'id': None, 'first_name': None, 'last_name': 'Lagaffe', ...}
97
+ Other(**person)
98
+ ```
99
+
100
+ **After:**
101
+ ```python
102
+ person = Person(last_name='Lagaffe')
103
+
104
+ person.last_name.value # 'Lagaffe'
105
+ list(person._ho_fields) # every column name
106
+ person.ho_dict() # {'last_name': 'Lagaffe'} -- only what is set
107
+ Other(**person.ho_dict())
108
+ ```
109
+
110
+ `ho_dict()` leaves out the columns that carry no constraint, where
111
+ `dict(rel)` listed them with `None`. Passed back to a constructor the two
112
+ are equivalent, `None` meaning "no constraint" there.
113
+
114
+ The idiom most likely to be affected rebuilt a relation from a row and then
115
+ read it like one:
116
+
117
+ ```python
118
+ aa = Person(**Person(last_name='aa').ho_get())
119
+ aa['id'] # before
120
+ aa.id.value # after -- or keep the row: Person(...).ho_get()['id']
121
+ ```
122
+
123
+ A column named `keys` or `items` is now an ordinary column.
@@ -33,6 +33,7 @@ from psycopg import ClientCursor, AsyncConnection
33
33
  from psycopg.rows import dict_row
34
34
 
35
35
  from half_orm import model_errors
36
+ from half_orm import naming
36
37
  from half_orm import pg_meta
37
38
  from half_orm import utils
38
39
  from half_orm.relation_factory import factory, register_class
@@ -280,6 +281,23 @@ class Model:
280
281
  :meth:`get_relation_class` instance, never imported from a
281
282
  generated package module.
282
283
 
284
+ field_names (dict | None): Python names for columns,
285
+ ``{'schema.relation': {'column': 'python_name'}}``.
286
+ reverse_names (dict | None): names for reverse foreign keys,
287
+ ``{('schema.relation', 'constraint'): 'name'}`` — the relation
288
+ and constraint are those of the *referencing* side; the key is
289
+ then exposed as ``rfk_<name>`` on the referenced relation.
290
+ ignore (Iterable[str] | str | None): relations to leave out of the
291
+ model, as ``schema.relation`` patterns (``'old.*'``); a
292
+ comma-separated string is accepted too. An ignored relation is
293
+ not loaded, and no foreign key leads to it.
294
+
295
+ The last three settle the naming problems reported by
296
+ :class:`~half_orm.model_errors.NamingError`, for a database in which the
297
+ names cannot be declared with a comment — see :mod:`half_orm.naming`.
298
+ They are part of what identifies a Model: two Models that do not declare
299
+ the same names share nothing.
300
+
283
301
  If no file named ``config_file`` is found in ``HALFORM_CONF_DIR``, it is
284
302
  used directly as the database name and a peer-authentication connection
285
303
  is attempted (no user/password/host/port) — development use only.
@@ -287,6 +305,11 @@ class Model:
287
305
  Raises:
288
306
  MalformedConfigFile: if ``name`` is missing from the file.
289
307
  psycopg.OperationalError: if the database connection fails.
308
+ NamingError: if two names derived from the catalog collide — two
309
+ reverse foreign keys spelled alike, a column named like a foreign
310
+ key attribute or like something Relation uses. Raised here and
311
+ by ``reconnect(reload=True)``, listing every problem.
312
+ ValueError: if a naming argument does not have the documented shape.
290
313
  """
291
314
  # Models and relation classes are shared between the Model objects that
292
315
  # reach the same database *as the same role*: (host, port, dbname, user),
@@ -298,8 +321,10 @@ class Model:
298
321
  __registries = {} # identity -> {dbname: {fqrn: relation class}}
299
322
  __first_seen = {} # dbname -> Model, for the _deja_vu() lookup by name
300
323
  __sql_trace = False
301
- def __init__(self, config_file: None, scope: str=None, with_half_orm_meta=False):
324
+ def __init__(self, config_file: None, scope: str=None, with_half_orm_meta=False,
325
+ field_names=None, reverse_names=None, ignore=None):
302
326
  self.__connection_params = {}
327
+ self.__naming = naming.normalize(field_names, reverse_names, ignore)
303
328
  self._production_mode = True
304
329
  self.__load_config(config_file)
305
330
  self._scope = scope and scope.split('.')[0]
@@ -334,7 +359,10 @@ class Model:
334
359
  leaves stops designating it.
335
360
  """
336
361
  info = conn.info
337
- identity = (info.host, info.port, info.dbname, info.user)
362
+ # The naming declarations too: they decide what a relation's
363
+ # attributes are called, so classes built under different ones are
364
+ # not the same classes.
365
+ identity = (info.host, info.port, info.dbname, info.user, self.__naming)
338
366
  previous = self.__identity
339
367
  if previous is not None and previous != identity \
340
368
  and Model.__deja_vu.get(previous) is self:
@@ -463,7 +491,14 @@ class Model:
463
491
  conn.adapters.register_dumper(Null, NullDumper)
464
492
  conn.adapters.register_dumper(Field, FieldDumper)
465
493
  conn.adapters.register_dumper(dict, JsonbDumper)
466
- self.__pg_meta = pg_meta.PgMeta(conn, self.__with_half_orm_meta, reload)
494
+ try:
495
+ self.__pg_meta = pg_meta.PgMeta(
496
+ conn, self.__with_half_orm_meta, reload, self.__naming)
497
+ except model_errors.NamingError:
498
+ # Refused before anything was recorded on the Model: the
499
+ # connection it was about to adopt must not be left open.
500
+ conn.close()
501
+ raise
467
502
  self.__set_identity(conn)
468
503
  if reload:
469
504
  self.__schema_generation += 1
@@ -604,6 +639,26 @@ class Model:
604
639
  ```
605
640
 
606
641
  """
642
+ schema, table = self._split_qtn(relation_name)
643
+ return factory({'fqrn': (self.__dbname, schema, table), 'model': Model.__deja_vu[self.__identity], 'fields_aliases':fields_aliases})
644
+
645
+
646
+ def _split_qtn(self, relation_name):
647
+ """Split a qualified relation name into ``(schema, relation)``.
648
+
649
+ The one place where a `schema.relation` string is taken apart. A dot
650
+ may belong to the schema or to the relation, so the string is first
651
+ looked up as it stands among the relations of the database; only a
652
+ name the catalog does not know is parsed, quotes included, and then
653
+ split on its last dot -- which is right for every relation whose own
654
+ name holds none.
655
+
656
+ Raises:
657
+ MissingSchemaInName: if `relation_name` has no schema part.
658
+ """
659
+ resolved = self.__pg_meta.resolve(self.__dbname, relation_name)
660
+ if resolved is not None:
661
+ return resolved
607
662
  # Not `relation_name.replace('"', '')`: deleting the quotes made
608
663
  # `"a""b"."t"` and `ab.t` the same name, so a relation whose name
609
664
  # holds one could not be reached -- or reached a different relation
@@ -615,9 +670,7 @@ class Model:
615
670
  parts = relation_name.rsplit('.', 1)
616
671
  if len(parts) < 2:
617
672
  raise model_errors.MissingSchemaInName(relation_name)
618
- schema, table = '.'.join(parts[:-1]), parts[-1]
619
- return factory({'fqrn': (self.__dbname, schema, table), 'model': Model.__deja_vu[self.__identity], 'fields_aliases':fields_aliases})
620
-
673
+ return '.'.join(parts[:-1]), parts[-1]
621
674
 
622
675
  @staticmethod
623
676
  def _deja_vu(dbname):
@@ -1112,7 +1165,11 @@ class Model:
1112
1165
  Returns:
1113
1166
  bool
1114
1167
  """
1115
- return self.__pg_meta.has_relation(self.__dbname, *qtn.rsplit('.', 1))
1168
+ try:
1169
+ schema, relation = self._split_qtn(qtn)
1170
+ except model_errors.MissingSchemaInName:
1171
+ return False
1172
+ return self.__pg_meta.has_relation(self.__dbname, schema, relation)
1116
1173
 
1117
1174
  def _import_class(self, qtn, scope=None):
1118
1175
  """Return the class for `qtn` from the scope package, if there is one.
@@ -0,0 +1,91 @@
1
+ """This module provides the errors for the model module."""
2
+
3
+ class MissingConfigFile(Exception):
4
+ """The config file has not been found."""
5
+ def __init__(self, filename):
6
+ self.filename = filename
7
+ Exception.__init__(self, f'Missing config file: {filename}')
8
+
9
+ class MalformedConfigFile(Exception):
10
+ """The config file is malformed.
11
+
12
+ The missing parameters are indicated in the error message.
13
+ """
14
+ def __init__(self, filename, msg, missing_param):
15
+ self.filename = filename
16
+ Exception.__init__(
17
+ self,
18
+ f"Malformed config file: {filename}\n{msg}: {missing_param}")
19
+
20
+ class UnknownRelation(Exception):
21
+ """The FQRN doesn't match any relation in the database."""
22
+ def __init__(self, sfqrn):
23
+ self.dbname = sfqrn[0]
24
+ self.schema = sfqrn[1]
25
+ self.relation = sfqrn[2]
26
+ Exception.__init__(self, f"'{sfqrn[1]}.{sfqrn[2]}' does not exist in the database {sfqrn[0]}.")
27
+
28
+ class MissingSchemaInName(Exception):
29
+ """The QRN should contain a schema name."""
30
+ def __init__(self, qrn):
31
+ Exception.__init__(self, f"do you mean 'public.{qrn}'?")
32
+
33
+
34
+ class NamingProblem:
35
+ """One thing that keeps the names of a database from being used as they are.
36
+
37
+ Attributes:
38
+ kind (str): ``'reverse_fkey'`` (two foreign keys filed under one
39
+ name), ``'attribute'`` (two attributes of a relation with one
40
+ name), ``'reserved'`` (a column named like something Relation
41
+ uses), ``'qualified_name'`` (two relations spelled alike without
42
+ quotes) or ``'declaration'`` (a declared name that cannot be
43
+ used).
44
+ name (str): the name in dispute.
45
+ relation (str | None): ``schema.relation`` it is in dispute on.
46
+ members (list[str]): what is competing for it.
47
+ hint (str): what to do about it.
48
+ """
49
+ def __init__(self, kind, name, relation, members, hint):
50
+ self.kind = kind
51
+ self.name = name
52
+ self.relation = relation
53
+ self.members = list(members)
54
+ self.hint = hint
55
+
56
+ def __str__(self):
57
+ where = f' on {self.relation}' if self.relation else ''
58
+ lines = [f'- [{self.kind}] {self.name!r}{where}']
59
+ lines += [f' {member}' for member in self.members]
60
+ lines.append(f' -> {self.hint}')
61
+ return '\n'.join(lines)
62
+
63
+ def __repr__(self):
64
+ return f'NamingProblem({self.kind!r}, {self.name!r}, {self.relation!r})'
65
+
66
+
67
+ class NamingError(Exception):
68
+ """Names derived from the catalog collide, or a declared name is unusable.
69
+
70
+ Raised when a Model is created or reloaded. Every problem is listed, in
71
+ the message and in :attr:`problems`: until they are all settled no Model
72
+ can be opened on the database with these declarations. See
73
+ :mod:`half_orm.naming` for how to settle them.
74
+
75
+ Attributes:
76
+ dbname (str): the database.
77
+ problems (list[NamingProblem]): everything that was found.
78
+ """
79
+ def __init__(self, dbname, problems):
80
+ self.dbname = dbname
81
+ self.problems = list(problems)
82
+ count = len(self.problems)
83
+ Exception.__init__(
84
+ self,
85
+ f"{count} naming problem{'s' if count > 1 else ''} in database "
86
+ f"'{dbname}':\n"
87
+ + '\n'.join(str(problem) for problem in self.problems)
88
+ + "\nGive one side of each a name of its own -- an '@ho_name' or "
89
+ "'@ho_reverse_name' line in a comment, or the field_names, "
90
+ "reverse_names and ignore arguments of Model. "
91
+ "See half_orm.naming.")