TxtSql
A lightweight DBMS that stores data in tab-separated-value (TSV) files with a simple SQL interface.
Architecture
SQL string → Lexer → Tokens → Parser → AST → Optimizer → Executor → Storage (TSV + Indexes)
↓ ↓
Plan / Trace Evaluator (3VL)
| Module | Role |
|---|---|
lexer.py |
Tokenises SQL text into Token stream |
parser.py |
Recursive-descent parser producing AST nodes (ast.py) |
index.py |
In-memory hybrid Hash + sorted-array (bisect) secondary indexes (ColumnIndex) |
optimizer.py |
Predicate pushdown (outer-join safe), implicit comma-join rewrite, equi-join key extraction |
plan.py |
PlanNode tree, runtime operator metrics, token & AST serialization (EXPLAIN [ANALYZE]) |
evaluator.py |
Evaluates expressions & compiles SQL three-valued-logic predicates (EvalContext) |
executor.py |
QueryExecutor runs statements (Index Scan, Hash Join, EXPLAIN, transactions, CHECK TABLE) |
io_handlers.py |
External .xlsx / .csv / .tsv import and export |
storage.py |
Directory-scoped StorageEngine & Table with (mtime_ns, size) cache, indexes.txt, and snapshots |
result.py |
Structured QueryResult (including plan, tokens_info, ast_tree) and StatementKind |
engine.py |
Database(data_dir, enable_optimizations=True) orchestrator & execute_sql() |
cli.py |
Interactive REPL with ASCII table output |
gui_controller.py |
Headless GUI controller (script spans, context autocomplete, history, metadata, formatting) |
gui.py |
Tkinter desktop GUI client (txtsql-gui) with active-statement highlight & plan visualizer |
Requirements
- Python >= 3.12
openpyxl(forIMPORTfrom.xlsxfiles)
pip install openpyxl
Usage
CLI (interactive REPL):
python -m txtsql [--dir ./data]
# or: txtsql
GUI (Tkinter desktop client):
python -m txtsql --gui [--dir ./data]
# or: txtsql-gui
Python API (directory-scoped session & structured results):
from txtsql import Database
db = Database("./my_data")
res = db.execute("SELECT id, name FROM employees ORDER BY id ASC;")
print(res.columns, res.rows)
Welcome to TxtSql CLI. Type your SQL statement and press Enter.
txtsql> CREATE TABLE employees (id NUMBER, name STRING, salary NUMBER)
txtsql> INSERT INTO employees VALUES (1, 'Alice', 75000)
txtsql> INSERT INTO employees VALUES (2, 'Bob', 62000)
txtsql> SELECT * FROM employees ORDER BY salary DESC
+----+-------+--------+
| id | name | salary |
+----+-------+--------+
| 1 | Alice | 75000 |
| 2 | Bob | 62000 |
+----+-------+--------+
SQL Reference
CREATE TABLE
CREATE TABLE [IF NOT EXISTS] table_name (col1 TYPE, col2 TYPE, ...);
Types: STRING, NUMBER (INT / DECIMAL / VARCHAR accepted as aliases)
INSERT
INSERT INTO table_name VALUES (val1, val2, ...);
INSERT INTO table_name (col1, col2) VALUES (val1, val2);
INSERT INTO table_name VALUES (1, 'a'), (2, 'b');
INSERT INTO dst (id, name) SELECT id, name FROM src WHERE active = TRUE;
Values: 'string', 42, 3.14, -5, NULL, TRUE, FALSE
SELECT
SELECT [DISTINCT] *, table.*, col1, col2, ... FROM table_name
[WHERE condition]
[GROUP BY col, ...]
[HAVING aggregate_condition]
[ORDER BY col [ASC|DESC], ...]
[LIMIT n] [OFFSET n];
SELECT COUNT(*) AS cnt, COUNT(DISTINCT dept) AS depts FROM emp;
SELECT COUNT(*), dept, AVG(salary) AS avg_sal FROM emp GROUP BY dept HAVING COUNT(*) > 1;
Subqueries & UNION
SELECT * FROM a WHERE id IN (SELECT id FROM b);
SELECT * FROM a WHERE EXISTS (SELECT * FROM b WHERE b.id = a.id);
SELECT * FROM a WHERE salary > (SELECT AVG(salary) FROM a);
SELECT * FROM a WHERE score > ANY (SELECT min_score FROM thresholds);
SELECT id, name FROM a UNION SELECT id, name FROM b ORDER BY id;
SELECT id, name FROM a UNION ALL SELECT id, name FROM b;
JOIN
SELECT * FROM a JOIN b ON a.id = b.id;
SELECT * FROM a LEFT JOIN b USING (id);
SELECT * FROM a RIGHT OUTER JOIN b ON a.id = b.id;
SELECT * FROM a FULL OUTER JOIN b USING (id);
SELECT * FROM a CROSS JOIN b;
SELECT * FROM a NATURAL LEFT JOIN b;
SELECT * FROM a, b WHERE a.id = b.id; -- comma is a cross join + WHERE
JOIN/INNER JOIN/LEFT [OUTER] JOIN/RIGHT [OUTER] JOIN/FULL [OUTER] JOINCROSS JOIN(also written as a comma-separatedFROMlist)NATURAL [INNER | LEFT | RIGHT | FULL] JOINmatches all common column namesJOIN ... USING (col1, col2)matches the listed columns and merges them inSELECT *SELECT *uses unqualified column names; when a name is duplicated across tables, the later columns keep their table qualifier
UPDATE
UPDATE table_name SET col1 = expr1, col2 = expr2 [WHERE condition];
DELETE
DELETE FROM table_name [WHERE condition];
DROP TABLE
DROP TABLE [IF EXISTS] table_name;
Secondary Indexes
CREATE INDEX [IF NOT EXISTS] idx_name ON table_name (column_name);
DROP INDEX [IF EXISTS] idx_name;
SHOW INDEXES [FROM table_name];
- Hybrid in-memory Hash (
=/IN) + sorted arraybisect(>/>=/</<=/BETWEEN) secondary index - Index metadata persisted in
indexes.txt; automatically invalidated and rebuilt when.txtfiles are updated via SQL or edited externally DROP TABLEautomatically cascades and removes associated indexes
EXPLAIN & EXPLAIN ANALYZE
EXPLAIN SELECT u.name, o.amount FROM users u JOIN orders o ON u.id = o.uid WHERE u.city = 'Harbin';
EXPLAIN ANALYZE SELECT * FROM scores WHERE grade BETWEEN 80 AND 100;
EXPLAINprints the logical/physical plan tree highlightingIndexScan,HashJoin, andPredicate PushdownEXPLAIN ANALYZEexecutes the query and reports per-operatorRowsIn,RowsOut,Selectivity, andTime(ms)
Integrity Audit & Snapshot Transactions
CHECK TABLE table_name;
BEGIN [TRANSACTION];
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
ROLLBACK [TRANSACTION]; -- or COMMIT [TRANSACTION];
CHECK TABLEscans the TSV file and reports exact 1-based line numbers for column-count mismatches or invalidNUMBERvaluesBEGIN/COMMIT/ROLLBACKprovide directory-level atomic snapshot rollback across DML, DDL, and index changes
SHOW TABLES / DESCRIBE (system commands)
SHOW TABLES;
DESCRIBE table_name;
SHOW TABLESlists all tables with column names and row countsDESCRIBEshows column definitions and row count for a specific table
IMPORT (Excel)
IMPORT table_name FROM 'path/to/file.xlsx';
IMPORT table_name (col1 STRING, col2 NUMBER) FROM 'path/to/file.xlsx';
- First row must be column headers
- Types are auto-inferred (NUMBER if all values are numeric, otherwise STRING)
- Optional column definitions override auto-inference
EXPORT (query results to file)
SELECT * FROM table_name INTO OUTFILE 'path/to/data.xlsx';
SELECT dept, AVG(salary) AS avg FROM emp GROUP BY dept INTO OUTFILE 'report.csv';
- Format determined by file extension:
.xlsx,.csv,.tsv - Headers are automatically included in the output
- Returns number of rows exported
WHERE / HAVING expressions
WHERE salary > 50000 AND NOT (name = 'Bob')
WHERE dept IN ('Sales', 'Eng') OR dept != 'HR'
WHERE salary BETWEEN 5000 AND 10000 AND name LIKE 'A%'
WHERE score IS NULL
WHERE (a > 1 AND b < 2) OR c = 3
WHERE price * qty > 100
=,<>,!=,>,<,>=,<=- Arithmetic operators
+,-,*,/(withNULLpropagation) AND,OR,NOT, parentheses (SQL three-valued logic)IS NULL,IS NOT NULL,[NOT] IN (list | subquery),[NOT] BETWEEN ... AND ...,[NOT] LIKE(%,_)ANY,ALL,EXISTS,NOT EXISTS, and scalar(SELECT ...)subqueriesTRUE/FALSEliterals evaluate toNUMBER1/0- Escaped single quotes (
'') inside string literals and--single-line SQL comments
Storage Format
Tables are stored as TSV files in the working directory:
metadata.txt — table registry (name, column count, col_name, type, ...)
indexes.txt — secondary index registry (index_name, table_name, column_name)
<table_name>.txt — data rows (tab-separated, QUOTE_ALL quoting)
NULLvalues are stored using the\Nsentinel; literal backslashes in strings are escaped (\\), so empty strings''andNULLare strictly distinguished- All writes (including
metadata.txt,indexes.txt, and transaction rollback restores) are atomic (temp file + rename) - Row and index caches track
(st_mtime_ns, st_size)file fingerprints to automatically detect external edits - TSV quoting protects strings containing tabs, newlines, or quotes
Query Optimization & Benchmarks
TxtSql includes an automated optimizer pipeline (Database(data_dir, enable_optimizations=True)) featuring Hash Join (O(M + N)), outer-join-safe Predicate Pushdown, implicit comma-join rewriting, and hybrid Hash/bisect Index Scan.
Run the benchmark suite locally:
.venv/bin/python benchmarks/run_benchmark.py
Measured local results (with result-equivalence assertions against enable_optimizations=False):
| Scenario | Scale | Unoptimized (ms) | Optimized (ms) | Speedup | Mechanism |
|---|---|---|---|---|---|
Equi-Join (JOIN) |
1,000 × 1,000 rows | 2220.82 | 3.65 | 608.1x | Hash Join (O(M+N)) |
Equi-Join (JOIN) |
2,000 × 2,000 rows | 9154.34 | 8.92 | 1026.4x | Hash Join (O(M+N)) |
Point Lookup (=) |
10,000 rows | 15.73 | 0.16 | 98.2x | Hash Secondary Index (IndexScan) |
Range Query (BETWEEN) |
10,000 rows | 24.88 | 0.23 | 106.9x | Sorted Array bisect |
| Comma Join + Filters | 1,200 × 1,200 rows | 7294.73 | 2.83 | 2580.8x | Index + Pushdown + Implicit Rewrite + Hash Join |
Limitations
- Single-session directory-level snapshot transactions (
BEGIN/COMMIT/ROLLBACK) without multi-client concurrency locks or WAL recovery - Secondary indexes are rebuilt in memory from TSV files on first query or file modification rather than stored as on-disk B+ trees
DISTINCTapplies to the SELECT result row;ORDER BYsupports column names, qualified names, and SELECT aliases (not arbitrary expressions)
License
MIT
Metadata
Release files for txt-sql 0.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| txt_sql-0.3.0.tar.gz | 102.3 kB | With provenance | Details for txt_sql-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| txt_sql-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for txt_sql-0.3.0-py3-none-any.whl |
Total release size: 186.7 kB
Release files / txt_sql-0.3.0.tar.gz
| Download URL | txt_sql-0.3.0.tar.gz |
|---|---|
| Size | 102.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
9ba1a1f4196d6acbb588b037d355ce1a970f0c9bf35a109ff206330fafa6ea57
|
|
BLAKE2b-256 checksum How to use checksums |
d5f39f4132c58da40ebd5a5917a74b155031c11f2a5439ade300312c543c0597
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Transparency logRelease files / txt_sql-0.3.0-py3-none-any.whl
| Download URL | txt_sql-0.3.0-py3-none-any.whl |
|---|---|
| Size | 84.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
883190996e03c634db29bf37a1c2bc8c5a4b9cff1d2a0077bca423b00cb7d4d5
|
|
BLAKE2b-256 checksum How to use checksums |
56a620ddebeb4f6189bb9f35e3e5884fc926b542a930260994ed8b84963763a6
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Transparency logSecurity for txt-sql 0.3.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for txt_sql-0.3.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.