Metadata-Version: 2.4
Name: sqlingpl
Version: 0.1.1
Summary: Run Oracle PL/SQL without Oracle: an interpreter over SQLite, DuckDB, Postgres and MariaDB
Author: Data Design Group, Inc.
License-Expression: MIT
Project-URL: Homepage, https://sqling.com/plsql-engine/
Project-URL: Source, https://github.com/sqling-com/sqlingpl
Project-URL: Playground, https://sqling.com/tools/plsql-playground.html
Keywords: plsql,pl/sql,oracle,sqlite,duckdb,postgres,mariadb,interpreter,sqlplus
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: SQL
Classifier: Topic :: Database
Classifier: Topic :: Software Development :: Interpreters
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: duckdb
Requires-Dist: duckdb>=0.9; extra == "duckdb"
Requires-Dist: numpy; extra == "duckdb"
Provides-Extra: postgres
Requires-Dist: psycopg[binary]>=3.1; extra == "postgres"
Provides-Extra: mariadb
Requires-Dist: pymysql>=1.0; extra == "mariadb"
Provides-Extra: oracle
Requires-Dist: oracledb>=2.0; extra == "oracle"
Provides-Extra: crypto
Requires-Dist: cryptography>=41; extra == "crypto"
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Dynamic: license-file

# sqlingpl

A PL/SQL interpreter that runs on top of SQLite, DuckDB, Postgres or MariaDB.

Write procedures, functions, packages, anonymous blocks, cursors, exception
handlers and collections — the Oracle way — against an ordinary SQLite file. No
Oracle installation, no server, no dependencies beyond the standard library.
Point the same code at a Postgres or MariaDB server and the engine translates
the dialect on the way.

```sql
-- shop.sql
CREATE OR REPLACE FUNCTION discounted(p_price NUMBER, p_pct NUMBER)
  RETURN NUMBER
IS
BEGIN
  RETURN ROUND(p_price * (1 - p_pct / 100), 2);
END;
/

DECLARE
  v_total NUMBER := 0;
BEGIN
  FOR p IN (SELECT name, price FROM product ORDER BY price DESC) LOOP
    v_total := v_total + discounted(p.price, 10);
    DBMS_OUTPUT.PUT_LINE(RPAD(p.name, 12) || TO_CHAR(p.price, 'FM$9,990.00'));
  END LOOP;
  DBMS_OUTPUT.PUT_LINE('Discounted total: ' || TO_CHAR(v_total, 'FM$9,990.00'));
EXCEPTION
  WHEN NO_DATA_FOUND THEN
    DBMS_OUTPUT.PUT_LINE('nothing in stock');
END;
/
```

```console
$ sqlingpl -d shop.sqlite shop.sql
```

## Install

```console
$ pip install sqlingpl                # SQLite only; nothing else required
$ pip install "sqlingpl[duckdb]"      # add the DuckDB engine (duckdb + numpy)
$ pip install "sqlingpl[postgres]"    # add the Postgres engine (psycopg)
$ pip install "sqlingpl[mariadb]"     # add the MariaDB engine (PyMySQL)
```

