Metadata-Version: 2.4
Name: dumpb
Version: 0.0.3
Summary: Pure-stdlib SQLite database dumper
Author-email: robelta <robelta@Indiantech.com>
License: MIT
Keywords: sqlite,database,dump,json,backup,export
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Database
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

SQLite database dumper, dump any SQLite database into JSON-ready Python objects with schema introspection, caching, and a checksummed binary config system.

## Features

- **Full dumps + table filters**: dump everything, or restrict to specific tables.
- **JSON-ready output**: `to_dict()`, `to_json()`, and atomic `save()` to file.
- **Schema introspection**: `CREATE` statements, view names, and index names captured.
- **Smart caching**: LRU cache invalidated automatically when the database file changes (mtime/size) or the table filter differs.
- **Safety limits**: row limits with truncation flags, database size guards, optional strict mode.
- **Binary config files**: sha256-checksummed, tamper-detecting, optionally bz2/lzma/zlib-compressed.
- **Zero dependencies**: pure Python standard library (`sqlite3`, `json`, `hashlib`, `pickle`, `bz2`, `lzma`, `zlib`)

## Installation

```bash
pip install dumpb
```

Requires Python 3.8+. No third-party dependencies.

## Quickstart

```python
import dumpb

# Dump the whole database
result = dumpb.dump("app.db")

print(result.stats())
# {'tables': 3, 'rows': 128, 'views': 1, 'indexes': 2}

users = result.get_table("users")
print(users.schema)      # 'CREATE TABLE users (...)' as stored in sqlite_master
print(users.rows)        # [{'id': 1, 'name': 'alice', 'score': 9.5}, ...]
print(users.row_count)   # 3

# Persist as pretty-printed JSON (written atomically)
result.save("dump.json", indent=2)
```

### Filtered dumps

```python
result = dumpb.dump("app.db", tables=["users", "orders"])
result.tables        # [TableDump users, TableDump orders]
```

Requesting a table that does not exist records an error in
`result.errors` instead of raising — unless strict mode is on.

### Custom engine

```python
from dumpb import DumpEngine

engine = DumpEngine({
    "row_limit": 100,        # max rows per table
    "strict_mode": True,     # raise DumpbError on any dump issue
    "max_file_size_mb": 50,  # refuse databases larger than 50 MB
})
result = engine.dump("app.db")
```

Reusing an engine enables the LRU result cache: dumping the same database
twice (unchanged file, same filter) returns the same `DumpResult` instantly.

## Configuration keys

Defaults live in `dumpb.DEFAULT_CONFIG` and can be overridden per engine, per
config file, or per `dump()` call (table filters only).

| Key                 | Type            | Default  | Description                                          |
|---------------------|-----------------|----------|------------------------------------------------------|
| `tables`            | `list` / `None` | `None`   | Table filter; `None` dumps all tables                |
| `include_schema`    | `bool`          | `True`   | Capture `CREATE` statements in each `TableDump`      |
| `row_limit`         | `int` / `None`  | `None`   | Max rows per table; sets `truncated` when hit        |
| `max_file_size_mb`  | `float` / `None`| `100`    | Refuse databases larger than this; `0` disables      |
| `cache_size`        | `int`           | `20`     | LRU cache capacity (number of dump results)          |
| `read_only`         | `bool`          | `True`   | Open the database in SQLite read-only URI mode       |
| `detect_types`      | `bool`          | `True`   | Enable `sqlite3.PARSE_DECLTYPES` type detection      |
| `strict_mode`       | `bool`          | `False`  | Raise `DumpbError` instead of collecting errors      |

## Config files

`dumpb.settings` persists engine settings with a strict binary layout:

```
raw:   [8-byte sha256 checksum][4-byte size][pickle payload]
bz2:   [8-byte sha256 checksum][4-byte size][bz2.compress(pickle payload)]
lzma:  [8-byte sha256 checksum][4-byte size][lzma.compress(pickle payload)]
zlib:  [8-byte sha256 checksum][4-byte size][zlib.compress(pickle payload)]
```

