reportdesigner 0.4.5__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,193 @@
1
+ """ReportDesigner for Python — thin ctypes wrapper over the native C ABI (rdnext.h, ABI v1). No dependencies."""
2
+ from __future__ import annotations
3
+
4
+ import ctypes as C
5
+ import datetime as _dt
6
+ import json
7
+ import os
8
+ import platform
9
+ import struct
10
+ import sys
11
+ from pathlib import Path
12
+ from typing import Any, Callable, Dict, List, Mapping, Optional, Union
13
+
14
+ from .sql import SqlProvider, bind_named # noqa: E402
15
+
16
+ __all__ = ["ReportEngine", "ReportError", "SqlProvider", "bind_named", "features_used", "native_version"]
17
+ _ABI = 1
18
+
19
+
20
+ class ReportError(Exception):
21
+ """The engine rejected the request (bad report, missing data, licence, data source failure)."""
22
+
23
+
24
+ class _Buf(C.Structure):
25
+ _fields_ = [("data", C.c_void_p), ("len", C.c_size_t)]
26
+
27
+
28
+ _DataCb = C.CFUNCTYPE(C.c_int, C.c_void_p, C.c_char_p, C.c_char_p, C.c_void_p)
29
+
30
+
31
+ def _find_library() -> str:
32
+ if os.environ.get("RDNEXT_LIB"):
33
+ return os.environ["RDNEXT_LIB"]
34
+ name = {"win32": "rdnext.dll", "darwin": "librdnext.dylib"}.get(sys.platform, "librdnext.so")
35
+ arch = {"x86_64": "x64", "amd64": "x64", "aarch64": "arm64", "arm64": "arm64", "i686": "x86", "x86": "x86"}.get(platform.machine().lower(), platform.machine().lower())
36
+ if sys.platform == "win32" and struct.calcsize("P") == 4:
37
+ arch = "x86" # 32-bit Python on 64-bit Windows still reports machine() == AMD64
38
+ here = Path(__file__).resolve().parent
39
+ for p in (here / "native" / f"{sys.platform}-{arch}" / name, here / "native" / name,
40
+ here.parent.parent.parent / "target" / "release" / name):
41
+ if p.exists():
42
+ return str(p)
43
+ return name # normal library search path
44
+
45
+
46
+ _lib = C.CDLL(_find_library())
47
+ _lib.rd_abi_version.restype = C.c_uint32
48
+ _lib.rd_version.restype = C.c_char_p
49
+ _lib.rd_engine_new.restype = C.c_void_p
50
+ _lib.rd_engine_free.argtypes = [C.c_void_p]
51
+ _lib.rd_add_font.argtypes = [C.c_void_p, C.c_char_p, C.c_size_t, C.c_char_p, C.POINTER(_Buf)]
52
+ _lib.rd_render.argtypes = [C.c_void_p, C.c_char_p, C.c_int, _DataCb, C.c_void_p, C.POINTER(_Buf)]
53
+ _lib.rd_features_used.argtypes = [C.c_char_p, C.c_char_p, C.POINTER(_Buf)]
54
+ _lib.rd_sink_write.argtypes = [C.c_void_p, C.c_char_p, C.c_size_t]
55
+ _lib.rd_buffer_free.argtypes = [C.POINTER(_Buf)]
56
+ if _lib.rd_abi_version() != _ABI:
57
+ raise ImportError(f"rdnext native library ABI {_lib.rd_abi_version()} does not match this package (expects {_ABI})")
58
+
59
+
60
+ def native_version() -> str:
61
+ return _lib.rd_version().decode()
62
+
63
+
64
+ def _take(buf: _Buf) -> bytes:
65
+ try:
66
+ return C.string_at(buf.data, buf.len) if buf.len else b""
67
+ finally:
68
+ _lib.rd_buffer_free(C.byref(buf))
69
+
70
+
71
+ def _check(rc: int, buf: _Buf) -> bytes:
72
+ data = _take(buf)
73
+ if rc != 0:
74
+ raise ReportError(data.decode("utf-8", "replace"))
75
+ return data
76
+
77
+
78
+ def _json_default(o: Any) -> Any:
79
+ if isinstance(o, _dt.datetime):
80
+ if o.tzinfo is not None:
81
+ o = o.astimezone(_dt.timezone.utc).replace(tzinfo=None)
82
+ return o.isoformat(timespec="milliseconds") + "Z"
83
+ if isinstance(o, _dt.date):
84
+ return o.isoformat() + "T00:00:00.000Z"
85
+ if hasattr(o, "__float__"): # Decimal, numpy scalars
86
+ return float(o)
87
+ if isinstance(o, (bytes, bytearray)):
88
+ import base64
89
+ return base64.b64encode(bytes(o)).decode()
90
+ return str(o)
91
+
92
+
93
+ def _dumps(o: Any) -> str:
94
+ return json.dumps(o, default=_json_default, ensure_ascii=False)
95
+
96
+
97
+ def features_used(report: Union[str, Mapping[str, Any]], tier: Optional[str] = None) -> Dict[str, Any]:
98
+ """`{"used": [...], "unlicensed": [{"feature", "tier"}]}` for a report definition (dict or JSON string)."""
99
+ out = _Buf()
100
+ rc = _lib.rd_features_used((report if isinstance(report, str) else _dumps(report)).encode(), tier.encode() if tier else None, C.byref(out))
101
+ return json.loads(_check(rc, out))
102
+
103
+
104
+ DataSource = Callable[[Dict[str, Any], Dict[str, Any]], List[Dict[str, Any]]]
105
+
106
+
107
+ class ReportEngine:
108
+ """
109
+ One per process; reuse it. Rendering is thread-safe (the GIL is released during the native call).
110
+
111
+ `data_source(ds, params) -> rows` supplies rows for sql/rest sources: `ds` is the source definition,
112
+ `params` the report parameters in effect (dates as ISO strings). Return a list of dicts or raise.
113
+ """
114
+
115
+ def __init__(self, data_source: Optional[DataSource] = None) -> None:
116
+ self._h = _lib.rd_engine_new()
117
+ self.data_source = data_source
118
+
119
+ def add_font(self, font_bytes: bytes, family: Optional[str] = None) -> None:
120
+ """Register a TrueType/OpenType font for embedding (Bengali, Arabic, ...)."""
121
+ out = _Buf()
122
+ _check(_lib.rd_add_font(self._handle(), font_bytes, len(font_bytes), family.encode() if family else None, C.byref(out)), out)
123
+
124
+ def render_html(self, report: Union[str, Mapping[str, Any]], **options: Any) -> str:
125
+ return self._render(report, 0, options).decode("utf-8")
126
+
127
+ def render_pdf(self, report: Union[str, Mapping[str, Any]], **options: Any) -> bytes:
128
+ return self._render(report, 1, options)
129
+
130
+ def render_xlsx(self, report: Union[str, Mapping[str, Any]], **options: Any) -> bytes:
131
+ """Excel workbook (.xlsx) bytes."""
132
+ return self._render(report, 2, options)
133
+
134
+ def render_docx(self, report: Union[str, Mapping[str, Any]], **options: Any) -> bytes:
135
+ """Word document (.docx) bytes."""
136
+ return self._render(report, 3, options)
137
+
138
+ def render(self, request: Mapping[str, Any], fmt: str = "html") -> Union[str, bytes]:
139
+ """Render a full request dict (`report`, `parameters`, `data`, `subreports`, `now`, `tier`, `grants`).
140
+ `fmt` is "html" (str) or "pdf", "xlsx", "docx" (bytes)."""
141
+ req = dict(request)
142
+ report = req.pop("report")
143
+ if fmt not in ("html", "pdf", "xlsx", "docx"):
144
+ raise ValueError(f"unknown format {fmt!r}")
145
+ return {"html": self.render_html, "pdf": self.render_pdf, "xlsx": self.render_xlsx, "docx": self.render_docx}[fmt](report, **req)
146
+
147
+ def close(self) -> None:
148
+ h, self._h = self._h, None
149
+ if h:
150
+ _lib.rd_engine_free(h)
151
+
152
+ def __enter__(self) -> "ReportEngine":
153
+ return self
154
+
155
+ def __exit__(self, *exc: Any) -> None:
156
+ self.close()
157
+
158
+ def __del__(self) -> None:
159
+ try:
160
+ self.close()
161
+ except Exception:
162
+ pass
163
+
164
+ def _handle(self) -> int:
165
+ if not self._h:
166
+ raise ReportError("engine is closed")
167
+ return self._h
168
+
169
+ def _render(self, report: Union[str, Mapping[str, Any]], fmt: int, options: Dict[str, Any]) -> bytes:
170
+ req: Dict[str, Any] = {"report": json.loads(report) if isinstance(report, str) else report}
171
+ for k in ("parameters", "data", "tier", "grants"):
172
+ if options.get(k) is not None:
173
+ req[k] = options[k]
174
+ if options.get("subreports"):
175
+ req["subreports"] = {k: json.loads(v) if isinstance(v, str) else v for k, v in options["subreports"].items()}
176
+ req["now"] = options.get("now") or _dt.datetime.now(_dt.timezone.utc)
177
+ provider = self.data_source
178
+
179
+ def on_data(_user, ds_json, params_json, sink): # never raise into native code
180
+ try:
181
+ rows = provider(json.loads(ds_json), json.loads(params_json)) # type: ignore[misc]
182
+ payload = _dumps(list(rows)).encode("utf-8")
183
+ _lib.rd_sink_write(sink, payload, len(payload))
184
+ return 0
185
+ except BaseException as e: # noqa: BLE001
186
+ msg = str(e).encode("utf-8", "replace")
187
+ _lib.rd_sink_write(sink, msg, len(msg))
188
+ return 1
189
+
190
+ cb = _DataCb(on_data) if provider else _DataCb() # a NULL function pointer when there is no provider
191
+ out = _Buf()
192
+ rc = _lib.rd_render(self._handle(), _dumps(req).encode("utf-8"), fmt, cb, None, C.byref(out))
193
+ return _check(rc, out)
reportdesigner/sql.py ADDED
@@ -0,0 +1,148 @@
1
+ """
2
+ Ready-made ``data_source`` for ``sql`` sources (any DB-API 2.0 driver: sqlite3, pyodbc, pymssql, ...).
3
+
4
+ from reportdesigner import ReportEngine, SqlProvider
5
+ sql = SqlProvider({"main": lambda: pyodbc.connect(CONN_STR)}) # factory: one connection per query
6
+ ReportEngine(data_source=sql)
7
+
8
+ The report's ``connection`` names a registry entry (empty -> the first one). ``@Name`` tokens in the
9
+ query are bound from the report parameters of the same name (missing -> NULL); quoted strings,
10
+ "identifiers", [identifiers] and comments are left alone.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ import sys
16
+ from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple, Union
17
+
18
+ __all__ = ["SqlProvider", "bind_named"]
19
+
20
+ _NAME_START = re.compile(r"[A-Za-z_]")
21
+ _WORD = re.compile(r"\w")
22
+
23
+
24
+ def bind_named(text: str, placeholder: Callable[[int, str], str] = lambda i, n: "?", escape_percent: bool = False) -> Tuple[str, List[str]]:
25
+ """Rewrite ``@Name`` (outside quotes/comments) with ``placeholder(index, name)``; returns (text, names in order)."""
26
+ names: List[str] = []
27
+ out: List[str] = []
28
+ i, n = 0, len(text)
29
+ while i < n:
30
+ c = text[i]
31
+ if c in "'\"`":
32
+ j = i + 1
33
+ while j < n:
34
+ if text[j] == c:
35
+ if j + 1 < n and text[j + 1] == c:
36
+ j += 2
37
+ continue
38
+ break
39
+ j += 1
40
+ seg = text[i:j + 1]
41
+ out.append(seg.replace("%", "%%") if escape_percent else seg)
42
+ i = j + 1
43
+ elif c == "[":
44
+ j = text.find("]", i)
45
+ e = n if j < 0 else j + 1
46
+ out.append(text[i:e])
47
+ i = e
48
+ elif c == "-" and text[i + 1:i + 2] == "-":
49
+ j = text.find("\n", i)
50
+ if j < 0:
51
+ j = n
52
+ out.append(text[i:j].replace("%", "%%") if escape_percent else text[i:j])
53
+ i = j
54
+ elif c == "/" and text[i + 1:i + 2] == "*":
55
+ j = text.find("*/", i + 2)
56
+ e = n if j < 0 else j + 2
57
+ out.append(text[i:e].replace("%", "%%") if escape_percent else text[i:e])
58
+ i = e
59
+ elif c == "@" and _NAME_START.match(text[i + 1:i + 2] or " ") and not (i > 0 and (text[i - 1] == "@" or _WORD.match(text[i - 1]))):
60
+ j = i + 1
61
+ while j < n and _WORD.match(text[j]):
62
+ j += 1
63
+ names.append(text[i + 1:j])
64
+ out.append(placeholder(len(names), names[-1]))
65
+ i = j
66
+ else:
67
+ out.append("%%" if escape_percent and c == "%" else c)
68
+ i += 1
69
+ return "".join(out), names
70
+
71
+
72
+ def _db_value(v: Any) -> Any:
73
+ if isinstance(v, bool):
74
+ return int(v)
75
+ if isinstance(v, (dict, list)):
76
+ import json
77
+ return json.dumps(v)
78
+ return v
79
+
80
+
81
+ Connect = Union[Callable[[], Any], Any]
82
+
83
+
84
+ class SqlProvider:
85
+ """``SqlProvider({"name": factory_or_connection, ...})`` — pass the instance as ``data_source``."""
86
+
87
+ def __init__(self, connections: Mapping[str, Connect], paramstyle: Optional[str] = None) -> None:
88
+ if not connections:
89
+ raise ValueError("SqlProvider needs at least one connection")
90
+ self._conns: Dict[str, Connect] = dict(connections)
91
+ self._paramstyle = paramstyle
92
+
93
+ @staticmethod
94
+ def _style(conn: Any, forced: Optional[str]) -> str:
95
+ if forced:
96
+ return forced
97
+ mod = sys.modules.get(type(conn).__module__.split(".")[0])
98
+ style = getattr(mod, "paramstyle", None)
99
+ if style is None:
100
+ # pyodbc / sqlite3 connection classes live in C modules that do expose paramstyle; default to qmark
101
+ style = "qmark"
102
+ return style
103
+
104
+ def __call__(self, ds: Dict[str, Any], params: Dict[str, Any]) -> List[Dict[str, Any]]:
105
+ if ds.get("type") != "sql":
106
+ raise ValueError('SqlProvider handles only "sql" sources, not "%s" (source "%s")' % (ds.get("type"), ds.get("name")))
107
+ key = ds.get("connection") or next(iter(self._conns))
108
+ if key not in self._conns:
109
+ raise ValueError('connection "%s" is not registered (source "%s"); registered: %s' % (key, ds.get("name"), ", ".join(self._conns)))
110
+ query = ds.get("query")
111
+ if not query:
112
+ raise ValueError('source "%s" has no query' % ds.get("name"))
113
+ entry = self._conns[key]
114
+ is_factory = callable(entry) and not hasattr(entry, "cursor")
115
+ conn = entry() if is_factory else entry
116
+ try:
117
+ style = self._style(conn, self._paramstyle)
118
+ ph = {
119
+ "qmark": lambda i, n: "?",
120
+ "numeric": lambda i, n: ":%d" % i,
121
+ "named": lambda i, n: ":p%d" % i,
122
+ "format": lambda i, n: "%s",
123
+ "pyformat": lambda i, n: "%%(p%d)s" % i,
124
+ }.get(style)
125
+ if ph is None:
126
+ raise ValueError("unsupported paramstyle: %s" % style)
127
+ text, names = bind_named(query, ph, escape_percent=style in ("format", "pyformat"))
128
+ values = [_db_value(params.get(nm)) for nm in names]
129
+ if style in ("named", "pyformat"):
130
+ args: Any = {"p%d" % (i + 1): v for i, v in enumerate(values)}
131
+ else:
132
+ args = values
133
+ cur = conn.cursor()
134
+ try:
135
+ cur.execute(text, args)
136
+ if cur.description is None:
137
+ return []
138
+ cols = [d[0] for d in cur.description]
139
+ return [dict(zip(cols, row)) for row in cur.fetchall()]
140
+ finally:
141
+ close = getattr(cur, "close", None)
142
+ if close:
143
+ close()
144
+ finally:
145
+ if is_factory:
146
+ close = getattr(conn, "close", None)
147
+ if close:
148
+ close()
@@ -0,0 +1,18 @@
1
+ Metadata-Version: 2.4
2
+ Name: reportdesigner
3
+ Version: 0.4.5
4
+ Summary: ReportDesigner engine for Python (Django, Flask, FastAPI, scripts): JSON report + data -> HTML/PDF. Native Rust core.
5
+ License: Apache-2.0
6
+ Requires-Python: >=3.8
7
+ Description-Content-Type: text/markdown
8
+
9
+ # reportdesigner (Python)
10
+
11
+ Render ReportDesigner reports to HTML, PDF, Excel and Word from Python. Native Rust engine, no other dependencies.
12
+
13
+ ```python
14
+ from reportdesigner import ReportEngine
15
+ pdf = ReportEngine().render_pdf(report, data={"orders": rows})
16
+ ```
17
+
18
+ Guide: https://github.com/arifulalam/ReportDesigner/blob/main/docs/python.md
@@ -0,0 +1,12 @@
1
+ reportdesigner/__init__.py,sha256=KGiSA5RWE4y7h2rzrOTuJaox8NzNn3A98j6KO3SMM18,7873
2
+ reportdesigner/sql.py,sha256=t4YdbOwTuP5P2hB29B9ZFapA1kB-M7YPMKM6n0A3q8U,5892
3
+ reportdesigner/native/darwin-arm64/librdnext.dylib,sha256=ZwupJ3whikBfUTgWL1yTgjTDdXfSBdwH5ldi9WW2STQ,4582176
4
+ reportdesigner/native/darwin-x64/librdnext.dylib,sha256=6X9xH1RObFo1m9A5KRBILm_AQ9EdHJFzZEB1gKV0fxw,4528424
5
+ reportdesigner/native/linux-arm64/librdnext.so,sha256=trKHpO79bcFql-s7Xqhh7rKVgArCR7UF5Jrau1ZL840,5216360
6
+ reportdesigner/native/linux-x64/librdnext.so,sha256=E_8fC_0FjRG1gGiAqsc2TsNiJTCHnmvntvceUYMQXmA,5419568
7
+ reportdesigner/native/win32-x64/rdnext.dll,sha256=Xyq7PDaEwyg5WOpRNkvf9XIgrkTqanqyLPvti0HZiQk,3561984
8
+ reportdesigner/native/win32-x86/rdnext.dll,sha256=dNTlCZa-GBnT5uSnFF5oNw1M17h4e7c1NosDLZd8CQc,2958848
9
+ reportdesigner-0.4.5.dist-info/METADATA,sha256=yoT1dWTS4SBy2eHmg_yMtfbOmYsxKbfGTSZ8903sSTQ,607
10
+ reportdesigner-0.4.5.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
11
+ reportdesigner-0.4.5.dist-info/top_level.txt,sha256=3OvzrJB2SAGuMpNAR0vej6Rcr2s0IptmN9zHVEDCuH8,15
12
+ reportdesigner-0.4.5.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ reportdesigner