half-orm 0.18.13__tar.gz → 0.18.15__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 (37) hide show
  1. {half_orm-0.18.13/half_orm.egg-info → half_orm-0.18.15}/PKG-INFO +13 -2
  2. {half_orm-0.18.13 → half_orm-0.18.15}/half_orm/__main__.py +7 -3
  3. {half_orm-0.18.13 → half_orm-0.18.15}/half_orm/cli.py +129 -34
  4. {half_orm-0.18.13 → half_orm-0.18.15}/half_orm/field.py +68 -3
  5. {half_orm-0.18.13 → half_orm-0.18.15}/half_orm/hotest.py +18 -1
  6. {half_orm-0.18.13 → half_orm-0.18.15}/half_orm/model.py +166 -26
  7. {half_orm-0.18.13 → half_orm-0.18.15}/half_orm/pg_meta.py +17 -8
  8. {half_orm-0.18.13 → half_orm-0.18.15}/half_orm/relation.py +85 -36
  9. {half_orm-0.18.13 → half_orm-0.18.15}/half_orm/sql_ast.py +8 -2
  10. {half_orm-0.18.13 → half_orm-0.18.15}/half_orm/transaction.py +25 -3
  11. half_orm-0.18.15/half_orm/version.txt +1 -0
  12. {half_orm-0.18.13 → half_orm-0.18.15/half_orm.egg-info}/PKG-INFO +13 -2
  13. {half_orm-0.18.13 → half_orm-0.18.15}/test/test_cli.py +185 -6
  14. {half_orm-0.18.13 → half_orm-0.18.15}/test/test_sql_ast.py +12 -0
  15. half_orm-0.18.13/half_orm/version.txt +0 -1
  16. {half_orm-0.18.13 → half_orm-0.18.15}/AUTHORS +0 -0
  17. {half_orm-0.18.13 → half_orm-0.18.15}/LICENSE +0 -0
  18. {half_orm-0.18.13 → half_orm-0.18.15}/README.md +0 -0
  19. {half_orm-0.18.13 → half_orm-0.18.15}/half_orm/__init__.py +0 -0
  20. {half_orm-0.18.13 → half_orm-0.18.15}/half_orm/cli_utils.py +0 -0
  21. {half_orm-0.18.13 → half_orm-0.18.15}/half_orm/field_errors.py +0 -0
  22. {half_orm-0.18.13 → half_orm-0.18.15}/half_orm/fkey.py +0 -0
  23. {half_orm-0.18.13 → half_orm-0.18.15}/half_orm/model_errors.py +0 -0
  24. {half_orm-0.18.13 → half_orm-0.18.15}/half_orm/null.py +0 -0
  25. {half_orm-0.18.13 → half_orm-0.18.15}/half_orm/relation_errors.py +0 -0
  26. {half_orm-0.18.13 → half_orm-0.18.15}/half_orm/relation_factory.py +0 -0
  27. {half_orm-0.18.13 → half_orm-0.18.15}/half_orm/sql_adapter.py +0 -0
  28. {half_orm-0.18.13 → half_orm-0.18.15}/half_orm/utils.py +0 -0
  29. {half_orm-0.18.13 → half_orm-0.18.15}/half_orm.egg-info/SOURCES.txt +0 -0
  30. {half_orm-0.18.13 → half_orm-0.18.15}/half_orm.egg-info/dependency_links.txt +0 -0
  31. {half_orm-0.18.13 → half_orm-0.18.15}/half_orm.egg-info/entry_points.txt +0 -0
  32. {half_orm-0.18.13 → half_orm-0.18.15}/half_orm.egg-info/requires.txt +0 -0
  33. {half_orm-0.18.13 → half_orm-0.18.15}/half_orm.egg-info/top_level.txt +0 -0
  34. {half_orm-0.18.13 → half_orm-0.18.15}/pyproject.toml +0 -0
  35. {half_orm-0.18.13 → half_orm-0.18.15}/setup.cfg +0 -0
  36. {half_orm-0.18.13 → half_orm-0.18.15}/setup.py +0 -0
  37. {half_orm-0.18.13 → half_orm-0.18.15}/test/test_main.py +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: half_orm
