> For the complete documentation index, see [llms.txt](https://docs.hipersnipe.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.hipersnipe.com/architecture/database.md).

# Database and migrations

## Storage

* **Engine:** SQLite 3
* **File:** `users.db` (git-ignored, live production data)
* **Mode:** WAL (Write-Ahead Logging) for multi-process access

## Schema ownership

| Layer          | Location                                                           |
| -------------- | ------------------------------------------------------------------ |
| Table creation | `db/core.py` → `create_db_and_table()`                             |
| Migrations     | `db_handler_aio.py` → `init_db()` / `update_schema()`              |
| DAO modules    | `db/users_dao.py`, `db/limits_dao.py`, `db/positions_dao.py`, etc. |

## Migration rules (strict)

1. **Never drop** `users.db` in production.
2. **Auto-migrate only** — forward-only `ALTER TABLE ADD COLUMN` on startup.
3. **Idempotent** — safe to run every boot.

Example pattern:

```python
async with db.execute("PRAGMA table_info(users)") as cur:
    cols = {row[1] for row in await cur.fetchall()}
if "new_column" not in cols:
    await db.execute("ALTER TABLE users ADD COLUMN new_column TEXT DEFAULT ''")
```

## Key tables

| Table / field       | Contents                                                                  |
| ------------------- | ------------------------------------------------------------------------- |
| `users`             | Telegram ID, encrypted private key, wallet address, trades JSON, settings |
| `limit_orders`      | Pending limit buy/sell orders                                             |
| `auto_sell_configs` | Trading Shield per user+token                                             |
| `dca_orders`        | Recurring buy schedules                                                   |
| `copy_targets`      | Wallets to mirror                                                         |
| `global_config`     | Infra keys, sniper config, fee settings                                   |
| `partners`          | Channel ID → referral code mappings                                       |

## Trades JSON structure

Per-mint trade history stored in `users.trades`:

```json
{
  "MINT_ADDRESS": {
    "trades": [
      {"type": "buy", "sol_amount": 0.5, "token_amount": 1000000, "timestamp": 1710000000},
      {"type": "sell", "sol_amount": 0.3, "token_amount": 500000, "timestamp": 1710003600}
    ],
    "last_cycle_closed_at": 0
  }
}
```

`pnl_tracker.py` replays this JSON with cycle reset logic when balance hits dust.

## Concurrency

* `_db_lock` serializes writes in single process
* Cross-process: retry on `database is locked` (up to 5 attempts)
* Connection timeout: 30 seconds

## Backup

Back up `users.db` regularly in production. The file contains encrypted private keys—treat backups as highly sensitive.

## Related

* [Security model](/architecture/security.md)
* [Development: contributing](/development/contributing.md)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.hipersnipe.com/architecture/database.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
