Metadata-Version: 2.4
Name: sqliac
Version: 0.2.0
Summary: An alternative to Terraform for SQL databases without using a state.
Author-email: Ruslan Gonzalez Konstantinov <rus.kgo@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://codeberg.org/ruskgo/sqliac
Project-URL: Bug Tracker, https://codeberg.org/ruskgo/sqliac/issues
Keywords: sql,iac,terraform-alternative,database
Requires-Python: >=3.13
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: Jinja2
Requires-Dist: sqlparse
Requires-Dist: dictdiffer
Requires-Dist: pg8000>=1.31.5
Provides-Extra: dev
Requires-Dist: pytest>=9.1.1; extra == "dev"
Provides-Extra: snowflake
Requires-Dist: sqliac-snowflake; extra == "snowflake"
Provides-Extra: postgres
Requires-Dist: sqliac-postgres; extra == "postgres"
Provides-Extra: mssql
Requires-Dist: sqliac-mssql; extra == "mssql"
Dynamic: license-file

# SQLIaC — SQL Infrastructure as Code

**An alternative to Terraform for SQL databases — without a state file.**

SQLIaC lets you declare SQL database resources (databases, schemas, tables, roles, views, warehouses, grants…) in TOML definition files. Under the hood it queries the live database to detect drift, then renders and executes Jinja-templated DDL to bring the database into the declared state. No state file. No lock file. Just your definitions and the database.

## How It Works

1. **You declare** resources in `./definitions/<provider name>/*.toml` — one file per resource type.
2. **SQLIaC queries** the live database using `state.sql` templates to discover what currently exists.
3. **Drift is detected** by comparing definition → state; actions are determined: CREATE, ALTER, DROP, or no-op.
4. **Jinja-templated DDL** renders the appropriate SQL statements.
5. **Execution runs in parallel** respecting a dependency DAG built from your definitions.

## Installation

```bash
pip install sqliac
```

You'll also need at least one database adapter:

```bash
pip install sqliac-snowflake   # Snowflake
pip install sqliac-postgres    # PostgreSQL
pip install sqliac-mssql       # SQL Server
# pip install sqliac-oracle    # Oracle (future)
```

## Quick Start

### 1. Scaffold a project

```bash
sqliac init
```

This creates:

```
.sqliac/
├── provider/
│   ├── config.toml          # resource registry with DDL commands & context schemas
│   ├── credentials.toml     # database connection credentials
│   ├── <provider name>/
│       ├── database/
│       │   ├── ddl_template.sql # Jinja DDL template
│       │   └── state.sql        # state introspection query
│       ├── event_table/
│       │   ├── ddl_template.sql
│       │   └── state.sql
│       ├── schema/
│       │   ├── ddl_template.sql
│       │   └── state.sql
│       └── table/
│           ├── ddl_template.sql
│           └── state.sql
definitions/
├── <provider name>
    ├── database.toml             # declare your databases here
    ├── schema.toml               # declare your schemas here
    └── table.toml                # declare your tables here
.agents/skills/sqliac/        # AI agent skill for generating template pairs
```

The scaffolding includes working examples (Porvider DDL + state queries for `database`, `schema`, and `table`). Adjust the provider config to match your engine and resources.

### 2. Configure credentials (Snowflake)

```bash
export SNOWFLAKE_ACCOUNT="my_account"
export SNOWFLAKE_USER="my_user"
export SNOWFLAKE_PASSWORD="my_password"
export SNOWFLAKE_WAREHOUSE="my_warehouse"
```

Or write them in `.sqliac/provider/snowflake/credentials.toml` (env vars take precedence):

```toml
[snowflake]
account = "my_account"
user = "my_user"
password = "my_password"
warehouse = "my_warehouse"
```

#### Key-pair authentication (Snowflake)

Instead of a password, you can use Snowflake key-pair authentication — either by passing the PEM key string directly or by pointing to a key file:

```bash
# Option A: key string (PEM content)
export SNOWFLAKE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----"

# Option B: key file (path resolved relative to .sqliac/provider/)
export SNOWFLAKE_PRIVATE_KEY_PATH="keys/rsa_key.p8"

# Optional, if the key is encrypted
export SNOWFLAKE_PRIVATE_KEY_PASSPHRASE="my_passphrase"
```

Or in `.sqliac/provider/credentials.toml`:

```toml
[snowflake]
account = "my_account"
user = "my_user"
private_key_path = "keys/rsa_key.p8"   # or: private_key = "-----BEGIN PRIVATE KEY-----..."
private_key_passphrase = "my_passphrase"  # optional
warehouse = "my_warehouse"
```

Either `password`, `private_key`, or `private_key_path` must be provided.

### 3. Declare your resources (Snowflake)

Edit the definition files under `definitions/snowflake`. For example, `definitions/snowflake/schema.toml`:

```toml
[[schema]]
object_name = "MY_DB.STAGING"
transient = false
managed_access = false
data_retention_time_in_days = 1
comment = "Staging schema"
[schema.depends_on]
database = ["MY_DB"]

[[schema]]
object_name = "MY_DB.PRODUCTION"
transient = false
[Sschema.depends_on]
database = ["MY_DB"]
```

- `object_name` — fully qualified name (uppercase by convention)
- `depends_on` — declare ordering constraints between resources
- `wait_time` — optional delay (seconds) between DDL execution and the next resource

### 4. Preview and apply

```bash
sqliac apply --dry-run     # see what would change
sqliac apply               # execute for real
```

### 5. Tear down

