sqlalchemy-cf-analytics-engine 0.0.1__py3-none-any.whl

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.
@@ -0,0 +1,96 @@
1
+ """DBAPI driver and SQLAlchemy dialect for Cloudflare Workers Analytics Engine."""
2
+
3
+ from datetime import date as Date
4
+ from datetime import datetime as Timestamp
5
+ from datetime import time as Time
6
+ from time import localtime
7
+
8
+ from sqlalchemy_cf_analytics_engine.dbapi import (
9
+ INTEGER_TYPES,
10
+ Connection,
11
+ Cursor,
12
+ apilevel,
13
+ connect,
14
+ paramstyle,
15
+ threadsafety,
16
+ )
17
+ from sqlalchemy_cf_analytics_engine.exceptions import (
18
+ DatabaseError,
19
+ DataError,
20
+ Error,
21
+ IntegrityError,
22
+ InterfaceError,
23
+ InternalError,
24
+ NotSupportedError,
25
+ OperationalError,
26
+ ProgrammingError,
27
+ Warning,
28
+ )
29
+
30
+ Binary = bytes
31
+
32
+
33
+ def DateFromTicks(ticks: float) -> Date:
34
+ """Construct a local date from epoch seconds."""
35
+ return Date(*localtime(ticks)[:3])
36
+
37
+
38
+ def TimeFromTicks(ticks: float) -> Time:
39
+ """Construct a local time from epoch seconds."""
40
+ return Time(*localtime(ticks)[3:6])
41
+
42
+
43
+ def TimestampFromTicks(ticks: float) -> Timestamp:
44
+ """Construct a local timestamp from epoch seconds."""
45
+ return Timestamp.combine(DateFromTicks(ticks), TimeFromTicks(ticks))
46
+
47
+
48
+ class _TypeCategory:
49
+ """Compare a DBAPI category with Cloudflare cursor description type codes."""
50
+
51
+ def __init__(self, *codes: str) -> None:
52
+ self.codes = codes
53
+
54
+ def __eq__(self, other: object) -> bool:
55
+ if isinstance(other, str):
56
+ return other in self.codes
57
+ return self is other
58
+
59
+
60
+ STRING = _TypeCategory("String")
61
+ NUMBER = _TypeCategory(*INTEGER_TYPES, "Float64")
62
+ DATETIME = _TypeCategory("DateTime")
63
+ BINARY = _TypeCategory()
64
+ ROWID = _TypeCategory()
65
+
66
+
67
+ __all__ = [
68
+ "BINARY",
69
+ "DATETIME",
70
+ "NUMBER",
71
+ "ROWID",
72
+ "STRING",
73
+ "Binary",
74
+ "Connection",
75
+ "Cursor",
76
+ "DataError",
77
+ "DatabaseError",
78
+ "Date",
79
+ "DateFromTicks",
80
+ "Error",
81
+ "IntegrityError",
82
+ "InterfaceError",
83
+ "InternalError",
84
+ "NotSupportedError",
85
+ "OperationalError",
86
+ "ProgrammingError",
87
+ "Time",
88
+ "TimeFromTicks",
89
+ "Timestamp",
90
+ "TimestampFromTicks",
91
+ "Warning",
92
+ "apilevel",
93
+ "connect",
94
+ "paramstyle",
95
+ "threadsafety",
96
+ ]
@@ -0,0 +1,293 @@
1
+ """
2
+ PEP 249 driver for the Workers Analytics Engine SQL API.
3
+
4
+ The driver sends SQL to
5
+ ``https://api.cloudflare.com/client/v4/accounts/{account_id}/analytics_engine/sql``
6
+ with the API token as a bearer token, and turns the JSON reply into
7
+ ``description`` and rows. The API host is fixed: it never comes from the
8
+ connection URI, so the token cannot be sent anywhere else.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import math
14
+ import re
15
+ import time
16
+ from collections.abc import Mapping, Sequence
17
+ from datetime import date, datetime
18
+ from typing import Any
19
+
20
+ import httpx
21
+
22
+ from sqlalchemy_cf_analytics_engine.exceptions import (
23
+ InterfaceError,
24
+ NotSupportedError,
25
+ OperationalError,
26
+ ProgrammingError,
27
+ )
28
+
29
+ apilevel = "2.0"
30
+ threadsafety = 1 # threads may share the module, but not connections
31
+ paramstyle = "pyformat"
32
+
33
+ INTEGER_TYPES = (
34
+ "Int8",
35
+ "Int16",
36
+ "Int32",
37
+ "Int64",
38
+ "UInt8",
39
+ "UInt16",
40
+ "UInt32",
41
+ "UInt64",
42
+ )
43
+
44
+ API_URL = (
45
+ "https://api.cloudflare.com/client/v4/accounts/{account_id}/analytics_engine/sql"
46
+ )
47
+ _READ_ONLY_QUERY_PREFIX = re.compile(r"(?:SELECT\b|SHOW\s+TABLES\b)", re.IGNORECASE)
48
+ _FORMAT_JSON_SUFFIX = re.compile(r"\bFORMAT\s+JSON$", re.IGNORECASE)
49
+
50
+ # Mask comments and quoted tokens before checking statement boundaries.
51
+ _SQL_TOKEN = re.compile(
52
+ r"""'(?:''|[^'])*'|"(?:""|[^"])*"|`(?:``|[^`])*`|--[^\r\n]*|/\*.*?\*/""",
53
+ re.DOTALL,
54
+ )
55
+ _BIND_TOKEN = re.compile(_SQL_TOKEN.pattern + r"|%%|%\(([^()]+)\)s", re.DOTALL)
56
+
57
+
58
+ def _prepare_statement(operation: str) -> str:
59
+ sql = operation.strip()
60
+
61
+ def mask(match: re.Match[str]) -> str:
62
+ token = match.group()
63
+ fill = " " if token.startswith(("--", "/*")) else "?"
64
+ return fill * len(token)
65
+
66
+ masked = _SQL_TOKEN.sub(mask, sql).rstrip()
67
+ if masked.endswith(";"):
68
+ end = len(masked) - 1
69
+ sql = sql[:end] + sql[end + 1 :]
70
+ masked = masked[:end].rstrip()
71
+ if ";" in masked or not _READ_ONLY_QUERY_PREFIX.match(masked.lstrip()):
72
+ raise NotSupportedError("Expected one SELECT or SHOW TABLES query")
73
+ if not _FORMAT_JSON_SUFFIX.search(masked):
74
+ sql += "\nFORMAT JSON"
75
+ return sql
76
+
77
+
78
+ def validate_string_literal(value: str) -> None:
79
+ """Reject characters Cloudflare cannot represent in string literals."""
80
+ if "'" in value or "\\" in value:
81
+ raise ValueError("Cloudflare strings cannot contain apostrophes or backslashes")
82
+
83
+
84
+ def _render_value(value: object, name: str) -> str:
85
+ # Exact types keep subclass-defined string conversions out of SQL.
86
+ # pylint: disable=unidiomatic-typecheck
87
+ if value is None:
88
+ return "NULL"
89
+ if isinstance(value, bool):
90
+ return "1" if value else "0"
91
+ if type(value) is int or (type(value) is float and math.isfinite(value)):
92
+ return str(value)
93
+ if type(value) is datetime:
94
+ return f"'{value.isoformat(sep=' ')}'"
95
+ if type(value) is date:
96
+ return f"'{value.isoformat()}'"
97
+ if type(value) is str:
98
+ try:
99
+ validate_string_literal(value)
100
+ except ValueError as exc:
101
+ raise ProgrammingError(str(exc)) from exc
102
+ return "'" + value + "'"
103
+ raise ProgrammingError(f"Unsupported value for bound parameter {name!r}")
104
+
105
+
106
+ def _bind(sql: str, parameters: Mapping[str, Any]) -> str:
107
+ def render(match: re.Match[str]) -> str:
108
+ name = match.group(1)
109
+ if name is None:
110
+ return match.group().replace("%%", "%")
111
+ if name not in parameters:
112
+ raise ProgrammingError(f"Missing bound parameter {name!r}")
113
+ return _render_value(parameters[name], name)
114
+
115
+ return _BIND_TOKEN.sub(render, sql)
116
+
117
+
118
+ def connect(account_id: str, api_token: str, timeout: float = 30.0) -> Connection:
119
+ """Return a connection. Nothing is sent to Cloudflare until a query runs."""
120
+ if not account_id or not api_token:
121
+ raise InterfaceError(
122
+ "Both a Cloudflare account ID and an API token are required, "
123
+ "e.g. cfwae://{account_id}:{api_token}@"
124
+ )
125
+ return Connection(account_id, api_token, timeout)
126
+
127
+
128
+ class Connection:
129
+ """Holds the credentials. The SQL API is stateless, so there is no session."""
130
+
131
+ def __init__(self, account_id: str, api_token: str, timeout: float) -> None:
132
+ self.client = httpx.Client()
133
+ self.account_id = account_id
134
+ self.api_token = api_token
135
+ self.timeout = timeout
136
+ self.closed = False
137
+
138
+ def cursor(self) -> Cursor:
139
+ self._check_open()
140
+ return Cursor(self)
141
+
142
+ def close(self) -> None:
143
+ self.client.close()
144
+ self.closed = True
145
+
146
+ def commit(self) -> None:
147
+ """Check the connection; the SQL API has no transactions."""
148
+ self._check_open()
149
+
150
+ def rollback(self) -> None:
151
+ """Check the connection; the SQL API has no transactions."""
152
+ self._check_open()
153
+
154
+ def _check_open(self) -> None:
155
+ if self.closed:
156
+ raise InterfaceError("Connection is closed")
157
+
158
+
159
+ class Cursor:
160
+ """Runs one query at a time and holds its result."""
161
+
162
+ arraysize = 1
163
+
164
+ def __init__(self, connection: Connection) -> None:
165
+ self.connection = connection
166
+ self.description: list[tuple[Any, ...]] | None = None
167
+ self.rowcount = -1
168
+ self.closed = False
169
+ self._rows: list[tuple[Any, ...]] = []
170
+ self._position = 0
171
+
172
+ def execute(self, operation: str, parameters: Any = None) -> Cursor:
173
+ """Execute one read-only query and buffer its result."""
174
+ self._check_open()
175
+ self.description = None
176
+ self._rows = []
177
+ self._position = 0
178
+ self.rowcount = -1
179
+
180
+ sql = _prepare_statement(operation)
181
+ if isinstance(parameters, Mapping):
182
+ sql = _bind(sql, parameters)
183
+ elif parameters is not None and parameters != ():
184
+ raise ProgrammingError("Expected a mapping of named parameters")
185
+
186
+ connection = self.connection
187
+ for attempt in range(3):
188
+ try:
189
+ response = connection.client.post(
190
+ API_URL.format(account_id=connection.account_id),
191
+ headers={"Authorization": f"Bearer {connection.api_token}"},
192
+ content=sql.encode(),
193
+ timeout=connection.timeout,
194
+ )
195
+ except httpx.TimeoutException as exc:
196
+ if attempt == 2:
197
+ raise OperationalError("Cloudflare query timed out") from exc
198
+ except httpx.RequestError as exc:
199
+ raise OperationalError("Cloudflare request failed") from exc
200
+ else:
201
+ if response.status_code != 429 and response.status_code < 500:
202
+ break
203
+ if attempt == 2:
204
+ raise OperationalError(
205
+ f"Cloudflare returned HTTP {response.status_code}"
206
+ )
207
+ time.sleep(0.25 * 2**attempt)
208
+
209
+ if not response.is_success:
210
+ raise ProgrammingError(
211
+ f"Cloudflare HTTP {response.status_code}: {response.text}"
212
+ )
213
+
214
+ try:
215
+ result = response.json()
216
+ meta, data = result["meta"], result["data"]
217
+ if not isinstance(meta, list) or not isinstance(data, list):
218
+ raise TypeError("Expected arrays for meta and data")
219
+ columns = [(column["name"], column["type"]) for column in meta]
220
+ rows = [
221
+ tuple(_convert(row[name], type_name) for name, type_name in columns)
222
+ for row in data
223
+ ]
224
+ except (KeyError, TypeError, ValueError) as exc:
225
+ raise InterfaceError("Invalid Cloudflare SQL response") from exc
226
+
227
+ self.description = [
228
+ (name, kind, None, None, None, None, None) for name, kind in columns
229
+ ]
230
+ self._rows = rows
231
+ self.rowcount = len(rows)
232
+ return self
233
+
234
+ def executemany(self, operation: str, seq_of_parameters: Sequence[Any]) -> None:
235
+ """Batch execution is unsupported for this read-only driver."""
236
+ self._check_open()
237
+ raise NotSupportedError("executemany is not supported")
238
+
239
+ def fetchone(self) -> tuple[Any, ...] | None:
240
+ self._check_executed()
241
+ if self._position >= len(self._rows):
242
+ return None
243
+ row = self._rows[self._position]
244
+ self._position += 1
245
+ return row
246
+
247
+ def fetchmany(self, size: int | None = None) -> list[tuple[Any, ...]]:
248
+ self._check_executed()
249
+ if size is None:
250
+ size = self.arraysize
251
+ if size < 0:
252
+ raise ProgrammingError("fetchmany size must be non-negative")
253
+ rows = self._rows[self._position : self._position + size]
254
+ self._position += len(rows)
255
+ return rows
256
+
257
+ def fetchall(self) -> list[tuple[Any, ...]]:
258
+ self._check_executed()
259
+ rows = self._rows[self._position :]
260
+ self._position = len(self._rows)
261
+ return rows
262
+
263
+ def close(self) -> None:
264
+ self.closed = True
265
+ self._rows.clear()
266
+
267
+ def setinputsizes(self, sizes: Any) -> None:
268
+ """Required by PEP 249; does nothing."""
269
+
270
+ def setoutputsize(self, size: Any, column: Any = None) -> None:
271
+ """Required by PEP 249; does nothing."""
272
+
273
+ def _check_open(self) -> None:
274
+ if self.closed:
275
+ raise InterfaceError("Cursor is closed")
276
+ self.connection._check_open()
277
+
278
+ def _check_executed(self) -> None:
279
+ self._check_open()
280
+ if self.description is None:
281
+ raise InterfaceError("No query has been executed")
282
+
283
+
284
+ def _convert(value: Any, type_name: str) -> Any:
285
+ if value is None:
286
+ return None
287
+ if type_name == "DateTime":
288
+ return datetime.fromisoformat(value)
289
+ if type_name in INTEGER_TYPES:
290
+ return int(value)
291
+ if type_name == "Float64":
292
+ return float(value)
293
+ return str(value)
@@ -0,0 +1,228 @@
1
+ """SQLAlchemy dialect for Cloudflare Workers Analytics Engine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from types import ModuleType
6
+ from typing import Any
7
+
8
+ from sqlalchemy import exc
9
+ from sqlalchemy.engine import Connection, default, reflection
10
+ from sqlalchemy.engine.url import URL
11
+ from sqlalchemy.sql import operators
12
+ from sqlalchemy.sql.compiler import SQLCompiler
13
+ from sqlalchemy.sql.elements import BindParameter, ColumnClause
14
+ from sqlalchemy.sql.type_api import TypeEngine
15
+
16
+ from sqlalchemy_cf_analytics_engine.dbapi import validate_string_literal
17
+ from sqlalchemy_cf_analytics_engine.types import get_sqla_type
18
+
19
+
20
+ # Inherit SQLAlchemy's defaults for unsupported compiler operations.
21
+ class CloudflareSQLCompiler(SQLCompiler): # pylint: disable=abstract-method
22
+ """Compile SQLAlchemy expressions for the Analytics Engine SQL API."""
23
+
24
+ def visit_column(self, column: ColumnClause[Any], **kwargs: Any) -> str:
25
+ # WAE accepts bare column names. Keep outer references and references
26
+ # in multi-source queries qualified so their meaning is preserved.
27
+ if self.stack and self.stack[-1].get("asfrom_froms") == {column.table}:
28
+ kwargs["include_table"] = False
29
+ return super().visit_column(column, **kwargs)
30
+
31
+ def visit_binary(self, binary, override_operator=None, **kw):
32
+ op = override_operator or binary.operator
33
+ if (
34
+ op in (operators.in_op, operators.not_in_op)
35
+ and isinstance(binary.right, BindParameter)
36
+ and self._expands_membership(binary.right)
37
+ ):
38
+ # The list can be empty on one execution and populated on the next.
39
+ # Let expansion supply the operator along with the list.
40
+ left = self.process(binary.left, **kw)
41
+ # SQLAlchemy encloses an expanding bind in parentheses.
42
+ right = self.process(binary.right, **kw)[1:-1]
43
+ predicate = f"({left} {right})"
44
+ return f"(NOT {predicate})" if op is operators.not_in_op else predicate
45
+ return super().visit_binary(binary, override_operator=override_operator, **kw)
46
+
47
+ def _expands_membership(self, parameter):
48
+ # SQLAlchemy applies custom type-level SQL wrappers to each expanded
49
+ # value. Keep its native rendering for those expressions.
50
+ return (
51
+ parameter.expanding
52
+ and parameter.expand_op in (operators.in_op, operators.not_in_op)
53
+ and not parameter.type.dialect_impl(self.dialect)._has_bind_expression
54
+ )
55
+
56
+ def _membership_rhs(self, parameter, values, sql):
57
+ if not self._expands_membership(parameter):
58
+ return sql
59
+ # WAE type-checks IN (NULL) even when followed by AND 1=0.
60
+ return f"IN ({sql})" if values else "IS NULL AND 1 = 0"
61
+
62
+ def _literal_execute_expanding_parameter(self, name, parameter, values, **kw):
63
+ params, sql = super()._literal_execute_expanding_parameter(
64
+ name, parameter, values, **kw
65
+ )
66
+ if parameter.literal_execute:
67
+ return params, sql # already rendered by the literal-binds path
68
+ return params, self._membership_rhs(parameter, values, sql)
69
+
70
+ def _literal_execute_expanding_parameter_literal_binds(
71
+ self, parameter, values, **kw
72
+ ):
73
+ params, sql = super()._literal_execute_expanding_parameter_literal_binds(
74
+ parameter, values, **kw
75
+ )
76
+ return params, self._membership_rhs(parameter, values, sql)
77
+
78
+ def render_literal_value(self, value: Any, type_: TypeEngine[Any]) -> str:
79
+ if isinstance(value, str):
80
+ try:
81
+ validate_string_literal(value)
82
+ except ValueError as error:
83
+ raise exc.CompileError(str(error)) from error
84
+ return super().render_literal_value(value, type_)
85
+
86
+
87
+ class CloudflareAnalyticsEngineDialect(default.DefaultDialect):
88
+ """
89
+ Read-only dialect for ``cfwae://{account_id}:{api_token}@`` URIs.
90
+
91
+ Each Analytics Engine dataset is exposed as a table in a single, unnamed
92
+ schema.
93
+ """
94
+
95
+ name = "cfwae"
96
+ driver = "httpx"
97
+ statement_compiler = CloudflareSQLCompiler
98
+
99
+ supports_statement_cache = True
100
+ supports_alter = False
101
+ supports_sequences = False
102
+ supports_native_boolean = False
103
+ postfetch_lastrowid = False
104
+
105
+ @classmethod
106
+ def import_dbapi(cls) -> ModuleType:
107
+ import sqlalchemy_cf_analytics_engine as dbapi
108
+
109
+ return dbapi
110
+
111
+ def create_connect_args(self, url: URL) -> tuple[list[Any], dict[str, Any]]:
112
+ """
113
+ Turn the URI into ``connect()`` arguments.
114
+
115
+ The host is ignored, so the token always goes to Cloudflare's fixed API
116
+ address. Missing credentials are reported by ``connect()``.
117
+ """
118
+ return [], {"account_id": url.username, "api_token": url.password}
119
+
120
+ def do_rollback(self, dbapi_connection: Any) -> None:
121
+ """Nothing to roll back: the driver is read-only."""
122
+
123
+ def get_schema_names(self, connection: Connection, **kw: Any) -> list[str]:
124
+ return []
125
+
126
+ @reflection.cache
127
+ def get_table_names(
128
+ self, connection: Connection, schema: str | None = None, **kw: Any
129
+ ) -> list[str]:
130
+ if schema is not None:
131
+ return []
132
+ return list(connection.exec_driver_sql("SHOW TABLES").scalars())
133
+
134
+ def get_view_names(
135
+ self, connection: Connection, schema: str | None = None, **kw: Any
136
+ ) -> list[str]:
137
+ return []
138
+
139
+ def has_table(
140
+ self,
141
+ connection: Connection,
142
+ table_name: str,
143
+ schema: str | None = None,
144
+ **kw: Any,
145
+ ) -> bool:
146
+ return table_name in self.get_table_names(connection, schema=schema, **kw)
147
+
148
+ def _require_table(
149
+ self, connection: Connection, table_name: str, schema: str | None, **kw: Any
150
+ ) -> None:
151
+ # Even a nonexistent dataset can return column metadata from SELECT *.
152
+ if not self.has_table(connection, table_name, schema, **kw):
153
+ raise exc.NoSuchTableError(
154
+ f"{schema}.{table_name}" if schema else table_name
155
+ )
156
+
157
+ @reflection.cache
158
+ def get_columns(
159
+ self,
160
+ connection: Connection,
161
+ table_name: str,
162
+ schema: str | None = None,
163
+ **kw: Any,
164
+ ) -> list[dict[str, Any]]:
165
+ self._require_table(connection, table_name, schema, **kw)
166
+ identifier = self.identifier_preparer.quote_identifier(table_name)
167
+ with connection.exec_driver_sql(
168
+ f"SELECT * FROM {identifier} LIMIT 0"
169
+ ) as result:
170
+ return [
171
+ {
172
+ "name": name,
173
+ "type": get_sqla_type(kind),
174
+ "nullable": True,
175
+ "default": None,
176
+ }
177
+ for name, kind, *_ in result.cursor.description
178
+ ]
179
+
180
+ def get_pk_constraint(
181
+ self,
182
+ connection: Connection,
183
+ table_name: str,
184
+ schema: str | None = None,
185
+ **kw: Any,
186
+ ) -> dict[str, Any]:
187
+ self._require_table(connection, table_name, schema, **kw)
188
+ return {"constrained_columns": [], "name": None}
189
+
190
+ def get_foreign_keys(
191
+ self,
192
+ connection: Connection,
193
+ table_name: str,
194
+ schema: str | None = None,
195
+ **kw: Any,
196
+ ) -> list[dict[str, Any]]:
197
+ self._require_table(connection, table_name, schema, **kw)
198
+ return []
199
+
200
+ def get_indexes(
201
+ self,
202
+ connection: Connection,
203
+ table_name: str,
204
+ schema: str | None = None,
205
+ **kw: Any,
206
+ ) -> list[dict[str, Any]]:
207
+ self._require_table(connection, table_name, schema, **kw)
208
+ return []
209
+
210
+ def get_unique_constraints(
211
+ self,
212
+ connection: Connection,
213
+ table_name: str,
214
+ schema: str | None = None,
215
+ **kw: Any,
216
+ ) -> list[dict[str, Any]]:
217
+ self._require_table(connection, table_name, schema, **kw)
218
+ return []
219
+
220
+ def get_check_constraints(
221
+ self,
222
+ connection: Connection,
223
+ table_name: str,
224
+ schema: str | None = None,
225
+ **kw: Any,
226
+ ) -> list[dict[str, Any]]:
227
+ self._require_table(connection, table_name, schema, **kw)
228
+ return []
@@ -0,0 +1,43 @@
1
+ """The exception hierarchy required by PEP 249."""
2
+
3
+ # pylint: disable=redefined-builtin
4
+
5
+
6
+ class Warning(Exception):
7
+ """Important warnings, such as data truncation."""
8
+
9
+
10
+ class Error(Exception):
11
+ """Base class of every error raised by this driver."""
12
+
13
+
14
+ class InterfaceError(Error):
15
+ """The driver was misused, or Cloudflare's reply could not be read."""
16
+
17
+
18
+ class DatabaseError(Error):
19
+ """An error reported by Cloudflare."""
20
+
21
+
22
+ class DataError(DatabaseError):
23
+ """A problem with the data, such as a value out of range."""
24
+
25
+
26
+ class OperationalError(DatabaseError):
27
+ """The request failed: network errors, timeouts, rate limits, 5xx replies."""
28
+
29
+
30
+ class IntegrityError(DatabaseError):
31
+ """Relational integrity was affected. Unused: the driver is read-only."""
32
+
33
+
34
+ class InternalError(DatabaseError):
35
+ """Cloudflare reported an internal error."""
36
+
37
+
38
+ class ProgrammingError(DatabaseError):
39
+ """The query was rejected: bad SQL, unknown dataset or column, bad token."""
40
+
41
+
42
+ class NotSupportedError(DatabaseError):
43
+ """The query or method is not supported, such as writes or transactions."""
File without changes
@@ -0,0 +1,21 @@
1
+ """Mapping from Workers Analytics Engine column types to SQLAlchemy types."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from sqlalchemy import types
6
+
7
+ from sqlalchemy_cf_analytics_engine.dbapi import INTEGER_TYPES
8
+
9
+ TYPE_MAP: dict[str, type[types.TypeEngine]] = {
10
+ "DateTime": types.DateTime,
11
+ "String": types.String,
12
+ "Float64": types.Float,
13
+ **dict.fromkeys(INTEGER_TYPES, types.Integer),
14
+ "Int64": types.BigInteger,
15
+ "UInt64": types.BigInteger,
16
+ }
17
+
18
+
19
+ def get_sqla_type(type_name: str) -> types.TypeEngine:
20
+ """Return the SQLAlchemy type for a WAE type name. Unknown types are text."""
21
+ return TYPE_MAP.get(type_name, types.String)()
@@ -0,0 +1,114 @@
1
+ Metadata-Version: 2.5
2
+ Name: sqlalchemy-cf-analytics-engine
3
+ Version: 0.0.1
4
+ Summary: Read-only DBAPI driver and SQLAlchemy dialect for Cloudflare Workers Analytics Engine
5
+ Project-URL: Homepage, https://github.com/sqlalchemy-cf-wae/sqlalchemy-cf-analytics-engine
6
+ Author: Prithvi Seran, Eva Abdul, Dibya Jyoti Goswami, Jonathan Manuel
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Topic :: Database
13
+ Requires-Python: >=3.11
14
+ Requires-Dist: httpx<1,>=0.27
15
+ Requires-Dist: sqlalchemy<3,>=2.0
16
+ Provides-Extra: dev
17
+ Requires-Dist: pytest>=8; extra == 'dev'
18
+ Requires-Dist: ruff<0.17.0,>=0.16.8; extra == 'dev'
19
+ Description-Content-Type: text/markdown
20
+
21
+ # sqlalchemy-cf-analytics-engine
22
+
23
+ Query [Cloudflare Workers Analytics Engine](https://developers.cloudflare.com/analytics/analytics-engine/)
24
+ datasets as tables with SQLAlchemy 2.x. The package includes a read-only
25
+ SQLAlchemy dialect and Python DBAPI driver for Cloudflare's SQL API. 
26
+
27
+ ## Installation
28
+
29
+ Use Python 3.11 or newer. From the root of a cloned repository, install the
30
+ package into your Python environment.
31
+
32
+ ```bash
33
+ python -m pip install .
34
+ ```
35
+
36
+ ## Connect and list your datasets
37
+
38
+ You'll need your Cloudflare account ID and an API token with **Account
39
+ Analytics: Read** access to that account. For tools that accept a SQLAlchemy
40
+ connection string, use the following URI, including the trailing `@`.
41
+ The driver connects directly to Cloudflare's API.
42
+
43
+ ```text
44
+ cfwae://{account_id}:{api_token}@
45
+ ```
46
+
47
+ In Python, set the environment variables `CFWAE_ACCOUNT_ID` and
48
+ `CFWAE_API_TOKEN` in your shell, then run this example to print the name
49
+ of each available dataset.
50
+
51
+ ```python
52
+ import os
53
+
54
+ from sqlalchemy import URL, create_engine, inspect
55
+
56
+ url = URL.create(
57
+ "cfwae",
58
+ username=os.environ["CFWAE_ACCOUNT_ID"],
59
+ password=os.environ["CFWAE_API_TOKEN"],
60
+ )
61
+ engine = create_engine(url)
62
+ for dataset in inspect(engine).get_table_names():
63
+ print(dataset)
64
+ ```
65
+
66
+ For help creating a token or populating a sample dataset, see the
67
+ [Cloudflare setup guide](dev/cloudflare/README.md).
68
+
69
+ ## Query sampled data
70
+
71
+ Each stored row represents `_sample_interval` events. To estimate the event
72
+ count, sum that column. Reuse the engine from above and replace `api_requests`
73
+ with a dataset name from your account.
74
+
75
+ ```python
76
+ from sqlalchemy import text
77
+
78
+ with engine.connect() as connection:
79
+ result = connection.execute(text("SELECT SUM(_sample_interval) FROM api_requests"))
80
+ print(result.scalar_one())
81
+ ```
82
+
83
+ | Metric | SQL expression |
84
+ | --- | --- |
85
+ | Number of events | `SUM(_sample_interval)` |
86
+ | Sum of `double1` | `SUM(_sample_interval * double1)` |
87
+ | Average of `double1` | `SUM(_sample_interval * double1) / SUM(_sample_interval)` |
88
+
89
+ ## Development
90
+
91
+ From the repository root, install an editable copy with the development tools.
92
+
93
+ ```bash
94
+ python3.11 -m venv .venv
95
+ source .venv/bin/activate
96
+ python -m pip install -e ".[dev]"
97
+ ```
98
+
99
+ Run the same lint, formatting, and test checks as CI. The tests use recorded
100
+ API responses and run without Cloudflare credentials.
101
+
102
+ ```bash
103
+ ruff check .
104
+ ruff format --check .
105
+ pytest
106
+ ```
107
+
108
+ To apply available lint fixes, run `ruff check --fix .`. To format the code,
109
+ run `ruff format .`. See [Contributing](CONTRIBUTING.md) for the pull request
110
+ workflow.
111
+
112
+ ## License
113
+
114
+ Apache License 2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,11 @@
1
+ sqlalchemy_cf_analytics_engine/__init__.py,sha256=N9BdWBjQwKafMKmc0L5Csf5-yRs4NT9aFtVOVottMYg,2110
2
+ sqlalchemy_cf_analytics_engine/dbapi.py,sha256=nteEXXye6GsDOYUpkVxnDrPSf7USjiSX96X5JBihdMs,9872
3
+ sqlalchemy_cf_analytics_engine/dialect.py,sha256=FrysYaENc9hS8rmWxE8u96iLUu19_CcoTE1EL_3iMso,8193
4
+ sqlalchemy_cf_analytics_engine/exceptions.py,sha256=GL-QET2bs3uoIsdCVMMkQQLg5mg9T-Uhbz3RzvniU3U,1105
5
+ sqlalchemy_cf_analytics_engine/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ sqlalchemy_cf_analytics_engine/types.py,sha256=gOUEJFdihtRxXKmH06R22HHr_yKdsOSauiWgxgb50ZQ,651
7
+ sqlalchemy_cf_analytics_engine-0.0.1.dist-info/METADATA,sha256=mZy5AuVyN41QaUirdOiyI5OpyKDZt5X5BhOYiPpMbTY,3450
8
+ sqlalchemy_cf_analytics_engine-0.0.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ sqlalchemy_cf_analytics_engine-0.0.1.dist-info/entry_points.txt,sha256=RPxI-T50PianY1IGXaFHcNjnaLWp1tfaRLrnt19Ujj4,188
10
+ sqlalchemy_cf_analytics_engine-0.0.1.dist-info/licenses/LICENSE,sha256=gXPVwptPlW1TJ4HSuG5OMPg-a3h43OGMkZRR1rpwfJA,10850
11
+ sqlalchemy_cf_analytics_engine-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [sqlalchemy.dialects]
2
+ cfwae = sqlalchemy_cf_analytics_engine.dialect:CloudflareAnalyticsEngineDialect
3
+ cfwae.httpx = sqlalchemy_cf_analytics_engine.dialect:CloudflareAnalyticsEngineDialect
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.