tinyetl 0.12.0

Fast, zero-config ETL in a single binary for transforming data between formats and databases
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
# TinyETL
**Data from here to there, in one command.**

[![CI](https://github.com/alrpal/TinyETL/actions/workflows/pr.yaml/badge.svg?branch=master)](https://github.com/alrpal/TinyETL/actions/workflows/pr.yaml)
[![Version](https://img.shields.io/badge/version-0.12.0-blue)](https://github.com/alrpal/tinyetl/releases)
[![Rust](https://img.shields.io/badge/rust-1.94%2B-orange)](https://www.rust-lang.org/tools/install)
[![Download size](https://img.shields.io/badge/download-~20MB-green)](https://github.com/alrpal/tinyetl/releases)

![TinyETL Demo](examples/tinyetl_preview2-normal-framerate.gif)

TinyETL replaces the throwaway script. Move any file or database to any other in one command: no Python, no drivers, no setup. It works out formats, column types and tables on its own, and it's fast and predictable enough to be the transfer step in a production pipeline. Think `cp`, for data.

```bash
# MySQL → Parquet with inline transformation 
tinyetl "mysql://user:@host/db#orders" orders.parquet \
  --transform "total_usd=row.amount * row.exchange_rate"

# Load a CSV into Snowflake (staged and loaded with COPY INTO)
tinyetl orders.csv "snowflake://LOADER@MYORG-MYACCOUNT/ANALYTICS/RAW?warehouse=LOAD_WH#orders"

# Excel sheet → Parquet on S3
tinyetl "budget.xlsx#Q4" s3://my-bucket/finance/q4.parquet

# Download & convert web data
tinyetl "https://api.data.gov/export.json" analysis.parquet
```

## Why TinyETL?

- ✅ **Single binary** — about a 20 MB download (50 MB unpacked), with no runtime dependencies: no Python, no JVM, no shared libraries to install
- ✅ **Fast and streaming** — 140k–345k rows/sec on a laptop, with memory that stays flat as files grow (see [Performance](#performance))
- ✅ **Zero configuration** — column types are detected and tables created for you; a schema file or YAML job file takes over when you need control
- ✅ **Universal connectivity** — CSV, JSON, Excel, Parquet, Avro, MySQL, PostgreSQL, SQLite, CrateDB, DuckDB, SQL Server, ODBC and Snowflake, over local files, HTTP, SSH and S3
- ✅ **SQL and Lua transforms** — reshape data on the way with SQL (filters, joins, aggregates, window functions, run in the built-in DuckDB) or row by row with Lua
- ✅ **Pipeline-ready** — each database load runs in one transaction, so a failed run leaves the table as it was; errors are plain text with a non-zero exit code; jobs can live in YAML files with environment variables for secrets
- ✅ **Cross-platform** — Linux, macOS and Windows, on x86_64 and ARM64

Most data movement doesn't need a platform. TinyETL keeps it to one command.

## Contents

- [Quick Install](#quick-install) · [Get Started in 30 Seconds](#get-started-in-30-seconds) · [Usage](#usage)
- [Sources and targets](#supported-data-sources-and-targets): [Files and protocols](#file-based-sources-multiple-protocols) · [Endpoint options](#endpoint-options) · [CSV delimiters](#csv-delimiters) · [Excel](#excel)
- [Databases](#database-connection-strings): [PostgreSQL](#postgresql) · [MySQL](#mysql) · [SQLite](#sqlite) · [SQL Server](#sql-server-native) · [CrateDB](#cratedb) · [DuckDB](#duckdb) · [ODBC](#odbc) · [Snowflake](#snowflake)
- [Source queries](#source-queries) · [Passwords and secrets](#secure-password-management)
- [Transforms](#data-transformations) ([SQL](#sql-transforms), [Lua](#lua-inline-transformations)) · [Schema files](#schema-files) · [YAML job files](#yaml-job-files) ([HTTP options](#http-source-options), [S3 options](#s3-options), [environment variables](#environment-variables))
- [Performance](#performance) · [Roadmap](#roadmap) · [License](#license)

## Quick Install

**Download the binary** (recommended):

Visit the [releases page](https://github.com/alrpal/tinyetl/releases/latest) and download the appropriate binary for your platform:
- Linux x64, Linux ARM64
- macOS Apple Silicon, macOS Intel
- Windows x64, Windows ARM64

The Linux binary needs glibc 2.35 or later (Ubuntu 22.04+, Debian 12+, Fedora 36+). On older systems, such as RHEL/Rocky 9 or Amazon Linux 2023, build from source with Cargo (below).

Each download is a single self-contained binary with nothing else to install. The Linux and macOS binaries include the unixODBC driver manager (LGPL-2.1-or-later); see [License](#license).

**Linux x86_64** (use `tinyetl-linux-aarch64` for ARM64):
```bash
mkdir tinyetl && cd tinyetl
curl -L https://github.com/alrpal/TinyETL/releases/latest/download/tinyetl-linux-x86_64.tar.gz | tar xz
sudo mv tinyetl /usr/local/bin/   # optional: put it on your PATH
```

**macOS Apple Silicon** (use `tinyetl-macos-intel-x86_64` for Intel Macs):
```bash
mkdir tinyetl && cd tinyetl
curl -L https://github.com/alrpal/TinyETL/releases/latest/download/tinyetl-macos-apple-silicon-aarch64.tar.gz | tar xz
sudo mv tinyetl /usr/local/bin/
```
The binary isn't notarized by Apple. If you downloaded it with a browser and macOS blocks it, run `xattr -d com.apple.quarantine tinyetl` (files fetched with `curl` aren't affected).

**Windows x86_64** (use `tinyetl-windows-aarch64` for ARM64):
```powershell
Invoke-WebRequest -Uri "https://github.com/alrpal/TinyETL/releases/latest/download/tinyetl-windows-x86_64.zip" -OutFile "tinyetl.zip"
Expand-Archive -Path "tinyetl.zip" -DestinationPath "tinyetl"
# then add the tinyetl folder to your PATH
```

Each archive also contains `LICENSE`, `THIRD_PARTY_LICENSES.md` and a `licenses/` folder.

**Or install with Cargo** (builds from source):
```bash
cargo install tinyetl
```

Building from source needs Rust 1.94 or later (`rustup update`) and a C/C++ compiler. The bundled C libraries (DuckDB, SQLite, Lua, unixODBC, AWS-LC, and OpenSSL on Linux) are compiled from source, so no system libraries are needed. A clean build takes several minutes, mostly DuckDB:
- Debian/Ubuntu: `sudo apt install build-essential perl` (`perl` is used to build OpenSSL)
- macOS: `xcode-select --install`

**Verify installation**:
```bash
tinyetl --version
```

## Get Started in 30 Seconds

```bash
# File format conversion (auto-detects schemas)
tinyetl data.csv output.parquet
tinyetl data.json analysis.db
tinyetl report.xlsx report.csv

# Database to database 
tinyetl "postgresql://user:@host/db#users" "mysql://user:@host/db#users"

# Only the rows you need, selected on the source database
tinyetl "postgresql://user:@host/db" active_users.csv --source-query "SELECT * FROM users WHERE active"

# Transform while transferring, with SQL or Lua
tinyetl sales.csv totals.parquet --sql "SELECT region, SUM(revenue) AS revenue FROM source GROUP BY region"
tinyetl sales.csv results.db --transform "profit=row.revenue - row.costs; margin=profit / row.revenue"

# Large files stream with flat memory
tinyetl huge_dataset.csv output.parquet

# Download and convert web data
tinyetl "https://example.com/api/export" local_data.json --source-type=csv

# Run complex ETL jobs from configuration files
tinyetl run my_etl_job.yaml
```

## Usage
<div style="overflow-x: auto;">

```
A tiny ETL tool for moving data between sources

Usage: tinyetl [OPTIONS] [SOURCE] [TARGET]
       tinyetl <COMMAND>

Commands:
  run                      Run a job from a YAML configuration file
  generate-default-config  Generate a default YAML configuration example and output to STDOUT
  generate-config          Generate a YAML configuration file from CLI arguments and output to STDOUT
  help                     Print this message or the help of the given subcommand(s)

Arguments:
  [SOURCE]  Source connection string (file path or connection string)
  [TARGET]  Target connection string (file path or connection string)

Options:
      --infer-schema               Auto-detect columns and types
      --schema-file <FILE>         Path to schema file (YAML) to override auto-detection
      --batch-size <BATCH_SIZE>    Number of rows per batch [default: 10000]
      --preview <N>                Show first N rows and inferred schema without copying
      --dry-run                    Validate source/target without transferring data
      --log-level <LOG_LEVEL>      Log level: info, warn, error [default: info]
      --truncate                   Truncate target before writing (overrides append-first behavior)
      --transform-file <FILE>      Path to Lua file containing a 'transform' function
      --transform <EXPRESSIONS>    Inline transformation expressions (semicolon-separated, e.g., "new_col=row.old_col * 2; name=row.first .. ' ' .. row.last")
      --sql <SQL>                  SQL transform over all source rows, run in DuckDB (the rows are a table named `source`), e.g. "SELECT region, SUM(amount) AS total FROM source GROUP BY region"
      --source-type <TYPE>         Force source file type (csv, json, parquet, avro, xlsx, ...) - useful for URLs without clear extensions
      --source-query <SQL>         SQL query to read from a database source instead of a whole table (the URL then has no #table)
      --source-secret-id <ID>      Secret ID for source password (resolves to TINYETL_SECRET_{id})
      --dest-secret-id <ID>        Secret ID for destination password (resolves to TINYETL_SECRET_{id})
      --source-option <KEY=VALUE>  Source option, repeatable (e.g. delimiter=tab); the same keys as `options:` in YAML
      --target-option <KEY=VALUE>  Target option, repeatable (e.g. delimiter=|); the same keys as `options:` in YAML
  -h, --help                       Print help
  -V, --version                    Print version
```

</div>

Basic usage examples:

```bash
# Local file operations
tinyetl data.csv output.db
tinyetl data.csv output.parquet
tinyetl data.csv output.avro
tinyetl data.json output.csv
tinyetl data.avro output.json
tinyetl events.jsonl events.parquet
tinyetl events.json.gz "postgresql://user:@localhost/mydb#events"
tinyetl orders.parquet orders.csv.gz
tinyetl "budget.xlsx#Q4" q4.csv
tinyetl "postgresql://user:@localhost/mydb#orders" orders.xlsx

# Download from web
tinyetl "https://example.com/data.csv" output.json
tinyetl "https://api.example.com/export" data.csv --source-type=csv

# Secure file transfer via SSH
tinyetl "ssh://user@server.com/data.csv" output.parquet

# Database operations
tinyetl data.csv "postgresql://user:pass@localhost/mydb#customers"
tinyetl data.csv "mysql://user:pass@localhost:3306/mydb#customers"
tinyetl "sqlite:///source.db#users" output.csv

# Cloud storage and warehouses
tinyetl s3://my-bucket/raw/orders.csv orders.parquet
tinyetl orders.parquet "snowflake://LOADER@MYORG-MYACCOUNT/ANALYTICS/RAW?warehouse=LOAD_WH#orders"

# Data inspection and validation
tinyetl data.csv output.db --preview 10     # show rows and the inferred schema
tinyetl data.csv output.db --dry-run        # check connections and schema only

# Replace a table's rows instead of appending
tinyetl data.csv output.db --truncate

# Custom batch size
tinyetl data.csv output.db --batch-size 5000

# Apply inline transformations
tinyetl data.csv output.db --transform "full_name=row.first_name .. ' ' .. row.last_name; age_next_year=row.age + 1"

# Apply transformations from Lua file
tinyetl data.csv output.db --transform-file transform.lua
```

### Supported Data Sources and Targets

TinyETL supports two main categories of data sources and targets:

#### File-Based Sources (Multiple Protocols)

**File Formats:**
- **CSV** - Comma-separated values; tab, semicolon and pipe delimiters are detected, and `.tsv` files are tab-separated (see "CSV Delimiters" below)
- **JSON** - An array of objects. A `.json` file that starts with `{` is read as objects one after another, so JSON Lines saved as `.json`, pretty-printed objects back to back and a single object all work. Nested objects and arrays are kept as JSON: a `jsonb` column in PostgreSQL, nested in JSON output, compact JSON text in CSV and Parquet
- **JSON Lines** - One JSON object per line (`.jsonl`, `.ndjson`)
- **Compressed files** - Add `.gz` (gzip) or `.zst` (Zstandard) to any file format: `data.csv.gz`, `events.jsonl.gz`, `trips.parquet.zst`. Sources are decompressed to a temporary file as they're read, targets are compressed when the transfer finishes. Works locally and over HTTP, SSH and S3
- **Parquet** - Columnar storage format (written with Snappy compression)
- **Avro** - Binary serialization format with schema evolution
- **Excel** - Reads `.xlsx`, `.xlsm`, `.xlsb`, `.xls` and OpenDocument `.ods`; writes `.xlsx`. Pick a sheet with `file.xlsx#Sheet` (see "Excel" below)

**Access Protocols:**
- **Local Files** - Direct file system access
  ```bash
  tinyetl data.csv output.json
  tinyetl data.csv output.avro
  tinyetl /path/to/file.parquet data.csv
  tinyetl data.avro output.json
  ```
- **HTTP/HTTPS** - Download from web servers (supports authentication and custom headers via endpoint options)
  ```bash
  tinyetl "https://example.com/data.csv" output.parquet
  tinyetl "https://api.example.com/export" data.csv --source-type=csv
  # For authenticated APIs, use --source-option or a YAML config (see HTTP Source Options section)
  ```
- **SSH/SCP** - Download a remote file with the system's `scp` (sources only; key-based login as configured for `ssh`)
  ```bash
  tinyetl "ssh://user@server.com/data/file.csv" output.json
  tinyetl "ssh://user@server.com:2222/remote/data.parquet" local.csv
  ```

- **Amazon S3** - Read and write single objects (also works with S3-compatible stores such as Cloudflare R2)
  ```bash
  tinyetl s3://my-bucket/raw/orders.csv orders.parquet
  tinyetl "postgres://user@host/db#orders" s3://my-bucket/exports/orders.parquet
  ```

**Protocol Features:**
- **file://** - Local file system (default for simple paths)
- **http://** and **https://** - Web downloads (sources only)
  - Basic and Bearer token authentication, and custom headers, via endpoint options
- **ssh://** - Downloads with the system's `scp` command, which must be installed (sources only)
- **s3://** - Amazon S3 and S3-compatible object storage, as both source and target
  - Credentials from `AWS_*` environment variables, IAM roles, or YAML options (see S3 Options section)
- **--source-type** parameter for format override (useful for URLs without clear extensions)

#### Database Sources

**Supported Databases:**
- **SQLite** - Embedded database
- **PostgreSQL** - Advanced open-source database
- **MySQL** - Popular relational database
- **SQL Server** - Native driver (`mssql://`), no ODBC driver needed
- **CrateDB** - Distributed SQL database, through `postgresql://` URLs
- **DuckDB** - Embedded analytical database optimized for OLAP workloads
- **ODBC** - Any database with an ODBC driver (tested: SQL Server, PostgreSQL, MySQL/MariaDB, SQLite)
- **Snowflake** - Cloud data warehouse; bulk loads through stage + `COPY INTO`

**Connection Examples:**
```bash
# SQLite
tinyetl "sqlite:///path/to/db.sqlite#table" output.csv
tinyetl data.csv "sqlite:///output.db#customers"

# PostgreSQL  
tinyetl "postgresql://user:@localhost/mydb#orders" output.parquet
tinyetl data.csv "postgresql://user:@localhost/mydb#customers"

# MySQL
tinyetl "mysql://user:@localhost:3306/mydb#products" output.json
tinyetl data.csv "mysql://user:@localhost:3306/mydb#sales"

# SQL Server (native)
tinyetl "mssql://sa:pass@localhost:1433/mydb#orders" output.parquet
tinyetl data.csv "mssql://sa:pass@localhost:1433/mydb#customers"

# CrateDB
tinyetl "postgresql://crate:@localhost/doc#orders" output.parquet
tinyetl data.csv "postgresql://crate:@localhost/doc#customers"

# DuckDB
tinyetl "products.duckdb#inventory" output.csv
tinyetl data.csv "analytics.duckdb#sales"

# Snowflake (key-pair auth; see "Snowflake" below)
tinyetl data.csv "snowflake://LOADER@MYORG-MYACCOUNT/ANALYTICS/RAW?warehouse=LOAD_WH#orders"
tinyetl "snowflake://LOADER@MYORG-MYACCOUNT/ANALYTICS/RAW?warehouse=LOAD_WH#orders" orders.parquet

# ODBC (any database with an ODBC driver; see "ODBC" below)
tinyetl data.csv "odbc://Driver={ODBC Driver 18 for SQL Server};Server=localhost;Database=mydb;UID=sa;PWD=MyPass123;TrustServerCertificate=yes#orders"
tinyetl "odbc://Driver={PostgreSQL Unicode};Server=localhost;Database=mydb;UID=user;PWD=pass#public.orders" output.csv
```

#### Source Type Override

When using HTTP/HTTPS or SSH protocols, URLs may not always indicate the file format clearly (e.g., API endpoints, URLs with query parameters). Use the `--source-type` parameter to explicitly specify the format:

```bash
# API endpoint that returns CSV data
tinyetl "https://api.example.com/export?format=csv&limit=1000" output.json --source-type=csv

# Google Drive download (no file extension in URL)
tinyetl "https://drive.google.com/uc?id=FILE_ID&export=download" data.csv --source-type=csv

# SSH file without clear extension
tinyetl "ssh://user@server.com/data/export_20241107" output.parquet --source-type=json

# Local files usually don't need source-type (auto-detected from extension)
tinyetl data.csv output.json  # No --source-type needed
```

**Supported source types:** `csv`, `tsv`, `json`, `jsonl`, `parquet`, `avro`, `xlsx` (and the other spreadsheet extensions above)

#### Endpoint Options

Some sources and targets take options: HTTP headers and authentication, S3 credentials, Snowflake keys, the CSV delimiter. Set them with `--source-option KEY=VALUE` / `--target-option KEY=VALUE` (repeat the flag for more), or under `options:` for the source or target in a YAML config. The keys are the same either way.

| Endpoint | Options |
|---|---|
| CSV / TSV files (local, HTTP, SSH, S3, compressed) | `delimiter` |
| HTTP / HTTPS sources | `header.<Name>`, `auth.basic.username`, `auth.basic.password`, `auth.bearer` |
| S3 | `region`, `endpoint`, `access_key_id`, `secret_access_key`, `session_token`, `allow_http`, `path_style` |
| Snowflake | `private_key_path`, `private_key_passphrase`, `warehouse`, `role`, `load_method`, `stage_file_rows` |

An option the endpoint doesn't take is an error, so a misspelled key fails instead of being ignored. Other databases take no options; their settings go in the connection URL (for example PostgreSQL `?sslmode=require`).

#### CSV Delimiters

When reading a CSV file, TinyETL looks at its first lines and picks comma, tab, semicolon or pipe: the one that appears the same number of times on every line, outside quotes. Comma is the default when nothing fits. Files ending in `.tsv` are read and written tab-separated. Set the delimiter with the `delimiter` option, either a single character or `tab`. This works for local files, HTTP, SSH and S3:

```bash
tinyetl export.csv data.parquet                                 # pipe-delimited .csv: detected
tinyetl data.tsv out.csv                                        # tab in, comma out
tinyetl export.csv out.json --source-option "delimiter=;"       # skip detection
tinyetl data.parquet out.csv --target-option "delimiter=|"      # write pipes
```

### Excel

```bash
tinyetl sales.xlsx sales.csv                 # first sheet
tinyetl "sales.xlsx#Q4 2024" q4.parquet      # a named sheet
tinyetl "postgresql://user:@host/db#orders" "orders.xlsx#Orders"   # write; the sheet defaults to Sheet1
```

- **Reading:** the first row is the header; blank header cells become `column_N` and repeated names get `_2`, `_3`, …. Rows with no values are skipped. The whole sheet is loaded into memory (the spreadsheet libraries read a sheet at once), so use CSV or Parquet for very large data.
- **Types:** Excel stores every number as a double: whole numbers are read as integers, others as decimals. Date cells are read as dates, booleans as booleans, and text cells stay text (so `02134` keeps its leading zero). Error cells (`#N/A`, `#DIV/0!`) are read as NULL.
- **Writing:** produces an `.xlsx` with a bold header row; dates get a date format, and integers beyond ±2^53, which a double can't hold exactly, are written as text. Rows are streamed to a temporary file, so memory stays low. A sheet holds at most 1,048,576 rows; larger exports fail with a message. Writing replaces an existing file (it doesn't add a sheet to it).
- **S3 and HTTP:** `s3://bucket/report.xlsx` works as a source and a target; HTTP(S) URLs ending in a spreadsheet extension, or with `--source-type xlsx`, work as sources.

### Database Connection Strings

TinyETL uses standard database connection URLs with an optional table specification using the `#` separator.

#### PostgreSQL
```bash
# Basic format
postgresql://username:password@hostname:port/database#table_name

# Examples
tinyetl data.csv "postgresql://user:@localhost/mydb#customers"
tinyetl data.csv "postgresql://admin:@db.example.com:5432/analytics#sales_data"

# A table in another schema, and a connection parameter
tinyetl data.csv "postgresql://admin:@db.example.com/analytics?sslmode=require#staging.sales"
```
URL parameters such as `sslmode` go to the driver unchanged.

#### MySQL
```bash
# Basic format  
mysql://username:password@hostname:port/database#table_name

# Examples
tinyetl data.csv "mysql://user:@localhost:3306/mydb#customers"
tinyetl data.csv "mysql://admin:@db.example.com:3306/analytics#sales_data"

# Default table name is 'data' if not specified
tinyetl data.csv "mysql://user:@localhost:3306/mydb"  # Creates table named 'data'
```

#### SQLite
```bash
# File path (table name inferred from filename without extension)
tinyetl data.csv output.db              # Creates table named 'output'
tinyetl data.csv /path/to/database.db   # Creates table named 'database'

# Explicit table name using connection string format
tinyetl data.csv "sqlite:///path/to/database.db#custom_table"
```
When reading, column types come from the declared types (`INTEGER`, `VARCHAR(255)`, `DECIMAL(10,2)`, `DATETIME`, …). Columns declared `JSON` are read as JSON, including JSON stored as `BLOB`, unless sampled values aren't valid JSON, in which case they're read as text. Other `BLOB` values are read as text if they're valid UTF-8, and as hex otherwise.

#### SQL Server (native)
```bash
# Basic format (username and password are required)
mssql://username:password@hostname:port/database#table_name

# Examples
tinyetl data.csv "mssql://sa:MyPass123@localhost:1433/mydb#customers"
tinyetl "mssql://sa:MyPass123@localhost:1433/mydb#orders" orders.csv

# Verify the server's certificate (e.g. Azure SQL)
tinyetl data.csv "mssql://user:pass@myserver.database.windows.net/mydb?trust_server_certificate=false#customers"
```
Connections are encrypted, like ODBC Driver 18. Parameters: `encrypt=false` encrypts only the login; `trust_server_certificate=false` checks the server's certificate, which is trusted by default since most servers use a self-signed one. Percent-encode special characters in the password (`@` → `%40`, `:` → `%3A`, `/` → `%2F`).
Tables are in the login's default schema (usually `dbo`); `schema.table` names aren't supported by the native connector yet. For other schemas, Windows authentication or other driver features, use `odbc://` with Microsoft's ODBC driver (below).

#### CrateDB
```bash
# Basic format
postgresql://username:password@hostname:port/schema#table_name

# Examples
tinyetl data.csv "postgresql://user:@localhost/doc#customers"
tinyetl data.csv "postgresql://admin:@db.example.com:5432/analytics#sales_data"
```
TinyETL detects CrateDB and creates decimal columns as `NUMERIC(38,10)`, since CrateDB needs a precision and scale.

#### DuckDB
```bash
# File path (table name inferred from filename without extension)
tinyetl data.csv output.duckdb              # Creates table named 'output'
tinyetl data.csv /path/to/analytics.duckdb   # Creates table named 'analytics'

# Explicit table name using # separator
tinyetl data.csv "analytics.duckdb#sales_data"

# Reading from DuckDB table
tinyetl "products.duckdb#inventory" output.csv
tinyetl "analytics.duckdb#daily_sales" report.parquet
```

#### ODBC

`odbc://` works with any database that has an ODBC driver. Everything after `odbc://` up to the last `#` is passed to the driver unchanged, and the text after `#` is the table (`table`, or `schema.table`).

```bash
# SQL Server (Microsoft ODBC Driver 18)
tinyetl data.csv "odbc://Driver={ODBC Driver 18 for SQL Server};Server=localhost,1433;Database=mydb;UID=sa;PWD=MyPass123;TrustServerCertificate=yes#customers"

# SQL Server with Windows Authentication
tinyetl data.csv "odbc://Driver={ODBC Driver 18 for SQL Server};Server=localhost\MSSQLSERVER01;Database=master;Trusted_Connection=Yes;TrustServerCertificate=Yes#customers"

# PostgreSQL (psqlODBC)
tinyetl "odbc://Driver={PostgreSQL Unicode};Server=localhost;Port=5432;Database=mydb;UID=user;PWD=pass#public.orders" orders.parquet

# MySQL / MariaDB (MariaDB Connector/ODBC also works with MySQL servers)
tinyetl data.csv "odbc://Driver={MariaDB Unicode};Server=localhost;Port=3306;Database=mydb;UID=user;PWD=pass#sales"

# SQLite (SQLite ODBC driver)
tinyetl data.csv "odbc://Driver={SQLite3};Database=/path/to/file.db#customers"

# A DSN configured in odbc.ini, or a driver library given by path
tinyetl "odbc://DSN=warehouse;UID=user;PWD=pass#facts" facts.csv
tinyetl data.csv "odbc://Driver=/opt/homebrew/lib/psqlodbcw.so;Server=localhost;Database=mydb;UID=user;PWD=pass#customers"
```

How it works:
- **Reading** runs one `SELECT * FROM <table>` and streams the rows. Column types come from the driver, so integers, decimals, booleans and dates keep their types
- **Writing** creates the table if it doesn't exist, using column types for the database the driver reports: SQL Server, PostgreSQL, MySQL/MariaDB and SQLite get the same types as TinyETL's native connectors; other databases get standard ANSI SQL types (`VARCHAR(4000)`, `BIGINT`, `DECIMAL(38,10)`, `BOOLEAN`, `DATE`, `TIMESTAMP`). To control the types, create the table yourself first. Rows are inserted in batches with ODBC parameter arrays inside one transaction, committed at the end
- Identifiers are quoted the way the driver reports (`"name"` for most databases, `` `name` `` for MySQL)
- Text is exchanged with the driver as UTF-16, so any Unicode text works

Tested with SQL Server (ODBC Driver 18), PostgreSQL (psqlODBC), MySQL (MariaDB Connector/ODBC) and SQLite (SQLite ODBC Driver); see `test_env/odbc/`. Other databases (Oracle, DB2, Snowflake, …) should work through the ANSI fallback but haven't been tested.

**ODBC Driver Requirements:**

TinyETL includes the ODBC driver manager, so you only need the driver for your database. You do not need to install unixODBC.
- **Windows**: Drivers are typically pre-installed or available via vendor installers. TinyETL uses the driver manager built into Windows. Non-ASCII text on Windows hasn't been tested yet
- **macOS**: Install drivers via Homebrew (e.g. `brew install microsoft/mssql-release/msodbcsql18`, `brew install psqlodbc`). TinyETL finds drivers registered in Homebrew's `odbcinst.ini` automatically. Oracle's MySQL Connector/ODBC for macOS is built for the iODBC driver manager and needs `libiodbc` installed; the MariaDB driver doesn't
- **Linux**: Install drivers via your package manager (`apt install odbc-postgresql odbc-mariadb libsqliteodbc`, Microsoft's `msodbcsql18`). Drivers registered by file name in `/etc/odbcinst.ini`, as Debian and Ubuntu do, are found in `/usr/lib/<arch>/odbc/` when you name them with `Driver=`. For a DSN in `odbc.ini`, give its `Driver` as a full library path (or set `LD_LIBRARY_PATH=/usr/lib/<arch>/odbc`)
- Drivers and DSNs are read from `odbcinst.ini` / `odbc.ini` in `/etc`, or from the directory in the `ODBCSYSINI` environment variable if set. You can also skip registration and give the driver's library path: `Driver=/path/to/libdriver.so`

**Important ODBC Notes:**
- Always quote ODBC connection strings to prevent shell interpretation
- Put values containing `;` in braces, e.g. `PWD={pa;ss}`
- The database must exist before using TinyETL
- For SQL Server driver names: `ODBC Driver 18 for SQL Server` (latest), `ODBC Driver 17 for SQL Server`, or `SQL Server` (older). Driver 18 encrypts by default; add `TrustServerCertificate=yes` for servers with self-signed certificates

#### Snowflake

```bash
# Format
snowflake://user[:password]@account/database/schema?warehouse=WH[&role=ROLE]#table

# Load a file into a table (created if it doesn't exist)
export SNOWFLAKE_PRIVATE_KEY_PATH=~/.snowflake/rsa_key.p8
tinyetl orders.csv "snowflake://LOADER@MYORG-MYACCOUNT/ANALYTICS/RAW?warehouse=LOAD_WH#orders"

# Replace the table's rows instead of appending
tinyetl orders.csv "snowflake://LOADER@MYORG-MYACCOUNT/ANALYTICS/RAW?warehouse=LOAD_WH#orders" --truncate

# Export a table (or schema.table / database.schema.table)
tinyetl "snowflake://LOADER@MYORG-MYACCOUNT/ANALYTICS/RAW?warehouse=LOAD_WH#orders" orders.parquet
```

- **Account:** the account identifier, `ORGNAME-ACCOUNTNAME` (or a legacy locator such as `xy12345.us-east-1`). `SELECT CURRENT_ORGANIZATION_NAME() || '-' || CURRENT_ACCOUNT_NAME()` shows it
- **Authentication:** use key-pair authentication; Snowflake is phasing out password-only sign-in, especially for service users. Point TinyETL at an unencrypted or passphrase-protected PKCS#8 private key with `SNOWFLAKE_PRIVATE_KEY_PATH` (and `SNOWFLAKE_PRIVATE_KEY_PASSPHRASE`), or with the `private_key_path` / `private_key_passphrase` options in a YAML config. Alternatively, put a password or programmatic access token in the URL, or pass it with `--source-secret-id` / `--dest-secret-id`. A key wins over a password
- **Loading:** rows are written to Zstandard-compressed CSV files (several times smaller than gzip, since the upload is usually the slow part), uploaded to the table's own stage (`@%table`, so no `CREATE STAGE` privilege is needed) and loaded with one `COPY INTO` at the end. The load, and the `DELETE` for `--truncate`, run in one transaction: if anything fails, the table keeps its old rows. Memory use stays flat, since each staged file (500,000 rows by default) is uploaded as soon as it's full
- **Azure and Google Cloud accounts:** TinyETL can only upload to stages on AWS-hosted accounts so far. On other clouds it detects this and loads with batched `INSERT` statements instead, which works but is slower and uses more warehouse time. Reading works on every cloud
- **Reading** streams the result of `SELECT * FROM <table>`. NUMBER, FLOAT, BOOLEAN, DATE, TIMESTAMP and VARIANT/OBJECT/ARRAY (as JSON) keep their types; other types are read as text
- **Names:** plain names (letters, digits, `_`, `$`) are left unquoted, so Snowflake stores them upper-case: a CSV column `customer_id` becomes `CUSTOMER_ID`, which you can query as `customer_id`, and reading the table back gives `CUSTOMER_ID`. Names with other characters are quoted and keep their exact case
- **Column types for new tables:** `VARCHAR`, `NUMBER(38,0)`, `NUMBER(38,10)`, `BOOLEAN`, `DATE`, `TIMESTAMP_NTZ` (TinyETL's timestamps are UTC) and `VARIANT` for JSON. To choose your own types, create the table first

Endpoint options for Snowflake (`--source-option` / `--target-option`, or `options:` in a job file):

| Option | Default | Meaning |
|---|---|---|
| `private_key_path` | `SNOWFLAKE_PRIVATE_KEY_PATH` | Private key for key-pair auth |
| `private_key_passphrase` | `SNOWFLAKE_PRIVATE_KEY_PASSPHRASE` | Passphrase of an encrypted key |
| `warehouse`, `role` | from the URL | Override the URL's values |
| `load_method` | `auto` | `auto` (stage on AWS, INSERT elsewhere), `stage` or `insert` |
| `stage_file_rows` | `500000` | Rows per staged file |

See [`examples/22_snowflake`](examples/22_snowflake/) for a complete setup, from creating a key pair to a test run.

**Important Notes:**
- Tables are created if they don't exist; the database (and schema) must already exist
- Existing tables are appended to; `--truncate` replaces their rows
- Each load runs in one transaction (PostgreSQL, MySQL, SQLite, DuckDB, SQL Server, ODBC, Snowflake): if the transfer fails, the table keeps its previous rows, including with `--truncate`. CrateDB has no transactions, so a failed load there can leave a partial table
- Reading runs one `SELECT * FROM <table>` and streams the rows, so memory stays flat for any table size
- DuckDB is optimized for analytical (OLAP) workloads and offers better performance than SQLite for aggregations
- Connection strings should be quoted to prevent shell interpretation
- Default ports: PostgreSQL (5432), CrateDB (5432), MySQL (3306)

### Source Queries

Read the result of a SQL query instead of a whole table with `--source-query` (YAML: `source_query`). The query runs on the source database, so filtering, joins and aggregation happen there and only the result crosses the network. Leave the `#table` off the source:

```bash
# Yesterday's orders from PostgreSQL to Parquet
tinyetl "postgresql://user@host/shop" orders.parquet \
  --source-query "SELECT id, customer_id, total FROM orders WHERE created_at >= now() - interval '1 day'"

# A join and an aggregate from SQL Server into Snowflake
tinyetl "mssql://user:pass@host/erp" "snowflake://LOADER@MYORG-MYACCOUNT/ANALYTICS/RAW?warehouse=LOAD_WH#daily_sales" \
  --source-query "SELECT o.day, c.region, SUM(o.amount) AS amount FROM orders o JOIN customers c ON c.id = o.customer_id GROUP BY o.day, c.region"
```

```yaml
source: postgresql://user:${DB_PASSWORD}@host/shop
source_query: |
  SELECT id, customer_id, total
  FROM orders
  WHERE created_at >= now() - interval '1 day'
target: s3://my-bucket/orders/latest.parquet
```

- Works with PostgreSQL (and CrateDB), MySQL, SQL Server, SQLite, DuckDB, ODBC and Snowflake. Use the database's own SQL dialect; the query runs as written, including `WITH` and `ORDER BY`
- Column types come from the database where it can describe a query (SQL Server, DuckDB, ODBC, Snowflake), and otherwise from the first rows of the result, as for tables
- To get the column types, PostgreSQL and MySQL run the query once with a `LIMIT` before reading it in full, so an expensive query does some of its work twice. The other databases describe the query, or read the sample from the same run
- There's no row count up front, so the progress bar doesn't show a percentage
- For ODBC, the whole text after `odbc://` is the connection string

### Secure Password Management

TinyETL provides secure methods for handling database passwords to avoid exposing sensitive credentials in command-line arguments or shell history.

#### Environment Variables (Recommended)

Instead of including passwords directly in connection strings, use environment variables and use the `--source-secret-id` and `--dest-secret-id` parameters:

```bash
# Set custom environment variables
export TINYETL_SECRET_prod_db="production_password"
export TINYETL_SECRET_dev_db="development_password"

# Use explicit secret IDs
tinyetl "postgres://user@prod.example.com/db#orders" \
        "mysql://user@dev.example.com:3306/testdb#orders" \
        --source-secret-id prod_db \
        --dest-secret-id dev_db
```

**How it works:** `--source-secret-id ID` reads the environment variable `TINYETL_SECRET_ID` and sets it as the password in the source URL (`--dest-secret-id` does the same for the target). The ID is any name you choose, such as `prod_db`. It works for URL-style connection strings (`postgres://`, `mysql://`, `mssql://`, `snowflake://`); for `odbc://`, put the password in the connection string or a DSN, and for S3 use the AWS variables.


#### Security Warnings

TinyETL automatically detects when passwords are included in CLI parameters and warns you:

```bash
# This will show a security warning:
tinyetl data.csv "mysql://user:password123@localhost/db#table"
WARN Warning: Using passwords in CLI parameters for target is insecure. Consider using --source-secret-id / --dest-secret-id.
```

**Security Best Practices:**
- ✅ Use environment variables for passwords
- ✅ Use explicit secret IDs for multiple environments
- ✅ Keep connection strings in CI/CD without embedded passwords
- ❌ Avoid putting passwords directly in connection strings
- ❌ Avoid storing passwords in shell scripts or command history

## Data Transformations

Reshape data on the way from source to target, with SQL or Lua:

- **SQL** (`--sql`) sees the whole dataset: filters, aggregates, joins, window functions, `DISTINCT`, `ORDER BY`. It runs in DuckDB, which is built into TinyETL
- **Lua** (`--transform`, `--transform-file`) works one row at a time, streaming: add or change columns, drop rows

A job uses one or the other. To filter a database table before it leaves the database, use a [source query](#source-queries) instead (or as well).

### SQL Transforms

The source's rows are a table named `source`:

```bash
# Totals per region
tinyetl sales.csv totals.parquet \
  --sql "SELECT region, COUNT(*) AS orders, SUM(amount) AS total FROM source GROUP BY region"

# Running totals with a window function, into PostgreSQL
tinyetl sales.csv "postgresql://user@host/db#sales_running" \
  --sql "SELECT *, SUM(amount) OVER (PARTITION BY region ORDER BY day) AS running_total FROM source"

# Deduplicate, keeping the latest row per id
tinyetl events.jsonl latest.csv \
  --sql "SELECT * FROM source QUALIFY row_number() OVER (PARTITION BY id ORDER BY updated_at DESC) = 1"

# Reach into nested JSON (GH Archive events)
tinyetl 2015-01-01-15.json.gz pushes.csv \
  --sql "SELECT actor->>'login' AS login, SUM(CAST(payload->>'size' AS INT)) AS commits FROM source WHERE type = 'PushEvent' GROUP BY 1 ORDER BY 2 DESC"
```

```yaml
source: sales.csv
target: totals.parquet
sql: |
  SELECT region, COUNT(*) AS orders, SUM(amount) AS total
  FROM source
  GROUP BY region
```

- The query is [DuckDB SQL](https://duckdb.org/docs/sql/introduction), with its functions for text, dates, JSON (`->>`, `json_extract`) and lists. Column types come from the query's result
- **How it runs:** every source row is first loaded into a temporary DuckDB database (in the system temp directory, `TMPDIR`), then the query runs once and its result is written to the target. DuckDB spills to disk, so memory stays bounded, but the temp directory needs free space for a copy of the data. 1M rows grouped into 50 totals take about 1.6 s and 120 MB of memory on a laptop
- Decimals stay exact (`SUM` of money doesn't pick up float noise). Lists, structs and maps in the result become JSON
- A schema file (`--schema-file`) checks the source rows before they're loaded; the query's result isn't checked against it
- `--preview` and `--dry-run` load the source and run the query, so a mistake in the SQL shows up before anything is written

### Lua: Inline Transformations


Use the `--transform` option with semicolon-separated expressions. **All original columns are automatically preserved**, and you can add new columns or override existing ones:

```bash
# Add a new column while keeping all existing columns
tinyetl users.csv output.db --transform "full_name=row.first_name .. ' ' .. row.last_name"

# Multiple transformations (original columns + new calculated columns)
tinyetl sales.csv output.db --transform "total=row.quantity * row.price; profit=total * 0.3; year=2024"

# Override existing columns and add new ones
tinyetl data.csv output.db --transform "email=string.lower(row.email); age_group=row.age < 30 and 'young' or 'mature'"
```

### Lua Files

For complex transformations, create a Lua file with a `transform` function. **Note**: With Lua files, you have full control over which columns to include. Only columns explicitly returned are kept:

**transform.lua:**
```lua
function transform(row)
    -- Create result table
    local result = {}
    
    -- Explicitly copy fields you want to keep
    result.id = row.id
    result.created_at = row.created_at
    
    -- Create new calculated fields
    result.full_name = row.first_name .. ' ' .. row.last_name
    result.total_amount = row.quantity * row.unit_price
    result.discount = result.total_amount > 100 and result.total_amount * 0.1 or 0
    result.final_amount = result.total_amount - result.discount
    
    -- String processing
    if row.email then
        result.email_domain = row.email:match('@(.+)')
        result.is_business_email = result.email_domain:find('%.com$') and true or false
    end
    
    -- Date manipulation (dates come as RFC3339 strings)
    if row.birth_date then
        local year = tonumber(row.birth_date:match('^(%d%d%d%d)'))
        result.age = 2024 - year
        result.generation = year < 1980 and 'Gen X' or year < 1997 and 'Millennial' or 'Gen Z'
    end
    
    return result
end
```

```bash
tinyetl data.csv output.db --transform-file transform.lua
```

### Lua in YAML Job Files

```yaml
# Assignments, one per line (or separated by ";"), like --transform
transform: |
  full_name = row.first_name .. ' ' .. row.last_name
  total_amount = row.quantity * row.unit_price
  profit = total_amount * 0.3

# Or a Lua file, like --transform-file
transform_file: transform.lua
```

Job files from earlier versions, with `transform: { type: script|inline|file, value: ... }` under `options:`, still work.

### Lua Transformation Rules

1. **Schema Inference**: The output schema is determined by the first transformed row
2. **Column Preservation**: For assignments (`--transform`, YAML `transform`), all original columns are preserved, and each assignment can use the ones before it by name (`total=row.qty * row.price; profit=total * 0.3`)
3. **Column Override**: Transformations can override existing columns with new values
4. **New Columns**: New columns returned by transform are added to the target schema  
5. **Column Filtering**: For Lua files, only columns returned by the transform function are kept
6. **Row Filtering**: Return `nil` or empty table `{}` from Lua functions to filter out rows
7. **Type Conversion**: Lua values are converted back to TinyETL types (see below)
8. **Error Handling**: Transformation errors stop the process with clear error messages

### Available Data Types

- **Strings**: `"text"` or `'text'`
- **Numbers**: `42`, `3.14` (Lua integers become integers, other numbers become decimals)
- **Booleans**: `true`, `false`
- **Null**: `nil` (becomes NULL in target)
- **Dates**: Passed to Lua as RFC 3339 strings (`2024-01-15T10:30:00+00:00`), returned as strings
- **JSON**: Passed to Lua as JSON text

### Lua Built-ins Available

- String functions: `string.find()`, `string.match()`, `string.gsub()`, concatenation with `..`
- Math functions: `math.floor()`, `math.ceil()`, `math.abs()`, basic operators
- Logic: `and`, `or`, `not`, conditional expressions
- Pattern matching with string methods

### Row Filtering (Lua Files Only)

You can filter out rows by returning `nil` or an empty table `{}` from your transform function:

```lua
function transform(row)
    -- Filter out rows with missing data
    if not row.email or row.email == "" then
        return nil  -- Remove this row
    end
    
    -- Filter by conditions
    if row.age and row.age < 18 then
        return nil  -- Remove minors
    end
    
    -- Filter out test data
    if row.country ~= "United States" then
        return nil  -- Keep only US records
    end
    
    -- Transform and return the row
    row.full_name = row.first_name .. ' ' .. row.last_name
    return row
end
```

**Note**: Inline expressions (`--transform`) always preserve all rows. Row filtering only works with Lua files (`--transform-file`).

### Transform Examples

```bash
# Clean and standardize phone numbers
tinyetl contacts.csv clean_contacts.db --transform "clean_phone=row.phone:gsub('[^%d]', '')"

# Category mapping
tinyetl products.csv categorized.db --transform "category=row.price < 50 and 'budget' or row.price < 200 and 'standard' or 'premium'"

# Extract year from date and calculate age
tinyetl people.csv processed.db --transform "birth_year=tonumber(row.birth_date:match('^(%d%d%d%d)')); age=2024 - birth_year"

# Filter and transform with Lua file (removes invalid rows)
tinyetl messy_data.csv clean_data.db --transform-file filter.lua

# Preview transformations before applying
tinyetl data.csv output.db --transform "total=row.qty * row.price" --preview 5
```

## Schema Files

A schema file sets column types and validates rows, instead of inferring types (`--schema-file schema.yaml`).

### Schema File Format

Create a YAML file defining your expected schema. Here's the complete format:

> **📝 Note on Schema Inference:** When TinyETL automatically infers schema from your data, all columns are marked as `nullable: true` by default. This is a safety measure for ETL operations—sample data may not represent all possible values in your dataset. If you need `NOT NULL` constraints or other strict validation, you must provide an explicit schema file.
>
> **How types are inferred:** column types come from the first 1,000 rows. A column whose values all have one type gets that type; whole and fractional numbers together (`84`, `29.85`) make a decimal column; any other mix makes a text column. Blank values (empty or whitespace only) don't count. While copying, every value is converted to its column's type: numbers in a text column become text, text that parses in a numeric, boolean, date or JSON column is converted, and blank values in non-text columns become NULL. A later value that can't be converted (`abc` in an integer column) is written unchanged where the target allows it (files, SQLite) and fails with the column name on typed databases such as PostgreSQL. Use a schema file to fix the types up front.

**schema.yaml:**
```yaml
columns:
  - name: "id"
    type: "Integer"
    nullable: false
    
  - name: "email"
    type: "String"
    nullable: false
    pattern: '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    
  - name: "age"
    type: "Integer" 
    nullable: true
    default: 0
    
  - name: "salary"
    type: "Decimal"
    nullable: true
    
  - name: "is_active"
    type: "Boolean"
    nullable: false
    default: true
    
  - name: "created_at"
    type: "DateTime"
    nullable: true
    pattern: '^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}'
```

### Supported Data Types

Type names are case-insensitive:

- **String** - Text values, supports regex pattern validation
- **Integer** - Whole numbers (64-bit signed)
- **Decimal** - Exact decimal numbers (`rust_decimal`, up to 28 significant digits)
- **Boolean** - `true` / `false`
- **Date**, **DateTime** - Dates and timestamps (values are UTC)
- **Json** - JSON values; text in a Json column is parsed as JSON

### Schema Field Properties

| Property | Type | Required | Description |
|----------|------|----------|-------------|
| `name` | String | ✅ | Column name (must match source data) |
| `type` | String | ✅ | Data type: String, Integer, Decimal, Boolean, Date, DateTime, Json |
| `nullable` | Boolean | ❌ | Allow null/empty values (default: true) |
| `pattern` | String | ❌ | Regex pattern for validation (Text/DateTime types) |
| `default` | Any | ❌ | Default value when field is missing or null |

### Validation Behavior

**Type Checking:**
- Each value must already have the column's type. CSV values are typed as they're read: whole numbers, decimals, `true`/`false` and dates are recognized; anything else is text
- Text in a `Json` column is parsed as JSON
- A mismatch (`yes` in a Boolean column, `abc` in an Integer column) stops the transfer with the column name

**Null Handling:**
- Missing fields use `default` value if specified
- Null/empty values use `default` value if specified  
- If `nullable: false`, null values without defaults cause validation errors

**Pattern Validation:**
- Regex patterns applied to Text and DateTime fields
- Validation failures stop processing with clear error messages
- Write patterns in single quotes (`pattern: '^\d{4}$'`): in double-quoted YAML strings, `\d` is an invalid escape

**Error Handling:**
- Schema validation errors halt processing immediately
- Clear error messages indicate field name, expected type, and actual value
- Pattern validation failures show the expected regex pattern

### Schema Examples

**Customer Data Schema:**
```yaml
columns:
  - name: "customer_id"
    type: "Integer"
    nullable: false
    
  - name: "full_name"
    type: "String"
    nullable: false
    
  - name: "email"
    type: "String"
    nullable: false
    pattern: '^[\w\.-]+@[\w\.-]+\.[a-zA-Z]{2,}$'
    
  - name: "phone"
    type: "String"
    nullable: true
    pattern: '^\+?[1-9]\d{1,14}$'  # E.164 format
    
  - name: "registration_date"
    type: "DateTime"
    nullable: false
    pattern: '^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}'
    
  - name: "is_premium"
    type: "Boolean"
    nullable: false
    default: false
    
  - name: "credit_limit"
    type: "Decimal"
    nullable: true
    default: "0.00"
```

**Sales Data Schema:**
```yaml
columns:
  - name: "order_id"
    type: "String"
    nullable: false
    pattern: '^ORD-\d{8}$'  # Format: ORD-12345678
    
  - name: "quantity"
    type: "Integer"
    nullable: false
    default: 1
    
  - name: "unit_price"
    type: "Decimal" 
    nullable: false
    
  - name: "discount_rate"
    type: "Decimal"
    nullable: true
    default: "0.0"
    
  - name: "total_amount"
    type: "Decimal"
    nullable: false
    
  - name: "order_date"
    type: "DateTime"
    nullable: false
```

### Command Examples

```bash
# Basic schema validation
tinyetl customer_data.csv clean_customers.db --schema-file customer_schema.yaml

# Schema validation with preview
tinyetl large_import.csv target.db --schema-file validation.yaml --preview 5

# Combined schema validation and transformations
tinyetl sales_export.csv analytics.db \
  --schema-file sales_schema.yaml \
  --transform "profit_margin=(row.total_amount - row.cost) / row.total_amount"

# Validate API data before processing
tinyetl "https://api.example.com/export" local_data.db \
  --source-type=csv \
  --schema-file api_schema.yaml
```

### Integration with Transformations

Schema validation occurs **before** transformations, ensuring input data quality:

```bash
# Validate input, then transform 
tinyetl raw_sales.csv processed.db \
  --schema-file sales_schema.yaml \
  --transform "profit=row.total_amount * 0.3; order_year=tonumber(row.order_date:match('^(%d%d%d%d)'))"
```

**Validation Flow:**
1. **Load schema** from YAML file
2. **Validate each row** against schema (type checking, patterns, nullability)
3. **Apply defaults** for missing/null fields
4. **Apply transformations** to validated data
5. **Transfer** to target

### Use Cases

- **Data Quality Assurance**: Ensure incoming data meets quality standards
- **API Integration**: Validate data from external APIs before processing
- **ETL Pipelines**: Enforce consistent schemas across pipeline stages
- **Data Contracts**: Define and enforce data format agreements
- **Migration Validation**: Ensure data integrity during system migrations

## YAML Job Files

For complex ETL jobs, TinyETL supports YAML configuration files that make your data pipelines more maintainable and version-controllable:

```bash
# Run ETL job from configuration file
tinyetl run config.yaml
```

A job file needs only a source and a target:

```yaml
source: sales.csv
target: postgres://etl:${DB_PASSWORD}@localhost/analytics#sales
```

Every other key is optional and has the name of a command-line flag: `batch_size` is `--batch-size`, `transform_file` is `--transform-file`. A key TinyETL doesn't know is an error, so a typo fails instead of being ignored. `tinyetl generate-config <SOURCE> <TARGET> [OPTIONS]` turns a command line into a job file, and `tinyetl generate-default-config` prints this annotated example:

```yaml
# TinyETL job file. Run it with: tinyetl run job.yaml
#
# Only source and target are required. Every other key is optional and has the
# name of a command-line flag (batch_size is --batch-size). Unknown keys are an
# error. ${VAR} inserts an environment variable, ${VAR:-default} a default when
# it isn't set. Generate a job from a command line with:
#   tinyetl generate-config <SOURCE> <TARGET> [OPTIONS] > job.yaml

source: employees.csv                  # a file, URL or database connection string
target: postgres://etl:${DB_PASSWORD:-etl}@localhost/hr#employees

# A source or target with options (see "Endpoint Options" in the README):
# source:
#   uri: https://example.com/export.csv
#   options:
#     auth.bearer: ${API_TOKEN}
#     delimiter: ";"

# source_query: SELECT * FROM orders WHERE paid   # a database source's query, instead of #table
# truncate: true                       # replace the target's rows instead of appending
# batch_size: 10000                    # rows per batch
# schema_file: employees_schema.yaml   # column types and validation, instead of inference
# source_type: csv                     # when the source has no file extension
# preview: 10                          # show 10 rows and stop
# dry_run: true                        # check the source and schema, write nothing
# log_level: warn                      # info, warn or error

# Lua transform: one assignment per line (or separated by ";"). Every column
# is kept; each line adds or replaces one, and can use the ones before it.
transform: |
  full_name = row.first_name .. " " .. row.last_name
  annual_salary = row.monthly_salary * 12
  hire_year = tonumber(string.sub(row.hire_date, 1, 4))

# Or a Lua file with a transform(row) function, which can also drop rows:
# transform_file: transform.lua

# Or SQL over all the source rows (a table named source), run in DuckDB:
# sql: SELECT department, COUNT(*) AS people FROM source GROUP BY department
```

Job files from earlier versions, with `version: 1`, `uri:` under `source:` and `target:`, and the settings under `options:`, still work.

### Source and Target Options

TinyETL supports connector-specific options that can be passed to sources and targets. These options are particularly useful for HTTP sources that require authentication or custom headers.

#### HTTP Source Options

When reading from HTTP/HTTPS URLs, you can specify authentication and custom headers:

```yaml
source:
  uri: "http://api.example.com/data.csv"
  options:
    # Custom headers (prefix with "header.")
    header.User-Agent: "TinyETL/0.12.0"
    header.Accept: "text/csv"
    header.X-API-Version: "v2"
    
    # Basic authentication
    auth.basic.username: "myuser"
    auth.basic.password: "${API_PASSWORD}"
    
    # OR Bearer token authentication
    # auth.bearer: "${API_TOKEN}"

target: output.json
```

**Available HTTP Options:**
- `header.{HeaderName}` - Add custom HTTP headers (e.g., `header.User-Agent`, `header.Accept`)
- `auth.basic.username` - Username for HTTP Basic authentication
- `auth.basic.password` - Password for HTTP Basic authentication  
- `auth.bearer` - Bearer token for token-based authentication

**Security Best Practice:** Use environment variables for sensitive values like passwords and tokens:
```yaml
source:
  uri: "https://api.example.com/data"
  options:
    auth.bearer: "${API_TOKEN}"  # Read from environment variable
```

See [Example 18: HTTP with Authentication](examples/18_http_with_auth/) for complete working examples.

#### S3 Options

`s3://bucket/path/file.ext` works as both a source and a target for CSV, TSV, JSON, JSON Lines, Parquet, Avro and Excel (`.xlsx`) files, and their `.gz` / `.zst` compressed forms:

```bash
export AWS_ACCESS_KEY_ID=...
export AWS_SECRET_ACCESS_KEY=...
export AWS_REGION=eu-west-1

tinyetl s3://my-bucket/raw/orders.csv orders.parquet
tinyetl orders.csv s3://my-bucket/exports/orders.parquet
```

Settings are read from the standard AWS environment variables (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`, `AWS_REGION`, `AWS_ENDPOINT`, `AWS_ALLOW_HTTP`). On AWS infrastructure, IAM roles (EC2 instance profiles, ECS task roles, web identity) are picked up automatically. In a YAML config, each endpoint can override them:

```yaml
source:
  uri: "s3://my-bucket/raw/orders.csv"
  options:
    region: "eu-west-1"
    access_key_id: "${S3_ACCESS_KEY_ID}"
    secret_access_key: "${S3_SECRET_ACCESS_KEY}"

target:
  uri: "s3://other-bucket/exports/orders.parquet"
  options:
    endpoint: "https://<account-id>.r2.cloudflarestorage.com"   # S3-compatible stores
    access_key_id: "${R2_ACCESS_KEY_ID}"
    secret_access_key: "${R2_SECRET_ACCESS_KEY}"
```

**Available S3 Options:**
- `region` - AWS region of the bucket (defaults to `us-east-1`)
- `endpoint` - Custom endpoint URL for S3-compatible stores
- `access_key_id`, `secret_access_key`, `session_token` - Static credentials
- `allow_http` - Allow non-TLS endpoints (`true`/`false`; implied by an `http://` endpoint option)
- `path_style` - `true` for path-style requests (the default), `false` for virtual-hosted-style

**Behavior and limitations:**
- One object per source or target; prefixes and wildcards are not supported
- The file format comes from the object key's extension (sources can override it with `--source-type`)
- Data is staged in a local temporary file, so the machine needs free disk space for the object
- Writing replaces an existing object. The upload happens once the transfer has finished, so a failed run leaves the existing object untouched
- The credentials need `s3:ListBucket` on the bucket and `s3:GetObject` / `s3:PutObject` on its objects (the target checks whether the object exists before writing)
- Profiles in `~/.aws/credentials` / `~/.aws/config` and AWS SSO are not read; use environment variables instead
- `--source-secret-id` / `--dest-secret-id` do not apply to S3 URLs

See [Example 19: S3](examples/19_s3/) for a complete working example.

### Environment Variables

`${VAR}` inserts an environment variable into any text value (connection strings, endpoint options, file paths, transforms); `${VAR:-default}` uses the default when the variable isn't set or is empty. A variable without a default that isn't set is an error.

```yaml
source: postgresql://${DB_USER}:${DB_PASSWORD}@${DB_HOST:-localhost}:5432/mydb#users
target: ${OUTPUT_DIR:-.}/processed_users.parquet
```

```bash
DB_USER=me DB_PASSWORD=secret tinyetl run job.yaml
```

### Examples

**File conversion:**
```yaml
source: sales_data.csv
target: sales_data.parquet
```

**Database load with a transform:**
```yaml
source: postgresql://user:${DB_PASSWORD}@host/db#raw_orders
target: analytics.db#processed_orders
truncate: true
transform: |
  -- Order totals and profit margins
  total_amount = row.quantity * row.unit_price
  profit_margin = (total_amount - row.cost) / total_amount
  order_year = tonumber(string.sub(row.order_date, 1, 4))
```

**Authenticated download to S3:**
```yaml
source:
  uri: https://api.example.com/export.csv
  options:
    auth.bearer: ${API_TOKEN}
target: s3://my-bucket/exports/export.parquet
```

## Sample Output

```
$ tinyetl sales.csv "sales.db#sales" --transform "total=row.amount * row.quantity"
INFO tinyetl::transfer: → Connecting to source: sales.csv
INFO tinyetl::transfer: → Connecting to target: sales.db#sales
INFO tinyetl::transfer: → Inferring schema from source...
INFO tinyetl::transfer: → 8 columns detected
INFO tinyetl::transfer: → Transformation enabled
INFO tinyetl::transfer: → Schema updated by transformations: 9 columns
INFO tinyetl::transfer: → Creating target table: sales
INFO tinyetl::transfer: → Copying 100000 rows
INFO tinyetl::transfer: → Done in 1.0s
INFO tinyetl: Transfer completed successfully!
INFO tinyetl: Processed 100000 rows in 0.98s (101586 rows/sec)
```

(Timestamps trimmed. A progress bar is shown while copying.)

## Performance

An 8-column CSV converted on an Apple M4 Pro with the default batch size. Times are for 1,000,000 rows (83 MB); peak memory is shown for 1M and 10M rows (843 MB):

| Target | Time (1M rows) | Rows/sec | Peak memory, 1M rows | Peak memory, 10M rows |
|---|---|---|---|---|
| CSV | 2.9 s | 345k | 32 MB | 32 MB |
| Parquet | 2.9 s | 345k | 58 MB | 70 MB |
| JSON Lines | 3.4 s | 294k | 32 MB | 32 MB |
| DuckDB | 3.6 s | 278k | 118 MB | 218 MB |
| JSON | 3.8 s | 263k | 32 MB | 32 MB |
| Avro | 4.4 s | 227k | 47 MB | 47 MB |
| SQLite | 7.2 s | 139k | 53 MB | 58 MB |
| Excel (.xlsx) | 7.3 s | 137k | 33 MB | (Excel's limit is 1,048,576 rows) |

Every source and file target streams: rows are read and written a batch at a time, so memory stays flat as files grow. Reading the 10M-row Parquet, JSON or Avro file back to CSV peaks at 31–79 MB. Excel is the exception on the read side: a sheet is loaded whole. Network databases and warehouses depend mostly on the server and the network.

## Roadmap

**Done:**
- Files: CSV/TSV, JSON, JSON Lines, Parquet, Avro, Excel, streamed with flat memory, gzip and zstd compressed ✅
- Databases: SQLite, DuckDB, PostgreSQL, MySQL, SQL Server, CrateDB, any ODBC driver ✅
- Snowflake (staged bulk loads) ✅
- Remote files over HTTP(S), SSH and S3 ✅
- Schema inference, schema files, Lua transforms, YAML jobs ✅
- Source queries: read a SQL query's result instead of a whole table ✅
- SQL transforms in the built-in DuckDB ✅

**Next:**
- Many files at once: globs and partitioned datasets
- Reading from stdin and writing to stdout
- Incremental loads and upserts

## Contributors

Special thanks to:
- Michael Descy @mjdescy (Excel)
- Chris Riccomini @criccomini
- Andreas Motl @amotl (CrateDB)

for contributing to TinyETL!


## License

This project is licensed under a modified Apache License 2.0 - see the [LICENSE](LICENSE) file for details.

Commercial use is explicitly allowed with the exception of reselling TinyETL in a cloud SaaS format, please contact licensing@tinyetl.com for additional commercial licensing terms.

**Bundled third-party libraries:** to keep the binary free of runtime dependencies, the Linux and macOS binaries statically link the [unixODBC](https://www.unixodbc.org/) driver manager (2.3.14), licensed under the GNU LGPL v2.1 or later, the Linux binary also includes OpenSSL (Apache License 2.0), and every binary includes AWS-LC (ISC/Apache-2.0, used for TLS by the Snowflake client). They are not covered by TinyETL's license, and the commercial terms above do not apply to them. Their license texts ship with every download, and [THIRD_PARTY_LICENSES.md](THIRD_PARTY_LICENSES.md) explains where to get their source and how to rebuild TinyETL against a modified unixODBC.


---

Built with Rust for performance, safety, and reliability.