3
- Version: 0.18.13
3
+ Version: 0.18.15
4
4
  Summary: A simple PostgreSQL to Python mapper.
5
5
  Home-page: https://github.com/half-orm/half-orm
6
6
  Author: Joël Maïzi
@@ -29,6 +29,17 @@ License-File: AUTHORS
29
29
  Requires-Dist: psycopg[binary]
30
30
  Requires-Dist: click
31
31
  Requires-Dist: importlib-metadata; python_version < "3.8"
32
+ Dynamic: author
33
+ Dynamic: author-email
34
+ Dynamic: classifier
35
+ Dynamic: description
36
+ Dynamic: description-content-type
37
+ Dynamic: home-page
38
+ Dynamic: license
39
+ Dynamic: license-file
40
+ Dynamic: project-url
41
+ Dynamic: requires-dist
42
+ Dynamic: summary
32
43
 
33
44
  # halfORM
34
45
 
@@ -40,7 +40,7 @@ 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) as exc:
43
+ except (psycopg.Error, model_errors.MalformedConfigFile, ValueError) as exc:
44
44
  sys.stderr.write(f'❌ {cnx_file}: {exc}\n')
45
45
  else:
46
46
  print("💡 No database configuration files found.")
@@ -77,10 +77,11 @@ def main():
77
77
  if database == '':
78
78
  sys.stderr.write("❌ Empty database name\n")
79
79
  sys.exit(1)
80
+ return
80
81
  try:
81
82
  model = Model(database)
82
83
  print(model)
83
- except (psycopg.Error, model_errors.MalformedConfigFile) as exc:
84
+ except (psycopg.Error, model_errors.MalformedConfigFile, ValueError) as exc:
84
85
  sys.stderr.write(f"❌ Error connecting to database '{database}': {exc}\n")
85
86
  sys.stderr.write(f"💡 Use 'python -m half_orm --help' for usage information\n")
86
87
  sys.exit(1)
@@ -92,14 +93,17 @@ def main():
92
93
  if database == '':
93
94
  sys.stderr.write("❌ Empty database name\n")
94
95
  sys.exit(1)
96
+ return
95
97
  if relation == '':
96
98
  sys.stderr.write("❌ Empty relation name\n")
97
99
  sys.exit(1)
100
+ return
98
101
  try:
99
102
  model = Model(database)
100
103
  relation_class = model.get_relation_class(relation)
101
104
  print(relation_class())
102
- except (psycopg.Error, model_errors.MalformedConfigFile, model_errors.UnknownRelation, model_errors.MissingSchemaInName) as exc:
105
+ except (psycopg.Error, model_errors.MalformedConfigFile, ValueError,
106
+ model_errors.UnknownRelation, model_errors.MissingSchemaInName) as exc:
103
107
  sys.stderr.write(f"❌ Error accessing relation '{relation}' in database '{database}': {exc}\n")
104
108
  sys.stderr.write(f"💡 Use 'python -m half_orm --help' for usage information\n")
105
109
  sys.exit(1)
@@ -83,34 +83,113 @@ _cached_extensions = None
83
83
  _trust_extensions = False
84
84
 
85
85
  # Liste des extensions officielles
86
+ # Extensions trusted without asking. Every name here must be a project the
87
+ # halfORM maintainers actually own on PyPI: an unclaimed name on this list is
88
+ # a free pass for whoever registers it first.
86
89
  OFFICIAL_EXTENSIONS = {
87
- 'half_orm_test_extension',
88
90
  'half_orm_inspect',
89
91
  'half_orm_dev',
90
92
  }
91
93
 
94
+ # Pre-1.0 trust store, kept only to warn that it is no longer honoured.
95
+ LEGACY_CONFIG_NAME = '.half_orm_cli'
96
+
97
+ # Directory entries that mark the root of a project.
98
+ PROJECT_MARKERS = ('.hop', '.git')
99
+
100
+ _legacy_config_warned = False
101
+
92
102
  def get_config_file():