That puts the `sqlingpl` command on your PATH (`sqling` is the same command).
To try it without installing anything, use the
[PL/SQL Playground](https://sqling.com/tools/plsql-playground.html) in your
browser.

To work on the code itself, install from a checkout instead; `-e` makes the
install follow your edits:

```console
$ git clone https://github.com/sqling-com/sqlingpl
$ cd sqlingpl
$ pip install -e '.[dev]'
```

Python 3.9 or newer.

### In VS Code

Download [sqlingpl-vscode.vsix](https://github.com/sqling-com/sqlingpl/releases/latest/download/sqlingpl-vscode.vsix) and install it in VS Code
(Extensions view → **…** → **Install from VSIX…**). Then open a `.sql` file
and press **Ctrl+Alt+R** (**Cmd+Alt+R** on a Mac) to run it, or the selected
part of it. See [vscode/README.md](vscode/README.md).

## Running

sqlingpl is a package, not a single file, so there is no `sqlingpl.py`. Run the
package itself — the directory form and the `-m` form both work:

```console
python sqlingpl                     start the REPL (from a checkout)
python sqlingpl script.sql          run a script
python -m sqlingpl                  the same, as a module
```

After `pip install sqlingpl` it is on your PATH, and works from any directory:

Inside a session, `@file`, `@@file` and `START file` run another script;
`@@` resolves relative to the calling script, `@` tries the working directory
first. Words after the name become the script's `&1`, `&2`, …

```console
sqlingpl                            start the REPL (in-memory database)
sqlingpl script.sql                 run a script against an in-memory database
sqlingpl -d app.sqlite script.sql   run against a file — stored code persists
sqlingpl -d app.duckdb -e duckdb    use DuckDB instead of SQLite
sqlingpl -c "BEGIN NULL; END;"      run one statement
cat script.sql | sqlingpl -         read from standard input
```

In the REPL, a `;` ends a SQL statement and a line containing only `/` ends a
PL/SQL block — the SQL\*Plus convention, because a block's own statements end in
`;` too.

The prompt has full line editing: arrow keys to move and recall, `TAB` to
complete, `Ctrl-R` to search backwards, `Ctrl-A`/`Ctrl-E` for start and end of
line. History is kept in `~/.sqlingpl_history` between sessions.

`TAB` completes against what is actually in *this* database — tables you just
created, stored procedures and packages, `SET` option names, bind variables you
declared — as well as PL/SQL keywords and the built-in functions:

```console
SQL> SET FEED<TAB>            -> SET FEEDBACK
SQL> SELECT * FROM employ<TAB> -> SELECT * FROM employees
SQL> PRINT <TAB>              -> lists your bind variables
```

The REPL opens by saying what it is connected to:

```console
$ sqlingpl -d shop.sqlite
sqling 0.1.1 -- PL/SQL on SQLite, DuckDB, Postgres, MariaDB and Oracle
Engine:   SQLite 3.51.0
Database: /Users/you/shop.sqlite
Type HELP for commands, EXIT to quit.  End a PL/SQL block with "/".
SQL> SELECT COUNT(*) FROM product;
SQL> BEGIN DBMS_OUTPUT.PUT_LINE(SYSDATE); END;
  2  /
SQL> SHOW CONNECTION
SQL> EXIT
```

An in-memory session says so plainly — `Database: in-memory (nothing is saved
on exit)` — and on DuckDB without numpy the banner adds a `Note:` line
explaining that the Oracle function set is unavailable.

`SHOW CONNECTION` prints the same thing at any time, and `CONNECT <path>
[engine]` switches database and reports where it landed. Script and `-c` runs
print **no** banner, so their output stays parseable.

## Translating to another backend

Three flags read a script and print what it would become somewhere else,
without running any of it.

```console
$ sqling --rewrite postgres app.sql          # the SQL, target dialect
$ sqling --audit postgres app.sql            # Oracle and target, side by side
$ sqling --translate postgres app.sql        # the same, PL/SQL included
```

`--rewrite` and `--audit` stop at SQL. A PL/SQL block comes out of them saying
it is interpreted and nothing is sent — true of how the runtime works, and no
use in a migration report.

`--translate` compiles it instead: a function becomes the backend's own
procedural language, and the Oracle functions the target lacks are defined
above the statements that call them, with a note saying which.

```console
$ sqling --translate postgres --format sql app.sql > app.pg.sql   # runnable
$ sqling --translate postgres --format html --out report.html schema/
```

`--format` takes `text` (side by side, the default), `json` (one object per
line, for `jq`), `html` (a self-contained page that opens from a `file:` URL),
and — for `--translate` only — `sql`, one runnable script. `--out` writes to a
file, `--only-changed` drops the rows where nothing moved. Given a folder,
`--translate` reads every `.sql` in it in name order and reports the schema as
one document, each file named in place.

Backends: `sqlite`, `duckdb`, `postgres`, `mariadb`.

## Using sqlingpl as a library

Install it into your project (`pip install sqlingpl`, or add `sqlingpl` to
your requirements) and import `Interpreter`:

```python
from sqlingpl import Interpreter

with Interpreter(database="app.sqlite", capture_output=True) as db:
    db.run_source(open("procs.sql").read())

    total = db.call("line_total", 3, 19.99)        # -> Decimal("59.97")
    parts = db.call("split_name", "Ada Lovelace")  # -> {"p_first": ..., "p_last": ...}

    for line in db.take_output():                  # DBMS_OUTPUT, as lines
        log.info(line)
```

| | |
|---|---|
| `run_source(text)` | run PL/SQL and SQL; raises `PlsqlError` on failure |
| `call(name, *args, **kwargs)` | invoke a procedure or function; positional or named notation, declared defaults applied |
| `get(name)` / `set(name, value)` | read and write session variables; `set` declares on first use |
| `evaluate_expression(text)` | evaluate one PL/SQL expression |
| `query(sql, params=None)` | run a query, get `(columns, rows)`; session variables bind into the SQL |
| `take_output()` | captured output as a list of lines, draining the buffer |

A **function** returns its value. A **procedure** returns a dict of its `OUT`
and `IN OUT` parameters, since that is the only way a procedure returns
anything. Errors raised in PL/SQL — including `RAISE_APPLICATION_ERROR` — arrive
as `PlsqlError`, carrying `.code` and `.sqlerrm`.

### Values across the boundary

`NUMBER` is `decimal.Decimal` in and out, so precision survives the round trip.
A Python `float` is converted through its `repr`, meaning `0.075` arrives as
exactly `Decimal("0.075")` rather than the binary approximation:

```python
db.set("v_rate", 0.075)
db.get("v_rate")                       # Decimal('0.075')
db.evaluate_expression("0.1 + 0.2")    # Decimal('0.3')
```

`str`, `bool`, `datetime` and `None` pass through unchanged. Python lists and
dicts are rejected with an explanation — a collection or record needs declared
element types, so build it in PL/SQL.

### Sharing the connection your application already owns

Pass a live `sqlite3` or `duckdb` connection instead of a path. Both sides then
see the same data and the same transaction, and sqlingpl never closes a handle
it did not open:

```python
import sqlite3
from sqlingpl import Interpreter

conn = sqlite3.connect("app.sqlite")        # your application's connection
db = Interpreter(connection=conn)           # engine is detected from it
db.run_source("BEGIN refresh_totals; END;\n/\n")
db.close()                                  # conn stays open and usable
```

The Oracle function set is installed into that connection, so your own cursors
get `NVL`, `TO_CHAR`, `DECODE` and the rest too. `CONNECT` is refused on an
adopted connection, since the handle is not sqlingpl's to repoint.

`examples/embed.py` is a runnable version of all of the above.

## Transactions

Nothing is committed until something says so, as in SQL\*Plus:

```sql
INSERT INTO emp VALUES (9, 'Zoe', 30, 1234);   -- pending; no other session sees it
SAVEPOINT before_raise;
UPDATE emp SET sal = sal * 1.1;
ROLLBACK TO before_raise;                       -- SQLite only; DuckDB has no SAVEPOINT
COMMIT;                                         -- now it is durable
```

What resolves an open transaction:

| Event | Result |
|---|---|
| `COMMIT` / `ROLLBACK` | as written |
| session ends cleanly (`EXIT`, end of script, `close()`) | **commit** |
| session ends because of an error | **rollback** |
| `EXIT COMMIT` / `EXIT ROLLBACK` | as written |
| `SET AUTOCOMMIT ON` | commit after each statement or block |
| `SET AUTOCOMMIT n` | commit after every `n` statements |
| DDL — `CREATE TABLE`, `CREATE PROCEDURE`, `DROP` | commits, as Oracle's DDL does |
| an exception **handled** inside PL/SQL | nothing; the work stands |

`WHENEVER SQLERROR` chooses what a failure does:

```sql
WHENEVER SQLERROR EXIT ROLLBACK     -- the default here
WHENEVER SQLERROR EXIT COMMIT       -- keep the work and stop
WHENEVER SQLERROR CONTINUE          -- keep going, leave the transaction alone
WHENEVER SQLERROR CONTINUE ROLLBACK -- discard, but keep going
```

Two deliberate divergences from SQL\*Plus, both chosen for safety in a tool
that writes to a database:

* **A failed script rolls back.** SQL\*Plus's `WHENEVER SQLERROR EXIT` commits
  by default. Committing half of a script that blew up is a data-integrity
  hazard, so the default here is `EXIT ROLLBACK`. Say
  `WHENEVER SQLERROR EXIT COMMIT` for the other behaviour.
* **A failed script stops.** SQL\*Plus defaults to `CONTINUE`. Say
  `WHENEVER SQLERROR CONTINUE` to get that.

When sqlingpl is embedded and given a connection the host already owns, it
**never** commits or rolls back that connection — including on `close()`.
Pending work is left for the host to resolve.

## SET options

The familiar SQL\*Plus settings, with `SHOW` to read them back:

```console
SQL> SET FEEDBACK OFF          -- stop "3 rows selected."
SQL> SET FEEDBACK 25           -- ...or report only results of 25 rows or more
SQL> SET HEADING OFF           -- drop the column headings
SQL> SET NULL '(null)'         -- print something for NULL instead of a blank
SQL> SET LINESIZE 200          -- widen before a wide query
SQL> SET TIMING ON             -- "Elapsed: 00:00:00.03" after each statement
SQL> SHOW FEEDBACK
feedback OFF
SQL> SHOW ALL
```

| Option | Default | Effect |
|---|---|---|
| `FEEDBACK ON\|OFF\|n` | `ON` | row-count messages; `n` reports only results of at least `n` rows |
| `HEADING ON\|OFF` | `ON` | column headings |
| `PAGESIZE n` | `14` | lines per page; `0` suppresses headings, titles and paging |
| `NEWPAGE n` | `1` | blank lines between pages; `0` sends a form feed |
| `LINESIZE n` | `120` | maximum result width; wide columns are trimmed |
| `NULL text` | `""` | text printed for a NULL value |
| `COLSEP text` | `"\|"` | column separator |
| `SERVEROUTPUT ON\|OFF` | `ON` | whether `DBMS_OUTPUT` is printed |
| `TERMOUT ON\|OFF` | `ON` | whether query results are printed at all |
| `ECHO ON\|OFF` | `OFF` | echo each statement of a script as it runs |
| `TIMING ON\|OFF` | `OFF` | elapsed time after each statement |
| `NUMWIDTH n` | `10` | default display width for numbers |
| `NUMFORMAT fmt` | `""` | format model for every number without a `COLUMN FORMAT` |
| `SQLFORMAT <name>` | `default` | how result sets are rendered — see above |
| `AUTOCOMMIT ON\|OFF\|n` | `OFF` | commit automatically after each statement, or every `n` |
| `AUTOPRINT ON\|OFF` | `OFF` | print bind variables after a successful block or DML |
| `DEFINE ON\|OFF\|char` | `&` | substitution prefix, or OFF |
| `ESCAPE ON\|OFF\|char` | `OFF` | character that prevents substitution |
| `VERIFY ON\|OFF` | `OFF` | show each substitution's before and after |

Unambiguous abbreviations work (`SET FEED OFF`, `SET PAGES 50`), and an empty
result reports `no rows selected` — Oracle's wording — whatever the threshold.

`SET ECHO ON` shows a script's statements as they run, which is what makes a
migration log readable. The text comes from the source rather than the parse
tree, so comments and layout appear as written. Only scripts are echoed — at
the prompt the statement is already on screen, which is why SQL\*Plus does
the same.

`FEEDBACK` also governs what a DML statement reports:

```console
SQL> UPDATE emp SET sal = sal * 1.1 WHERE dept = 10;
2 rows updated.
SQL> DELETE FROM emp WHERE id = 99;
0 rows deleted.
```

Only at the top level — DML inside a block stays quiet, or a loop updating one
row at a time would bury the block's own output. Unlike a query's row count,
this is not subject to the threshold: `FEEDBACK 50` still reports a one-row
update, because the threshold exists to hide small *result sets*.

To read the values yourself outside a block, the implicit cursor persists
across statements:

```console
SQL> UPDATE emp SET sal = sal + 1 WHERE sal >= 5000;
2 rows updated.
SQL> EXEC DBMS_OUTPUT.PUT_LINE('affected: ' || SQL%ROWCOUNT)
affected: 2
SQL> PRINT SQL%ROWCOUNT
+--------------+
| SQL%ROWCOUNT |
+--------------+
| 2            |
+--------------+
```

(`PRINT` of a cursor attribute is an extension — SQL\*Plus restricts `PRINT` to
bind variables — but it is the obvious thing to type after a DML statement.)

### Cursor attributes

`SQL%…` reports on the most recent DML or `SELECT INTO`; the same four work on
any explicit cursor or cursor variable as `c%…`:

| Attribute | Meaning |
|---|---|
| `%ROWCOUNT` | rows affected; for an explicit cursor, rows fetched **so far** |
| `%FOUND` | did it affect/fetch a row — **NULL** before anything has run |
| `%NOTFOUND` | the inverse, also NULL before anything has run |
| `%ISOPEN` | always `FALSE` for `SQL`; the real state for an explicit cursor |
| `SQL%BULK_ROWCOUNT` | indexed: `(i)` is iteration *i* of a `FORALL` |

`BULK_ROWCOUNT` is a collection, so `.COUNT`, `.FIRST` and `.LAST` work on it:

```sql
FORALL i IN 1 .. v_ids.COUNT
  UPDATE emp SET sal = sal + 1 WHERE id = v_ids(i);

DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT);            -- the total across iterations
FOR i IN 1 .. SQL%BULK_ROWCOUNT.COUNT LOOP
  DBMS_OUTPUT.PUT_LINE(i || ' -> ' || SQL%BULK_ROWCOUNT(i));
END LOOP;
```

An unrecognised attribute is reported, so a typo does not quietly read as zero.

### FORALL and SAVE EXCEPTIONS

`SAVE EXCEPTIONS` lets a batch finish past its failures, then reports them all
at once as `ORA-24381` — catchable as `DML_ERRORS`. The detail is in
`SQL%BULK_EXCEPTIONS`, an indexed collection of `ERROR_INDEX` (which iteration)
and `ERROR_CODE` (positive, as Oracle reports it):

```sql
BEGIN
  FORALL i IN 1 .. v_ids.COUNT SAVE EXCEPTIONS
    INSERT INTO t VALUES (v_ids(i), 'new');
EXCEPTION
  WHEN DML_ERRORS THEN
    DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT || ' inserted, ' ||
                         SQL%BULK_EXCEPTIONS.COUNT || ' failed');
    FOR j IN 1 .. SQL%BULK_EXCEPTIONS.COUNT LOOP
      DBMS_OUTPUT.PUT_LINE('  iteration ' || SQL%BULK_EXCEPTIONS(j).ERROR_INDEX
        || ': ' || SQLERRM(-SQL%BULK_EXCEPTIONS(j).ERROR_CODE));
    END LOOP;
END;
```

```
2 inserted, 2 failed
  iteration 2: ORA-00001: unique constraint violated
  iteration 4: ORA-00001: unique constraint violated
```

`SQL%BULK_ROWCOUNT` records `0` for a failed iteration, `SQL%ROWCOUNT` is the
total that actually succeeded, and both lists are cleared by the next
statement. Without `SAVE EXCEPTIONS`, the first failure ends the batch
immediately and raises its own error, as in Oracle.

Options this interpreter has nothing to apply — `ECHO`, `VERIFY`, `MARKUP`,
`TRIMSPOOL` and similar — are **accepted and ignored**, so existing scripts run.
Anything not on either list is reported:

```console
SQL> SET FEEDBCK OFF
ORA-02000: unknown SET option "FEEDBCK" (SHOW ALL lists what is supported)
```

That distinction is the point of keeping the ignored list explicit: a typo
should not look like it worked.

One divergence worth knowing: SQL\*Plus defaults `FEEDBACK` to `6`, so small
results report nothing. Here the default is `ON`, which suits an interactive
session better; `SET FEEDBACK 6` gives you Oracle's behaviour.

## Report formatting

`COLUMN`, `BREAK`, `COMPUTE`, `TTITLE` and `BTITLE` are a small formatting
language of their own. Between them they turn a flat result set into a
paginated report with grouped subtotals — none of which the query knows about:

```console
SQL> SET LINESIZE 68
SQL> SET PAGESIZE 20
SQL> COLUMN deptno HEADING 'Dept|No' FORMAT 999
SQL> COLUMN ename  HEADING 'Employee' FORMAT A12
SQL> COLUMN sal    HEADING 'Salary'   FORMAT $99,990.00
SQL> BREAK ON deptno SKIP 1 ON REPORT
SQL> COMPUTE SUM OF sal ON deptno
SQL> COMPUTE SUM LABEL 'TOTAL' OF sal ON REPORT
SQL> TTITLE LEFT 'ACME Inc' CENTER 'Payroll' RIGHT 'Page ' SQL.PNO SKIP 2
SQL> SELECT deptno, ename, sal FROM emp ORDER BY deptno, ename;
ACME Inc                      Payroll                         Page 1

Dept
  No Employee          Salary
---- ------------ -----------
  10 CLARK          $2,450.00
     KING           $5,000.00
     MILLER         $1,300.00
****
sum                 $8,750.00

  20 FORD           $3,000.00
     SMITH            $800.00
****
sum                 $3,800.00
TOTA               $12,550.00
```

| Command | What it does |
|---|---|
| `COLUMN col ...` | `FORMAT` (`A20`, `$99,990.00`), `HEADING` (`\|` starts a new line), `JUSTIFY`, `NULL`, `NOPRINT`/`PRINT`, `WRAPPED`/`TRUNCATED`, `ON`/`OFF`, `CLEAR`, `LIKE` |
| `BREAK ON col ...` | `SKIP n`, `SKIP PAGE`, `DUPLICATES`, nested breaks, `ON REPORT` |
| `COMPUTE fn OF col ON brk` | `SUM`, `AVG`, `COUNT`, `MIN`, `MAX`, `NUMBER`, with an optional `LABEL` |
| `TTITLE` / `BTITLE` | `LEFT`/`CENTER`/`RIGHT`, `COL n`, `TAB n`, `SKIP n`, `FORMAT`, `SQL.PNO`, `OFF`/`ON` |
| `REPHEADER` / `REPFOOTER` | the same positioning language, shown **once** — at the top of the first page and the end of the last |
| `CLEAR ...` | `COLUMNS`, `BREAKS`, `COMPUTES`, `SCREEN`, `BUFFER`, `SQL`, `TIMING` |

Defining any of them switches result output from the bordered grid to the
plain SQL\*Plus layout: a subtotal inside a box would look wrong, and these
commands exist to produce SQL\*Plus-shaped reports. `CLEAR COLUMNS`, `CLEAR
BREAKS` and `CLEAR COMPUTES` put the grid back; titles go off with `TTITLE
OFF`. An explicit `SET SQLFORMAT csv` still wins, since choosing an export
format is a more specific instruction than choosing a layout.

`REPHEADER` and `REPFOOTER` are the report's own titles rather than each
page's: the header sits under the first page's `TTITLE` and above the column
headings, and the footer at the end of the data, above the last page's
`BTITLE`. They take the same positioning words.

`SET NUMFORMAT` sets the house style for numbers — every numeric column that
has not been given a `COLUMN FORMAT` of its own, in both the grid and the
report layout. A column's own format always wins.

`PAGESIZE` counts every line on the page — title, headings and data alike —
which is what lets a title reappear at a predictable interval, and `BTITLE`
is reserved out of that budget so it lands at the foot of the page rather
than wherever the data stopped. `SQL.PNO` is the page number. Title elements
are joined without a separator, so the idiom is `RIGHT 'Page ' SQL.PNO` with
the space inside the quotes. A line command can be continued with a trailing
`-`, which titles usually need; in SQL a trailing `-` is left alone, since
there it is a subtraction.

A `COMPUTE` label is left-justified in the break column and truncated to fit
it, as in Oracle — so a column with an explicit narrow `FORMAT` will clip a
long label. Where the width comes from the data instead, the column is
widened to fit both the label and the total: a column of four-digit salaries
sums to five digits, and silently truncating that would print a wrong number
rather than an obviously broken one.

One divergence: SQL\*Plus requires `BREAK ON REPORT` before a `COMPUTE ... ON
REPORT` will fire, and silently prints nothing otherwise. Here the grand
total is emitted regardless — a missing total is a trap, and this is the same
latitude SQL\*Plus itself takes when no `BREAK` is defined at all.

### Adding an output format

This layout is thoroughly of 1985, so the report machinery is built in three
layers rather than as one renderer, and `sqlingpl/report/` is the only part of
the codebase that knows any of it:

| Module | Holds |
|---|---|
| `spec.py` | what the user asked for — the `COLUMN`/`BREAK`/`COMPUTE`/`TTITLE` declarations and the commands that build them |
| `document.py` | what the report *is* — the result set walked once into rows, break rules, subtotals and page breaks, values already formatted, with no notion of width or page |
| `text.py` | how it *looks* — the fixed-width renderer, and the only layer that knows `LINESIZE`, `PAGESIZE`, wrapping or pagination |

A renderer for HTML or PDF is a fourth module implementing
`render(document, stream, settings, state)` plus an entry in
`report.RENDERERS`; it reuses the first two layers unchanged. Each row
carries its raw values alongside the display text, since a renderer that is
not laying out characters — or a chart — wants the number, not the string.
`tests/test_report_document.py` asserts against the document directly,
including a miniature HTML renderer that proves the model is sufficient to
write one.

Splitting it this way also fixed something: building the whole document
before measuring means a subtotal's width is now known exactly. Rendering
while measuring cannot do that — the SUM column's width has to be settled
before the first row prints, long before any subtotal exists, which
previously meant bounding it with an estimate.

## DESCRIBE and INFO

`DESCRIBE` works on tables and views, and — as in Oracle — on stored program
units, where it lists the parameters:

```console
SQL> DESCRIBE emp
TABLE EMP
+-------+----------+------------------------+
| Name  | Null?    | Type                   |
+-------+----------+------------------------+
| id    | NOT NULL | INTEGER                |
| name  | NOT NULL | VARCHAR2(20)           |
| sal   |          | NUMBER(10,2) DEFAULT 0 |
+-------+----------+------------------------+

SQL> DESCRIBE give_raise
PROCEDURE GIVE_RAISE
+-----------+--------+--------+-----------+
| Argument  | Type   | In/Out | Optional? |
+-----------+--------+--------+-----------+
| P_ID      | NUMBER | IN     |           |
| P_PCT     | NUMBER | IN     | DEFAULT   |
| P_NEW_SAL | NUMBER | OUT    |           |
+-----------+--------+--------+-----------+
```

On a package it lists every subprogram with its signature. That matters more
here than in SQL\*Plus: stored code lives in the database, so a session is
often looking at code it did not write.

`INFO` (SQLcl's richer form) adds the table's constraints and indexes, or a
package's state variables. `DESC` and `INFORMATION` are accepted as
abbreviations. Output keeps the readable grid regardless of `SQLFORMAT`.

### Parquet

Parquet loads like any other format — `LOAD 'sales.parquet' INTO sales NEW` —
and, unlike querying a file in place, it works on **every** engine: DuckDB
does the reading whichever engine the rows are going into (SQLite, DuckDB,
Postgres or MariaDB). It is the one
format that is not pure standard library, so it needs the duckdb package
(`pip install "sqlingpl[duckdb]"`); a clear error says so if it is missing.

It is also the only *typed* source. A CSV hands over text and the column types
are inferred from it; Parquet already knows them, so a date arrives as a
`DATE` and a decimal as a number without a format model. Dates and decimals
cross as ISO text on the way in, since neither driver will bind those Python
types directly, and are parsed back into the target column's type like any
other field. Nested values become JSON text, as they do for JSON and XML.

A binary file read as text used to fail with a `UnicodeDecodeError` out of a
codec; it now says which format it tried and suggests naming one.

## Exporting: SET SQLFORMAT

`SQLFORMAT` swaps the result-set renderer, which turns `SPOOL` into an export
tool — the SQLcl idiom:

```sql
SET SQLFORMAT CSV
SET FEEDBACK OFF
SPOOL employees.csv
SELECT id, name, sal FROM emp ORDER BY id;
SPOOL OFF
```

| Format | Output |
|---|---|
| `default` | the bordered grid |
| `text` / `ansiconsole` | SQL\*Plus layout — headings underlined, no box |
| `csv` | comma separated, quoted only where needed |
| `delimited <d> <l> <r>` | your own delimiter and quotes (`delimited ; [ ]`) |
| `fixed` | every field quoted and padded to its column width |
| `loader` | pipe separated, no heading, no quoting |
| `insert` | one `INSERT` statement per row, table name taken from the query |
| `json` / `json-formatted` | array of row objects; numbers stay numbers |
| `xml` | `<RESULTS><ROW><COL>…` |
| `html` | a plain `<table>` |

`HEADING`, `NULL` and `TERMOUT` apply throughout; `FEEDBACK` is independent, so
`SET FEEDBACK OFF` is part of the export idiom. `SHOW`, `PRINT` and the other
internal listings keep the readable grid regardless, so a session set to CSV is
still navigable.

The `insert` format round-trips:

```console
SET SQLFORMAT INSERT
SPOOL emp.sql
SELECT * FROM emp;
SPOOL OFF
-- later, elsewhere
@emp.sql
```

## Importing: LOAD

`LOAD` (or `IMPORT`) reads a file into a table, converting each field to the
target column's type. File first, then `INTO`, then the table — the reading
order follows the data, and `INTO` already means "destination" everywhere else
in PL/SQL:

```console
SQL> LOAD 'employees.csv' INTO emp
3 rows loaded.

SQL> IMPORT 'orders.json' INTO orders NEW     -- create the table from the file
SQL> LOAD 'data.txt' INTO emp FORMAT CSV TERMINATOR ';' SKIP 1 TRUNCATE
```

The format comes from the file extension and `FORMAT` overrides it:

| Format | From | Shape |
|---|---|---|
| `CSV` / `DELIMITED` | `.csv` `.tsv` `.txt` `.dat` | header row names the columns |
| `JSON` | `.json` | array of objects, or one object |
| `JSONL` | `.jsonl` `.ndjson` | one object per line |
| `XML` | `.xml` | repeating element → row, children and attributes → columns |

Column names match case-insensitively; an empty field becomes NULL. For JSON
and XML the columns are the union of every record's keys, so a record that
omits one simply loads NULL there. The delimiter is sniffed when `TERMINATOR`
is not given.

**Nested data is not decomposed.** Top-level scalars become columns; anything
nested is stored as JSON text. SQLite and DuckDB both shred that in SQL, and
`->>` reads identically on each:

```sql
LOAD 'orders.json' INTO orders NEW;
SELECT id, item->>'$.sku' AS sku FROM orders;
```

That is deliberately more flexible than any fixed normalisation — you choose
the shape. `NORMALIZE`, for decomposing into related tables, is reserved and
reports that it is not implemented rather than being silently ignored.
(`json_extract` exists on SQLite and DuckDB but differs: DuckDB returns the JSON
value, SQLite the bare scalar. `->>` is the portable spelling.)

| Option | |
|---|---|
| `FORMAT f` | `CSV`, `DELIMITED`, `JSON`, `JSONL`, `PARQUET` or `XML`; inferred from the extension when omitted |
| `NEW` / `CREATE` | create the table, inferring each column's type from a sample |
| `RECORD t` | XML only: the element that marks one row |
| `TRUNCATE` / `APPEND` | empty the table first, or add to it (the default) |
| `SKIP n` | ignore `n` lines before the header |
| `TERMINATOR c` / `DELIMITER c` | field separator; `\t` and `TAB` are understood |
| `ENCLOSURE c` | quote character, `"` by default |
| `ROW_LIMIT n` | stop after `n` rows |
| `BATCH_SIZE n` | rows per round trip, 500 by default |
| `DATE_FORMAT m` | how to read date columns |
| `ERRORS n` | how many bad rows to tolerate, 50 by default |
| `ENCODING e` | file encoding |
| `NORMALIZE` | reserved; not implemented |

An option that does not apply to the chosen format is **rejected**, not
ignored — `SKIP` with `FORMAT JSON` says so.

**A bad row does not stop the load.** Each failure is reported with its line
number and reason, and the rest of the file still loads — the common case is a
handful of dud rows, and aborting on the first means finding them one run at a
time:

```console
SQL> LOAD emp messy.csv
2 rows loaded.
3 rows rejected:
  line 3: ORA-01722: invalid number: 'notanumber'
  line 5: expected 5 values, found 3
  line 6: ORA-01861: literal does not match format string ('not-a-date')
```

A load runs inside the current transaction, so `ROLLBACK` undoes all of it.
With `SET SQLFORMAT` it round-trips:

```sql
SET SQLFORMAT CSV
SPOOL emp.csv
SELECT * FROM emp;
SPOOL OFF
-- elsewhere
LOAD emp_copy emp.csv NEW
```

## Comments

`--` to the end of a line and `/* ... */` work as in PL/SQL. `REM[ARK]` is
the SQL\*Plus form: when it is the first word on a line, the rest of that line
is commentary, whatever it contains — `;`, `--` and quotes included.

```sql
REM ============================================
REM  Payroll run -- Alice & Bob, quarter 1
REM ============================================
```

A `REM` line is dropped before substitution runs, so an `&` in prose stays an
`&` rather than prompting for a value. A `--` comment is still scanned,
because that one can sit at the end of a line of real code where the
substitution may be deliberate — `examples/06_report.sql` notes the trap.

A `REM` line ends at its newline — at the prompt it runs immediately rather
than waiting for a terminator, and a file may end on one with no trailing
newline at all.

`REM` has to be a whole word: `REMfoo` and `REMARKS` are identifiers, not
comments. One ambiguity remains, as it does in SQL\*Plus — a line whose first
word is exactly `rem` is a comment, so a column of that name has to share its
line with something else. The exception is `rem := ...`, which is treated as
the assignment it is: a variable may legitimately be called `rem`, and
dropping its assignment would change what the program computes without
saying so.

## Substitution variables and SPOOL

`&name` is replaced before anything is parsed, so a variable can supply any
fragment at all — a value, a column list, a whole predicate:

```sql
DEFINE dept = 10
DEFINE filter = "sal > 3000 AND job = 'ANALYST'"
SELECT ename FROM emp WHERE deptno = &dept AND &filter;
```

| | |
|---|---|
| `&name` | substitute; prompt if undefined, and **don't** remember the answer |
| `&&name` | substitute; prompt if undefined, and keep it for the session |
| `&1`, `&2` | the script's positional parameters |
| `&name.` | a trailing dot ends the name and is consumed (`&base..txt`) |
| `DEFINE n = v` | define one; the right-hand side is itself substituted |
| `DEFINE n` / `DEFINE` | show one / list them all |
| `UNDEFINE n` | remove one |
| `ACCEPT n [PROMPT 't'] [DEFAULT d] [HIDE]` | prompt and define |
| `SET DEFINE OFF \| <char>` | disable substitution, or change the `&` |
| `SET ESCAPE ON \| <char>` | `\&name` stays literal |
| `SET VERIFY ON` | print the `old:` / `new:` form of each line |

Positional parameters come from the command line or from `@`:

```console
$ sqlingpl -d hr.sqlite report.sql 10 SALES   # &1 is 10, &2 is SALES
SQL> @report.sql 10 SALES
```

Two things to know. Substitution applies inside string literals *and comments*
— faithful to SQL\*Plus, and the usual trap (`'AT&T'` will ask for `T`); use
`SET DEFINE OFF` or `SET ESCAPE` around such text. And because the whole
source is expanded before any of it runs, prompting happens up front rather
than when execution reaches the statement; for the scripts this exists for —
parameters at the top, used below — the two are indistinguishable.

`SPOOL` writes to a file **and** the screen, as SQL\*Plus does:

```sql
SPOOL report.lst          -- ".lst" is added when no extension is given
SELECT ... ;              -- grids, DBMS_OUTPUT and PROMPT all captured
SPOOL report.lst APPEND   -- or REPLACE, the default
SPOOL OFF
```

`SHOW SPOOL` reports the destination. The file is closed when the session ends.
`examples/06_report.sql` puts the two together as a parameterised report.

## Stored code lives in the database

`CREATE OR REPLACE PROCEDURE`, `FUNCTION`, `PACKAGE` and `PACKAGE BODY` write
their source into a `sqlingpl_source` table inside the SQLite or DuckDB file.
A unit compiled in one session is callable from the next, and the database
carries its own code the way an Oracle schema does:

```console
$ sqlingpl -d shop.sqlite examples/03_stored.sql    # defines shop package
$ sqlingpl -d shop.sqlite examples/04_use_stored.sql # calls it, defines nothing
```

`SHOW OBJECTS` lists what is stored; `DROP PROCEDURE|FUNCTION|PACKAGE` removes it.

`OR REPLACE` means what it says: without it, a `CREATE` over a name already in
use raises `ORA-00955: name is already used by an existing object`, as Oracle
does. Overwriting working code is exactly what the clause is there to request,
so a plain `CREATE` that quietly did it anyway would throw away the only signal
it carries. Procedures, functions and packages share one namespace, so any of
them collides with any other; a package body collides only with another body,
since sharing its spec's name is the point of it. The check covers stored
program units — a unit and a table of the same name do not collide here,
though they would in Oracle.

A standalone unit cannot be overloaded, in Oracle or here: `CREATE OR REPLACE`
of a procedure with different parameters replaces it outright rather than
adding a second version. Overloading is a package feature.

Source text is stored rather than a compiled form, so it survives upgrades and
can be read back with plain SQL:

```sql
SELECT name, type FROM sqlingpl_source;
```

## What is supported

**Blocks and control flow** — `DECLARE`/`BEGIN`/`EXCEPTION`/`END`, nested and
labelled blocks, `IF`/`ELSIF`/`ELSE`, simple and searched `CASE` (statement and
expression), `LOOP`, `WHILE`, numeric `FOR`, cursor `FOR`, `EXIT`/`CONTINUE`
with labels and `WHEN`, `GOTO` and `<<labels>>`, `NULL`.

**Declarations** — variables with `CONSTANT`, `NOT NULL`, `DEFAULT`/`:=`;
`%TYPE` and `%ROWTYPE` anchoring to tables, columns, variables and cursors;
`SUBTYPE`; `TYPE ... IS RECORD`; associative arrays, nested tables and
`VARRAY`; `REF CURSOR`; `EXCEPTION` with `PRAGMA EXCEPTION_INIT`.

**Types** — `NUMBER(p,s)`, `PLS_INTEGER` and the other integer subtypes,
`VARCHAR2(n)`, `CHAR(n)`, `DATE`, `TIMESTAMP`, `BOOLEAN`, `CLOB`, records and
collections. NUMBER is decimal, not binary floating point, so `0.1 + 0.2` is
exactly `0.3`. Length and precision constraints raise `VALUE_ERROR` on
assignment, as they do in Oracle.

**Subprograms** — nested and stored procedures and functions, `IN`/`OUT`/
`IN OUT` parameters, defaults, named notation (`p => v`), recursion, overloading
by argument count, and lexical scoping.

**Packages** — spec and body, package-level variables with session-lifetime
state, package types and exceptions, body-private subprograms, and the
initialisation section.

**SQL** — `SELECT INTO`, `BULK COLLECT INTO`, `INSERT`/`UPDATE`/`DELETE`/
`MERGE`, `RETURNING INTO`, explicit cursors with parameters, cursor `FOR` loops,
cursor variables (`OPEN ... FOR`), `EXECUTE IMMEDIATE` with `INTO`/`USING`,
cursor attributes (`%FOUND`, `%NOTFOUND`, `%ROWCOUNT`, `%ISOPEN`, `SQL%…`),
`COMMIT`/`ROLLBACK`/`SAVEPOINT`, and scalar subqueries in expressions.

### Bind variables

Every form Oracle offers. PL/SQL variables are bound into SQL automatically,
with or without a `:` prefix — never string-interpolated, so a value containing
a quote cannot change the statement:

```sql
SELECT name INTO v_name FROM emp WHERE dept = v_dept;      -- bare
SELECT name INTO v_name FROM emp WHERE dept = :v_dept;     -- explicit
```

When a name is both a column and a variable, the column wins — Oracle's rule.
A record *field* binds too (`WHERE id = r.id`), and a table alias of the same
name still takes precedence.

Dynamic SQL binds positionally through `USING`, including `OUT` and `IN OUT`:

```sql
EXECUTE IMMEDIATE 'SELECT name FROM emp WHERE id = :1' INTO v USING 2;
OPEN c FOR 'SELECT name FROM emp WHERE id = :1' USING 2;

-- A dynamic PL/SQL block binds by name, so a repeated :n is one bind,
-- and OUT values are written back:
EXECUTE IMMEDIATE 'BEGIN :result := :input * 2; END;' USING OUT v, 21;
EXECUTE IMMEDIATE 'BEGIN add_one(:x); END;' USING IN OUT v;
```

And SQL\*Plus host variables, which live for the session and are visible to
top-level SQL, to `EXEC`, and to any block:

```console
SQL> VARIABLE deptno NUMBER
SQL> EXEC :deptno := 10
SQL> SELECT name FROM emp WHERE dept = :deptno;
SQL> PRINT deptno
```

A block can read and write them too — `BEGIN :deptno := 20; END;`.

**Exceptions** — the predefined conditions (`NO_DATA_FOUND`, `TOO_MANY_ROWS`,
`DUP_VAL_ON_INDEX`, `ZERO_DIVIDE`, `VALUE_ERROR`, `INVALID_CURSOR`,
`CASE_NOT_FOUND`, `COLLECTION_IS_NULL`, `SUBSCRIPT_*` …), user-declared
exceptions, `WHEN ... OR ...`, `WHEN OTHERS`, bare `RAISE` to re-raise,
`RAISE_APPLICATION_ERROR`, `SQLCODE` and `SQLERRM`. Database errors are
translated: a UNIQUE violation arrives as `DUP_VAL_ON_INDEX`, not as a driver
message.

**Built-ins** — roughly 120 functions with Oracle semantics, including the
easy-to-get-wrong ones: 1-based `SUBSTR` with negative offsets, `INSTR`
returning 0 for no match, `MOD` taking the sign of the dividend, `ADD_MONTHS`
clamping to month end, `DECODE` matching NULL to NULL, and the `TO_CHAR` /
`TO_DATE` / `TO_NUMBER` format models (`'FM$9,999.00'`, `'DD-MON-RR'`,
`'Day DD Month YYYY'`).

**Supplied packages** — `DBMS_OUTPUT`, `DBMS_RANDOM`, `UTL_FILE`,
`DBMS_UTILITY` (error stack), and no-op stubs for `DBMS_LOCK`, `DBMS_SESSION`
and `DBMS_APPLICATION_INFO` so existing scripts run rather than stopping.

**Oracle functions inside SQL, not just PL/SQL.** Neither SQLite nor DuckDB has `TO_CHAR`
with an Oracle format model, `NVL`, `DECODE`, four-argument `INSTR`, `INITCAP`,
`SOUNDEX`, `ADD_MONTHS`, `MONTHS_BETWEEN` or `DUAL`. sqlingpl installs them into
whichever engine is connected, so this works on SQLite and DuckDB alike and returns the same bytes:

```sql
SELECT TO_CHAR(SYSDATE, 'MM/DD/YYYY'),
       NVL(commission, 0) + salary,
       DECODE(status, 'A', 'Active', 'I', 'Inactive', 'Unknown')
  FROM emp;
```

The full set installed on SQLite and DuckDB:

| | |
|---|---|
| Null handling | `NVL`, `NVL2`, `NULLIF`, `NANVL`, `DECODE` |
| Text | `SUBSTR`, `SUBSTRB`, `INSTR`, `LPAD`, `RPAD`, `LTRIM`, `RTRIM`, `INITCAP`, `TRANSLATE`, `SOUNDEX`, `REVERSE`, `CHR`, `ASCII`, `LENGTHB`, `VSIZE` |
| Numbers | `MOD`, `REMAINDER`, `POWER`, `SQRT`, `SIGN`, `CEIL`, `FLOOR`, `BITAND`, `WIDTH_BUCKET`, `ORA_HASH`, `GREATEST`, `LEAST` |
| Dates | `SYSDATE`, `SYSTIMESTAMP`, `CURRENT_DATE`, `CURRENT_TIMESTAMP`, `LOCALTIMESTAMP`, `ADD_MONTHS`, `MONTHS_BETWEEN`, `LAST_DAY`, `NEXT_DAY`, `TRUNC`, `ROUND` |
| Patterns | `REGEXP_LIKE`, `REGEXP_REPLACE`, `REGEXP_SUBSTR`, `REGEXP_INSTR`, `REGEXP_COUNT` |
| Conversion | `TO_CHAR`, `TO_DATE`, `TO_NUMBER`, with Oracle format models |
| Session | `USER`, `SYS_GUID`, `SYS_CONTEXT('USERENV', …)` |

**`LISTAGG` and `ROWNUM`** are rewritten rather than installed, being syntax
rather than functions:

```sql
SELECT deptno, LISTAGG(name, ', ') WITHIN GROUP (ORDER BY name) FROM emp
 GROUP BY deptno;                      -- becomes string_agg(...)

SELECT * FROM emp WHERE ROWNUM <= 10;  -- becomes LIMIT 10
SELECT ROWNUM, name FROM emp;          -- becomes row_number() OVER ()

SELECT name FROM (SELECT name FROM emp ORDER BY sal DESC)
 WHERE ROWNUM <= 3;                    -- the top-N idiom, which works
```

`ROWNUM <` is one fewer than `ROWNUM <=`, and a `ROWNUM` predicate sitting
beside others keeps them. An existing `LIMIT` is never overridden.

**One divergence, and it is the famous one.** Oracle assigns `ROWNUM` *before*
`ORDER BY`, so `SELECT * FROM emp WHERE ROWNUM <= 10 ORDER BY sal DESC` gives
ten arbitrary rows and then sorts those ten. Here it becomes `LIMIT`, which
applies after the sort — so you get the ten highest salaries. That is almost
always what the code meant, but it is *not* what Oracle returns, and a report
being migrated may have been written around the Oracle behaviour. Wrapping
the ordering in a subquery, as the top-N idiom above does, is unambiguous on
SQLite and DuckDB alike.

`ROUND` is the one that needs care: `ROUND(sal, 2)` is the engine's own, while
`ROUND(hired, 'MM')` is Oracle's date rounding. They are told apart by the
second argument being a quoted format model, which means scanning the
arguments rather than matching them — the first may hold commas and
parentheses of its own, as in `ROUND(TO_DATE(x, 'YYYY'), 'MM')`.

Oracle column type names work in DDL too — `sal NUMBER(10,2)`,
`name VARCHAR2(30)`, `note CLOB` — on SQLite and DuckDB.

**A bare `SELECT` inside a block prints its rows.** Oracle rejects a `SELECT`
with no `INTO` in PL/SQL (`PLS-00428`); here it displays a result grid, which
makes a block usable as a report:

```sql
BEGIN
  FOR d IN (SELECT DISTINCT dept FROM emp ORDER BY dept) LOOP
    DBMS_OUTPUT.PUT_LINE('-- ' || d.dept || ' --');
    SELECT name, sal FROM emp WHERE dept = d.dept;   -- prints, no INTO needed
  END LOOP;
END;
/
```

It obeys `TERMOUT`, `HEADING` and `FEEDBACK`, sets `SQL%ROWCOUNT`, works inside
stored procedures, and interleaves correctly with `DBMS_OUTPUT`. Note the
direction of this divergence: code written this way runs here and **fails to
compile on Oracle**, so add the `INTO` if you plan to port it.

**Three-valued logic** throughout: `NULL = NULL` is NULL, `FALSE AND NULL` is
FALSE, `x NOT IN (list containing NULL)` is never TRUE, and the empty string is
NULL.

## Sequences

`CREATE SEQUENCE`, `NEXTVAL` and `CURRVAL` work on SQLite and DuckDB, in every
position Oracle allows them:

```sql
CREATE SEQUENCE emp_seq START WITH 100 INCREMENT BY 5 MAXVALUE 900 NOCYCLE;

INSERT INTO emp VALUES (emp_seq.NEXTVAL, 'Alice');
SELECT emp_seq.CURRVAL FROM dual;
INSERT INTO dst SELECT emp_seq.NEXTVAL, x FROM src;   -- a number per row
CREATE TABLE t (id INTEGER DEFAULT emp_seq.NEXTVAL);  -- as a column default
v_id := emp_seq.NEXTVAL;                              -- in PL/SQL
```

DuckDB has real sequences and its own are used, with only the option spelling
translated (`NOCYCLE` becomes `NO CYCLE`, `CACHE` is dropped — it is a
performance hint, not a promise about values). SQLite has none, so they are
emulated: a row per sequence in a catalog table, plus `nextval`/`currval`
registered as functions on the connection. They are *functions* rather than a
value pasted into the statement, which is what gives each row of a multi-row
`INSERT` its own number and what lets a sequence stand as a column `DEFAULT` —
`CREATE TABLE` is rewritten on the way through for that.

A rollback does not reissue a number on SQLite or DuckDB, as in Oracle: handing
the same key to two sessions would be worse than leaving a gap. On SQLite the
counter advances in memory and is written back after each statement, so a
process killed mid-statement loses the numbers it had issued — a gap, which is
what Oracle's `CACHE` produces too. A sequence promises uniqueness, not
consecutiveness.

`USER_SEQUENCES` describes them. The errors carry Oracle's numbers on SQLite
and DuckDB — `ORA-08002` for a `CURRVAL` before any `NEXTVAL`, `ORA-02289` for a
sequence that does not exist, `ORA-08004` for one that has run out — so a
script that handles them handles them either way. One engine difference
remains: DuckDB will not create a sequence whose range holds a single value
(`MINVALUE 1 MAXVALUE 1`).

## Schemas

An application that reads out of several schemas writes every reference
qualified, and that works here — differently for data and for code.

In Oracle a schema is simply *there*, and a script that says `hr.employees`
expects it to be. So it is here: name a schema and it comes into being.

```console
$ sqlingpl -d app.sqlite
SQL> CREATE TABLE hr.employees  (id INTEGER, name VARCHAR2(20));
Schema HR created.
SQL> CREATE TABLE abc.employees (id INTEGER, name VARCHAR2(20));
Schema ABC created.
SQL> CREATE OR REPLACE PROCEDURE hr.load_emp IS ...
SQL> SELECT owner, table_name FROM all_tables WHERE table_name = 'EMPLOYEES';
| ABC   | EMPLOYEES |
| HR    | EMPLOYEES |
```

No setup, and the two are genuinely separate: `hr.employees` and
`abc.employees` are different tables, with stored code qualified the same way.
On DuckDB a schema is made with `CREATE SCHEMA`; on SQLite it becomes a file
beside the database (`app.sqlite` → `app_hr.db`), attached for the session and
re-attached automatically the next time it is named. `SET AUTOSCHEMA OFF`
turns this off and restores the plain "no such schema" error.

**Tables and views** are the engine's business, and SQLite and DuckDB already have
a namespace for them — but not the same one.

DuckDB has real schemas, several to a file:

```sql
CREATE SCHEMA hr;
CREATE TABLE hr.emp (...);
SELECT * FROM hr.emp JOIN payroll.run ON ...;
```

SQLite has none, and uses one file per schema, attached under a name:

```sql
ATTACH DATABASE '/data/hr.sqlite' AS hr;
SELECT * FROM hr.emp;
```

`ATTACH DATABASE` is accepted by both, so the file-per-schema arrangement
works either way if you want one story across engines. Writing it out
yourself matters when a schema's file is somewhere other than beside the
database, which is the one thing `AUTOSCHEMA` cannot guess.

An attachment belongs to the **connection**, not to the file: a new session
sees nothing until it attaches again. Naming them at startup saves an
application replaying that on every connection it takes from a pool:

```console
$ sqlingpl -d app.sqlite --attach hr=/data/hr.sqlite --attach payroll=/data/pay.sqlite
SQL> SELECT e.name, r.amount FROM hr.emp e JOIN payroll.run r ON r.id = e.id;
```

```python
Interpreter(database="app.sqlite", attach={"hr": "/data/hr.sqlite"})
```

They are re-attached after a `CONNECT`, since that replaces the connection
they were living on, and recorded in the register so that later sessions
need no `--attach` at all:

```console
$ sqlingpl -d app.sqlite --attach hr=/data/legacy.sqlite   # once
Schema HR created.
$ sqlingpl -d app.sqlite                                  # every session after
SQL> SELECT COUNT(*) FROM hr.employees;
```

A file that is not there yet is **made**, rather than refused — naming a
schema is how one comes into being everywhere else, and onboarding should
not need a separate step to create an empty file first. A path that cannot
be opened at all, such as one in a directory that does not exist, is still
reported before anything runs.

This is also how an existing database is given a schema name: point
`--attach` at the customer's file and their tables answer to `HR.` from then
on.

A transaction spanning an attached schema and the main database is atomic —
a rollback undoes both. Note that SQLite documents that guarantee for
rollback-journal mode and **not** for WAL, so it is worth re-verifying if you
turn WAL on for read concurrency.

**Stored code** is not a database object here — it is a row in a catalog
table — so its schema is simply part of its name:

```sql
CREATE OR REPLACE PROCEDURE hr.greet      IS BEGIN ... END;
CREATE OR REPLACE PROCEDURE payroll.greet IS BEGIN ... END;

BEGIN hr.greet; END;            -- two different procedures,
BEGIN payroll.greet; END;       -- both callable
```

`HR.GREET` and `PAYROLL.GREET` are two names, stored and resolved as such.
Packages qualify the same way, so `hr.util.tag` finds member `TAG` of package
`HR.UTIL` — the package is everything but the last part, which leaves an
unqualified `util.tag` meaning what it always did. `DROP` and `DESCRIBE` take
qualified names too.

The dictionary reports the two parts separately, as Oracle does: `USER_SOURCE`
and `USER_OBJECTS` give the bare name, and `ALL_OBJECTS`, `ALL_SOURCE` and
`USER_PROCEDURES` carry the schema as `OWNER`, so `WHERE owner = 'HR'` finds
what is in a schema. A unit created without a prefix is owned by the session
user.

`ALL_TABLES`, `ALL_VIEWS` and `ALL_TAB_COLUMNS` see every schema and report
the one an object actually lives in as `OWNER`, so a schema can be asked what
it holds:

```sql
SELECT table_name FROM all_tables WHERE owner = 'HR';
```

`USER_TABLES` keeps to the session's own schema, as `USER_` means in Oracle.
Underneath, SQLite is read through `pragma_table_list`, which spans attached
databases, and DuckDB through `information_schema`, where a table's owner is
its schema — or its catalog, when it came from an attached file.

The two halves differ in one way worth knowing. For a **table** the schema
is a place, so it has to exist first — `CREATE TABLE hr.employees` needs `hr`
attached, or created with `CREATE SCHEMA` on DuckDB. For **stored code** the
schema is only part of the name, so `CREATE PROCEDURE hr.greet` compiles
whether or not any `hr` exists. That is usually what you want when code is
deployed as source, but it does mean a mistyped schema on a procedure is not
caught.

A missing schema reports the same way on SQLite and DuckDB, rather than SQLite's
"unknown database" and DuckDB's "unknown schema":

```console
SQL> CREATE TABLE hr.employees (id INTEGER);
ORA-00942: table or view does not exist: there is no schema HR
           (attach one with --attach hr=<file>, or ATTACH DATABASE '<file>' AS hr)
```

One limit worth knowing: an unqualified call does **not** search other
schemas. There is no `CURRENT_SCHEMA` and no search path, so `greet` will not
find `HR.GREET`.

## Where the interpreter keeps its own tables

Your database holds your data. The stored program source, comments,
sequences and the schema register live apart from it:

```
app.sqlite      emp, orders, ..., dual    your tables, plus DUAL
app_system.db       sqlingpl_source, sqlingpl_comment, sqlingpl_sequence,
                    sqlingpl_schema, sqlingpl_dictionary, dual, and the
                    dictionary views
app_hr.db           employees, dual           a schema's data, plus DUAL
```

`DUAL` is the one thing the interpreter does put in your database, and in
every schema attached to it — `CREATE TABLE IF NOT EXISTS dual (dummy
VARCHAR2(1))` with a single `'X'`. PL/SQL and SQL both select from it
constantly, `hr.dual` has to resolve, and anything opening the file directly
should find it there. A table of that name that already exists is left
exactly as it is, contents and columns included.

That is the SQLite arrangement. DuckDB gets the same separation a different
way — a `sqlingpl_sys` **schema** inside the same file — because it refuses to
write to two attached databases in one transaction, so a separate file would
fail the first time a statement touched both, such as saving a procedure
while an insert was pending.

`sqlingpl_schema` is the register: which schema lives in which file. It is
what lets a schema sit somewhere other than beside the database, and what
makes every known schema available at startup rather than only after
something names it. `--system PATH` puts the system database elsewhere; an
in-memory session keeps it in memory.

One consequence worth knowing: on SQLite a dictionary view may only read
tables in its own database, so every view takes user metadata from pragma
functions, which are the one thing that does reach across. That is why
`USER_VIEWS.TEXT` is null — no pragma reports a view's SQL.

## Columns and constraints in any order

Oracle's `relational_properties` takes column definitions and out-of-line
constraints in any order, and hand-written DDL interleaves them — a column,
the constraint that belongs to it, the next column. SQLite's grammar does not:
once a table constraint appears, everything after it must be one too, so the
statement stops at the next column and takes the rest of the script with it.

This is SQLite alone. Oracle allows the interleaving and so does DuckDB, which
is what makes the fix free — there is no engine on the other side of the
trade. The body is reordered, columns first and constraints after, each group
in the order it was written:

```sql
CREATE TABLE contacts (
  WorkPhone NUMBER(10) NOT NULL,
  CONSTRAINT wtel_length CHECK (LENGTH(WorkPhone) = 10),
  HomePhone NUMBER(10) NOT NULL,          -- used to be a syntax error here
  CONSTRAINT htel_length CHECK (LENGTH(HomePhone) = 10)
)
```

Nothing about the table changes. SQLite attaches no meaning to the order of
constraints among themselves, and column order, which does matter, is
preserved exactly — a moved `CHECK` still refuses the row it always refused.

The rule is *not* "move the lines starting with CONSTRAINT", because a column
can carry a named constraint of its own and has to stay where it is:

```sql
WorkPhone NUMBER(10) CONSTRAINT wp_nn NOT NULL   -- a column
CONSTRAINT wtel CHECK (LENGTH(WorkPhone) = 10)   -- a table constraint
```

What decides is how the piece begins: a table constraint opens with
`CONSTRAINT <name>` followed by `PRIMARY KEY`, `UNIQUE`, `FOREIGN KEY` or
`CHECK`, or with one of those directly. Anything else is a column, because
misreading one would move it and change the shape of the table while the
statement still ran. A body already in a legal order is returned untouched.

## Calling the session's own PL/SQL from SQL

Oracle lets a query call a stored function as if it were built in. Neither
engine knows the package, and SQLite cannot even *parse* the call: it reads
`a.b(...)` as a qualified name followed by a bracket and stops there, so the
statement fails with a syntax error rather than "no such function". A bare
call parses and resolves to nothing.

A name in call position that this session has a function body for is
registered on the connection as a user-defined function. A dotted call is
rewritten to the flat name it was registered under; a bare one already lexes,
so it is registered under its own name and the statement is left as written:

```sql
SELECT purch.pkg_contracts.get_vendor_name(cc.pk) FROM stocks.contracts_v cc
-- the call becomes  __plsql_PKG_CONTRACTS__GET_VENDOR_NAME(cc.pk)
```

All three spellings work — `f(x)`, `pkg.f(x)`, `schema.pkg.f(x)`. The schema
is ignored when resolving, because this interpreter's packages are not
schema-scoped, and a module written against one schema has to run against
this one. The registered name carries the package, so two packages that each
have a `get_name` stay apart.

**A function may run SQL of its own** — looking a value up is the commonest
thing a stored function does. That takes a fresh cursor: the shared one
belongs to the query still being fetched, and sqlite3 refuses to have it
reused ("Recursive use of cursors not allowed"). A statement issued from
inside a call is part of the outer statement and does not begin a transaction
of its own.

**What is deliberately left alone** is a name SQL already provides. A PL/SQL
function called `LENGTH` does not shadow the engine's, because a query that
has always meant the built-in must go on meaning it — so everything sqlingpl
registers itself, plus the engine's own aggregates and core functions, is off
limits. A procedure is not callable either: it returns nothing and cannot
appear in an expression.

**Not on DuckDB.** SQLite registers a function with a name and a callable;
Postgres and MariaDB get the function compiled into their own language. DuckDB
wants the parameter and return types up front and has no variadic form, so
there is no single signature to register a function under — one with a default
is legitimately called with two arguments in one query and three in the next.
On DuckDB these statements fail as they always have.

## The `(+)` outer join

Oracle marks the *optional* side of a join by putting `(+)` on the column
that may be missing. None of the engines here has the old syntax, and a
query using it does not fail in some interesting way — it is a syntax error at
the bracket, so the statement is refused whole. It is rewritten into the ANSI
join every engine has:

```sql
SELECT e.ename, d.dname FROM emp e, dept d WHERE e.deptno = d.deptno (+)
-- becomes
SELECT e.ename, d.dname FROM emp e LEFT JOIN dept d ON e.deptno = d.deptno
```

Two rules do all the work. The table whose columns carry `(+)` is the one
that may be absent, so it becomes the right-hand side of a `LEFT JOIN`. And
a predicate carrying `(+)` belongs in that join's `ON`, not in the `WHERE` —
that distinction is the whole point of an outer join, because a condition on
the optional table evaluated in the `WHERE` throws away exactly the rows the
outer join was keeping:

```sql
WHERE e.deptno = d.deptno (+) AND d.loc (+) = 'NY'   -- every employee
WHERE e.deptno = d.deptno (+) AND d.loc     = 'NY'   -- only the NY ones
```

A predicate that moves into an `ON` takes its bind placeholders with it, so
the parameters are reordered to match — getting that wrong swaps two values
and the query still runs, which is the dangerous kind of wrong.

**What it refuses, and why it refuses rather than guesses.** A wrong join
returns a plausible answer and nothing downstream can tell, so a statement
this cannot read with confidence raises Oracle's own error instead:

| | |
|---|---|
| `(+)` in an operand of `OR` | ORA-01719 — Oracle refuses it too: which rows survive is decided by the other branch |
| `(+)` on both sides of one predicate | ORA-01468 |
| an unqualified `(+)` | ORA-00918 — which table it belongs to needs every table's columns |
| a table function in the `FROM` | ORA-00933 |
| the old and ANSI syntaxes mixed | ORA-00933 |
| every table optional | ORA-01417 |

A subquery in the `FROM` can be the optional side, and a subquery can use
`(+)` for a join of its own; each is translated where it stands. Grouping
brackets are seen through: `WHERE (a.x = b.y (+) AND c.z = d.w (+))` is the
same conjunction as the one without them, and modules write it both ways.
Nothing is ever returned still carrying a mark — a statement that kept one is
not translated but broken, so that is checked rather than assumed.

## Oracle DDL with no counterpart here

A schema script carried over from Oracle is full of statements SQLite and
DuckDB have no notion of. They fall into three groups, and the difference
matters more than the list.

**Accepted, and said so.** `GRANT`, `REVOKE`, `AUDIT`, `CREATE`/`DROP ROLE`,
tablespace and profile DDL, `ANALYZE … COMPUTE STATISTICS`, `ALTER SESSION`,
`SET ROLE`. None can change what a later statement means — there is no
privilege to grant and statistics are an optimiser hint — so the script runs
rather than stopping on line 1:

```console
SQL> GRANT SELECT ON hr.employees TO scott;
GRANT ignored.
```

Reported rather than passed over in silence, so a migration log shows what
was skipped. `ALTER SESSION` adds a note that `NLS_` settings are not
applied, since dropping `NLS_DATE_FORMAT` quietly would change the shape of
every date.

**Implemented, because later statements depend on them.**

```sql
CREATE SYNONYM emp FOR hr.employees;   -- becomes a view
SELECT name FROM emp;                  -- which is why it must not be ignored

CREATE USER scott IDENTIFIED BY tiger; -- in Oracle a user is a schema
CREATE TABLE scott.t (x INTEGER);      -- so the schema has to exist
```

A synonym is a view, which is what one amounts to for reading. Where the view
goes differs by engine, and each rule follows from what that engine will not
do: SQLite forbids a view in one database from reading another but finds an
unqualified name in any attached database, so the view is made beside its
target; DuckDB is the reverse, so the view is made where it was named.

**Stripped, so the statement itself can run.** Oracle's storage directives
say where and how the rows sit on disk, which is the one thing a different
engine is entitled to decide for itself. A table definition exported from
Oracle is used as written:

```sql
CREATE TABLE emp (
  "EMPNO"  NUMBER(4,0) NOT NULL ENABLE,
  "ENAME"  VARCHAR2(10 BYTE),
  "SAL"    NUMBER(7,2) DEFAULT 0 NOT NULL ENABLE
) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255
  NOCOMPRESS LOGGING TABLESPACE "USERS"
  STORAGE (INITIAL 65536 NEXT 1048576 FREELISTS 1 BUFFER_POOL DEFAULT);
```

`TABLESPACE`, `STORAGE (…)`, `PCTFREE`, `PCTUSED`, `INITRANS`, `MAXTRANS`,
`FREELISTS`, `BUFFER_POOL`, `LOGGING`/`NOLOGGING`, `PARALLEL`, `COMPRESS`,
`CACHE`, `MONITORING`, `ROWDEPENDENCIES`, `SEGMENT CREATION`, `ORGANIZATION`
and `ENABLE ROW MOVEMENT` all go, on `CREATE TABLE` and `CREATE INDEX` alike.
So does the `ENABLE` that Oracle writes after `NOT NULL` inside the column
list. What is *kept* is everything that describes the data: types, defaults,
`NOT NULL`, and constraints.

Only outside quoted text and only at the statement's top level, so a column
named `CACHE`, a default of `'TABLESPACE users'` and a `CONSTRAINT … PRIMARY
KEY (id)` are all left alone.

Partitioning goes too. `PARTITION BY` and everything after it — the method,
the key, the partition list and each partition's own storage — describes
where rows are kept rather than what they are, and its clause runs to the end
of the statement, so it is taken whole rather than picked apart:

```sql
CREATE TABLE sales (id NUMBER, sold DATE) TABLESPACE users
  PARTITION BY RANGE (sold)
  (PARTITION p1 VALUES LESS THAN (TO_DATE('2024-01-01','YYYY-MM-DD'))
     TABLESPACE u1,
   PARTITION p2 VALUES LESS THAN (MAXVALUE) TABLESPACE u2);
```

`SUBPARTITION BY` and `PARTITIONS n` come with it.

**Enforced where it can be, recorded where it cannot.** An Oracle export
declares its tables first and their keys afterwards, and neither SQLite nor DuckDB will
add an arbitrary constraint to a table that already exists. Refusing would
stop the script; ignoring would leave a schema that looks as though it has no
keys at all. So there are three attempts, in order of how much each buys:

1. the statement as written, in case the engine takes it — DuckDB accepts a
   primary key this way, SQLite nothing;
2. for a primary or unique key, a **real unique index**, which SQLite and DuckDB
   will create on an existing table and will enforce;
3. failing those, a row in the catalog, so the dictionary can still report a
   key that nothing polices.

Step 2 is the one that matters in practice: it keeps a duplicate from passing
here and failing only once the application reaches real Oracle. Oracle backs
its own keys with an index of the constraint's name, so `USER_INDEXES` ends up
more faithful too, not less.

```console
SQL> ALTER TABLE dept ADD CONSTRAINT dept_code_uk UNIQUE (code);
Table altered.

SQL> INSERT INTO dept VALUES (2, 'A');
ORA-00001: unique constraint violated

SQL> ALTER TABLE emp ADD CONSTRAINT fk_emp_dept
  2    FOREIGN KEY (deptno) REFERENCES dept (id);
Constraint FK_EMP_DEPT recorded; this engine cannot add one to an existing
table, so it is not enforced.

SQL> SELECT constraint_name, constraint_type, status, references_what
  2    FROM user_constraints;
| DEPT_CODE_UK | U | ENABLED  |          |
| FK_EMP_DEPT  | R | DISABLED | DEPT(ID) |
```

`DISABLED` is Oracle's own word for a constraint that is declared but not
enforced, so the distinction shows up in the vocabulary a script already
knows. What a recorded key still buys is that an application can read how its
tables relate — Forms builds master-detail blocks from exactly this — even
where the engine will not police it. Run against the HR schema, 7 primary
keys and 1 unique key come out enforced on SQLite and DuckDB, and only the 10
foreign keys are left recorded.

Two details worth knowing:

* **A unique index is not quite a primary key.** Oracle's `PRIMARY KEY` is
  `UNIQUE` *and* `NOT NULL`, and an index is only the first half. DuckDB will
  add the second to an existing column; SQLite cannot, and says so rather
  than leaving a key that quietly admits nulls:

  ```console
  Constraint T_PK enforces uniqueness; ID can still be null, which this
  engine cannot change on an existing table.
  ```

  Columns declared `NOT NULL` in the `CREATE TABLE` — which is what an export
  emits — never reach this.

* **Duplicate rows refuse the key.** Oracle raises ORA-02437 rather than
  declaring a key its data breaks, and so does this: recording it `DISABLED`
  would leave the schema claiming something untrue of the rows already there.

`ALTER TABLE ... DROP CONSTRAINT` drops the index with the constraint, so the
rule never outlives the declaration. Neither SQLite nor DuckDB has that
statement either.

**Stored, and fired.** A `CREATE TRIGGER` is kept as source and fired by the
engine around the DML it runs — row triggers with `:NEW` and `:OLD`, and
statement triggers:

```console
SQL> CREATE OR REPLACE TRIGGER secure_employees
  2    BEFORE INSERT OR UPDATE OR DELETE ON EMPLOYEES
  3    FOR EACH ROW
  4  BEGIN secure_dml; END;
  5  /
TRIGGER SECURE_EMPLOYEES recorded.
```

It also appears in `USER_OBJECTS` and its text in `USER_SOURCE`, so whoever
has to port it can find it.

**And its header is taken apart**, into the columns `USER_TRIGGERS` and
`ALL_TRIGGERS` publish — so "what fires on EMP, and when" has an answer
without reading the source back and parsing it again:

```console
SQL> SELECT trigger_name, trigger_type, triggering_event, table_name, status
  2    FROM user_triggers;
| EMP_AUDIT        | BEFORE EACH ROW | INSERT OR UPDATE           | EMP       | DISABLED |
| SECURE_EMPLOYEES | BEFORE EACH ROW | INSERT OR UPDATE OR DELETE | EMPLOYEES | DISABLED |
```

`WHEN_CLAUSE`, `REFERENCING_NAMES`, `BASE_OBJECT_TYPE`, `ACTION_TYPE`,
`DESCRIPTION` and `TRIGGER_BODY` are there too, with Oracle's meanings: a
statement trigger reads `AFTER STATEMENT`, an `INSTEAD OF` one is on a
`VIEW`, `AFTER LOGON ON DATABASE` is an `AFTER EVENT`, and a compound trigger
is `COMPOUND`.

`STATUS` is always `DISABLED`. It is the same word the recorded constraints
use and it means the same thing — the object is known and not in force.
Reporting `ENABLED` would be the one answer an admin screen could act on and
be wrong about.

Reading the header is deliberately tolerant rather than a grammar: a schema
script is where triggers arrive from, and a header this does not understand
should cost the header, not the script. Unknown words are skipped, so the DB2
triggers that turn up in ported schemas still yield a usable row —

```sql
CREATE TRIGGER cq.pth0401 NO CASCADE BEFORE INSERT ON cq.s_addr_org
  REFERENCING NEW AS n FOR EACH ROW MODE DB2SQL
  BEGIN ATOMIC SET n.partition_column = 1; END
```

— `NO CASCADE` and `MODE DB2SQL` mean nothing here and are passed over, while
the timing, the event, the table and `REFERENCING NEW AS n` all come through.
Anything illegible comes back as null rather than as an error.

`ALTER TRIGGER ... ENABLE`/`DISABLE`/`COMPILE` is accepted and does nothing,
which is what it amounts to when nothing fires: a load script that turns its
triggers off and on again should not stop over it. `DROP TRIGGER` removes
both the source and the dictionary row. A database written before these views
existed is filled in from the source it already holds the first time it is
opened — otherwise `USER_OBJECTS` would list triggers that `USER_TRIGGERS`
denied.

**Oracle's view DDL.** `CREATE OR REPLACE VIEW` works on SQLite and DuckDB —
SQLite has no such form, so the old view is dropped first, which is what `OR
REPLACE` asks for — and the trailing `WITH READ ONLY` or `WITH CHECK OPTION`
is stripped, neither SQLite nor DuckDB having a notion of either.

One subtlety worth knowing about, since it bites exactly this kind of file:
a string literal may continue onto a line that begins with a word the
interpreter otherwise treats as a command. Oracle's own HR comments do it —

```sql
COMMENT ON COLUMN employees.department_id IS 'Department id where employee
works; foreign key to department_id
column of the departments table';
```

— where the third line starts with `COLUMN`. Substitution and the line
commands are handled a line at a time, so an open literal is tracked across
lines and such a line is left as the text it is.

A semicolon inside the text is the same hazard from the other side:

```sql
COMMENT ON COLUMN employees.phone_number IS 'Phone number of the employee;
includes country code and area code';
```

At the prompt a statement is taken to end at a trailing `;`, so the first
line there looks finished when it is not. An unclosed literal suspends that
rule, and the prompt asks for more.

A schema as Oracle SQL Developer Data Modeler emits it — storage clauses,
`CHAR (2 BYTE)`, constraints added after the tables, a `WITH READ ONLY` view,
sequences carrying Oracle's 28-nine maximum, triggers and all — runs with no
errors on SQLite or DuckDB. `tests/data/hr_schema.sql` is exactly that, kept as
a test.

**Every object type a Data Modeler script can emit** is accounted for, so a
schema export runs from end to end:

| | |
|---|---|
| Built for real | `TABLE`, `INDEX`, `VIEW`, `SEQUENCE`, `SYNONYM`, `USER`, `PACKAGE`, `PACKAGE BODY`, `PROCEDURE`, `FUNCTION`, `DIRECTORY` |
| `GLOBAL TEMPORARY TABLE` | a permanent table whose rows are discarded where Oracle discards them |
| `MATERIALIZED VIEW` | made as a plain view — same rows, never stale, and the `REFRESH` clauses have nothing to do |
| Kept as source, and run | `TRIGGER` (fired around DML), `TYPE` and `TYPE BODY` (objects and their methods) — visible in `USER_OBJECTS` and `USER_SOURCE`, and a trigger's header in `USER_TRIGGERS` |
| Enforced or recorded | primary and unique keys become real unique indexes; foreign keys and checks are recorded |
| Accepted and noted | `ROLE`, `TABLESPACE`, `PROFILE`, `CLUSTER`, `CONTEXT`, `DIMENSION`, `DISKGROUP`, `ROLLBACK SEGMENT`, `DATABASE`, and the `DROP` of each |

A global temporary table splits what the engines join: in Oracle the
*definition* is permanent and belongs to the schema, while the *rows* belong
to a session and a transaction. A plain `CREATE TEMPORARY TABLE` would keep
the rows and lose the definition, so the table is made permanent and the rows
are cleared where Oracle clears them — at each `COMMIT` for `ON COMMIT DELETE
ROWS`, and at the end of the session either way:

```console
SQL> CREATE GLOBAL TEMPORARY TABLE taxable_emp (empno number(5), ...)
  2    ON COMMIT DELETE ROWS;
SQL> INSERT INTO taxable_emp VALUES (1,'Alice',5000,500);
SQL> SELECT COUNT(*) FROM taxable_emp;    -- 1
SQL> COMMIT;
SQL> SELECT COUNT(*) FROM taxable_emp;    -- 0
```

The clearing happens *before* the commit, so it is part of the same
transaction, which is where Oracle puts it. A session killed outright may
leave rows behind; the next session clears them on its way out.

`CREATE DIRECTORY` is honoured rather than ignored, because `UTL_FILE` opens
through it: Oracle names a directory object, not a path, and a script that
said `UTL_FILE.FOPEN('DMP', …)` would otherwise look for a folder called
`DMP`. A name that was never defined is still taken as a path.

`CREATE TYPE` is kept but not yet usable — PL/SQL cannot declare a variable
of a schema-level type, which is said plainly when one is recorded rather
than discovered later. Two things around it used to contradict that message
by accepting one in silence, and both are refused now, at the line that
writes them:

```console
SQL> CREATE TABLE people (id NUMBER, home addr_t);
ORA-06550: type 'ADDR_T' is a schema-level type, which cannot hold a value here
SQL> DECLARE a addr_t; BEGIN NULL; END;
ORA-06550: type 'ADDR_T' is a schema-level type, which cannot hold a value here
```

The column used to be *created* — SQLite accepts any word as a type name — so
the table held a column nothing could read or write and the dictionary
reported `ADDR_T` as its data type, which reads like support. The declaration
used to pass and fail two errors later, on an attribute read (`ORA-06530`) or
a constructor (`must be declared`), neither of which mentions schema-level
types. The permissiveness this narrows is kept where it belongs: a type name
nobody declared may be an Oracle type this does not model, and those are
still accepted.

**An object table is expanded rather than refused.** `CREATE TABLE a OF b` is
how an export script writes one, and no engine underneath parses it at all —
it stops at `OF`. The type's attributes become the table's columns:

```console
SQL> CREATE TABLE addresses OF addr_t OID '8A9B1C2D3E4F5061728394A5B6C7D8E9';
Table ADDRESSES built from the attributes of type ADDR_T: STREET, CITY, ZIP.
OID ignored -- there are no object identifiers here.
```

The rows are then ordinary columns rather than object instances, which is the
same trade the rest of the type support makes — a table whose columns are
right is useful, and a statement that stops the script is not. A constraint
list is carried over; `OID` and `OIDINDEX` describe storage for object
identifiers that do not exist here, so they are dropped and reported. A table
of a collection type, or of a type that was never created, is left alone:
there is no attribute list to build a shape from, and an invented one would
be worse than the error.

**Still refused.** `CREATE DATABASE LINK` — later code says `emp@remote`, and
pretending would fail confusingly there instead.

## The data dictionary

A PL/SQL script asks the database about itself in one language; SQLite and
DuckDB answer in their own. These views translate, so the same script works
on either:

```sql
SELECT table_name FROM user_tables;
SELECT column_name, data_type, nullable FROM user_tab_columns
 WHERE table_name = 'EMP' ORDER BY column_id;
SELECT text FROM user_source WHERE name = 'BONUS' ORDER BY line;
```

| View | Holds |
|---|---|
| `USER_TABLES` | tables |
| `USER_TAB_COLUMNS` | columns, with type, nullability and position |
| `USER_VIEWS` | views, with their text |
| `USER_OBJECTS` | tables, views and stored program units together |
| `USER_SOURCE` | stored source, **one row per line**, as Oracle gives it |
| `USER_PROCEDURES` | stored procedures, functions and packages |
| `USER_INDEXES`, `USER_IND_COLUMNS` | indexes |
| `USER_CONSTRAINTS` | primary, foreign and unique keys, with `STATUS` saying which are enforced |
| `USER_TRIGGERS` | triggers, header by header — when they fire, on what, and the body |
| `USER_TAB_COMMENTS`, `USER_COL_COMMENTS` | what `COMMENT ON` recorded |

Underneath, SQLite is read through `sqlite_master` and `pragma_table_info`,
DuckDB through `information_schema` and `duckdb_indexes()`. Two details make
these behave like Oracle's rather than like thin aliases:

* **Names come back uppercase.** Oracle folds unquoted identifiers up and
  scripts are written to match — `WHERE table_name = 'EMP'` is the idiom, and
  against a lowercased name it would silently return nothing.
* **The dictionary hides itself.** Neither these views nor the interpreter's
  own tables appear in `USER_TABLES`, `USER_OBJECTS` or `SHOW TABLES`, any
  more than Oracle lists its dictionary there.

Each view also exists under Oracle's `ALL_` name, carrying the extra `OWNER`
column those have — so a query written `WHERE owner = USER` works, which is
how much of the dictionary is queried. `USER` and `OWNER` come from one
definition for exactly that reason: were they to disagree, such a query would
return nothing at all rather than complain. There is one schema here, so the
`USER_`/`ALL_` distinction has nothing else to mean. `DBA_` views are not
provided. The views are created at connect time, so a query never has to ask
for them first.

## COMMENT ON

Oracle's object comments work on SQLite and DuckDB:

```sql
COMMENT ON TABLE  emp     IS 'Staff records, one row per employee';
COMMENT ON COLUMN emp.sal IS 'Monthly, before tax';
COMMENT ON TABLE  emp     IS NULL;          -- takes it back
```

Neither SQLite nor DuckDB can be left to do this. SQLite has no `COMMENT` statement at
all; DuckDB has one, but keeps the text where Oracle's dictionary views
cannot reach it. Both are intercepted, and the text is stored in the database
beside the stored program source — so a comment survives into the next
session, and a script behaves identically whichever engine it runs on.

Read them back the way an Oracle script would:

```sql
SELECT table_name, comments FROM user_tab_comments;
SELECT table_name, column_name, comments FROM user_col_comments;
```

`ALL_TAB_COMMENTS` and `ALL_COL_COMMENTS` are the same views under Oracle's
other name. `DESCRIBE` shows the comments too, but only once a table has
some, so output for an uncommented table is unchanged:

```console
SQL> DESCRIBE emp
TABLE EMP -- Staff records, one row per employee
+-------+----------+---------+---------------------+
| Name  | Null?    | Type    | Comments            |
+-------+----------+---------+---------------------+
| id    | NOT NULL | INTEGER |                     |
| sal   |          | NUMBER  | Monthly, before tax |
+-------+----------+---------+---------------------+
```

`TABLE`, `VIEW` and `COLUMN` are supported; commenting on something that does
not exist raises `ORA-00942` or `ORA-00904` rather than being recorded
against nothing. Dropping a table drops its comments with it. The tables and
views behind all this are hidden from `SHOW TABLES`, since a script asking
what tables exist did not mean the dictionary.

## Date arithmetic

In Oracle, adding a number to a date adds that many **days**, and sqlingpl
makes SQLite and DuckDB agree:

```sql
SELECT SYSDATE + 10 FROM dual;      -- ten days from now
SELECT hired - 30 FROM emp;         -- thirty days before
SELECT SYSDATE + 0.5 FROM dual;     -- twelve hours
```

Neither SQLite nor DuckDB does this unaided. SQLite has no date type — its dates are
text, and `+` coerces that text to a number, so `hired + 10` quietly returned
a *year*. DuckDB is typed and refused outright, since it adds an integer to a
`DATE` but not to the `TIMESTAMP` that `SYSDATE` returns.

The rewrite applies to terms that are certainly dates: the date
pseudo-columns (`SYSDATE`, `SYSTIMESTAMP`, `CURRENT_DATE`) and columns
declared `DATE` or `TIMESTAMP` in a table the statement names. The offset may
be a literal, a fraction, or a PL/SQL variable. Anything more elaborate on
the right-hand side — `SYSDATE + 1/24`, or date-minus-date — is left to the
engine rather than guessed at, since a wrong rewrite would change an answer
silently, which is the failure being fixed. Inside PL/SQL, where sqlingpl
evaluates the expression itself, all of it already worked.

## Engine differences

The same script should behave identically on SQLite and DuckDB; the test suite
runs in full against each. Three places where the engine shows through:

| | SQLite | DuckDB |
|---|---|---|
| `SAVEPOINT` / `ROLLBACK TO` | yes | **not implemented by DuckDB** — reported as `ORA-01086` |
| Constraint violation inside a transaction | rolls back the statement, as Oracle does | rolls back the **whole transaction**; sqlingpl reports this rather than letting later statements fail oddly |
| Oracle function set | always available | needs `numpy` for the format-model functions (`TO_CHAR`, `TO_DATE`, `DECODE`, `INSTR`, …); the rest are SQL macros and always work |
| Querying a file as a table | no | **yes** — `SELECT * FROM 'sales.csv'`, and Parquet, JSON and globs besides |
| `ROWID` as row identity | **durable** — survives deletes and reconnects | **positional** — renumbered when a delete's gap is compacted |
| Oracle column types in DDL | any type name is accepted as written | `VARCHAR2(30)` and `NUMBER(10,2)` are rewritten to DuckDB spellings, so `DESCRIBE` reports `VARCHAR` |

Oracle's length qualifier — `VARCHAR2(30 CHAR)`, `CHAR(5 BYTE)` — is
accepted on SQLite and DuckDB and dropped, since neither parses it and neither
enforces the length it qualifies.

### ROWID is not a key on DuckDB

SQLite and DuckDB both read `ROWID` and both accept it in a `WHERE` clause, so it looks
interchangeable. It is not. SQLite's is a durable identity; DuckDB's is the
row's position in storage:

```console
session A:  ROWID 0,1,2 for ids 1,2,3   →  DELETE id=1  →  ROWID 1,2 for ids 2,3
reopen:     ROWID 0,1   for ids 2,3     ←  renumbered
```

The delete leaves a gap, and reopening the file compacts it — after which
every surviving row has a different `ROWID`. Within one connection the value
holds steady, which is what makes this worth stating plainly: it tests fine
and fails later.

That rules `ROWID` out as a remembered row identity on DuckDB — for an
application that locks a row, holds its `ROWID`, and writes back through it,
a stale value does not raise an error. It addresses a **different row**, and
the update lands on the wrong record silently. Use the primary key instead,
which is portable, and which PostgreSQL will also require: its `ctid` has
exactly the same instability.

The file-querying row is worth knowing about. Under `-e duckdb`, a CSV, JSON or
Parquet file can be named wherever a table can — including inside a PL/SQL
block, and joined to real tables — because SQL reaches the engine as written:

```sql
SELECT region, SUM(amount) FROM 'sales_q*.csv' GROUP BY region;
```

Nothing in sqlingpl implements this; it is DuckDB's, and on SQLite the same
query is `ORA-00942`. `LOAD` is the portable route — what it adds is working
on SQLite too, and loading into a table you declared. DuckDB handles awkward
files perfectly well on its own: `null_padding=true` fills in a short row's
missing fields rather than dropping it, and `store_rejects=true` puts every
value it could not read into a `reject_errors` table with its line number.
`examples/09_duckdb_files.sql` covers both and where the line falls.

DuckDB's Python UDF machinery requires numpy. Without it, `NVL`, `NVL2`,
`SYSDATE` and `ADD_MONTHS` still work (they install as SQL macros), and
anything else raises a message that says why rather than a raw catalog error.

```console
$ pip install "sqlingpl[duckdb]"   # pulls in duckdb and numpy
```

## Running against Oracle

You do not need Oracle for anything above. If you already have an Oracle
database, sqlingpl can connect to it too, so the same script can be checked
against Oracle itself:

```console
$ pip install "sqlingpl[oracle]"
$ sqlingpl -e oracle -d user/password@host:1521/service script.sql
```

Nothing is translated there: each statement goes to Oracle as written, and
Oracle compiles and runs the stored code.

## Host operating-system commands

sqlingpl runs no host commands. `HOST`, `EDIT` and their abbreviations are
refused with an error rather than ignored: silently succeeding would tell a
script that work happened when it did not, and the script would go on to
depend on it. There is no `!` shorthand, no shell-out from `SET`, and nothing
in the interpreter spawns a process.

This rules out SQL\*Plus's `EDIT` entirely. The rest of its buffer commands
— `LIST`, `RUN`, `/`, `DEL`, `APPEND`, `CHANGE`, `INPUT` — are in-memory, and
`SAVE`, `GET` and `STORE` are plain file reads and writes of the same kind
`SPOOL`, `LOAD` and `START` already do, so none of them are affected by this.

## What is not supported

**Calling a PL/SQL function from SQL on DuckDB.** `SELECT my_function(col)
FROM t` works on SQLite, Postgres and MariaDB, for standalone functions and
package functions alike. DuckDB cannot call back into the interpreter, so
there the statement fails with "Scalar Function with name … does not exist".
Compute the value in PL/SQL and bind it instead:

```sql
FOR r IN (SELECT id, qty, price FROM orders) LOOP
  v_total := line_total(r.qty, r.price);            -- in PL/SQL
  UPDATE orders SET total = v_total WHERE id = r.id; -- r.id binds fine
END LOOP;
```

**The `MODEL` clause** is not translated, and fails as a syntax error.

**`TABLE()` over a collection built in the statement** —
`SELECT * FROM TABLE(nums(10, 30))`, or the same inside `CAST(... AS nums)` —
fails as a syntax error. `TABLE()` over a PL/SQL collection variable, a
package variable, or a function that returns a collection (pipelined or not)
works; build the collection in PL/SQL first and select from that.

**`FORALL`** runs as a loop, one statement per element, rather than a single
batched round trip. The results are the same, `SAVE EXCEPTIONS` included;
only the speed-up is missing.

**SQL beyond what the engines share.** SQL runs on the underlying database, so
it is that database's dialect underneath. The common Oracle forms are
translated or installed on top — `DUAL`, Oracle's scalar functions and type
names, `CONNECT BY`, `(+)` outer joins, `MERGE`, `ROWNUM` — so most
PL/SQL-embedded SQL runs unchanged, but less common Oracle-only syntax may not.

## Design

```
sqlingpl/
  lexer.py           source -> tokens (hand-written scanner)
  ast_nodes.py       AST dataclasses
  parser.py          tokens -> AST (recursive descent)
  interpreter.py     tree-walking evaluator
  scope.py           lexical scope chain
  types.py           type system, coercion, composite values
  cursors.py         cursor runtime and attribute semantics
  errors.py          conditions and control-flow signals
  builtins.py        built-in function library
  formats.py         TO_CHAR / TO_DATE format models
  sql_functions.py   Oracle SQL functions installed into SQLite and DuckDB
  packages.py        DBMS_OUTPUT, DBMS_RANDOM, UTL_FILE
  catalog.py         persistent store for stored program units
  sql_engine.py      SQLite / DuckDB access and bind-variable rewriting
  settings.py        SQL*Plus SET options
  substitution.py    &name expansion, DEFINE / ACCEPT
  renderers.py       SET SQLFORMAT output formats
  describe.py        DESCRIBE / INFO
  loader.py          LOAD
  repl_support.py    line editing, history, TAB completion
  cli.py             command line and REPL
  __main__.py        makes "python -m sqlingpl" work
```

Three decisions shape the rest:

**An AST, not a token walk.** The interpreter builds a tree and evaluates it,
using Python's own call stack and exceptions. An `EXCEPTION` block becomes a
`try`/`except` around a statement list, so a condition raised three subprograms
deep reaches the right handler with no unwinding bookkeeping; a recursive PL/SQL
function becomes a recursive Python call with a real frame per invocation; and a
package compiles once and is invoked from anywhere.

**SQL is captured as text, not parsed.** When the parser meets a `SELECT` or a
DML statement it slices the original source and hands it to the database, which
is a far better SQL parser than anything here and preserves whatever dialect
syntax was written. The parser only understands the PL/SQL parts bolted on to
SQL: a `SELECT`'s `INTO` list and a DML statement's `RETURNING ... INTO`.
Binding bare PL/SQL variables into that text needs both the symbol table and the
real column list of the tables involved, since an ambiguous name resolves to the
column.

**Ambiguity is resolved at runtime.** `t(1)` may be a function call or a
collection subscript; `a.b` may be a record field, a package variable, or a
collection method. PL/SQL cannot tell these apart syntactically either — it uses
the symbol table — so the parser emits neutral nodes and the interpreter decides.

Keywords deliberately are *not* a token kind. Almost every PL/SQL keyword is
non-reserved (`COUNT`, `VALUE`, `TYPE`, `NAME` and `LEVEL` are all legal
variable names), so words lex as identifiers and the parser asks for a keyword
by position.

## Tests

```console
$ python -m pytest                              # SQLite
$ SQLINGPL_TEST_ENGINE=duckdb python -m pytest   # the same suite, on DuckDB
$ python -m pytest -m "not slow"                # skip the terminal-driving tests
```

1094 tests covering the language, SQL integration, bind variables, transactions,
subprograms and packages, collections, the built-in library, SET options,
report formatting, the
embedding API, the command line, and the interactive prompt — the last of these
driving a real pseudo-terminal, since that is the only way to press an arrow
key — written against documented Oracle
behaviour, including the corner cases that are easy to get subtly wrong. The
whole suite runs against SQLite and against DuckDB; one test is skipped on each for the
`SAVEPOINT` difference above.

## Examples

```console
$ sqlingpl examples/01_tour.sql               # the language
$ sqlingpl examples/02_database.sql           # SQL, cursors, transactions
$ sqlingpl -d shop.sqlite examples/03_stored.sql  # stored procedures and a package
$ sqlingpl -d shop.sqlite examples/04_use_stored.sql   # calling them next session
$ sqlingpl examples/05_payroll.sql            # a payroll run, end to end
$ sqlingpl -d hr.sqlite examples/06_report.sql 10  # parameterised, spooled report
$ cd examples && sqlingpl 07_import_export.sql # LOAD, SQLFORMAT and SPOOL
$ sqlingpl examples/08_classic_report.sql     # COLUMN, BREAK, COMPUTE, TTITLE
$ cd examples && sqlingpl -e duckdb 09_duckdb_files.sql  # query CSV/JSON/Parquet in place
$ python examples/embed.py                   # sqlingpl used as a library
```

## Reporting problems

sqlingpl is free and comes without a support agreement, but problem reports
are welcome and read. Please
[open an issue](https://github.com/sqling-com/sqlingpl/issues) with the
script, or the smallest part of it that shows the problem, the engine you ran
it on, and what Oracle does with the same script. Fixes go out in new
releases; there is no promised response time.

sqlingpl is not affiliated with or endorsed by Oracle Corporation. Oracle,
PL/SQL and SQL*Plus are trademarks of Oracle and/or its affiliates.

## License

MIT — Copyright (c) 2026 Data Design Group, Inc. See [LICENSE](LICENSE).