```bash
sqliac destroy --dry-run   # preview cleanup
sqliac destroy             # drop all declared resources (in reverse DAG order)
```

## CLI Reference

| Command | Description |
|---------|-------------|
| `sqliac init` | Create project scaffolding with example templates and the agent skill |
| `sqliac list` | Show installed adapters and their available resource types |
| `sqliac graph` | Generate a `dependencies.dot` DAG file from your definitions |
| `sqliac compile --ddl create\|alter\|drop <resource>` | Render a DDL template with example context from config.toml |
| `sqliac compile --state <resource>` | Render a state query with example context from config.toml |
| `sqliac apply` | Compare definitions against live state and reconcile |
| `sqliac destroy` | Drop all declared resources in reverse dependency order |

### Apply / Destroy options

```
sqliac apply [--threads N] [--dry-run]
sqliac destroy [--threads N] [--dry-run]
```

- `--threads` — number of parallel workers (default: 3). Tasks execute concurrently within each topo-sorted batch of the DAG.
- `--dry-run` — preview what SQL would be executed without touching the database.

### Logging

```
sqliac --log --level debug apply                                        # console logging
sqliac --log-file --level debug apply                                   # file logging (sqliac.log)
sqliac --log-event-table DATABASE.SCHEMA.SQLIAC_EVENTS --level info apply   # stream logs into an event table in the database
```

`--log` and `--log-file` are boolean switches; `--log-event-table` takes the fully qualified table name. `--level` accepts `info` or `debug` and applies to all enabled destinations. The flags can be combined.

#### Event table logging

With `--log-event-table`, SQLIaC streams execution events — `create`/`alter`/`drop` executions and execution errors — into a table in your database. 
Log records are buffered and bulk-inserted; insert failures are reported to stderr and dropped — they never interrupt or mask the actual pipeline execution.

Setup requires the exitance of an event table:
```sql
-- mandatory DDL
CREATE TABLE DATABASE.SCHEMA.SQLIAC_EVENT_TABLE (
    LOG_TIMESTAMP DATETIME2,
    LOG_LEVEL VARCHAR(10),
    MESSAGE VARCHAR(MAX),
    )
```

## Provider Templates

Each resource type registered in `.sqliac/provider/config.toml` must have:

```
.sqliac/provider/<provider name>/<resource>/
├── ddl_template.sql    # Jinja DDL for CREATE/ALTER/DROP
└── state.sql           # query returning current state as a single JSON row
```

### Core invariant

> The keys returned by `state.sql` must be a 1:1 match with the Jinja variables consumed by `ddl_template.sql`.

If `ddl_template.sql` references `add.get('columns')`, then `state.sql` must return JSON containing `columns`. The tool detects mismatches and reports them at runtime, but you can validate pairs ahead of time using the agent skill's check script.

### The compile command

Use `sqliac compile` to iterate on templates without applying:

```bash
sqliac compile --ddl create database    # renders the CREATE/ALTER DDL
sqliac compile --state database         # renders the state introspection query
```

The `compile` command reads the example `ddl_context` from `config.toml`, so keep it populated with realistic values — it serves as documentation, test fixture, and developer playground all at once.

## Dependency Graph

Resources can declare inter-resource dependencies via `depends_on`. SQLIaC builds a DAG and executes in topo-sorted waves:

```toml
[[schema]]
object_name = "MY_DB.STAGING"
[schema.depends_on]
database = ["MY_DB"]
```

- `apply` — resources with no dependencies run first; downstream resources wait for their deps to succeed.
- `destroy` — the DAG is reversed so dependents are dropped before their dependencies.
- Circular dependencies are detected and reported with visual inline diagnostics.

```bash
sqliac graph   # writes dependencies.md + prints to terminal
```

## The sqliac Agent Skill

SQLIaC ships with an agent skill (for AI coding assistants like OpenCode, Cursor, etc.) that automates writing `ddl_template.sql` and `state.sql` pairs. To use it:

1. Run `sqliac init` — the skill is copied into `.agents/skills/sqliac/`.
2. Ask your AI assistant: *"create Snowflake templates for warehouse"* and reference the `.agents` skill directory.

The skill:

- Reads engine-specific reference files (Snowflake, PostgreSQL, Oracle, Databricks patterns).
- Produces a validated `ddl_template.sql` + `state.sql` pair with correct Jinja + SQL.
- Registers the resource in `config.toml` with example values.
- Runs `check_key_parity.py` to verify key parity between the template and state query.

See `.agents/skills/sqliac/SKILL.md` for the full skill documentation.

## Drift Detection

On each `apply`, SQLIaC:

1. Executes `state.sql` to fetch the live state as JSON.
2. Recursively normalizes both the definition and the state (filtering, sanitizing, aligning nested keys).
3. Runs a structured diff via `dictdiffer` to produce `add`, `change`, and `remove` sections.
4. Feeds those sections into the Jinja DDL template, which renders the appropriate `CREATE OR ALTER`, `ALTER`, or `DROP` statements.

If the resource does not exist (state query returns zero rows), a `CREATE` is generated. If no differences are found, no DDL is executed.

## Adapters

Adapters are self-contained packages discovered via Python entry points (`sqliac.adapters` group). Each adapter provides:

- A credentials dataclass with validation
- A connection manager for thread-safe connection pooling
- An adapter class wrapping query execution

All adapters follow the base classes in `sqliac.adapters.base`, making it straightforward to add support for new database engines.

## License

MIT © Ruslan Gonzalez Konstantinov