93
- """Get path to project-specific halfORM CLI configuration."""
94
- return Path.cwd() / '.half_orm_cli'
103
+ """Get path to the per-user halfORM CLI configuration.
104
+
105
+ This file holds the extension trust store, which suppresses the security
106
+ prompt raised for unofficial extensions. It therefore lives outside any
107
+ project directory: a checkout is untrusted input, and a repository able to
108
+ write its own trust store would silently grant itself consent.
109
+
110
+ Honours HALF_ORM_CLI_CONFIG, then the platform's per-user configuration
111
+ directory: %APPDATA% on Windows, $XDG_CONFIG_HOME (default ~/.config)
112
+ elsewhere. Both live inside the user's profile, which is what keeps the
113
+ file confidential -- the explicit 0600 applied on save is a Unix-only
114
+ reinforcement, where a permissive umask could otherwise widen it.
115
+ """
116
+ override = os.environ.get('HALF_ORM_CLI_CONFIG')
117
+ if override:
118
+ return Path(override).expanduser()
119
+
120
+ if sys.platform == 'win32':
121
+ appdata = os.environ.get('APPDATA')
122
+ base = Path(appdata) if appdata else Path.home() / 'AppData' / 'Roaming'
123
+ else:
124
+ xdg = os.environ.get('XDG_CONFIG_HOME')
125
+ base = Path(xdg).expanduser() if xdg else Path.home() / '.config'
126
+ return base / 'half_orm' / 'cli.json'
127
+
128
+ def get_project_key(start=None):
129
+ """Identify the project a trust decision applies to.
130
+
131
+ Walks up from `start` (default: the current directory) to the nearest
132
+ project marker, so that running a command from a subdirectory reuses the
133
+ decision already recorded for the project instead of asking again -- a
134
+ prompt that keeps reappearing is a prompt that gets answered unread.
135
+ """
136
+ try:
137
+ current = Path(start) if start else Path.cwd()
138
+ current = current.resolve()
139
+ except OSError:
140
+ return os.path.normcase(str(start or ''))
141
+
142
+ for directory in (current, *current.parents):
143
+ for marker in PROJECT_MARKERS:
144
+ if (directory / marker).exists():
145
+ return os.path.normcase(str(directory))
146
+ # normcase is a no-op on POSIX; on Windows it keeps C:\Proj and c:\proj
147
+ # from becoming two separate trust scopes for one directory.
148
+ return os.path.normcase(str(current))
149
+
150
+ def _warn_legacy_config():
151
+ """Warn once that a pre-1.0 project-local trust store is being ignored."""
152
+ global _legacy_config_warned
153
+ if _legacy_config_warned:
154
+ return
155
+ _legacy_config_warned = True
156
+
157
+ try:
158
+ legacy = Path.cwd() / LEGACY_CONFIG_NAME
159
+ if not legacy.exists():
160
+ return
161
+ except OSError:
162
+ return
163
+
164
+ click.echo(
165
+ f"⚠️ Ignoring '{legacy}': extension trust is no longer read from the "
166
+ "project directory, where a checkout could grant itself consent.",
167
+ err=True)
168
+ click.echo(f" Trust is now recorded in {get_config_file()}", err=True)
95
169
 
96
170
  def load_cli_config():
97
- """Load project-specific CLI configuration."""
98
- config_file = get_config_file()
99
- if config_file.exists():
100
- try:
101
- with open(config_file, 'r') as f:
102
- return json.load(f)
103
- except (json.JSONDecodeError, OSError):
104
- return {}
105
- return {}
171
+ """Load the per-user CLI configuration."""
172
+ _warn_legacy_config()
173
+ try:
174
+ with open(get_config_file(), 'r') as f:
175
+ config = json.load(f)
176
+ except (json.JSONDecodeError, OSError):
177
+ return {}
178
+ return config if isinstance(config, dict) else {}
106
179
 
