sqldump 2.1.1__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.
sqldump-2.1.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 pushion
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
sqldump-2.1.1/PKG-INFO ADDED
@@ -0,0 +1,142 @@
1
+ Metadata-Version: 2.4
2
+ Name: sqldump
3
+ Version: 2.1.1
4
+ Summary: Parse any SQLite database into plain Python dicts
5
+ Author-email: pushion <pushion@gmail.com>
6
+ License: MIT
7
+ Keywords: sqlite,database,parse,dict,dump,json,export
8
+ Classifier: Development Status :: 5 - Production/Stable
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.8
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Database
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.8
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: dumpb
25
+ Dynamic: license-file
26
+
27
+ Parse any SQLite database into plain Python dicts `table::rows` maps or fully detailed schema/rows/stats output.
28
+
29
+
30
+ ## Features
31
+
32
+ - Two output modes: flat dict keyed by table name, or full detail with schema, stats, views, and indexes
33
+ - Plain dicts: no result objects to unwrap; output is JSON-ready (BLOBs stringified safely by `json.dumps(..., default=str)`)
34
+ - Option passthrough: every `dumpb` engine option (`tables`, `row_limit`, `strict_mode`, …) works directly on `parse()`
35
+ - Strict validation: unknown options and bad option types raise immediately with the list of valid keys
36
+ - Typed: ships `py.typed`; fully annotated API
37
+ - Single-table helper: `parse_table()` for one-table extracts
38
+
39
+ ## Installation
40
+
41
+ ```bash
42
+ pip install sqldump
43
+ ```
44
+
45
+ Requires Python 3.8+.
46
+
47
+ ## Quickstart
48
+
49
+ ```python
50
+ import sqldump
51
+
52
+ # Flat mode (default): table name -> list of row dicts
53
+ data = sqldump.parse("app.db")
54
+ data["users"] # [{'id': 1, 'name': 'alice', 'score': 9.5}, ...]
55
+ data["orders"] # [{'id': 1, 'user_id': 1, 'total': 42.0}, ...]
56
+ ```
57
+
58
+ ### Detail mode
59
+
60
+ ```python
61
+ data = sqldump.parse("app.db", detail=True)
62
+ data["database"] # 'app.db'
63
+ data["stats"] # {'tables': 3, 'rows': 128, 'views': 1, 'indexes': 2}
64
+ data["views"] # ['user_emails']
65
+ data["indexes"] # ['idx_users_name']
66
+ data["errors"] # non-fatal issues collected during the parse
67
+
68
+ data["tables"]["users"]
69
+ # {'schema': 'CREATE TABLE users (...)', 'rows': [...],
70
+ # 'row_count': 3, 'truncated': False}
71
+ ```
72
+
73
+ ### Single table
74
+
75
+ ```python
76
+ sqldump.parse_table("app.db", "users")
77
+ # {'schema': ..., 'rows': [...], 'row_count': 3, 'truncated': False}
78
+ ```
79
+
80
+ Raises `sqldump.ParseError` if the table does not exist.
81
+
82
+ ### Options passthrough
83
+
84
+ ```python
85
+ sqldump.parse("app.db", tables=["users", "orders"], row_limit=100, strict_mode=True)
86
+ ```
87
+
88
+ All `dumpb` engine keys are accepted (everything in `dumpb.DEFAULT_CONFIG`
89
+ except `tables`, which is `parse()`'s own keyword).
90
+
91
+ ## Error handling
92
+
93
+ ```
94
+ SqldumpError # base error: unknown options, bad values, bad paths
95
+ └── ParseError # dump/parse failures (wraps dumpb.DumpbError),
96
+ # missing tables, strict-mode issues
97
+ ```
98
+
99
+ ```python
100
+ import sqldump
101
+ from sqldump import SqldumpError, ParseError
102
+
103
+ try:
104
+ data = sqldump.parse("missing.db")
105
+ except ParseError as exc:
106
+ print("parse failed:", exc)
107
+
108
+ try:
109
+ sqldump.parse("app.db", bogus=1)
110
+ except SqldumpError as exc:
111
+ print(exc) # unknown parse option 'bogus': valid options are ...
112
+ ```
113
+
114
+ ## Behavior notes
115
+
116
+ - Internal `sqlite_*` objects (`sqlite_sequence`, autoindexes, …) are excluded.
117
+ - Views and indexes appear only in detail mode as name lists.
118
+ - `tables=[]` (empty list) parses no tables; `None` (default) parses all.
119
+ - Missing tables under `tables=[...]` are recorded in `detail['errors']`
120
+ (flat mode silently skips them) unless `strict_mode=True`.
121
+ - The `bytes` values of BLOB columns are preserved in dicts; use
122
+ `json.dumps(data, default=str)` for JSON serialization.
123
+
124
+ ## API reference
125
+
126
+ | API | Description |
127
+ |------------------------------------|--------------------------------------------------|
128
+ | `parse(db, detail=False, tables=None, **options)` | Database as dict (flat or detail) |
129
+ | `parse_table(db, name, **options)` | Single table as dict |
130
+ | `DEFAULT_OPTIONS` | Default engine options (mirrors `dumpb.DEFAULT_CONFIG` minus `tables`) |
131
+ | `SqldumpError` | Base error |
132
+ | `ParseError` | Parse failures, missing tables |
133
+
134
+ | Module | Exports |
135
+ |-------------------|---------------------------------------------|
136
+ | `sqldump` | `parse`, `parse_table`, `SqldumpError`, `ParseError`, `DEFAULT_OPTIONS` |
137
+ | `sqldump.parser` | `parse`, `parse_table`, `DEFAULT_OPTIONS` |
138
+ | `sqldump.errors` | `SqldumpError`, `ParseError` |
139
+
140
+ ## License
141
+
142
+ [MIT](https://example.com/sqldump/blob/main/LICENSE)
@@ -0,0 +1,116 @@
1
+ Parse any SQLite database into plain Python dicts `table::rows` maps or fully detailed schema/rows/stats output.
2
+
3
+
4
+ ## Features
5
+
6
+ - Two output modes: flat dict keyed by table name, or full detail with schema, stats, views, and indexes
7
+ - Plain dicts: no result objects to unwrap; output is JSON-ready (BLOBs stringified safely by `json.dumps(..., default=str)`)
8
+ - Option passthrough: every `dumpb` engine option (`tables`, `row_limit`, `strict_mode`, …) works directly on `parse()`
9
+ - Strict validation: unknown options and bad option types raise immediately with the list of valid keys
10
+ - Typed: ships `py.typed`; fully annotated API
11
+ - Single-table helper: `parse_table()` for one-table extracts
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ pip install sqldump
17
+ ```
18
+
19
+ Requires Python 3.8+.
20
+
21
+ ## Quickstart
22
+
23
+ ```python
24
+ import sqldump
25
+
26
+ # Flat mode (default): table name -> list of row dicts
27
+ data = sqldump.parse("app.db")
28
+ data["users"] # [{'id': 1, 'name': 'alice', 'score': 9.5}, ...]
29
+ data["orders"] # [{'id': 1, 'user_id': 1, 'total': 42.0}, ...]
30
+ ```
31
+
32
+ ### Detail mode
33
+
34
+ ```python
35
+ data = sqldump.parse("app.db", detail=True)
36
+ data["database"] # 'app.db'
37
+ data["stats"] # {'tables': 3, 'rows': 128, 'views': 1, 'indexes': 2}
38
+ data["views"] # ['user_emails']
39
+ data["indexes"] # ['idx_users_name']
40
+ data["errors"] # non-fatal issues collected during the parse
41
+
42
+ data["tables"]["users"]
43
+ # {'schema': 'CREATE TABLE users (...)', 'rows': [...],
44
+ # 'row_count': 3, 'truncated': False}
45
+ ```
46
+
47
+ ### Single table
48
+
49
+ ```python
50
+ sqldump.parse_table("app.db", "users")
51
+ # {'schema': ..., 'rows': [...], 'row_count': 3, 'truncated': False}
52
+ ```
53
+
54
+ Raises `sqldump.ParseError` if the table does not exist.
55
+
56
+ ### Options passthrough
57
+
58
+ ```python
59
+ sqldump.parse("app.db", tables=["users", "orders"], row_limit=100, strict_mode=True)
60
+ ```
61
+
62
+ All `dumpb` engine keys are accepted (everything in `dumpb.DEFAULT_CONFIG`
63
+ except `tables`, which is `parse()`'s own keyword).
64
+
65
+ ## Error handling
66
+
67
+ ```
68
+ SqldumpError # base error: unknown options, bad values, bad paths
69
+ └── ParseError # dump/parse failures (wraps dumpb.DumpbError),
70
+ # missing tables, strict-mode issues
71
+ ```
72
+
73
+ ```python
74
+ import sqldump
75
+ from sqldump import SqldumpError, ParseError
76
+
77
+ try:
78
+ data = sqldump.parse("missing.db")
79
+ except ParseError as exc:
80
+ print("parse failed:", exc)
81
+
82
+ try:
83
+ sqldump.parse("app.db", bogus=1)
84
+ except SqldumpError as exc:
85
+ print(exc) # unknown parse option 'bogus': valid options are ...
86
+ ```
87
+
88
+ ## Behavior notes
89
+
90
+ - Internal `sqlite_*` objects (`sqlite_sequence`, autoindexes, …) are excluded.
91
+ - Views and indexes appear only in detail mode as name lists.
92
+ - `tables=[]` (empty list) parses no tables; `None` (default) parses all.
93
+ - Missing tables under `tables=[...]` are recorded in `detail['errors']`
94
+ (flat mode silently skips them) unless `strict_mode=True`.
95
+ - The `bytes` values of BLOB columns are preserved in dicts; use
96
+ `json.dumps(data, default=str)` for JSON serialization.
97
+
98
+ ## API reference
99
+
100
+ | API | Description |
101
+ |------------------------------------|--------------------------------------------------|
102
+ | `parse(db, detail=False, tables=None, **options)` | Database as dict (flat or detail) |
103
+ | `parse_table(db, name, **options)` | Single table as dict |
104
+ | `DEFAULT_OPTIONS` | Default engine options (mirrors `dumpb.DEFAULT_CONFIG` minus `tables`) |
105
+ | `SqldumpError` | Base error |
106
+ | `ParseError` | Parse failures, missing tables |
107
+
108
+ | Module | Exports |
109
+ |-------------------|---------------------------------------------|
110
+ | `sqldump` | `parse`, `parse_table`, `SqldumpError`, `ParseError`, `DEFAULT_OPTIONS` |
111
+ | `sqldump.parser` | `parse`, `parse_table`, `DEFAULT_OPTIONS` |
112
+ | `sqldump.errors` | `SqldumpError`, `ParseError` |
113
+
114
+ ## License
115
+
116
+ [MIT](https://example.com/sqldump/blob/main/LICENSE)
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "sqldump"
7
+ version = "2.1.1"
8
+ description = "Parse any SQLite database into plain Python dicts"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = { text = "MIT" }
12
+ authors = [
13
+ { name = "pushion", email = "pushion@gmail.com" },
14
+ ]
15
+ keywords = ["sqlite", "database", "parse", "dict", "dump", "json", "export"]
16
+ classifiers = [
17
+ "Development Status :: 5 - Production/Stable",
18
+ "Intended Audience :: Developers",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.8",
22
+ "Programming Language :: Python :: 3.9",
23
+ "Programming Language :: Python :: 3.10",
24
+ "Programming Language :: Python :: 3.11",
25
+ "Programming Language :: Python :: 3.12",
26
+ "Programming Language :: Python :: 3.13",
27
+ "Topic :: Database",
28
+ "Topic :: Software Development :: Libraries :: Python Modules",
29
+ "Typing :: Typed",
30
+ ]
31
+ dependencies = [
32
+ "dumpb",
33
+ ]
34
+
35
+ [tool.setuptools]
36
+ packages = ["sqldump"]
37
+
38
+ [tool.setuptools.package-data]
39
+ sqldump = ["py.typed", "*.tpl"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,48 @@
1
+ """sqldump: parse SQLite databases into plain Python dicts.
2
+
3
+ Backed by the dumpb package; adds a dict-first API with flat and detail
4
+ modes on top of dumpb's dumping engine, JSON export, and a config-file
5
+ flow (dumpb's schema.tpl) with a lazy default engine.
6
+ """
7
+
8
+ from dumpb import (
9
+ Config,
10
+ find_default_config,
11
+ load_config,
12
+ save_config,
13
+ )
14
+ from dumpb.settings import CONFIG_NAME, PathLike
15
+
16
+ from .engine import get_config, get_engine, get_load_error, reload
17
+ from .errors import (
18
+ ConfigChecksumError,
19
+ ConfigDecompressError,
20
+ ConfigLoadError,
21
+ ParseError,
22
+ SqldumpError,
23
+ )
24
+ from .jsonio import dump_json, to_json
25
+ from .parser import DEFAULT_OPTIONS, parse, parse_table
26
+
27
+ __all__ = [
28
+ 'parse',
29
+ 'parse_table',
30
+ 'dump_json',
31
+ 'to_json',
32
+ 'SqldumpError',
33
+ 'ParseError',
34
+ 'ConfigLoadError',
35
+ 'ConfigChecksumError',
36
+ 'ConfigDecompressError',
37
+ 'DEFAULT_OPTIONS',
38
+ 'CONFIG_NAME',
39
+ 'PathLike',
40
+ 'Config',
41
+ 'load_config',
42
+ 'save_config',
43
+ 'find_default_config',
44
+ 'get_config',
45
+ 'get_engine',
46
+ 'get_load_error',
47
+ 'reload'
48
+ ]
@@ -0,0 +1,74 @@
1
+ """Config-driven wiring: sqldump's dump engine over dumpb's settings."""
2
+
3
+ from typing import Any, Dict, Optional
4
+
5
+ from dumpb import DumpEngine
6
+ from dumpb.errors import ConfigLoadError as _DumpbConfigLoadError
7
+ from dumpb.settings import PathLike, load_config
8
+
9
+ from .errors import ConfigLoadError
10
+
11
+ config: Dict[str, Any] = {}
12
+ _engine: Optional[DumpEngine] = None
13
+ _load_error: Optional[Exception] = None
14
+
15
+
16
+ def _engine_config(settings: Dict[str, Any]) -> Dict[str, Any]:
17
+ """Engine settings without 'tables'; parse() always passes tables itself."""
18
+ return {key: value for key, value in settings.items() if key != 'tables'}
19
+
20
+
21
+ def _ensure() -> None:
22
+ global config, _engine, _load_error
23
+ if _engine is not None:
24
+ return
25
+ try:
26
+ loaded = load_config()
27
+ except _DumpbConfigLoadError as exc:
28
+ _load_error = exc
29
+ loaded = None
30
+ config = _engine_config(loaded.to_dict() if loaded is not None else {})
31
+ _engine = DumpEngine(config, use_cache=False)
32
+
33
+ _ensure()
34
+
35
+
36
+ def get_config() -> Dict[str, Any]:
37
+ """Return the active configuration dict (lazy-loaded)."""
38
+ return config
39
+
40
+
41
+ def get_engine() -> DumpEngine:
42
+ """Return the active dump engine built from schema.tpl."""
43
+ return _engine
44
+
45
+
46
+ def get_load_error() -> Optional[Exception]:
47
+ """Return the error that silenced the initial config load, if any."""
48
+ return _load_error
49
+
50
+
51
+ def reload(path: Optional[PathLike] = None) -> Dict[str, Any]:
52
+ """Load (or reload) a config and rebuild the active engine.
53
+
54
+ No path reloads the caller's schema.tpl; a path adopts that file.
55
+ Raises ConfigLoadError for a missing, invalid, or unsafe file.
56
+ """
57
+ global config, _engine, _load_error
58
+ try:
59
+ cfg = load_config(path)
60
+ except _DumpbConfigLoadError as exc:
61
+ raise ConfigLoadError(str(exc)) from exc
62
+ config = _engine_config(cfg.to_dict())
63
+ _engine = DumpEngine(config, use_cache=False)
64
+ _load_error = None
65
+ return config
66
+
67
+
68
+ __all__ = [
69
+ 'config',
70
+ 'get_config',
71
+ 'get_engine',
72
+ 'get_load_error',
73
+ 'reload',
74
+ ]
@@ -0,0 +1,72 @@
1
+ """Error types for the sqldump SQLite-to-dict parser."""
2
+
3
+ from typing import Any
4
+
5
+ import dumpb
6
+
7
+
8
+ class SqldumpError(Exception):
9
+ """Base error for all sqldump failures."""
10
+
11
+
12
+ class ParseError(SqldumpError):
13
+ """Parsing a SQLite database failed (wraps dumpb.DumpbError)."""
14
+
15
+
16
+ class ConfigLoadError(SqldumpError):
17
+ """Config file missing, unreadable, malformed, unsafe, or not discoverable."""
18
+
19
+
20
+ class ConfigChecksumError(ConfigLoadError):
21
+ """Config payload does not match its stored checksum."""
22
+
23
+
24
+ class ConfigDecompressError(ConfigLoadError):
25
+ """Compressed config payload could not be decompressed."""
26
+
27
+
28
+ VALID_OPTIONS = tuple(sorted(k for k in dumpb.DEFAULT_CONFIG if k != 'tables'))
29
+
30
+
31
+ def unknown_option_error(name: str) -> SqldumpError:
32
+ return SqldumpError(
33
+ "unknown parse option '{}': valid options are {}".format(
34
+ name, ', '.join(VALID_OPTIONS)
35
+ )
36
+ )
37
+
38
+
39
+ def invalid_option_error(name: str, value: Any, expected: str) -> SqldumpError:
40
+ return SqldumpError(
41
+ "invalid value for parse option '{}': expected {}; got {!r}".format(
42
+ name, expected, value
43
+ )
44
+ )
45
+
46
+
47
+ def tables_type_error(tables: Any) -> SqldumpError:
48
+ return SqldumpError(
49
+ 'tables must be None or an iterable of table names; got {!r}'.format(
50
+ tables
51
+ )
52
+ )
53
+
54
+
55
+ def wrap_dumpb_error(exc: Exception, database: Any) -> ParseError:
56
+ if isinstance(exc, dumpb.DumpbError):
57
+ return ParseError(str(exc))
58
+ return ParseError("failed to parse database {!r}: {}".format(database, exc))
59
+
60
+
61
+ __all__ = [
62
+ 'SqldumpError',
63
+ 'ParseError',
64
+ 'ConfigLoadError',
65
+ 'ConfigChecksumError',
66
+ 'ConfigDecompressError',
67
+ 'VALID_OPTIONS',
68
+ 'unknown_option_error',
69
+ 'invalid_option_error',
70
+ 'tables_type_error',
71
+ 'wrap_dumpb_error',
72
+ ]
@@ -0,0 +1,61 @@
1
+ """JSON export: write parse results to JSON files safely and atomically."""
2
+
3
+ import base64
4
+ import json
5
+ import os
6
+ import tempfile
7
+ from pathlib import Path
8
+ from typing import Any, Dict, Iterable, Optional, Union
9
+
10
+ from .parser import parse
11
+
12
+ PathLike = Union[str, os.PathLike]
13
+
14
+
15
+ def dump_json(database: Union[str, 'os.PathLike'],
16
+ path: PathLike,
17
+ detail: bool = False,
18
+ tables: Optional[Iterable[str]] = None,
19
+ indent: Optional[int] = 2,
20
+ **options: Any) -> Path:
21
+ """Parse a SQLite database and write the result to path as JSON.
22
+
23
+ Accepts the same options as parse(); BLOBs are base64-encoded.
24
+ Returns the written path.
25
+ """
26
+ data = parse(database, detail=detail, tables=tables, **options)
27
+ return to_json(data, path, indent=indent)
28
+
29
+
30
+ def to_json(data: Dict[str, Any], path: PathLike,
31
+ indent: Optional[int] = 2) -> Path:
32
+ """Write an already-parsed sqldump dict to path as JSON atomically."""
33
+ text = json.dumps(data, indent=indent, default=_json_default)
34
+ target = Path(path)
35
+ parent = target.parent if str(target.parent) else Path('.')
36
+ if not parent.exists():
37
+ parent.mkdir(parents=True, exist_ok=True)
38
+ fd, tmp_name = tempfile.mkstemp(dir=str(parent), suffix='.json.tmp')
39
+ try:
40
+ with os.fdopen(fd, 'w', encoding='utf-8') as handle:
41
+ handle.write(text)
42
+ os.replace(tmp_name, str(target))
43
+ except Exception:
44
+ try:
45
+ os.unlink(tmp_name)
46
+ except OSError:
47
+ pass
48
+ raise
49
+ return target
50
+
51
+
52
+ def _json_default(value: Any) -> str:
53
+ if isinstance(value, bytes):
54
+ return base64.b64encode(value).decode('ascii')
55
+ return str(value)
56
+
57
+
58
+ __all__ = [
59
+ 'dump_json',
60
+ 'to_json',
61
+ ]
@@ -0,0 +1,154 @@
1
+ """Parse SQLite databases into plain Python dicts, backed by dumpb."""
2
+
3
+ import sqlite3
4
+ from typing import Any, Dict, Iterable, List, Optional, Union
5
+
6
+ import dumpb
7
+ from dumpb import DumpEngine, DumpResult
8
+
9
+ from .engine import get_config
10
+ from .errors import (
11
+ ParseError,
12
+ SqldumpError,
13
+ invalid_option_error,
14
+ tables_type_error,
15
+ unknown_option_error,
16
+ wrap_dumpb_error,
17
+ )
18
+
19
+ DEFAULT_OPTIONS: Dict[str, Any] = {
20
+ key: value for key, value in dumpb.DEFAULT_CONFIG.items() if key != 'tables'
21
+ }
22
+
23
+ def parse(database: Union[str, 'os.PathLike'],
24
+ detail: bool = False,
25
+ tables: Optional[Iterable[str]] = None,
26
+ **options: Any) -> Dict[str, Any]:
27
+ """Parse a SQLite database into a plain Python dict.
28
+
29
+ Flat mode (default): ``{'users': [row, ...], 'orders': [row, ...]}``
30
+ Detail mode: metadata plus per-table schema/rows/row_count.
31
+ """
32
+ engine, effective_tables = _engine_for(database, tables, options)
33
+ result = _dump(engine, database, effective_tables)
34
+ if detail:
35
+ return _detail_dict(result)
36
+ return _flat_dict(result)
37
+
38
+
39
+ def parse_table(database: Union[str, 'os.PathLike'],
40
+ name: str,
41
+ **options: Any) -> Dict[str, Any]:
42
+ """Parse a single table into ``{'schema', 'rows', 'row_count', 'truncated'}``."""
43
+ if not isinstance(name, str) or not name:
44
+ raise SqldumpError('table name must be a non-empty string')
45
+ engine, _ = _engine_for(database, None, options)
46
+ result = _dump(engine, database, [name])
47
+ table = result.get_table(name)
48
+ if table is None:
49
+ raise ParseError("table '{}' not found in database {!r}".format(
50
+ name, database
51
+ ))
52
+ return _table_dict(table)
53
+
54
+
55
+ def _engine_for(database: Union[str, 'os.PathLike'],
56
+ tables: Optional[Iterable[str]],
57
+ options: Dict[str, Any]) -> Any:
58
+ if not isinstance(database, (str, bytes)):
59
+ import os
60
+ if not isinstance(database, os.PathLike):
61
+ raise SqldumpError(
62
+ 'database must be a path-like string; got {!r}'.format(database)
63
+ )
64
+ effective_tables = _normalize_tables(tables)
65
+ config = dict(DEFAULT_OPTIONS)
66
+ config.update(get_config())
67
+ for key, value in options.items():
68
+ if key not in DEFAULT_OPTIONS:
69
+ raise unknown_option_error(key)
70
+ config[key] = value
71
+ _validate_config(config)
72
+ if effective_tables is not None:
73
+ config['tables'] = effective_tables
74
+ return DumpEngine(config, use_cache=False), effective_tables
75
+
76
+
77
+ def _normalize_tables(tables: Optional[Iterable[str]]) -> Optional[List[str]]:
78
+ if tables is None:
79
+ return None
80
+ if isinstance(tables, str) or not isinstance(tables, Iterable):
81
+ raise tables_type_error(tables)
82
+ normalized: List[str] = []
83
+ for name in tables:
84
+ if not isinstance(name, str) or not name:
85
+ raise tables_type_error(tables)
86
+ if name not in normalized:
87
+ normalized.append(name)
88
+ return normalized
89
+
90
+
91
+ def _validate_config(config: Dict[str, Any]) -> None:
92
+ for bool_key in ('include_schema', 'read_only', 'detect_types', 'strict_mode'):
93
+ if not isinstance(config[bool_key], bool):
94
+ raise invalid_option_error(bool_key, config[bool_key], 'a bool')
95
+ for int_key in ('cache_size',):
96
+ if not isinstance(config[int_key], int) or isinstance(config[int_key], bool):
97
+ raise invalid_option_error(int_key, config[int_key], 'an int')
98
+ row_limit = config['row_limit']
99
+ if row_limit is not None and (
100
+ not isinstance(row_limit, int) or isinstance(row_limit, bool)
101
+ ):
102
+ raise invalid_option_error('row_limit', row_limit, 'an int or None')
103
+ max_size = config['max_file_size_mb']
104
+ if max_size is not None:
105
+ if isinstance(max_size, bool) or not isinstance(max_size, (int, float)):
106
+ raise invalid_option_error(
107
+ 'max_file_size_mb', max_size, 'a number or None'
108
+ )
109
+
110
+
111
+ def _dump(engine: DumpEngine,
112
+ database: Union[str, 'os.PathLike'],
113
+ tables: Optional[List[str]]) -> DumpResult:
114
+ try:
115
+ return engine.dump(database, tables=tables)
116
+ except dumpb.DumpbError as exc:
117
+ raise wrap_dumpb_error(exc, database) from exc
118
+ except sqlite3.Error as exc:
119
+ raise ParseError(
120
+ "failed to parse database {!r}: {}".format(database, exc)
121
+ ) from exc
122
+
123
+
124
+ def _flat_dict(result: DumpResult) -> Dict[str, Any]:
125
+ return {table.name: list(table.rows) for table in result.tables}
126
+
127
+
128
+ def _detail_dict(result: DumpResult) -> Dict[str, Any]:
129
+ return {
130
+ 'database': result.database,
131
+ 'stats': result.stats(),
132
+ 'views': list(result.views),
133
+ 'indexes': list(result.indexes),
134
+ 'tables': {table.name: _table_dict(table) for table in result.tables},
135
+ 'errors': list(result.errors),
136
+ }
137
+
138
+
139
+ def _table_dict(table: 'dumpb.TableDump') -> Dict[str, Any]:
140
+ return {
141
+ 'schema': table.schema,
142
+ 'rows': list(table.rows),
143
+ 'row_count': table.row_count,
144
+ 'truncated': table.truncated,
145
+ }
146
+
147
+
148
+ __all__ = [
149
+ 'DEFAULT_OPTIONS',
150
+ 'parse',
151
+ 'parse_table',
152
+ 'SqldumpError',
153
+ 'ParseError',
154
+ ]
File without changes
Binary file
@@ -0,0 +1,142 @@
1
+ Metadata-Version: 2.4
2
+ Name: sqldump
3
+ Version: 2.1.1
4
+ Summary: Parse any SQLite database into plain Python dicts
5
+ Author-email: pushion <pushion@gmail.com>
6
+ License: MIT
7
+ Keywords: sqlite,database,parse,dict,dump,json,export
8
+ Classifier: Development Status :: 5 - Production/Stable
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.8
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Database
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.8
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: dumpb
25
+ Dynamic: license-file
26
+
27
+ Parse any SQLite database into plain Python dicts `table::rows` maps or fully detailed schema/rows/stats output.
28
+
29
+
30
+ ## Features
31
+
32
+ - Two output modes: flat dict keyed by table name, or full detail with schema, stats, views, and indexes
33
+ - Plain dicts: no result objects to unwrap; output is JSON-ready (BLOBs stringified safely by `json.dumps(..., default=str)`)
34
+ - Option passthrough: every `dumpb` engine option (`tables`, `row_limit`, `strict_mode`, …) works directly on `parse()`
35
+ - Strict validation: unknown options and bad option types raise immediately with the list of valid keys
36
+ - Typed: ships `py.typed`; fully annotated API
37
+ - Single-table helper: `parse_table()` for one-table extracts
38
+
39
+ ## Installation
40
+
41
+ ```bash
42
+ pip install sqldump
43
+ ```
44
+
45
+ Requires Python 3.8+.
46
+
47
+ ## Quickstart
48
+
49
+ ```python
50
+ import sqldump
51
+
52
+ # Flat mode (default): table name -> list of row dicts
53
+ data = sqldump.parse("app.db")
54
+ data["users"] # [{'id': 1, 'name': 'alice', 'score': 9.5}, ...]
55
+ data["orders"] # [{'id': 1, 'user_id': 1, 'total': 42.0}, ...]
56
+ ```
57
+
58
+ ### Detail mode
59
+
60
+ ```python
61
+ data = sqldump.parse("app.db", detail=True)
62
+ data["database"] # 'app.db'
63
+ data["stats"] # {'tables': 3, 'rows': 128, 'views': 1, 'indexes': 2}
64
+ data["views"] # ['user_emails']
65
+ data["indexes"] # ['idx_users_name']
66
+ data["errors"] # non-fatal issues collected during the parse
67
+
68
+ data["tables"]["users"]
69
+ # {'schema': 'CREATE TABLE users (...)', 'rows': [...],
70
+ # 'row_count': 3, 'truncated': False}
71
+ ```
72
+
73
+ ### Single table
74
+
75
+ ```python
76
+ sqldump.parse_table("app.db", "users")
77
+ # {'schema': ..., 'rows': [...], 'row_count': 3, 'truncated': False}
78
+ ```
79
+
80
+ Raises `sqldump.ParseError` if the table does not exist.
81
+
82
+ ### Options passthrough
83
+
84
+ ```python
85
+ sqldump.parse("app.db", tables=["users", "orders"], row_limit=100, strict_mode=True)
86
+ ```
87
+
88
+ All `dumpb` engine keys are accepted (everything in `dumpb.DEFAULT_CONFIG`
89
+ except `tables`, which is `parse()`'s own keyword).
90
+
91
+ ## Error handling
92
+
93
+ ```
94
+ SqldumpError # base error: unknown options, bad values, bad paths
95
+ └── ParseError # dump/parse failures (wraps dumpb.DumpbError),
96
+ # missing tables, strict-mode issues
97
+ ```
98
+
99
+ ```python
100
+ import sqldump
101
+ from sqldump import SqldumpError, ParseError
102
+
103
+ try:
104
+ data = sqldump.parse("missing.db")
105
+ except ParseError as exc:
106
+ print("parse failed:", exc)
107
+
108
+ try:
109
+ sqldump.parse("app.db", bogus=1)
110
+ except SqldumpError as exc:
111
+ print(exc) # unknown parse option 'bogus': valid options are ...
112
+ ```
113
+
114
+ ## Behavior notes
115
+
116
+ - Internal `sqlite_*` objects (`sqlite_sequence`, autoindexes, …) are excluded.
117
+ - Views and indexes appear only in detail mode as name lists.
118
+ - `tables=[]` (empty list) parses no tables; `None` (default) parses all.
119
+ - Missing tables under `tables=[...]` are recorded in `detail['errors']`
120
+ (flat mode silently skips them) unless `strict_mode=True`.
121
+ - The `bytes` values of BLOB columns are preserved in dicts; use
122
+ `json.dumps(data, default=str)` for JSON serialization.
123
+
124
+ ## API reference
125
+
126
+ | API | Description |
127
+ |------------------------------------|--------------------------------------------------|
128
+ | `parse(db, detail=False, tables=None, **options)` | Database as dict (flat or detail) |
129
+ | `parse_table(db, name, **options)` | Single table as dict |
130
+ | `DEFAULT_OPTIONS` | Default engine options (mirrors `dumpb.DEFAULT_CONFIG` minus `tables`) |
131
+ | `SqldumpError` | Base error |
132
+ | `ParseError` | Parse failures, missing tables |
133
+
134
+ | Module | Exports |
135
+ |-------------------|---------------------------------------------|
136
+ | `sqldump` | `parse`, `parse_table`, `SqldumpError`, `ParseError`, `DEFAULT_OPTIONS` |
137
+ | `sqldump.parser` | `parse`, `parse_table`, `DEFAULT_OPTIONS` |
138
+ | `sqldump.errors` | `SqldumpError`, `ParseError` |
139
+
140
+ ## License
141
+
142
+ [MIT](https://example.com/sqldump/blob/main/LICENSE)
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ sqldump/__init__.py
5
+ sqldump/engine.py
6
+ sqldump/errors.py
7
+ sqldump/jsonio.py
8
+ sqldump/parser.py
9
+ sqldump/py.typed
10
+ sqldump/schema.tpl
11
+ sqldump.egg-info/PKG-INFO
12
+ sqldump.egg-info/SOURCES.txt
13
+ sqldump.egg-info/dependency_links.txt
14
+ sqldump.egg-info/requires.txt
15
+ sqldump.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ dumpb
@@ -0,0 +1 @@
1
+ sqldump