half-orm 1.2.0__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.
- {half_orm-1.2.0/half_orm.egg-info → half_orm-2.0.0}/PKG-INFO +6 -39
- {half_orm-1.2.0 → half_orm-2.0.0}/README.md +5 -38
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm/__main__.py +5 -2
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm/cli.py +25 -12
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm/field.py +66 -9
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm/fkey.py +17 -5
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm/migrations/BREAKING_CHANGES-1.0.0.md +29 -0
- half_orm-2.0.0/half_orm/migrations/BREAKING_CHANGES-2.0.0.md +123 -0
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm/model.py +168 -20
- half_orm-2.0.0/half_orm/model_errors.py +91 -0
- half_orm-2.0.0/half_orm/naming.py +179 -0
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm/pg_meta.py +264 -49
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm/relation.py +160 -51
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm/relation_factory.py +6 -3
- half_orm-2.0.0/half_orm/version.txt +1 -0
- {half_orm-1.2.0 → half_orm-2.0.0/half_orm.egg-info}/PKG-INFO +6 -39
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm.egg-info/SOURCES.txt +2 -0
- {half_orm-1.2.0 → half_orm-2.0.0}/pyproject.toml +1 -1
- {half_orm-1.2.0 → half_orm-2.0.0}/test/test_cli.py +20 -16
- half_orm-1.2.0/half_orm/model_errors.py +0 -31
- half_orm-1.2.0/half_orm/version.txt +0 -1
- {half_orm-1.2.0 → half_orm-2.0.0}/AUTHORS +0 -0
- {half_orm-1.2.0 → half_orm-2.0.0}/LICENSE +0 -0
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm/__init__.py +0 -0
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm/_predicate.py +0 -0
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm/cli_utils.py +0 -0
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm/field_errors.py +0 -0
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm/hotest.py +0 -0
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm/migrations/__init__.py +0 -0
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm/null.py +0 -0
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm/py.typed +0 -0
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm/relation_errors.py +0 -0
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm/sql_adapter.py +0 -0
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm/sql_ast.py +0 -0
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm/testing.py +0 -0
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm/transaction.py +0 -0
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm/utils.py +0 -0
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm.egg-info/dependency_links.txt +0 -0
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm.egg-info/entry_points.txt +0 -0
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm.egg-info/requires.txt +0 -0
- {half_orm-1.2.0 → half_orm-2.0.0}/half_orm.egg-info/top_level.txt +0 -0
- {half_orm-1.2.0 → half_orm-2.0.0}/setup.cfg +0 -0
- {half_orm-1.2.0 → half_orm-2.0.0}/test/test_main.py +0 -0
- {half_orm-1.2.0 → 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:
|
|
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
|
[](https://coveralls.io/github/half-orm/half-orm?branch=main)
|
|
38
38
|
[](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.
|
|
@@ -81,7 +44,9 @@ with your data. No migrations, no code generation.
|
|
|
81
44
|
**The central idea:** a `Relation` object is a **predicate**. It describes the
|
|
82
45
|
logical condition that rows must satisfy to belong to the relation. Its
|
|
83
46
|
*extension* — the set of rows currently satisfying the predicate in the
|
|
84
|
-
database — is what you read, update, or delete.
|
|
47
|
+
database — is what you read, update, or delete. Why a predicate rather than an
|
|
48
|
+
object mapped to a row is argued in
|
|
49
|
+
[A Relation Is a Predicate, Not an Object](https://half-orm.github.io/half-orm/dev/essays/relation-as-predicate/).
|
|
85
50
|
|
|
86
51
|
## Key features
|
|
87
52
|
|
|
@@ -164,6 +129,8 @@ Author(id=alice['id']).ho_delete()
|
|
|
164
129
|
|
|
165
130
|
- [Learn halfORM in half an hour](https://half-orm.github.io/half-orm/dev/half-an-hour/)
|
|
166
131
|
- [API Reference](https://half-orm.github.io/half-orm/dev/api/relation/)
|
|
132
|
+
- [Why database-first](https://half-orm.github.io/half-orm/dev/essays/) — the argument
|
|
133
|
+
behind the design, in six essays
|
|
167
134
|
- [Breaking changes](https://half-orm.github.io/half-orm/latest/breaking-changes/) — and
|
|
168
135
|
what to do coming from a 0.x release, all of which were published as Beta
|
|
169
136
|
- [Security](https://half-orm.github.io/half-orm/latest/security/) — advisories by
|
|
@@ -8,43 +8,6 @@
|
|
|
8
8
|
[](https://coveralls.io/github/half-orm/half-orm?branch=main)
|
|
9
9
|
[](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.
|
|
@@ -52,7 +15,9 @@ with your data. No migrations, no code generation.
|
|
|
52
15
|
**The central idea:** a `Relation` object is a **predicate**. It describes the
|
|
53
16
|
logical condition that rows must satisfy to belong to the relation. Its
|
|
54
17
|
*extension* — the set of rows currently satisfying the predicate in the
|
|
55
|
-
database — is what you read, update, or delete.
|
|
18
|
+
database — is what you read, update, or delete. Why a predicate rather than an
|
|
19
|
+
object mapped to a row is argued in
|
|
20
|
+
[A Relation Is a Predicate, Not an Object](https://half-orm.github.io/half-orm/dev/essays/relation-as-predicate/).
|
|
56
21
|
|
|
57
22
|
## Key features
|
|
58
23
|
|
|
@@ -135,6 +100,8 @@ Author(id=alice['id']).ho_delete()
|
|
|
135
100
|
|
|
136
101
|
- [Learn halfORM in half an hour](https://half-orm.github.io/half-orm/dev/half-an-hour/)
|
|
137
102
|
- [API Reference](https://half-orm.github.io/half-orm/dev/api/relation/)
|
|
103
|
+
- [Why database-first](https://half-orm.github.io/half-orm/dev/essays/) — the argument
|
|
104
|
+
behind the design, in six essays
|
|
138
105
|
- [Breaking changes](https://half-orm.github.io/half-orm/latest/breaking-changes/) — and
|
|
139
106
|
what to do coming from a 0.x release, all of which were published as Beta
|
|
140
107
|
- [Security](https://half-orm.github.io/half-orm/latest/security/) — advisories by
|
|
@@ -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,
|
|
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,
|
|
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
|
-
"""
|
|
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
|
-
|
|
257
|
-
|
|
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
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
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(
|
|
269
|
-
click.echo(f" Expected: {
|
|
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):
|
|
@@ -10,6 +10,7 @@ import warnings
|
|
|
10
10
|
import yaml
|
|
11
11
|
from collections.abc import Iterable
|
|
12
12
|
from half_orm.null import NULL
|
|
13
|
+
from half_orm.pg_meta import quote_ident
|
|
13
14
|
from half_orm.sql_adapter import SQL_ADAPTER
|
|
14
15
|
from half_orm.sql_ast import FieldExpr
|
|
15
16
|
|
|
@@ -93,6 +94,32 @@ def check_comparator(comp: str) -> str:
|
|
|
93
94
|
f"'=', '!=', '<', '>=', '@>', '@@'.")
|
|
94
95
|
|
|
95
96
|
|
|
97
|
+
# A type name PostgreSQL reads the same bare or quoted. Anything else -- an
|
|
98
|
+
# upper-case letter, a space, a quote, a semicolon -- is quoted before it is
|
|
99
|
+
# written into a cast.
|
|
100
|
+
_BARE_TYPE_NAME_RE = re.compile(r'^[a-z_][a-z0-9_]*$')
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _cast_to(sql_type: str) -> str:
|
|
104
|
+
"""Render the ``::type`` cast applied to a bound value.
|
|
105
|
+
|
|
106
|
+
The type name is read from the catalog and interpolated, no parameter
|
|
107
|
+
being able to stand for it. PostgreSQL lets a user-defined type be called
|
|
108
|
+
anything -- ``create type "int4); drop table t; --"`` is legal -- so a
|
|
109
|
+
name that is not a plain lower-case identifier is quoted, and can then
|
|
110
|
+
only ever be read as a name. Plain ones are left bare, which keeps the
|
|
111
|
+
statements for every built-in type exactly as they were.
|
|
112
|
+
"""
|
|
113
|
+
if _BARE_TYPE_NAME_RE.match(sql_type):
|
|
114
|
+
return f'::{sql_type}'
|
|
115
|
+
return f'::{quote_ident(sql_type)}'
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
# What IS / IS NOT may be followed by. They take a keyword, not a value, so
|
|
119
|
+
# none of this can be bound as a parameter.
|
|
120
|
+
_IS_OPERANDS = {True: 'TRUE', False: 'FALSE'}
|
|
121
|
+
|
|
122
|
+
|
|
96
123
|
class Expr:
|
|
97
124
|
"""A raw SQL expression for use with :meth:`Field.set`.
|
|
98
125
|
|
|
@@ -313,9 +340,17 @@ class Field():
|
|
|
313
340
|
select. Otherwise, returns the field name quoted with ".
|
|
314
341
|
"""
|
|
315
342
|
ho_id = f'r{ho_id}'
|
|
343
|
+
# quote_ident, not a bare pair of quotes: a column may be called
|
|
344
|
+
# `a"b`, and the quote inside it would otherwise close the identifier.
|
|
316
345
|
if query == 'select':
|
|
317
|
-
return f'{ho_id}.
|
|
318
|
-
return
|
|
346
|
+
return f'{ho_id}.{quote_ident(self.__name)}'
|
|
347
|
+
return quote_ident(self.__name)
|
|
348
|
+
|
|
349
|
+
def __is_operand(self):
|
|
350
|
+
"""The keyword following IS / IS NOT for the current value."""
|
|
351
|
+
if self.__value is NULL:
|
|
352
|
+
return 'NULL'
|
|
353
|
+
return _IS_OPERANDS[self.__value]
|
|
319
354
|
|
|
320
355
|
def _where_repr(self, query, ho_id):
|
|
321
356
|
"""Returns the SQL representation of the field for the where clause
|
|
@@ -329,9 +364,11 @@ class Field():
|
|
|
329
364
|
comp = 'in'
|
|
330
365
|
cast = ''
|
|
331
366
|
if self.__value != NULL and not isiterable:
|
|
332
|
-
cast =
|
|
367
|
+
cast = _cast_to(self.__sql_type)
|
|
333
368
|
rhs = _OPERATOR_RHS_TEMPLATES.get((comp, self.__sql_type), f'{comp_str}{cast}')
|
|
334
|
-
if
|
|
369
|
+
if comp in ('is', 'is not'):
|
|
370
|
+
where_repr = f"{self.__praf(query, ho_id)} {comp} {self.__is_operand()}"
|
|
371
|
+
elif col_is_array and comp == '=':
|
|
335
372
|
where_repr = f'{comp_str} = ANY({self.__praf(query, ho_id)})'
|
|
336
373
|
elif not self.unaccent or not self._is_text_like:
|
|
337
374
|
where_repr = f"{self.__praf(query, ho_id)} {comp} {rhs}"
|
|
@@ -366,12 +403,21 @@ class Field():
|
|
|
366
403
|
isiterable = type(self.__value) in {tuple, list, set}
|
|
367
404
|
col_is_array = self.__sql_type[0] == '_'
|
|
368
405
|
comp = self._comp()
|
|
406
|
+
if comp in ('is', 'is not'):
|
|
407
|
+
# A keyword, written into the statement: `IS %s` is not SQL.
|
|
408
|
+
return FieldExpr(
|
|
409
|
+
column=self.__praf(query, ho_id),
|
|
410
|
+
comp=comp,
|
|
411
|
+
placeholder='',
|
|
412
|
+
value=None,
|
|
413
|
+
col_ref=self.__is_operand(),
|
|
414
|
+
)
|
|
369
415
|
if comp == '=' and isiterable:
|
|
370
416
|
comp = 'in'
|
|
371
417
|
is_array_any = col_is_array and comp == '='
|
|
372
418
|
cast = ''
|
|
373
419
|
if not is_array_any and self.__value != NULL and not isiterable:
|
|
374
|
-
cast =
|
|
420
|
+
cast = _cast_to(self.__sql_type)
|
|
375
421
|
placeholder = _OPERATOR_RHS_TEMPLATES.get((comp, self.__sql_type), f'{comp_str}{cast}')
|
|
376
422
|
return FieldExpr(
|
|
377
423
|
column=self.__praf(query, ho_id),
|
|
@@ -407,7 +453,8 @@ class Field():
|
|
|
407
453
|
``=``. Supported comparators: ``=``, ``!=``, ``<``, ``<=``,
|
|
408
454
|
``>``, ``>=``, ``like``, ``not like``, ``ilike``, ``not ilike``,
|
|
409
455
|
``similar to``, ``not similar to``, ``in``, ``not in``, ``is``,
|
|
410
|
-
``is not
|
|
456
|
+
``is not`` (with ``NULL``, ``True`` or ``False`` only),
|
|
457
|
+
``is distinct from``, ``is not distinct from``, and
|
|
411
458
|
any operator spelled with PostgreSQL's operator characters —
|
|
412
459
|
including those added by extensions, such as ``@@``, ``@>``,
|
|
413
460
|
``&&`` or pgvector's ``<->``.
|
|
@@ -496,6 +543,15 @@ class Field():
|
|
|
496
543
|
value = tuple(value)
|
|
497
544
|
if value is NULL and comp not in {'is', 'is not'}:
|
|
498
545
|
raise ValueError("comp should be 'is' or 'is not' with NULL value!")
|
|
546
|
+
if comp in {'is', 'is not'} and value is not NULL \
|
|
547
|
+
and not isinstance(value, bool):
|
|
548
|
+
# Whatever the value, the condition used to be rendered as
|
|
549
|
+
# `IS NULL`: ('is', True) silently selected the rows where the
|
|
550
|
+
# column was NULL instead of those where it was true.
|
|
551
|
+
raise ValueError(
|
|
552
|
+
f"'{comp}' takes NULL, True or False, got {value!r}. Use "
|
|
553
|
+
"'is distinct from' / 'is not distinct from' to compare "
|
|
554
|
+
"with a value.")
|
|
499
555
|
self.__is_set = True
|
|
500
556
|
self.__value = value
|
|
501
557
|
self.__comp = comp
|
|
@@ -552,9 +608,10 @@ class Field():
|
|
|
552
608
|
|
|
553
609
|
def _comp(self):
|
|
554
610
|
"Returns the comparator associated to the value."
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
611
|
+
# Doubled wherever it appears, not only when it is the whole
|
|
612
|
+
# operator: pg_trgm's `%>` and `<%` reached psycopg as a malformed
|
|
613
|
+
# placeholder.
|
|
614
|
+
return self.__comp.replace('%', '%%')
|
|
558
615
|
|
|
559
616
|
@property
|
|
560
617
|
def _relation(self):
|
|
@@ -11,7 +11,7 @@ FKs. They are exposed as attributes on relation instances and used in two ways:
|
|
|
11
11
|
* **``.set(rel)``** to add a JOIN condition on the owning relation.
|
|
12
12
|
"""
|
|
13
13
|
|
|
14
|
-
from half_orm.pg_meta import normalize_fqrn, normalize_qrn
|
|
14
|
+
from half_orm.pg_meta import normalize_fqrn, normalize_qrn, quote_ident, unquote_ident
|
|
15
15
|
from half_orm import utils
|
|
16
16
|
|
|
17
17
|
def _would_create_cycle(from_rel, to_rel):
|
|
@@ -79,7 +79,10 @@ class FKey:
|
|
|
79
79
|
self.__confdeltype = confdeltype
|
|
80
80
|
self.__fk_fqrn = fk_sfqrn
|
|
81
81
|
self.__fields_names = fields
|
|
82
|
-
|
|
82
|
+
# Unquoted first: navigating a key hands the reverse one names that
|
|
83
|
+
# are already quoted. Then quoted properly, a bare pair of quotes
|
|
84
|
+
# leaving a quote inside the name free to close the identifier.
|
|
85
|
+
self.__fields = [quote_ident(unquote_ident(name)) for name in fields]
|
|
83
86
|
|
|
84
87
|
def __get_rel(self, fqtn):
|
|
85
88
|
"""Returns the relation class referenced by fqtn.
|
|
@@ -124,7 +127,10 @@ class FKey:
|
|
|
124
127
|
return f_relation
|
|
125
128
|
|
|
126
129
|
def values(self):
|
|
127
|
-
|
|
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))]
|
|
128
134
|
|
|
129
135
|
def set(self, ho_to_rel=None, **kwargs):
|
|
130
136
|
"""Bind this foreign key to a relation, adding a JOIN condition.
|
|
@@ -223,14 +229,20 @@ class FKey:
|
|
|
223
229
|
if from_._qrn == orig_rel._qrn:
|
|
224
230
|
from_id = orig_rel_id
|
|
225
231
|
from_fields = (f'{from_id}.{name}' for name in self.__fields)
|
|
226
|
-
|
|
232
|
+
# Quoted here: the names read from the catalog arrive bare, and
|
|
233
|
+
# went into the join condition as they were.
|
|
234
|
+
to_fields = (f'{to_id}.{quote_ident(unquote_ident(name))}'
|
|
235
|
+
for name in self.__fk_names)
|
|
227
236
|
bounds = " and ".join(
|
|
228
237
|
[f'{a} = {b}' for a, b in zip(to_fields, from_fields)])
|
|
229
238
|
return f"({bounds})"
|
|
230
239
|
|
|
231
240
|
#@utils.trace
|
|
232
241
|
def _fkey_prep_select(self):
|
|
233
|
-
|
|
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)))
|
|
234
246
|
|
|
235
247
|
@property
|
|
236
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.
|