107
180
  def save_cli_config(config):
108
- """Save project-specific CLI configuration."""
181
+ """Save the per-user CLI configuration, readable by its owner only."""
109
182
  config_file = get_config_file()
110
183
  try:
184
+ config_file.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
111
185
  config['last_updated'] = datetime.now().isoformat()
112
- with open(config_file, 'w') as f:
186
+ fd = os.open(config_file, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
187
+ with os.fdopen(fd, 'w') as f:
113
188
  json.dump(config, f, indent=2)
189
+ # O_CREAT only applies the mode on creation; an existing file keeps its
190
+ # own, so narrow it explicitly. On Windows this only clears the
191
+ # read-only flag, and confidentiality comes from the profile ACL.
192
+ os.chmod(config_file, 0o600)
114
193
  return True
115
194
  except OSError:
116
195
  return False
@@ -142,41 +221,57 @@ def is_official_extension(package_name):
142
221
  hyph_package_name = package_name.replace('-', '_')
143
222
  return package_name in OFFICIAL_EXTENSIONS or hyph_package_name in OFFICIAL_EXTENSIONS
144
223
 
145
- def is_trusted_extension(package_name, current_version=None):
146
- """Check if specific version of extension is trusted."""
147
- config = load_cli_config()
148
- trusted_extensions = config.get('trusted_extensions', {})
224
+ def _trusted_for_project(config, project_key):
225
+ """Return the trust entries recorded for one project.
149
226
 
150
- if package_name in trusted_extensions:
151
- trusted_version = trusted_extensions[package_name].get('version')
152
- return trusted_version == current_version
227
+ Tolerates a malformed store rather than raising: a corrupt file must not
228
+ break the CLI, and every shape it can take here means "not trusted".
229
+ """
230
+ trusted = config.get('trusted_extensions')
231
+ if not isinstance(trusted, dict):
232
+ return {}
233
+ entries = trusted.get(project_key)
234
+ return entries if isinstance(entries, dict) else {}
153
235
 
154
- return False
236
+ def is_trusted_extension(package_name, current_version=None):
237
+ """Check if this version of an extension is trusted for this project."""
238
+ entries = _trusted_for_project(load_cli_config(), get_project_key())
239
+ entry = entries.get(package_name)
240
+ if not isinstance(entry, dict):
241
+ return False
242
+ return entry.get('version') == current_version
155
243
 
156
244
  def add_trusted_extension(package_name, version):
157
- """Add specific version of extension to trusted list."""
245
+ """Trust a specific version of an extension, for this project only."""
158
246
  config = load_cli_config()
159
- trusted = config.get('trusted_extensions', {})
247
+ project_key = get_project_key()
160
248
 
161
- trusted[package_name] = {
249
+ trusted = config.get('trusted_extensions')
250
+ if not isinstance(trusted, dict):
251
+ trusted = {}
252
+ entries = dict(_trusted_for_project(config, project_key))
253
+ entries[package_name] = {
162
254
  'version': version,
163
255
  'trusted_at': datetime.now().isoformat()
164
256
  }
165
257
 
258
+ trusted[project_key] = entries
166
259
  config['trusted_extensions'] = trusted
167
260
  save_cli_config(config)
168
261
 
169
262
  def remove_trusted_extension(package_name):
170
- """Remove extension from trusted list."""
263
+ """Remove an extension from this project's trusted list."""
171
264
  config = load_cli_config()
172
- trusted = config.get('trusted_extensions', {})
265
+ project_key = get_project_key()
266
+ entries = dict(_trusted_for_project(config, project_key))
173
267
 
174
- if package_name in trusted:
175
- del trusted[package_name]
176
- config['trusted_extensions'] = trusted
177
- save_cli_config(config)
178
- return True
179
- return False
268
+ if package_name not in entries:
269
+ return False
270
+
271
+ del entries[package_name]
272
+ config['trusted_extensions'][project_key] = entries
273
+ save_cli_config(config)
274
+ return True
180
275
 
181
276
  def warn_unofficial_extension(package_name, current_version):
182
277
  """Show warning for non-official extensions."""
@@ -309,7 +404,7 @@ def get_extension_info(extensions: Dict[str, Any]) -> str:
309
404
  )
310
405
  @click.version_option(version=half_orm.__version__, prog_name='halfORM')
311
406
  @click.option('--list-extensions', is_flag=True, help='List all installed extensions')
312
- @click.option('--untrust', metavar='EXTENSION', help='Remove extension from trusted list')
407
+ @click.option('--untrust', metavar='EXTENSION', help="Remove extension from this project's trusted list")
313
408
  @click.option('--trusted-extensions', is_flag=True, help='Skip security warnings')
314
409
  @click.pass_context
315
410
  def main(ctx, list_extensions, untrust, trusted_extensions):
@@ -12,6 +12,57 @@ from half_orm.sql_adapter import SQL_ADAPTER
12
12
  from half_orm.sql_ast import FieldExpr
13
13
 
14
14
 
15
+ # Comparators are interpolated into the WHERE clause, not bound as parameters,
16
+ # so they must be constrained to things that can only ever *be* an operator.
17
+ #
18
+ # Word operators are enumerated. Symbolic ones are accepted by pattern rather
19
+ # than by list, because PostgreSQL extensions define their own -- pgvector's
20
+ # `<->`, PostGIS's `&&&`, pg_trgm's `%` -- and halfORM has always let those
21
+ # through. The pattern below is PostgreSQL's own operator character set: a
22
+ # comparator matching it cannot contain a space, a quote or a letter, so it
23
+ # cannot close the condition and start another one.
24
+ _WORD_COMPS = frozenset({
25
+ 'in', 'not in',
26
+ 'is', 'is not',
27
+ 'is distinct from', 'is not distinct from',
28
+ 'like', 'not like', 'ilike', 'not ilike',
29
+ 'similar to', 'not similar to',
30
+ })
31
+
32
+ _SYMBOLIC_COMP_RE = re.compile(r'^[-+*/<>=~!@#%^&|`?]{1,32}$')
33
+
34
+ # The operator character set can also spell the SQL comment openers, which
35
+ # would let a comparator swallow the rest of the condition.
36
+ _COMMENT_TOKENS = ('--', '/*', '*/')
37
+
38
+
39
+ def check_comparator(comp: str) -> str:
40
+ """Validate `comp` as a comparison operator and return its normalized form.
41
+
42
+ Accepts the SQL word operators listed in ``_WORD_COMPS`` (case- and
43
+ whitespace-insensitive) and any operator spelled with PostgreSQL's
44
+ operator characters. Everything else -- anything carrying a space, a
45
+ quote, a letter outside the word list, or a comment opener -- is
46
+ rejected, because it would reach the query as raw SQL.
47
+
48
+ Raises:
49
+ ValueError: if `comp` is not a usable comparison operator.
50
+ """
51
+ if not isinstance(comp, str):
52
+ raise ValueError(
53
+ f"comparator must be a string, got {type(comp).__name__}: {comp!r}")
54
+ normalized = ' '.join(comp.lower().split())
55
+ if normalized in _WORD_COMPS:
56
+ return normalized
57
+ if (_SYMBOLIC_COMP_RE.match(normalized)
58
+ and not any(tok in normalized for tok in _COMMENT_TOKENS)):
59
+ return normalized
60
+ raise ValueError(
61
+ f"Invalid comparator: {comp!r}. Use one of "
62
+ f"{', '.join(sorted(_WORD_COMPS))}, or a PostgreSQL operator such as "
63
+ f"'=', '!=', '<', '>=', '@>', '@@'.")
64
+
65
+
15
66
  class Expr:
16
67
  """A raw SQL expression for use with :meth:`Field.set`.
17
68
 
@@ -271,8 +322,18 @@ class Field():
271
322
  The constraint value. Pass ``None`` to *remove* the constraint.
272
323
  Pass a ``(comparator, value)`` tuple to use an operator other than
273
324
  ``=``. Supported comparators: ``=``, ``!=``, ``<``, ``<=``,
274
- ``>``, ``>=``, ``like``, ``ilike``, ``in``, ``is``, ``is not``,
275
- and any other PostgreSQL operator accepted in a WHERE clause.
325
+ ``>``, ``>=``, ``like``, ``not like``, ``ilike``, ``not ilike``,
326
+ ``similar to``, ``not similar to``, ``in``, ``not in``, ``is``,
327
+ ``is not``, ``is distinct from``, ``is not distinct from``, and
328
+ any operator spelled with PostgreSQL's operator characters --
329
+ including those added by extensions, such as ``@@``, ``@>``,
330
+ ``&&`` or pgvector's ``<->``.
331
+
332
+ The comparator is interpolated into the WHERE clause rather than
333
+ bound as a parameter, so anything else raises ``ValueError``.
334
+ Never build one by concatenating untrusted input; for a
335
+ condition that genuinely needs arbitrary SQL, pass an
336
+ :class:`Expr` as the *value*.
276
337
 
277
338
  Pass a sibling ``Field`` of the **same** relation instance, or an
278
339
  :class:`Expr` for arbitrary SQL expressions, to compare columns of
@@ -322,6 +383,11 @@ class Field():
322
383
  comp, value = value
323
384
  if value is None:
324
385
  raise ValueError("Can't have a None value with a comparator!")
386
+ if comp is not None:
387
+ # Validated here rather than further down: the Expr and Field
388
+ # branches below return early, and their comparator reaches the
389
+ # WHERE clause with no bound parameter at all.
390
+ comp = check_comparator(comp)
325
391
  # Expr (raw SQL expression)
326
392
  if isinstance(value, Expr):
327
393
  self.__is_set = True
@@ -345,7 +411,6 @@ class Field():
345
411
  comp = '='
346
412
  if isinstance(value, (list, set)):
347
413
  value = tuple(value)
348
- comp = comp.lower()
349
414
  if value is NULL and comp not in {'is', 'is not'}:
350
415
  raise ValueError("comp should be 'is' or 'is not' with NULL value!")
351
416
  self.__is_set = True
@@ -4,6 +4,19 @@ import unittest
4
4
  from typing import List
5
5
  from half_orm.relation import Relation
6
6
 
7
+ def _walk_attributes(obj, path: str):
8
+ """Follow `path` as a dotted attribute path on `obj`.
9
+
10
+ This was `eval(f"relation().{alias}")`, which let the string be any Python
11
+ expression while every caller only ever named an attribute -- including
12
+ the test files half-orm-dev generates, which reach the same object through
13
+ `rel.__dict__[alias]`.
14
+ """
15
+ for name in path.split('.'):
16
+ obj = getattr(obj, name)
17
+ return obj
18
+
19
+
7
20
  class HoTestCase(unittest.TestCase):
8
21
  def hotAssertIsPkey(self, relation: Relation, field_names: List[str]):
9
22
  "it shoud be the primary key"
@@ -30,7 +43,11 @@ class HoTestCase(unittest.TestCase):
30
43
  raise self.fail(f"{relation.__class__.__name__}()._ho_fkeys['{fk_name}']() does not reference {f_relation.__name__}")
31
44
 
32
45
  def hotAssertAliasReferences(self, relation: Relation, alias: str, f_relation: Relation):
33
- referenced = eval(f"relation().{alias}")
46
+ """Check that `alias` on `relation` points at `f_relation`.
47
+
48
+ `alias` names an attribute, or a dotted path of them.
49
+ """
50
+ referenced = _walk_attributes(relation(), alias)
34
51
  if referenced()._qrn != f_relation._qrn:
35
52
  raise self.fail(f"{relation.__class__.__name__}.{alias}() does not reference {f_relation.__name__}")
36
53