```python
from dumpb import save_config, load_config, find_default_config

save_config({"row_limit": 42}, "engine.config")            # raw
save_config({"row_limit": 7}, "engine.config", "lzma")     # compressed
save_config({"row_limit": 3}, "engine.config", "bz2")      # compressed
cfg = load_config("engine.config")
cfg.get("row_limit")                                       # 7

# No path: locates schema.tpl next to the caller's module
save_config({"tables": ["users"]})
find_default_config()                                      # Path to schema.tpl
```

## Data model

### `DumpResult`

| Member                        | Description                                        |
|-------------------------------|----------------------------------------------------|
| `database`                    | Path of the dumped database                        |
| `tables`                      | List of `TableDump` (tables only; views are names) |
| `views`, `indexes`            | Metadata name lists from `sqlite_master`           |
| `errors`                      | Non-fatal issues collected during the dump         |
| `get_table(name)`             | `TableDump` by name, or `None`                     |
| `iter_tables()`               | Iterator over tables                               |
| `total_rows()`                | Sum of row counts                                  |
| `stats()`                     | `{'tables': n, 'rows': n, 'views': n, 'indexes': n}`|
| `to_dict()` / `to_json()`     | Structured dict / JSON string (`default=str`)      |
| `save(path, indent=None)`     | Atomic JSON file write; returns the `Path`         |

### `TableDump`

| Member        | Description                                             |
|---------------|---------------------------------------------------------|
| `name`        | Table name                                              |
| `otype`       | Object type (`'table'`)                                 |
| `schema`      | `CREATE` statement from `sqlite_master` (if enabled)    |
| `rows`        | List of row dicts (column name → value)                 |
| `truncated`   | `True` when `row_limit` cut rows off                    |
| `row_count`   | Number of captured rows                                 |
| `column_names()` | Union of column keys across rows, in first-seen order |

## Error handling

```
DumpbError                    # dump failures, limits, strict-mode issues
ConfigLoadError               # missing, unreadable, malformed, unsafe configs
├── ConfigChecksumError       # payload fails its checksum (tamper/corruption)
└── ConfigDecompressError     # xz/zlib payload cannot be decompressed
```

```python
import dumpb
from dumpb import DumpbError, ConfigChecksumError

try:
    dumpb.dump("missing.db")
except DumpbError as exc:
    print("dump failed:", exc)
```

## Behavior notes

- Internal `sqlite_*` objects (`sqlite_sequence`, autoindexes, …) are excluded.
- Views and indexes are listed as metadata; only tables are row-dumped.
- `bytes` values (BLOB columns) are kept as-is in Python and stringified
  safely by `to_json()` / `save()`.
- Cache keys combine the absolute path, mtime, size, and the effective table
  filter, so editing the database or changing filters never returns stale data.
- `read_only=True` opens the file in SQLite URI read-only mode, falling back
  to a normal connection on unsupported platforms.

## API reference

| Module            | Exports                                                            |
|-------------------|--------------------------------------------------------------------|
| `dumpb`           | `dump`, `DumpEngine`, `DumpResult`, `TableDump`, `DEFAULT_CONFIG`, `Config`, `load_config`, `save_config`, `find_default_config`, all errors |
| `dumpb.dumper`    | `DumpEngine`, `LRUCache`, `DEFAULT_CONFIG`                         |
| `dumpb.reader`    | `DatabaseReader`                                                   |
| `dumpb.model`     | `DumpResult`, `TableDump`                                          |
| `dumpb.settings`  | `Config`, `load_config`, `save_config`, `find_default_config`      |
| `dumpb.errors`    | `DumpbError`, `ConfigLoadError`, `ConfigChecksumError`, `ConfigDecompressError` |

## License

[MIT](https://example.com/dumpb/blob/main/LICENSE)
