qodalis-cli-server-plugin-data-explorer 1.0.0b25__tar.gz → 1.0.0b27__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: qodalis-cli-server-plugin-data-explorer
3
- Version: 1.0.0b25
3
+ Version: 1.0.0b27
4
4
  Summary: Data Explorer plugin for Qodalis CLI servers
5
5
  Project-URL: Homepage, https://github.com/qodalis-solutions/cli-server-python
6
6
  Project-URL: Repository, https://github.com/qodalis-solutions/cli-server-python
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "qodalis-cli-server-plugin-data-explorer"
7
- version = "1.0.0b25"
7
+ version = "1.0.0b27"
8
8
  description = "Data Explorer plugin for Qodalis CLI servers"
9
9
  readme = { text = "", content-type = "text/plain" }
10
10
  license = "MIT"
@@ -16,6 +16,9 @@ from .data_explorer_policy import (
16
16
  can_use_source,
17
17
  filter_listing,
18
18
  filter_schema,
19
+ fix_name_case,
20
+ name_case_hint,
21
+ quote_name_ansi,
19
22
  glob_to_regex,
20
23
  is_object_allowed,
21
24
  is_read_only,
@@ -42,6 +45,9 @@ __all__ = [
42
45
  "create_data_explorer_router",
43
46
  "filter_listing",
44
47
  "filter_schema",
48
+ "fix_name_case",
49
+ "name_case_hint",
50
+ "quote_name_ansi",
45
51
  "glob_to_regex",
46
52
  "is_object_allowed",
47
53
  "is_read_only",
@@ -17,11 +17,15 @@ from .data_explorer_policy import (
17
17
  DataExplorerRateLimiter,
18
18
  apply_column_policy,
19
19
  filter_listing,
20
+ filter_schema,
20
21
  is_read_only,
21
22
  masked_column_error,
22
23
  masked_result_error,
23
24
  missing_permissions,
25
+ fix_name_case,
26
+ name_case_hint,
24
27
  objects_error,
28
+ quote_name_ansi,
25
29
  rate_limit_of,
26
30
  read_only_error,
27
31
  )
@@ -47,17 +51,26 @@ DataExplorerAuditSink = Callable[[DataExplorerAuditEntry], Awaitable[None]]
47
51
  #: Longest query text kept in an audit entry.
48
52
  AUDIT_QUERY_MAX_LENGTH = 2000
49
53
 
54
+ #: Most names whose case a query has fixed before it runs again
55
+ #: (``DataExplorerProviderOptions.fix_name_case``).
56
+ MAX_NAME_FIXES = 5
57
+
50
58
 
51
59
  def result_to_dict(result: DataExplorerResult) -> dict[str, Any]:
52
60
  """The result as a snake_case dict; ``error_code`` only when the server
53
- refused the query (works with older abstractions, whose result has no
54
- such field)."""
61
+ refused the query and ``executed_query`` only when the server changed it
62
+ (works with older abstractions, whose result has no such fields)."""
55
63
  data = asdict(result)
56
64
  code = getattr(result, "error_code", None)
57
65
  if code:
58
66
  data["error_code"] = code
59
67
  else:
60
68
  data.pop("error_code", None)
69
+ executed = getattr(result, "executed_query", None)
70
+ if executed:
71
+ data["executed_query"] = executed
72
+ else:
73
+ data.pop("executed_query", None)
61
74
  return data
62
75
 
63
76
 
@@ -103,37 +116,55 @@ class DataExplorerExecutor:
103
116
  return await self._refuse(
104
117
  request, options, caller, f"Too many queries: at most {max_queries} per {window:g} s", "rate_limited",
105
118
  )
106
- if is_read_only(options) and not getattr(provider, "read_only_queries", False):
107
- error = read_only_error(options.language, query)
108
- if error:
109
- return await self._refuse(request, options, caller, error, "read_only")
110
- objects = objects_error(options, query)
111
- if objects:
112
- return await self._refuse(request, options, caller, objects, "object_not_allowed")
113
- masked = masked_column_error(options, query)
114
- if masked:
115
- return await self._refuse(request, options, caller, masked, "masked_column")
116
-
117
- context = DataExplorerExecutionContext(query=query, parameters=parameters, options=options)
118
- timeout_s = options.timeout / 1000.0
119
- try:
120
- result = await asyncio.wait_for(provider.execute_async(context), timeout=timeout_s)
121
- except asyncio.TimeoutError:
122
- result = _failure(source, options, f"Query timed out after {options.timeout}ms", options.timeout)
123
- except Exception as exc:
124
- result = _failure(source, options, str(exc), _elapsed_ms(start))
125
- else:
126
- if result.row_count > options.max_rows:
127
- result.rows = result.rows[: options.max_rows]
128
- result.row_count = options.max_rows
129
- result.truncated = True
130
- masked = masked_result_error(options, query, result.columns) if result.success else None
119
+ sent = query
120
+ for fixes in range(MAX_NAME_FIXES + 1):
121
+ if is_read_only(options) and not getattr(provider, "read_only_queries", False):
122
+ error = read_only_error(options.language, query)
123
+ if error:
124
+ return await self._refuse(request, options, caller, error, "read_only")
125
+ objects = objects_error(options, query)
126
+ if objects:
127
+ return await self._refuse(request, options, caller, objects, "object_not_allowed")
128
+ masked = masked_column_error(options, query)
131
129
  if masked:
132
- # A masked column came back under another name: withhold the rows
133
- result = _failure(source, options, masked, _elapsed_ms(start), "masked_column")
134
- elif result.success:
135
- filter_listing(result, options, query)
136
- apply_column_policy(result, options)
130
+ return await self._refuse(request, options, caller, masked, "masked_column")
131
+
132
+ context = DataExplorerExecutionContext(query=query, parameters=parameters, options=options)
133
+ timeout_s = options.timeout / 1000.0
134
+ try:
135
+ result = await asyncio.wait_for(provider.execute_async(context), timeout=timeout_s)
136
+ except asyncio.TimeoutError:
137
+ result = _failure(source, options, f"Query timed out after {options.timeout}ms", options.timeout)
138
+ except Exception as exc:
139
+ error = str(exc)
140
+ schema = await self._visible_schema(provider, options) if _language_of(options) == "sql" else None
141
+ # A read-only query changed nothing, so it runs again with the name's case fixed (one name per run)
142
+ fixed = (
143
+ fix_name_case(query, error, schema, _quote_of(provider))
144
+ if is_read_only(options) and getattr(options, "fix_name_case", True) and fixes < MAX_NAME_FIXES
145
+ else None
146
+ )
147
+ if fixed is not None:
148
+ logger.info("Data explorer query on source '%s' runs again as: %s", source, fixed)
149
+ query = fixed
150
+ continue
151
+ hint = name_case_hint(error, schema)
152
+ result = _failure(source, options, error if hint is None else f"{error.rstrip()}\n{hint}", _elapsed_ms(start))
153
+ else:
154
+ if query != sent:
155
+ result.executed_query = query
156
+ if result.row_count > options.max_rows:
157
+ result.rows = result.rows[: options.max_rows]
158
+ result.row_count = options.max_rows
159
+ result.truncated = True
160
+ masked = masked_result_error(options, query, result.columns) if result.success else None
161
+ if masked:
162
+ # A masked column came back under another name: withhold the rows
163
+ result = _failure(source, options, masked, _elapsed_ms(start), "masked_column")
164
+ elif result.success:
165
+ filter_listing(result, options, query)
166
+ apply_column_policy(result, options)
167
+ break
137
168
 
138
169
  await self._write_audit(request, options, caller, result, _elapsed_ms(start))
139
170
  return result
@@ -143,6 +174,16 @@ class DataExplorerExecutor:
143
174
  await self._write_audit(request, options, caller, result, 0)
144
175
  return result
145
176
 
177
+ async def _visible_schema(self, provider: Any, options: Any) -> Any:
178
+ """The source's schema as its callers see it, or ``None`` when the
179
+ provider cannot give one."""
180
+ try:
181
+ schema = await provider.get_schema_async(options)
182
+ return filter_schema(schema, options) if schema is not None else None
183
+ except Exception:
184
+ logger.debug("No schema for the name hint on source '%s'", getattr(options, "name", ""), exc_info=True)
185
+ return None
186
+
146
187
  async def _write_audit(self, request: dict[str, Any], options: Any, caller: Any, result: DataExplorerResult, duration_ms: int) -> None:
147
188
  """Writes the ``data_query`` audit entry; a failing audit log does not fail the query."""
148
189
  if getattr(options, "audit", True) is False or self._audit is None:
@@ -151,18 +192,18 @@ class DataExplorerExecutor:
151
192
  sink = self._audit()
152
193
  if sink is None:
153
194
  return
154
- query = request.get("query", "") or ""
155
- if len(query) > AUDIT_QUERY_MAX_LENGTH:
156
- query = query[:AUDIT_QUERY_MAX_LENGTH] + "…"
157
195
  metadata: dict[str, Any] = {
158
196
  "source": options.name,
159
- "query": query,
197
+ "query": _truncate(request.get("query", "") or ""),
160
198
  "success": result.success,
161
199
  "rowCount": result.row_count,
162
200
  "durationMs": duration_ms,
163
201
  }
164
202
  if result.error:
165
203
  metadata["error"] = result.error
204
+ executed = getattr(result, "executed_query", None)
205
+ if executed:
206
+ metadata["executedQuery"] = _truncate(executed)
166
207
  remote = getattr(caller, "remote_address", None) if caller is not None else None
167
208
  if remote:
168
209
  metadata["remoteAddress"] = remote
@@ -176,6 +217,21 @@ class DataExplorerExecutor:
176
217
  logger.exception("Failed to write the data_query audit entry")
177
218
 
178
219
 
220
+ def _truncate(text: str) -> str:
221
+ return text[:AUDIT_QUERY_MAX_LENGTH] + "…" if len(text) > AUDIT_QUERY_MAX_LENGTH else text
222
+
223
+
224
+ def _quote_of(provider: Any) -> Callable[[str], str]:
225
+ """The provider's ``quote_name`` (older abstractions have none: ANSI)."""
226
+ quote = getattr(provider, "quote_name", None)
227
+ return quote if callable(quote) else quote_name_ansi
228
+
229
+
230
+ def _language_of(options: Any) -> str:
231
+ language = getattr(options, "language", "sql")
232
+ return str(getattr(language, "value", language))
233
+
234
+
179
235
  def _elapsed_ms(start: float) -> int:
180
236
  return int((time.monotonic() - start) * 1000)
181
237
 
@@ -94,6 +94,8 @@ class SqlToken:
94
94
  value: str
95
95
  #: As written (words keep their case for object names).
96
96
  raw: str
97
+ #: Offset of a word in the query (``-1`` for other tokens).
98
+ start: int = -1
97
99
 
98
100
 
99
101
  #: ``$$`` or ``$tag$`` (a tag is an identifier without ``$``: ``$a1$``, ``$é$``, not ``$1$``).
@@ -203,7 +205,9 @@ def _quoted_identifier(sql: str, i: int, close: str) -> tuple[str, int]:
203
205
 
204
206
  def tokenize_sql(sql: str, reading: SqlReading = SQL_READINGS[0]) -> list[SqlToken]:
205
207
  """Splits SQL into words, quoted identifiers and punctuation; comments and
206
- string literals are dropped, so keywords inside them do not count."""
208
+ string literals are dropped, so keywords inside them do not count. A ``"..."``
209
+ string (MySQL without ``ANSI_QUOTES``) stays a single name token, so it never
210
+ hides a keyword and still names what it quotes."""
207
211
  tokens: list[SqlToken] = []
208
212
  i, n = 0, len(sql)
209
213
  while i < n:
@@ -229,7 +233,15 @@ def tokenize_sql(sql: str, reading: SqlReading = SQL_READINGS[0]) -> list[SqlTok
229
233
  else:
230
234
  i = _skip_block_comment(sql, i, reading.nested_comments)
231
235
  continue
232
- if c == "'" or (c == '"' and reading.double_quoted_strings):
236
+ if c == '"' and reading.double_quoted_strings:
237
+ # A string here, but every other dialect reads a name, and a string cannot stand where a table
238
+ # or a column does: kept as that name, so FROM "Users" u WHERE ... still names the table
239
+ end = _skip_string(sql, i, c, reading.backslash_escapes)
240
+ name = sql[i + 1 : max(i + 1, end - 1)].replace('""', '"')
241
+ tokens.append(SqlToken("ident", name, name))
242
+ i = end
243
+ continue
244
+ if c == "'":
233
245
  i = _skip_string(sql, i, c, reading.backslash_escapes)
234
246
  continue
235
247
  if c == "$" and reading.dollar_quotes:
@@ -259,7 +271,7 @@ def tokenize_sql(sql: str, reading: SqlReading = SQL_READINGS[0]) -> list[SqlTok
259
271
  # Postgres escape string: E'it\'s'
260
272
  i = _skip_string(sql, j, "'", True)
261
273
  continue
262
- tokens.append(SqlToken("word", raw.upper(), raw))
274
+ tokens.append(SqlToken("word", raw.upper(), raw, i))
263
275
  i = j
264
276
  continue
265
277
  if c.isspace() or c.isdigit():
@@ -933,6 +945,92 @@ def filter_schema(schema: Any, options: Any) -> Any:
933
945
  return replace(schema, tables=tables)
934
946
 
935
947
 
948
+ # PostgreSQL: 'relation "users" does not exist', 'column "countrycode" does not exist', 'column u.countrycode does not exist'
949
+ _MISSING_NAME = re.compile(r'\b(relation|column) (?:"?[^"\s.]+"?\.)?"?([^"\s.]+)"? does not exist')
950
+ # MySQL (table names are case-sensitive on Linux): "Table 'shop.users' doesn't exist"
951
+ _MYSQL_MISSING_TABLE = re.compile(r"\bTable '(?:[^'.]+\.)?([^'.]+)' doesn't exist")
952
+ # SQL Server with a case-sensitive collation: "Invalid object name 'users'.", "Invalid column name 'countrycode'."
953
+ _MSSQL_MISSING_NAME = re.compile(r"\bInvalid (object|column) name '(?:[^'.]+\.)*([^'.]+)'")
954
+
955
+
956
+ def _missing_name_in(error: str) -> tuple[bool, str] | None:
957
+ """The table (``True``) or column an error says does not exist, as the database reports it."""
958
+ m = _MISSING_NAME.search(error)
959
+ if m:
960
+ return m.group(1) == "relation", m.group(2)
961
+ m = _MYSQL_MISSING_TABLE.search(error)
962
+ if m:
963
+ return True, m.group(1)
964
+ m = _MSSQL_MISSING_NAME.search(error)
965
+ if m:
966
+ return m.group(1) == "object", m.group(2)
967
+ return None
968
+
969
+
970
+ def _case_match(missing: tuple[bool, str], schema: Any) -> str | None:
971
+ """The name of ``schema`` that differs from the missing one only in case,
972
+ or ``None`` (none, the same name, or several that differ only in case)."""
973
+ table, name = missing
974
+ if table:
975
+ candidates = [t.name.split(".")[-1] for t in schema.tables]
976
+ else:
977
+ candidates = [c.name for t in schema.tables for c in t.columns]
978
+ lower = name.lower()
979
+ matches = list(dict.fromkeys(c for c in candidates if c.lower() == lower))
980
+ return matches[0] if len(matches) == 1 and matches[0] != name else None
981
+
982
+
983
+ def quote_name_ansi(name: str) -> str:
984
+ """A name in double quotes (ANSI SQL: PostgreSQL, SQLite)."""
985
+ return '"' + name.replace('"', '""') + '"'
986
+
987
+
988
+ def name_case_hint(error: str, schema: Any) -> str | None:
989
+ """For an error saying a table or column does not exist (PostgreSQL folds
990
+ unquoted names to lower case): the hint naming the same name with its
991
+ capitals, from ``schema`` as the source shows it (:func:`filter_schema`),
992
+ so a hidden table or dropped column is never named. ``None`` when nothing
993
+ matches."""
994
+ if schema is None:
995
+ return None
996
+ missing = _missing_name_in(error)
997
+ match = _case_match(missing, schema) if missing else None
998
+ return None if match is None else f'Names with capital letters need double quotes: "{match}"'
999
+
1000
+
1001
+ def fix_name_case(query: str, error: str, schema: Any, quote: Callable[[str], str] = quote_name_ansi) -> str | None:
1002
+ """The query with the name an error says does not exist written as
1003
+ ``schema`` spells it and quoted by ``quote``, so ``select * from Users``
1004
+ runs as ``select * from "Users"``; ``None`` when the error names no such
1005
+ table or column. Only an unquoted name outside strings and comments under
1006
+ every dialect's reading (:data:`SQL_READINGS`) is changed, never a
1007
+ function name (``count(``)."""
1008
+ if schema is None:
1009
+ return None
1010
+ missing = _missing_name_in(error)
1011
+ match = _case_match(missing, schema) if missing else None
1012
+ if match is None:
1013
+ return None
1014
+ name = missing[1].lower() # type: ignore[index]
1015
+ starts: set[int] | None = None
1016
+ for reading in SQL_READINGS:
1017
+ tokens = tokenize_sql(query, reading)
1018
+ here = {
1019
+ t.start for i, t in enumerate(tokens)
1020
+ if t.kind == "word" and t.raw.lower() == name
1021
+ and not (i + 1 < len(tokens) and tokens[i + 1].kind == "punct" and tokens[i + 1].value == "(")
1022
+ }
1023
+ starts = here if starts is None else starts & here
1024
+ if not starts:
1025
+ return None
1026
+ quoted = quote(match)
1027
+ length = len(missing[1]) # type: ignore[index]
1028
+ fixed = query
1029
+ for start in sorted(starts, reverse=True):
1030
+ fixed = fixed[:start] + quoted + fixed[start + length:]
1031
+ return fixed
1032
+
1033
+
936
1034
  _SHOW_COLLECTIONS = re.compile(r"^show\s+collections", re.IGNORECASE)
937
1035
 
938
1036
 
@@ -989,6 +1087,9 @@ __all__ = [
989
1087
  "can_use_source",
990
1088
  "filter_listing",
991
1089
  "filter_schema",
1090
+ "fix_name_case",
1091
+ "name_case_hint",
1092
+ "quote_name_ansi",
992
1093
  "glob_to_regex",
993
1094
  "is_object_allowed",
994
1095
  "is_read_only",