filesql

package module
v0.58.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 12, 2026 License: MIT Imports: 45 Imported by: 5 modules, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

filesql

Mentioned in Awesome Go Go Reference MultiPlatformUnitTest Coverage

logo

filesql loads files into an in-memory SQLite database. Open CSV, TSV, LTSV, JSON, JSONL, Parquet, XLSX, ACH, or Fedwire inputs, then query them with normal SQLite syntax.

The same module also includes prep, which cleans and validates rows before they become tables.

sqly is the shell built on the same core.

Documentation: https://pkg.go.dev/github.com/nao1215/filesql

Try it in 30 seconds

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/nao1215/filesql"
)

func main() {
	db, err := filesql.Open(context.Background(), "users.csv")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	var n int
	if err := db.QueryRow("SELECT COUNT(*) FROM users WHERE age > 25").Scan(&n); err != nil {
		log.Fatal(err)
	}
	fmt.Println(n)
}

The table is named after the file, so users.csv is users. Join across formats by opening more of them:

db, err := filesql.Open(ctx, "users.csv", "orders.jsonl", "returns.parquet")

Why filesql?

filesql is for cases where the data is already in a file and the fastest useful tool is SQL.

  • Open files as tables without setting up a server.
  • Join across CSV, TSV, LTSV, JSON, JSONL, Parquet, XLSX, ACH, and Fedwire.
  • Keep edits in memory until you decide to save them.
  • Clean inputs with prep before loading them.

Features

  • Query file data with standard SQLite syntax, including joins, CTEs, and json_extract().
  • Optionally query with MySQL, PostgreSQL, or GoogleSQL syntax via WithDialect (translated to SQLite).
  • Read from file paths, directories, io.Reader, and embed.FS.
  • Handle compressed CSV, TSV, LTSV, JSON, JSONL, Parquet, and XLSX files transparently.
  • Write csv, tsv, and ltsv output in Shift-JIS, EUC-JP, ISO-2022-JP, or UTF-16 as well as UTF-8.
  • Load into a new in-memory database or into a *sql.DB you already manage.
  • Save changes with DumpDatabase, EnableAutoSave, or EnableAutoSaveOnCommit.
  • Stay in one module for loading (filesql) and cleanup (prep).

Installation

go get github.com/nao1215/filesql

Requirements:

  • Go 1.25.13 or later, or 1.26.6 or later on the 1.26 line
  • Linux, macOS, or Windows

The patch releases are the point: 1.25.13 and 1.26.6 are the ones carrying the standard library fixes for GO-2026-6088 (encoding/xml) and GO-2026-5972 (encoding/asn1), and filesql reaches encoding/xml on every XLSX it reads. An earlier 1.26 is not supported, even though it is a later release than 1.25.13.

Recipes

filesql.Open takes a context, so a load can be given a timeout or canceled with the request it belongs to. Pass context.Background() when it needs neither.

Query files with SQLite
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/nao1215/filesql"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	db, err := filesql.Open(ctx, "users.csv", "orders.jsonl")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	rows, err := db.QueryContext(ctx, `
		SELECT
			u.name,
			COUNT(*) AS order_count
		FROM users u
		JOIN orders o
			ON u.id = json_extract(o.data, '$.user_id')
		GROUP BY u.name
		ORDER BY order_count DESC, u.name
	`)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	for rows.Next() {
		var name string
		var orderCount int
		if err := rows.Scan(&name, &orderCount); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%s: %d\n", name, orderCount)
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
}
Query with another SQL dialect

By default queries use SQLite syntax. WithDialect lets you write queries in MySQL, PostgreSQL, or GoogleSQL (BigQuery / Cloud Spanner) instead; filesql translates them to SQLite before running. Loading files always uses SQLite, so only the queries you write are affected.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/nao1215/filesql"
	"github.com/nao1215/filesql/dialect"
)

func main() {
	ctx := context.Background()

	db, err := filesql.NewBuilder().
		AddPath("users.csv").
		WithDialect(dialect.PostgreSQL).
		Open(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// PostgreSQL syntax: "::" cast and ILIKE.
	rows, err := db.QueryContext(ctx,
		"SELECT name, age::text FROM users WHERE name ILIKE 'a%'")
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()
	// ...
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
	fmt.Println("ok")
}

Translation implements a stated subset of SQL rather than a full emulator: the query is parsed, rewritten and written back out, so common incompatibilities (identifier quoting, DATE_ADD, SPLIT_PART, SAFE_DIVIDE, EXTRACT, casts, …) are rewritten or backed by helper functions, and a construct with no SQLite equivalent (for example QUALIFY, DISTINCT ON, MySQL's XOR, or MySQL's 0x literal, which is a string in one place and a number in another) returns a clear error. Nothing is passed to SQLite untranslated: a query outside the subset is refused with the line and column of the construct. What the translation cannot reach is SQLite's type system: there is no boolean, no interval and no array, so a comparison answers 1 or 0, an INTERVAL literal works only in date arithmetic, and a construct whose result would be one of those types is refused rather than answered. A non-SQLite dialect cannot be combined with auto-save. See the dialect package for the full list of supported translations.

Load into a database you already own
package main

import (
	"context"
	"database/sql"
	"log"

	"github.com/nao1215/filesql"
	_ "modernc.org/sqlite"
)

func main() {
	db, err := sql.Open("sqlite", ":memory:")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// A plain ":memory:" database is private per connection.
	db.SetMaxOpenConns(1)

	if err := filesql.LoadInto(context.Background(), db, "users.csv", "payments.parquet"); err != nil {
		log.Fatal(err)
	}
}
Clean rows before loading with prep

Use prep when the file needs normalization before it becomes a table: trimming, case normalization, defaults, and validation errors with row numbers.

package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"strings"

	"github.com/nao1215/filesql"
	"github.com/nao1215/filesql/prep"
)

type User struct {
	Name  string `prep:"trim" validate:"required"`
	Email string `prep:"trim,lowercase" validate:"required,email"`
	Role  string `prep:"trim,uppercase" validate:"required,oneof=ADMIN USER"`
}

func main() {
	csvData := `name,email,role
  Alice  ,ALICE@EXAMPLE.COM, admin
Bob,bob@example.com,user
`

	processor := prep.NewProcessor(prep.FileTypeCSV)
	var users []User

	reader, result, err := processor.Process(strings.NewReader(csvData), &users)
	if err != nil {
		log.Fatal(err)
	}
	if result.HasErrors() {
		log.Fatal(result.ValidationErrors())
	}

	fmt.Println(users[0].Name, users[0].Email, users[0].Role)

	cleaned, err := io.ReadAll(reader)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(string(cleaned))

	ctx := context.Background()
	db, err := filesql.NewBuilder().
		AddReader(strings.NewReader(string(cleaned)), "users", filesql.FileTypeCSV).
		Open(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
}

Supported File Formats

Extension Format Notes
.csv CSV Header row becomes column names
.tsv TSV Tab-separated text
.ltsv LTSV Labeled tab-separated text
.json JSON Query nested data with json_extract()
.jsonl JSONL One JSON value per line
.parquet Parquet Columnar format
.xlsx Excel XLSX One sheet becomes one table, named file_sheet (just file when the sheet repeats it). A workbook handed to AddReader hangs its sheets off the table name given there instead of off a file name, so a workbook added as book loads as book_Sheet1 and as plain book when the sheet is itself named book. ExcelSheetTableNames works out the same names when it is given that table name in place of a path, and sqlite_master has them after a load. Every sheet that names a column is loaded by default, a blank scratch sheet being passed over; see Excel Sheet Visibility
.ach ACH (NACHA) One table per record kind; see ACH and Fedwire
.fed Fedwire One message becomes one row 326 columns wide; see ACH and Fedwire

Two inputs are the same source only when they are in the same place. dir/users.csv and dir/users.csv.gz are one dataset offered twice, and the plain one is read; a/users.csv and b/users.csv are two files, and both are loaded. What happens when both then want the table users is the loading API's business: Open builds a fresh database and refuses it with ErrDuplicateTable, while LoadInto and LoadIntoTx load into a database you own and keep their last-wins rule, so the later input replaces the table. Neither one silently drops a file. Table names are compared the way SQLite compares identifiers, with ASCII case folded, so Users.csv and users.csv want the same table too.

Column names inside a file follow two separate rules, and a header that breaks either is refused with ErrDuplicateColumn before it reaches SQLite. Two names differing only in ASCII letter case are one column, because SQLite is what holds them — ID and id are a duplicate — and the folding stops at ASCII as SQLite's does, so ä and Ä stay two columns. Two names identical after their surrounding whitespace is trimmed are one column too: name and " name " are one name typed twice. The rules are applied one at a time and never combined, so " A" beside a is accepted, which is what SQLite does with it as well. LTSV carries its labels on every record rather than in a header, so the same check runs per record.

Compressed wrappers are supported for CSV, TSV, LTSV, JSON, JSONL, Parquet, and XLSX: .gz, .bz2, .xz, .zst, .z, .snappy, .s2, .lz4.

ACH and Fedwire do not use external compression wrappers.

An xz or zstd stream states in its header how much working memory its decoder must hold, and a decoder allocates it before reading any data. filesql caps that at a 256 MiB xz dictionary, four times what xz -9 declares, and a 128 MiB zstd window, which is the largest the zstd CLI reaches on its own. A damaged file therefore costs a fixed ceiling rather than whatever its header names. The zstd cap holds for every frame; the xz one is read from the first block of the first stream, so a later block or a concatenated second stream is not covered.

Format and compression are separate. FileType names the format only — FileTypeCSV is a CSV whether or not a codec wraps it — and a path says which codec that is. A reader has no path, so AddReader takes the codec as an option:

gz, err := os.Open("users.csv.gz")
if err != nil {
	return err
}
defer gz.Close()

builder.AddReader(gz, "users", filesql.FileTypeCSV, filesql.WithCompression(filesql.CompressionGZ))

Without WithCompression the reader's bytes are read as the format directly, so the ordinary three-argument call is unchanged.

Behavior and limits

The rules the loader and the writers follow are documented beside the API they belong to, so they are in reach while the call is being written: column typing and what a blank cell means, memory and chunked loading, sharing a database across goroutines, what each way of saving writes, Excel sheet visibility, and the ACH and Fedwire write-back. Read them at pkg.go.dev/github.com/nao1215/filesql, or with go doc github.com/nao1215/filesql.

Examples

API example index

The GoDoc examples are fully tested with go test. The tables below show the fastest path from a feature name in the README to the exact example function in the repo.

filesql
Feature Example function Source
Open files and query them ExampleOpen, ExampleOpen_timeout example_api_test.go, example_test.go
Load files into an existing *sql.DB ExampleLoadInto, ExampleDBBuilder_LoadInto example_api_test.go
Load into a transaction you own ExampleDBBuilder_LoadIntoTx example_api_test.go
Load into your own database, edit, and save it back ExampleLoadInto_dumpDatabase example_api_test.go
Build from readers, paths, or embedded FS ExampleNewBuilder, ExampleDBBuilder_AddReader, ExampleDBBuilder_AddPath, ExampleDBBuilder_AddFS example_test.go
Read a compressed reader ExampleDBBuilder_AddReader_compressed example_test.go
Tune chunked loading ExampleDBBuilder_SetDefaultChunkSize example_api_test.go
Handle malformed rows ExampleDBBuilder_WithMalformedRowPolicy example_api_test.go
Count the rows a skip policy discarded ExampleDBBuilder_SkippedRows example_api_test.go
Query with MySQL, PostgreSQL, or GoogleSQL syntax ExampleDBBuilder_WithDialect example_api_test.go
Load only the sheets a workbook shows ExampleDBBuilder_WithExcelSheetPolicy example_api_test.go
Report a workbook's sheets and their visibility ExampleExcelSheetsInFile, ExampleExcelSheetsInReader example_api_test.go
Check a workbook's sheets for table names that collide ExampleExcelSheetTableNames example_api_test.go
Attach a slog logger ExampleDBBuilder_WithLogger example_api_test.go
Open a database that refuses writes ExampleDBBuilder_OpenReadOnly example_api_test.go
Save on close or commit ExampleDBBuilder_EnableAutoSave, ExampleDBBuilder_EnableAutoSaveOnCommit example_api_test.go, example_test.go
Export under a deadline ExampleDumpDatabase_deadline example_api_test.go
Export tables with format/compression/encoding/line-ending options ExampleDumpDatabase, ExampleNewDumpOptions, ExampleDumpOptions_WithFormat, ExampleDumpOptions_WithCompression, ExampleDumpOptions_WithEncoding, ExampleDumpOptions_WithLineEnding example_api_test.go, example_test.go
Compress a stream, or open a compressed file ExampleCompressionType_NewWriter, ExampleCompressionType_NewReader, ExampleOpenReader example_api_test.go
Strip compression suffixes ExampleRemoveCompressionExtension example_api_test.go
Write an ACH or Fedwire file back after editing it ExampleDumpACH, ExampleDumpFedWire example_api_test.go
Write one back when the database came from an io.Reader ExampleDumpACHWithSource, ExampleDumpFedWireWithSource example_api_test.go
Load a compressed stream whose name is not a path ExampleWithCompression example_api_test.go
Tell which of several inputs failed to load ExampleParseError example_api_test.go
Inspect enum names ExampleMalformedRowPolicy_String, ExampleExcelSheetPolicy_String, ExampleFileType_String, ExampleCompressionType_String, ExampleEncoding_String, ExampleLineEnding_String, ExampleOutputFormat_String example_api_test.go
prep
Feature Example function Source
Strict tag parsing for invalid prep/validate tags ExampleWithStrictTagParsing prep/example_api_test.go
Keep only valid rows in the output stream ExampleWithValidRowsOnly prep/example_api_test.go
Clean CSV data into structs and a reusable reader ExampleProcessor_Process prep/example_api_test.go
Unwrap a codec before preprocessing ExampleProcessor_Process_compressed prep/example_api_test.go
Convert JSON arrays into JSONL output ExampleProcessor_Process_json prep/example_api_test.go
Stream cleaned output into any writer ExampleProcessor_ProcessToWriter prep/example_api_test.go
Inspect validation counts ExampleProcessResult_InvalidRowCount, ExampleProcessResult_HasErrors prep/example_api_test.go
Read validation error details ExampleProcessResult_ValidationErrors prep/example_api_test.go
See a struct field that names no column refused ExampleProcessor_Process_unknownColumn prep/example_api_test.go
Give a field a default when the column is absent ExampleProcessor_Process_defaultForAbsentColumn prep/example_api_test.go
Compare one column against another ExampleProcessor_Process_crossField prep/example_api_test.go
Require a column only when other columns say so ExampleProcessor_Process_conditionalRequired prep/example_api_test.go
Forbid a column when other columns say so ExampleProcessor_Process_conditionalExcluded prep/example_api_test.go
Validate IP address and port columns ExampleProcessor_Process_networkColumns prep/example_api_test.go
Validate JSON, time zone, version and digest columns ExampleProcessor_Process_encodedColumns prep/example_api_test.go
Verify a check digit on an ISBN or a card number ExampleProcessor_Process_checksummedIdentifiers prep/example_api_test.go
Validate country and currency code columns ExampleProcessor_Process_codeColumns prep/example_api_test.go
Refuse a duplicate in a key column ExampleProcessor_Process_uniqueColumn prep/example_api_test.go
Validate DNS label, color and numeric currency columns ExampleProcessor_Process_labelColorAndNumericCode prep/example_api_test.go
Read preprocessing error details ExampleProcessResult_PrepErrors prep/example_api_test.go
Check output and original formats ExampleProcessResult_OutputFormat prep/example_api_test.go
Load a processed reader into filesql ExampleProcessor_Process_intoFilesql prep/example_api_test.go
Rewind and reread the processed stream Example_streamSeek prep/example_api_test.go
dialect
Feature Example function Source
Translate a query into SQLite SQL and recognize what has no equivalent ExampleTranslate dialect/example_test.go
Run PostgreSQL constructs SQLite has no form for ExampleTranslate_postgreSQL dialect/example_test.go
Run BigQuery constructs SQLite has no form for ExampleTranslate_googleSQL dialect/example_test.go
Tell a construct SQLite cannot express from one outside the supported subset ExampleTranslate_unsupportedFeature dialect/example_test.go
Turn a user-supplied dialect name into a Dialect ExampleParse dialect/example_test.go
List the built-in dialects and spell one for a person ExampleDialects, ExampleDialect_DisplayName dialect/example_test.go
Integration examples

The examples directory shows how to use filesql with regular Go database tooling:

Example Description
basic Basic CSV queries
multi-format Join across CSV, TSV, and LTSV
sqlc Use filesql with sqlc
gorm Use filesql with GORM
sqlx Use filesql with sqlx
bun Use filesql with Bun
squirrel Use filesql with Squirrel
ent Use filesql with Ent
Project Description
sqly Interactive shell for ad-hoc SQL against files
filesql/prep Row cleanup and validation before SQL

Contributing

Contributions are welcome. See CONTRIBUTING.md before sending a PR.

Support

If filesql is useful in your work:

License

filesql is released under the MIT License.

Contributors ✨

Thanks goes to these wonderful people (emoji key):

CHIKAMATSU Naohiro
CHIKAMATSU Naohiro

💻 📖
Sai Asish Y
Sai Asish Y

📖
Krishna lokhande
Krishna lokhande

🐛

Documentation

Overview

Package filesql provides a file-based SQL driver implementation that enables querying CSV, TSV, LTSV, JSON, JSONL, Parquet, and Excel (XLSX) files using SQLite3 SQL syntax.

filesql allows you to treat structured text files as SQL databases without any data import or transformation steps. It uses SQLite3 as an in-memory database engine, providing full SQL capabilities including JOINs, aggregations, window functions, and CTEs.

ACH (NACHA) and Fedwire files are also loaded; see the ACH and Fedwire section below.

Features

  • Query CSV, TSV, LTSV, JSON, JSONL, Parquet, and Excel (XLSX) files using standard SQL
  • Automatic handling of compressed files: gzip (.gz), bzip2 (.bz2), xz (.xz), zstandard (.zst), zlib (.z), snappy (.snappy), s2 (.s2) and LZ4 (.lz4)
  • Support for multiple input sources (files, directories, io.Reader, embed.FS)
  • Efficient streaming for large files with configurable chunk sizes
  • Cross-platform compatibility (Linux, macOS, Windows)
  • Optional auto-save functionality to persist changes
  • Optional MySQL, PostgreSQL, and GoogleSQL query dialects (queries are translated to SQLite; see WithDialect and the dialect subpackage)

Basic Usage

The simplest way to use filesql is with the Open function:

db, err := filesql.Open(context.Background(), "data.csv")
if err != nil {
    log.Fatal(err)
}
defer db.Close()

rows, err := db.Query("SELECT * FROM data WHERE age > 25")
if err != nil {
    log.Fatal(err)
}
defer rows.Close()

Advanced Usage

For more complex scenarios, use the Builder pattern:

db, err := filesql.NewBuilder().
    AddPath("users.csv").
    AddPath("orders.tsv").
    EnableAutoSave("./output").
    Open(ctx)
if err != nil {
    log.Fatal(err)
}
defer db.Close()

Empty Sources

A file with nothing in it is refused with ErrEmptyData for CSV, TSV, LTSV, Parquet and XLSX, and loads as a table with no rows for JSON and JSONL. The two are the formats whose empty input a caller reads as "the step before this produced no rows", which is a table with no rows rather than a file that failed to arrive; in the others there is no way to say "no rows" without saying nothing at all, so an empty one is a truncated file. A document that does say there are no rows loads for every format: "[]" is a JSON table with no rows, and a CSV holding only its header is one too.

The rule follows the format rather than the kind of source, so a reader and the member of a compressed file answer the way a file does. The prep package is stricter and refuses an empty source for every format including the two, since it answers about a document rather than about a load.

Column Types

CSV, TSV, LTSV and XLSX carry no types, so the values decide whether a column is INTEGER, REAL or TEXT. Parquet, ACH and Fedwire bring their own schema and are not inferred; a Parquet UINT64 column loads as TEXT, since the upper half of its range is past what SQLite's INTEGER holds exactly.

The type follows from every value in the column, wherever the value sits and however large the file is. One value of these four kinds anywhere in the file makes the column TEXT, because a numeric column would damage it:

  • a leading zero, such as 007, which INTEGER drops
  • an integer past int64, such as 11040320260000000000, which float64 renders as 1.104032026e+19
  • a decimal a float64 cannot hold, such as 1e400 or 1e-400, which would be stored as an infinity or as an exact zero
  • a spelling Go parses and SQLite's affinity does not convert, such as 1_000 or 0x1p4
  • the padding a fixed-width code carries, such as " 42"

One decimal makes a numeric column REAL. An INTEGER column turns the column's arithmetic into integer division, so 5 / 2 answers 2 rather than 2.5. The exception is a column where a decimal meets an integer past 2^53 that REAL would round to a neighboring double: that column is TEXT, while the same integers with no decimal beside them stay INTEGER and exact.

Decimal formatting is not preserved: 2.50 loads as the REAL 2.5, 1.00 as 1, and 1e3 as 1000. The quantity is kept and the spelling is not, because a TEXT column is compared against a number as text, so WHERE amount > 9.5 over "9.00" and "10.00" would return nothing at all. Keep the source file when the original spelling matters. A dump keeps the type rather than the spelling: a REAL column is written with a decimal point, so 1.00 comes back as 1.0 and loads as REAL again, and an infinity is written as 9e999 and loads back as the infinity. A workbook keeps it the same way: a REAL column's cells hold the decimal point and wear a number format, since a cell drawn as a whole number would load as INTEGER and divide as one.

A column whose values are all datetimes is recognized as one and stored as TEXT. SQLite has no datetime storage class, and of the three ways it can hold one this package keeps the text, so the cell reads back as the file wrote it. A text cell is stored as the file wrote it, so a column written as 1/2/2024, 2024/01/02 or 02.01.2024 is recognized as a datetime and still needs converting before date() or strftime() can answer about it: those read ISO 8601 and "YYYY-MM-DD HH:MM:SS". An XLSX date cell is the one that is rewritten, into ISO 8601, because it holds a serial number and a number format rather than text.

A workbook draws a number the way its format says, and the drawing is not the value: a number of more than fifteen significant digits is drawn rounded to fifteen, a whole-number format draws 1234.5 as 1235, a scientific one draws it as 1.23E+03, and a percentage of 0.5 is drawn "50%". A numeric cell loads the number the file stores whatever its format would have drawn, so an 18-digit identifier keeps its digits, and a column of percentages, thousands-separated amounts, accounting figures or fractions is a number column that SUM and AVG answer about. Render the drawing back in SQL when it is the drawing you want.

A boolean cell is the same rule told in words: it is stored as 1 or 0 and drawn TRUE or FALSE, and it loads as the number it stores, so a boolean column is INTEGER and WHERE flag, SUM(flag) and a join against a Parquet BOOLEAN column all answer. Text holding the word "TRUE" is text and stays text.

Two kinds of cell keep what the sheet shows instead. One is text, which is text whatever its format says. The other is a number whose format draws a moment rather than a quantity -- a time of day, an elapsed duration -- since the serial behind one is not what it means. A date is the third of these and is rewritten into ISO 8601 rather than left as either.

A blank cell -- empty, or nothing but whitespace -- in an INTEGER or REAL column is a missing number and is stored as NULL, which is what makes MAX answer the largest value rather than the blank, AVG divide by the values that are there, COUNT(column) count them, and WHERE column IS NULL find the rows that have none. A blank cell in a TEXT column is what it is, which is a value the file holds, and a column recognized as a datetime is stored as TEXT and follows that rule. A number written with spaces around it is not blank and is not a number either: the padding is data a fixed-width code column depends on, so one keeps the column TEXT.

Memory and Streaming

Data is loaded into an in-memory SQLite database. CSV, TSV, JSONL, JSON arrays and Parquet arrive in chunks while loading; LTSV, a JSON document that is not an array, XLSX, ACH and Fedwire are read in full before they are turned into rows. A chunked format still holds one record at a time, since a record has to be complete before it can be read. A Parquet file named by path is read where it lies, since the format reads at an offset and a file already serves that; a Parquet reader passed to DBBuilder.AddReader is buffered whole instead, because a stream cannot go back and the format is read back to front.

One record is held whole while it is read, so a record longer than 64 MiB is refused rather than buffered: a delimited record, an LTSV record, a JSONL line, one element of a JSON array, a JSON document that is not an array -- which is one record, since it becomes one row holding the whole of it -- and an ACH or a Fedwire record. A file cannot cost more than its own size either way; what the bound is for is a source that is a stream, where a record with no terminator would otherwise ask for everything the sender chooses to send. The JSON refusal lands within one of the decoder's own reads of the bound rather than on it, so an unterminated element reads about twice the bound and not the whole stream.

The rows end up in SQLite rather than on the Go heap, so the heap is not where the cost is: loading CSVs of 16 MB through 131 MB kept the Go heap flat at about 24 MB while resident memory grew by about twice the file's size. For a chunked format, budget from the file size: over 200,000 rows, CSV and Parquet each cost about 2.1 times the file.

A workbook is read whole, so what it costs follows the cells it holds rather than the size of the file, which is a zip and shrinks with how well the sheet compressed. The same 200,000 rows cost about 26 times the file as a wide workbook and about 37 times as a workbook of one column, and against the file alone the ratio reaches 135 times for a small one-column workbook. Budget an XLSX load from the cells rather than from the file, and bound the decompressed size before loading a workbook that came from somewhere else, since nothing here does. Every figure is printed by "go test -tags benchmark -run TestLoadMemoryFootprint -v ." and "go test -tags benchmark -run TestLoadMemoryFootprintByFormat -v .", which print the tables they are drawn from so they can be re-derived rather than taken on trust.

A damaged Parquet file can cost more than any of that. A page header states how large the page's statistics are and the reader allocates that before reading them, so a damaged 473-byte file costs 98 MB before it is refused; the number sits inside a column chunk, where this package cannot check it first. Do not point a memory-constrained process at Parquet files you did not write.

DBBuilder.SetDefaultChunkSize tunes chunked loading. It changes when rows reach the database, not what reaches it: a column's type and the text of every cell are the same at any chunk size, because a file whose later chunk needs a wider type is read again under the types the whole file calls for. A reader passed to DBBuilder.AddReader cannot be read twice, so it is staged as text and typed once it has all been read, at the cost of one copy of the table inside SQLite. The final cost is still dominated by the size of the database: chunking reduces loader overhead, it does not make a large dataset free.

A blank line is not a record in CSV, in LTSV or in a sheet. In TSV it is one in a one-column file, where it is that column's empty value: TSV has no quote to write an empty field with, so an empty line is the only spelling left and a reader that skipped it would drop the row. An XLSX row holding no cell at all is skipped, so a workbook whose used range reaches far down the sheet holds no record for the rows between its header and a stray cell near the bottom. A row whose cells are there and empty is a record, which is what a sheet's own XML separates from the space under its data.

Concurrency

The *sql.DB returned by Open is safe to share across goroutines: a shared-cache in-memory database is used so pooled connections see the same tables. Auto-save does not change that, since EnableAutoSave saves once when Close returns and EnableAutoSaveOnCommit saves one at a time. A DBBuilder is not safe to share; build one per goroutine.

Loading into one database from several goroutines works. Creating a table takes a write lock and SQLite refuses a second holder rather than queueing it, so a load that meets another load's lock waits it out and starts over, for up to five seconds, before it returns the database's own error. Paths and directories are covered whatever database they load into. A reader passed to DBBuilder.AddReader is not fully covered, because starting over would have nothing left to read: only the steps before the reading are tried again. LoadIntoTx is not retried at all, since the transaction belongs to the caller and one transaction belongs to one goroutine.

Transactions

One transaction runs at a time. SQLite serializes them itself and the driver waits for its turn inside itself, with no context in that wait, so a second transaction used to park until the first ended whatever deadline its caller had put on the work. It now queues here instead: BeginTx waits for the transaction before it and returns the context's error if the wait outlives the context. Statements outside a transaction are not queued, since a query beside an open transaction is an ordinary thing to write; what that leaves is the wait this package cannot reach. While a transaction that has written is open, and while a rows iterator is still open, a statement touching the same table waits inside SQLite for it, and no context ends that wait -- so close a rows iterator when you are done with it, and do not leave a writing transaction open across work that queries the same tables. DumpDatabase reads every table and is subject to the same rule.

SQLite runs serializable transactions and has no other level, so a sql.TxOptions naming one of the weaker levels is refused when the transaction begins rather than taken and quietly downgraded; sql.LevelDefault and sql.LevelSerializable are the two a transaction can ask for. A transaction begun with ReadOnly set is held under SQLite's query_only pragma for as long as it runs, so a write inside it fails and the permission comes back when it commits or rolls back.

A transaction begun by running BEGIN as a statement rather than through database/sql belongs to whichever pooled connection ran it, and the next statement may reach a different one, so the rows are not where the caller expects and are discarded when that connection closes. Auto-save counts such a transaction as open and refuses to save while it is, the same as one begun with BeginTx, and saves at a COMMIT run as a statement just as it does at tx.Commit. A savepoint taken while no transaction is open begins one, so it counts the same way and the RELEASE naming it ends it; a savepoint taken inside a transaction is not one of its own, so releasing that one leaves the transaction around it open. A comment before the keyword does not hide it.

Table Naming

Table names are automatically derived from file paths:

  • "users.csv" becomes table "users"
  • "data.tsv.gz" becomes table "data"
  • "/path/to/logs.ltsv" becomes table "logs"
  • "sales.xlsx" with multiple sheets becomes tables "sales_Sheet1", "sales_Sheet2", etc.

The name is made into an identifier first: whitespace, a hyphen and a dot each become an underscore, and every character that is not a letter, a digit, a combining mark or an underscore is dropped. Letters and digits are judged by Unicode category, so a name written in any script survives; "売上 2026.csv" becomes table "売上_2026".

Two names cannot be written as an identifier at all and are adjusted rather than carried over. A name beginning with a digit is prefixed, so "2024.csv" becomes table "sheet_2024", because SQLite will not read an unquoted identifier that starts with one. A name that keeps no characters becomes "sheet", so "!!.csv" does. Both words come from workbooks, where every table is a sheet, and they name a table derived from any format. Two files whose names need the same adjustment ask for the same table and are refused with ErrDuplicateTable.

Excel Sheet Visibility

Every sheet of a workbook is loaded by default, whether or not the workbook shows it. Use DBBuilder.WithExcelSheetPolicy with ExcelSheetPolicyVisibleOnly to load only the shown ones, and ExcelSheetsInFile to report what a workbook holds without loading it.

The policy applies to every source alike: a path, a directory, an embedded filesystem, a reader, and a compressed workbook. Table names are worked out after it has run, so a hidden sheet that would sanitize to the same table as a visible one is not a collision when it is not loaded.

Excel separates "hidden", which a reader can undo from the sheet tabs, from "very hidden", which only the VBA editor can. The library this package reads workbooks with reports one boolean covering both, so the two are not told apart and ExcelSheetPolicyVisibleOnly leaves out either kind.

Data Modifications

INSERT, UPDATE, and DELETE operations affect only the in-memory database. Original files remain unchanged unless auto-save is enabled.

Saving Changes

There are three ways to write the database out. DumpDatabase exports it to files when an explicit step is wanted; DBBuilder.EnableAutoSave writes when Close runs; DBBuilder.EnableAutoSaveOnCommit writes after each committed transaction and again at close, so a statement run outside a transaction is not lost. A transaction still open when Close runs has been neither committed nor rolled back, so the save is skipped and Close says so.

DumpOptions decides the format, the compression, the text encoding and the line terminator of csv, tsv and ltsv output. Output is UTF-8 unless DumpOptions.WithEncoding says otherwise; this package reads UTF-8 only, so a file written in another encoding is for other tools, and transcoding it is the caller's step before loading it back. A value the encoding has no way to write fails the save with ErrEncoding and leaves the destination as it was, rather than writing a substitute character; the refusal names the column the value sits in, or the column whose name holds it, and the character itself. ISO-2022-JP additionally refuses an escape, U+001B, which it reads as the start of a character-set designator rather than as data.

A text format holds characters rather than bytes, so a value or a column name the database holds that is not valid UTF-8 fails the save with ErrUnsupportedFormat for CSV, TSV, LTSV and XLSX, naming the field and pointing at Parquet, which stores bytes and reads them back unchanged. Such a value reaches a table by being bound as a Go []byte, or through a CAST or a blob literal in a statement run during the session; a value read from a file is checked when it is loaded.

A save that writes several files produces all of them before it replaces any. A value a format cannot hold therefore costs a set what it costs one file: nothing is replaced, and the sources are left holding one state of the session rather than two. What is left after that is the rename of each finished file over its destination, and an operating system refusing one of those, after an earlier one has gone through, leaves the files before it replaced; the error names the destination it would not replace, and the files the save had not reached are discarded. An export into a directory is the exception, because what it writes are files of its own rather than the caller's sources: a table it refuses for its name is refused before the directory is created, and one it refuses for a value partway through leaves the tables it had already finished, as a canceled export does.

Records end with "\n" unless DumpOptions.WithLineEnding says otherwise, with one exception: EnableAutoSave("") writes a table back to the file it was loaded from and keeps that file's own terminator, so a CRLF file edited in place stays CRLF and the rows nobody touched keep the ending they had. A file with mixed terminators keeps whichever one the majority of its lines use. Every other save is an export and writes what the options say whatever sits in the destination, EnableAutoSave("./dir") included. Parquet and XLSX carry their own encoding and are not line-based, so they ignore both options.

A workbook written back to itself keeps what a table does not hold. The save writes onto the workbook it is replacing, so a sheet ExcelSheetPolicyVisibleOnly left out stays, and so do the column widths, merged ranges and comments of the sheets it did load. Each table goes back to the rows it came from, which for a sheet holding a row with no cell in it -- under a title, or between two blocks of records -- are not the rows from the top. A cell already holding the value the save would write is left as it is, so a date cell nothing edited keeps the serial and the number format that make a spreadsheet read it as a day. A cell the save does write takes the type its column has: a value of an INTEGER or REAL column is written as a number, so the column stays one a spreadsheet sums, while a value this package keeps as text -- a zero-padded code, a literal past int64 -- is written as text. A REAL column's cell keeps its decimal point and takes a number format that shows one, which is what a load reads the column's type back from.

A Parquet file written back to itself keeps the schema it declared. Nothing in the database remembers it -- a BOOLEAN column loads as the integers 1 and 0, a DATE and a TIMESTAMP as the integer they store, a DECIMAL and a UUID as their text -- so the file is read for its types before it is replaced, and each value is rebuilt from the text the column holds. A column keeps its type only when every one of its values comes back as itself; one that does not is a value the caller set that the type cannot hold, and it is written the way an export writes it rather than narrowed into a different number. A required column holding a null the caller set becomes optional, which is the one thing the data demands. Some types are rendered by a load in a form that says less than the value they store, and those keep what an export writes. A list or a map is rendered as text. An INT96 is rendered as nanoseconds since the Unix epoch rather than the Julian day it holds, and a FLOAT16 is widened to 32 bits.

ACH and Fedwire

ACH (.ach) and Fedwire (.fed) files are loaded, queried and written back like any other format, but an exported file still needs domain knowledge from the caller: both formats carry rules about what a valid file is, and this package checks only the ones the format itself defines.

Control records are derived rather than stored. Writing an ACH file rebuilds each batch control and the file control from the entries, so an edit to total_debit, total_credit, entry_hash or entry_addenda_count is overwritten by the recalculation. The batch_index, entry_index and addenda_index columns say which record a row updates rather than holding a value of their own, and a write refuses a row whose coordinates name a record that is not there or one another row has already named.

A Fedwire write is verified before it reaches the caller's file: the message is written to a buffer, read back, and compared column by column with the table it was written from, and a field that did not survive refuses the write by name, leaving the file as it was. One field reaches this today, remittance_originator_address_line_four, which the underlying library writes from line one. Fedwire files must be the delimiter-separated form; a fixed-width file is refused, naming every record it could not read.

A write-back rewrites the whole file, since both formats are written from the parsed structure rather than patched, so records the caller did not edit can come back formatted differently while holding the same values. Writing needs the source file, because fields no table exposes exist only in the original: DumpACH and DumpFedWire read the file the tables were loaded from and fail with ErrSourceUnavailable, naming it, when it is gone or unreadable. A database loaded from an io.Reader has no such file; hand the file's own bytes to DumpACHWithSource or DumpFedWireWithSource.

Each database records its own source, so two databases loaded from files that share a name in different directories each export their own data. The record lives in a reserved table named _filesql_sources. Table names beginning with _filesql_ belong to this package: they are hidden from a dump and from the table listings filesql returns, and an input that would load into one is refused with ErrReservedTableName. A name beginning with sqlite_ is refused the same way, because SQLite keeps that prefix for its own tables. Both comparisons ignore ASCII case, as SQLite does.

Cancellation

Open, DBBuilder.Open, DBBuilder.OpenReadOnly, LoadInto, LoadIntoTx and DumpDatabase all take a context, so any of them can be given a deadline or canceled; pass context.Background to a call that needs neither. A load stops soon after its context ends, and whatever the database said on the way out, the error it returns matches context.Canceled or context.DeadlineExceeded. Soon is the next read for a source that is a stream, and the next chunk for one that is an open file, which is left unwrapped so that a Parquet file is still read where it lies rather than copied whole. A read already blocked inside the source cannot be interrupted, so a sender that stops mid-body without closing needs a deadline on the connection instead.

SQL Syntax

Since filesql uses SQLite3 as its underlying engine, all SQL syntax follows SQLite3's SQL dialect. This includes support for:

  • Common Table Expressions (CTEs)
  • Window functions
  • JSON functions
  • Date and time functions
  • And all other SQLite3 features

Column Name Handling

A table holds at most 2000 columns, which is SQLite's own limit and is fixed when SQLite is compiled. A wider file is refused with ErrUnsupportedFormat, naming the limit and the width the file has.

A byte-order mark at the front of a text file belongs to the encoding rather than to the first column name, however many the file carries: a file marked twice names its first column the same as a file marked once. A U+FEFF anywhere else is a character the file wrote and is kept, in a later column's name and inside a value alike. Dumping a table whose first column name begins with one is refused with ErrUnsupportedFormat for CSV, TSV and LTSV, which write that name where a reader takes it for the encoding mark; XLSX and Parquet keep it.

A line with nothing on it is not a header: the columns are named by the first line that holds something, so a file that begins with a blank line -- what a hand-edited export or a rotated log leaves -- loads the same as one that does not. A line holding nothing but whitespace is the same thing to a caller and is passed over as well, judged the way a blank cell is, by category, so an ideographic space counts alongside a plain one. Only the search for the header reads a line that way: one further down is a record of one field, which the malformed-row policy decides on and SkippedRows reports. A blank line in the middle of a file was already passed over, and a sheet whose first row holds only empty cells is read the same way. A line holding empty fields is a different thing and is a header of that many columns: a comma or a tab on the line makes it more than one field, and its fields are the columns whatever they hold.

A header cell that is empty names nothing, so the column takes the name of its position: "a,,c" loads as a, column_2 and c. The generated name is moved along -- column_2_2, column_2_3 -- when the file wrote a column of that name itself. A header cell holding a space is a name the file wrote and is kept as it is. Dumping a table that holds a column with no name is refused with ErrUnsupportedFormat for CSV, TSV and XLSX, which write their names in a header row where an empty cell reads back as a positional name; LTSV writes the empty label beside each value and Parquet holds the name in its schema, so both carry it.

A column name holding a NUL is refused with ErrInvalidData, naming the column and its position. A NUL is valid UTF-8, so the encoding check passes it, and SQLite reads an identifier as a C string: the name would be cut there and the quote closing it would go with the rest. A value holding a NUL is a different matter and loads, since a value is bytes SQLite stores rather than a name it parses.

A header that names one column twice is refused with ErrDuplicateColumn. Two names are the same column if either of two separate rules says so, and the rules are applied one at a time rather than combined:

  • Two names that differ only in ASCII letter case are one column, which is SQLite's rule, since SQLite is what ends up holding them: "ID" and "id" are a duplicate. The folding stops at ASCII, as SQLite's does, so "ä" and "Ä" remain two columns.
  • Two names that are identical after leading and trailing whitespace is trimmed are one column, which is filesql's own rule: " name " and "name" are one name typed twice.

Because the two are separate, neither is applied on top of the other: " A" beside "a" is accepted, since trimming alone does not make them equal and folding alone does not either, and SQLite likewise keeps them as two columns.

LTSV carries its labels on every record rather than in a header, so the check runs per record; a record holding "A:1\ta:2" is refused for the same reason. Two rules above read differently there, because a label is trimmed as it is read: a space around one is malformed either way, and a value is not trimmed, so the same data written as LTSV and as CSV agrees on the values whatever the labels carry. So the trimming is not a rule applied beside the folding but something that has already happened when the folding runs, and " A:1\ta:2" is one label typed twice where " A" beside "a" in a CSV header is two columns. And a label that is empty names a column the empty string rather than taking the name of its position: a position names a column of a header, and an LTSV record does not have to carry the labels the record before it carried, so there is no position for a name to come from. Dumping to LTSV refuses a column name either rule would change -- one holding a colon, a tab or a newline, and one beginning or ending in whitespace -- rather than writing a label that reads back as a different name.

For complete SQL syntax documentation, see: https://www.sqlite.org/lang.html

Query Dialects

By default queries use SQLite3 syntax. To accept a different dialect, configure the builder with WithDialect:

db, err := filesql.NewBuilder().
    AddPath("users.csv").
    WithDialect(dialect.PostgreSQL).
    Open(ctx)
// db.Query("SELECT name::text FROM users WHERE name ILIKE 'a%'")

The supported dialects are MySQL, PostgreSQL, and GoogleSQL (BigQuery / Cloud Spanner). A query is translated to SQLite before it runs: what SQLite spells differently is rewritten, what a function can compute is computed, and what has no SQLite form is refused with an error naming it. A translated query answers what the dialect's own engine answers, and a release that moves an answer toward that engine's is a fix rather than a breaking change. Loading files always uses SQLite regardless of the dialect. See the dialect subpackage for the subset it accepts and what it promises.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrEmptyData indicates that the data source contains no records.
	ErrEmptyData = reader.ErrEmptyData

	// ErrUnsupportedFormat indicates an unsupported file format.
	ErrUnsupportedFormat = reader.ErrUnsupportedFormat

	// ErrInvalidData indicates malformed or invalid data.
	ErrInvalidData = reader.ErrInvalidData

	// ErrNoTables indicates no tables found in database.
	ErrNoTables = errors.New("filesql: no tables found in database")

	// ErrFileNotFound indicates file not found.
	ErrFileNotFound = errors.New("filesql: file not found")

	// ErrDuplicateColumn indicates duplicate column names in the data source.
	ErrDuplicateColumn = reader.ErrDuplicateColumn

	// ErrInvalidUTF8 indicates a text source that is not valid UTF-8. SQLite
	// stores TEXT as UTF-8, so such bytes would be stored verbatim and read back
	// as mojibake by every consumer; the load fails instead, and the caller
	// transcodes.
	ErrInvalidUTF8 = textin.ErrInvalidUTF8

	// ErrDuplicateTable indicates a table with the same name already exists.
	ErrDuplicateTable = errors.New("filesql: duplicate table name")

	// ErrReservedTableName indicates an input would be loaded into a table whose
	// name this package reserves for its own bookkeeping.
	ErrReservedTableName = errors.New("filesql: reserved table name")

	// ErrNilInput indicates a required input parameter is nil.
	ErrNilInput = errors.New("filesql: nil input")

	// ErrEmptyPath indicates an empty path was provided.
	ErrEmptyPath = errors.New("filesql: empty path")

	// ErrNoFiles indicates no supported files were found.
	ErrNoFiles = errors.New("filesql: no supported files found")

	// ErrTableNotFound indicates the specified table does not exist. A save
	// returns it for a source whose table the session dropped or renamed, which
	// is a table that is gone rather than a source with no records.
	ErrTableNotFound = errors.New("filesql: table not found")

	// ErrColumnMismatch indicates a record that does not fit the columns of its
	// table: a delimited record whose field count differs from the header, or an
	// LTSV record holding a field that names no label.
	ErrColumnMismatch = reader.ErrColumnMismatch

	// ErrDatabaseOperation indicates a database operation failed.
	ErrDatabaseOperation = errors.New("filesql: database operation failed")

	// ErrIOOperation indicates an I/O operation failed.
	ErrIOOperation = errors.New("filesql: I/O operation failed")

	// ErrCompression indicates a compression/decompression operation failed. A
	// file whose suffix claims a compression its bytes do not carry answers it
	// whichever codec the suffix names, whether that codec reads its header
	// when the stream opens or on the first read.
	ErrCompression = errors.New("filesql: compression operation failed")

	// ErrEncoding indicates a text encoding operation failed, which for a save
	// means the target encoding has no way to write a value the table holds.
	ErrEncoding = textin.ErrEncoding

	// ErrParsing indicates a file parsing operation failed.
	ErrParsing = reader.ErrParsing

	// ErrACH indicates an ACH file operation failed.
	ErrACH = errors.New("filesql: ACH operation failed")

	// ErrWire indicates a Fedwire file operation failed.
	ErrWire = errors.New("filesql: Fedwire operation failed")

	// ErrSourceUnavailable indicates an ACH or Fedwire export failed because the
	// file its tables were loaded from is unknown or unreadable.
	ErrSourceUnavailable = errors.New("filesql: source file for write-back is unavailable")
)

Sentinel errors for consistent error handling across the package. Use errors.Is() to check for these errors.

View Source
var ErrCleanup = errors.New("filesql: cleanup failed")

ErrCleanup marks a failure that happened while releasing or undoing something after an operation finished: rolling back a transaction, closing a prepared statement, detaching a database.

It is joined onto the error that the operation itself returned rather than replacing it, because the two answer different questions — "did the load do what I asked" and "is anything left over". A caller can test for either with errors.Is.

The rule this replaces was written by hand at each site as `_ = tx.Rollback()` or "assign the cleanup error only when the primary error is nil". Both drop the cleanup failure exactly when it matters most: a rollback runs because the load already failed, so its own failure — the one that says the database is now in a state neither the caller's intent nor the starting point describes — was the one guaranteed to be discarded.

Functions

func DumpACH added in v0.9.0

func DumpACH(ctx context.Context, db *sql.DB, baseTableName, outputPath string) error

DumpACH exports ACH tables from the database back to an ACH file. This function reconstructs the ACH file from the _file_header, _batches, _entries, and _addenda tables that were created when the file was loaded.

The original structure is rebuilt from the file db records as its source, so that file must still exist and be readable. A database loaded from an io.Reader has no such file; hand its bytes to DumpACHWithSource.

The file is written from that structure rather than patched, so a record the caller did not edit can come back formatted differently: field padding is normalized and every record is written at its full width.

Parameters:

  • ctx: Context for cancellation
  • db: The database containing ACH tables
  • baseTableName: The base name used when the ACH file was loaded (e.g., "payment" for payment.ach)
  • outputPath: The path where the ACH file should be written

Returns an error if the export fails, or ErrSourceUnavailable if the file the tables were loaded from cannot be read.

Example

ExampleDumpACH loads an ACH file, edits one entry, and writes the file back.

The write rebuilds the file from the source it was loaded from, so that file must still be readable. Control records are derived rather than stored: an edited amount is balanced by the write, and an edit to a control column is overwritten by the recalculation.

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

// exampleTempDir is a directory of its own for an example to write into, so
// that no example touches a path another program may already be using.
func exampleTempDir() string {
	dir, err := os.MkdirTemp("", "filesql-api-example")
	if err != nil {
		log.Fatal(err)
	}
	return dir
}

func main() {
	dir := exampleTempDir()
	defer os.RemoveAll(dir)

	ctx := context.Background()
	db, err := filesql.Open(context.Background(), "testdata/ppd-debit.ach")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	if _, err := db.ExecContext(ctx,
		`UPDATE ppd_debit_entries SET individual_name = 'Alice Smith'`); err != nil {
		log.Fatal(err)
	}

	out := filepath.Join(dir, "edited.ach")
	if err := filesql.DumpACH(ctx, db, "ppd_debit", out); err != nil {
		log.Fatal(err)
	}

	reloaded, err := filesql.Open(context.Background(), out)
	if err != nil {
		log.Fatal(err)
	}
	defer reloaded.Close()

	var name string
	var amount int64
	if err := reloaded.QueryRowContext(ctx,
		`SELECT individual_name, amount FROM edited_entries`).Scan(&name, &amount); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s %d\n", name, amount)
}
Output:
Alice Smith 100000000

func DumpACHWithSource added in v0.55.0

func DumpACHWithSource(ctx context.Context, db *sql.DB, baseTableName, outputPath string, source io.Reader) error

DumpACHWithSource exports ACH tables from the database back to an ACH file, reading the file's original structure from source.

Use this function when the database has no source file to read the structure back from, which is the case for one loaded from an io.Reader. source must yield the same ACH file the database was loaded from: an ACH file carries fields no table exposes, so the export applies the database's edits to the original rather than building a file out of the tables alone. DumpACH is the same export for a database that does know its source.

Parameters:

  • ctx: Context for cancellation
  • db: The database containing ACH tables
  • baseTableName: The base name used when the ACH file was loaded (e.g., "payment" for payment.ach)
  • outputPath: The path where the ACH file should be written
  • source: The original ACH file's bytes, read from the beginning

Returns an error if the export fails.

Example

ExampleDumpACHWithSource writes back a database loaded from an io.Reader. Such a database has no file to rebuild from, so DumpACH refuses it with ErrSourceUnavailable; hand the same bytes over instead.

package main

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"log"
	"os"
	"path/filepath"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

// exampleTempDir is a directory of its own for an example to write into, so
// that no example touches a path another program may already be using.
func exampleTempDir() string {
	dir, err := os.MkdirTemp("", "filesql-api-example")
	if err != nil {
		log.Fatal(err)
	}
	return dir
}

func main() {
	dir := exampleTempDir()
	defer os.RemoveAll(dir)

	body, err := os.ReadFile("testdata/ppd-debit.ach")
	if err != nil {
		log.Fatal(err)
	}

	ctx := context.Background()
	builder := filesql.NewBuilder().
		AddReader(bytes.NewReader(body), "payment", filesql.FileTypeACH)

	db, err := builder.Open(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	out := filepath.Join(dir, "payment.ach")
	err = filesql.DumpACH(ctx, db, "payment", out)
	fmt.Println("without the structure:", errors.Is(err, filesql.ErrSourceUnavailable))

	if _, err := db.ExecContext(ctx,
		`UPDATE payment_entries SET individual_name = 'Alice Smith'`); err != nil {
		log.Fatal(err)
	}
	if err := filesql.DumpACHWithSource(ctx, db, "payment", out, bytes.NewReader(body)); err != nil {
		log.Fatal(err)
	}

	reloaded, err := filesql.Open(context.Background(), out)
	if err != nil {
		log.Fatal(err)
	}
	defer reloaded.Close()

	var name string
	if err := reloaded.QueryRowContext(ctx,
		`SELECT individual_name FROM payment_entries`).Scan(&name); err != nil {
		log.Fatal(err)
	}
	fmt.Println(name)
}
Output:
without the structure: true
Alice Smith

func DumpDatabase

func DumpDatabase(ctx context.Context, db *sql.DB, outputDir string, opts ...DumpOptions) error

DumpDatabase saves all database tables to files in the specified directory.

Basic usage:

err := filesql.DumpDatabase(ctx, db, "./output")

This will save all tables as CSV files in the output directory.

Advanced usage with options:

// Default: Export as CSV files
err := DumpDatabase(ctx, db, "./output")

// Export as TSV files with gzip compression
options := NewDumpOptions().
	WithFormat(OutputFormatTSV).
	WithCompression(CompressionGZ)
err := DumpDatabase(ctx, db, "./output", options)

A destination that already exists as a symbolic link is followed: the file it names receives the rows and the link stays a link.

A table is written to a file named after it, so a table whose name cannot be a file name is refused rather than written: the two path separators, the characters < > : " | ? *, a control character, a name ending in a dot or a space, and the names Windows reserves for devices -- CON, PRN, AUX, NUL, COM1 to COM9 and LPT1 to LPT9, with or without an extension. The same set is refused on every platform, so a database dumped on Linux and on Windows agrees about which tables it can write. Rename the table before dumping it. A name derived from a file cannot reach that set except as a device name, since only letters, digits, marks and underscore survive; a name given to DBBuilder.AddReader or to CREATE TABLE can.

A table whose name a load would spell differently is refused for the same reason: a load names a table after the file and spells a space, a hyphen and a dot as an underscore, so "with space" would come back as with_space, and "a b" beside "a-b" would be two files and one table name. Rename the table before dumping it.

A value the output format cannot hold is refused rather than rewritten, with ErrUnsupportedFormat and the advice to dump the table as CSV: a tab or a line break in TSV, those and a colon in an LTSV label, and in XLSX a character an XML 1.0 document has no way to spell -- a control character other than tab, line feed and carriage return, and the two noncharacters U+FFFE and U+FFFF -- or a last column with no name, which a worksheet does not store. A table with no rows is refused for LTSV alone, which has no header to carry the columns and would leave an empty file -- and an empty file is not a table, so it blocks the load of every file beside it. The other formats keep the columns of an empty table.

A table whose column names a load would refuse is refused too, with ErrDuplicateColumn: this package reads " a", "a" and "a " as one name, and SQLite does not, so a table holding two of them is one only SQLite can hold.

The output directory is created when it is not there. One named with nothing, or with nothing but whitespace, is refused with ErrEmptyPath rather than created: a directory of spaces is one this package would refuse to read back.

A table it refuses for its name is refused before the destination is touched: where every table goes is settled with the list of them, so a database holding one such table leaves no output directory behind and no table written ahead of the refusal. A value a format cannot hold is found by reading the rows, so that refusal leaves the tables already finished, as a canceled export does.

The context gives the export a deadline or a way to cancel it. The export stops at the next table, row or write after the context ends. A table already written stays written, since the tables are separate files and nothing undoes one: what a canceled export leaves is the tables it had finished. The table it was in the middle of leaves nothing, because each file is staged and put in place only once it is whole. A cancellation before the first table leaves no output directory, for the same reason a refused table name does.

Example

ExampleDumpDatabase demonstrates exporting modified data

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/nao1215/filesql"
)

// createTempTestData creates temporary CSV files for the example
func createTempTestData() string {
	tmpDir, err := os.MkdirTemp("", "filesql_example")
	if err != nil {
		log.Fatal(err)
	}

	employeesData := `id,name,department_id,salary,hire_date
1,Alice Johnson,1,95000,2020-01-15
2,Bob Smith,1,85000,2019-03-22
3,Charlie Brown,1,80000,2021-06-10
4,David Wilson,1,75000,2022-02-28
5,Eve Davis,2,70000,2020-09-15
6,Frank Miller,2,65000,2021-11-30
7,Grace Lee,3,60000,2019-12-05
8,Henry Taylor,3,55000,2022-04-18`

	err = os.WriteFile(filepath.Join(tmpDir, "employees.csv"), []byte(employeesData), 0600)
	if err != nil {
		log.Fatal(err)
	}

	departmentsData := `id,name,budget,manager_id
1,Engineering,1000000,1
2,Marketing,800000,5
3,Sales,600000,7
4,HR,400000,9`

	err = os.WriteFile(filepath.Join(tmpDir, "departments.csv"), []byte(departmentsData), 0600)
	if err != nil {
		log.Fatal(err)
	}

	return tmpDir
}

func main() {
	tmpDir := createTempTestData()
	defer os.RemoveAll(tmpDir)

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	db, err := filesql.Open(ctx, filepath.Join(tmpDir, "employees.csv"))
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Modify data in memory
	_, err = db.ExecContext(ctx, `
		UPDATE employees 
		SET salary = salary * 1.10 
		WHERE department_id = 1
	`)
	if err != nil {
		log.Fatal(err)
	}

	// Add a new employee
	_, err = db.ExecContext(ctx, `
		INSERT INTO employees (id, name, department_id, salary, hire_date) 
		VALUES (99, 'New Employee', 2, 60000, '2024-01-01')
	`)
	if err != nil {
		log.Fatal(err)
	}

	// Create output directory
	outputDir := filepath.Join(tmpDir, "output")
	err = os.MkdirAll(outputDir, 0750)
	if err != nil {
		log.Fatal(err)
	}

	// Export modified data
	err = filesql.DumpDatabase(context.Background(), db, outputDir)
	if err != nil {
		log.Fatal(err)
	}

	// Verify export by reading the exported file
	exportedFile := filepath.Join(outputDir, "employees.csv")
	if _, err := os.Stat(exportedFile); err != nil {
		log.Fatal("Exported file not found:", err)
	}

	// Count records in exported file
	db2, err := filesql.Open(ctx, exportedFile)
	if err != nil {
		log.Fatal(err)
	}
	defer db2.Close()

	var count int
	err = db2.QueryRowContext(ctx, "SELECT COUNT(*) FROM employees").Scan(&count)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Original file: 8 employees\n")
	fmt.Printf("Modified and exported: %d employees\n", count)

	// Extract just the filename for consistent output (normalize path separators for cross-platform compatibility)
	exportPath := strings.Replace(exportedFile, tmpDir, "/tmp/filesql_example*", 1)
	exportPath = strings.ReplaceAll(exportPath, "\\", "/") // Convert Windows backslashes to forward slashes
	fmt.Printf("Export location: %s\n", exportPath)

}
Output:
Original file: 8 employees
Modified and exported: 9 employees
Export location: /tmp/filesql_example*/output/employees.csv
Example (DataProcessing)
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"

	"github.com/nao1215/filesql"
)

func main() {
	tempDir := filepath.Join(os.TempDir(), "filesql_processing_example")
	if err := os.MkdirAll(tempDir, 0750); err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(tempDir)

	// Open CSV file
	db, err := filesql.Open(context.Background(), filepath.Join("testdata", "sample.csv"))
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Process data with SQL
	_, err = db.ExecContext(context.Background(), `
		UPDATE sample 
		SET age = age + 1 
		WHERE name LIKE '%John%'
	`)
	if err != nil {
		log.Fatal(err)
	}

	// Add aggregated data
	_, err = db.ExecContext(context.Background(), `
		INSERT INTO sample (id, name, age, email) 
		SELECT 999, 'Summary: ' || COUNT(*), AVG(age), 'summary@example.com'
		FROM sample 
		WHERE id < 999
	`)
	if err != nil {
		log.Fatal(err)
	}

	// Export processed data in different formats for different use cases

	// 1. TSV for spreadsheet import
	options := filesql.NewDumpOptions().WithFormat(filesql.OutputFormatTSV)
	spreadsheetDir := filepath.Join(tempDir, "for_spreadsheet")
	if err := filesql.DumpDatabase(context.Background(), db, spreadsheetDir, options); err != nil {
		log.Fatal(err)
	}
	fmt.Println("Exported TSV for spreadsheet import")

	// 2. Compressed CSV for archival
	options = filesql.NewDumpOptions().
		WithFormat(filesql.OutputFormatCSV).
		WithCompression(filesql.CompressionGZ)
	archiveDir := filepath.Join(tempDir, "for_archive")
	if err := filesql.DumpDatabase(context.Background(), db, archiveDir, options); err != nil {
		log.Fatal(err)
	}
	fmt.Println("Exported compressed CSV for archival")

	// 3. LTSV for log analysis
	options = filesql.NewDumpOptions().WithFormat(filesql.OutputFormatLTSV)
	logDir := filepath.Join(tempDir, "for_logs")
	if err := filesql.DumpDatabase(context.Background(), db, logDir, options); err != nil {
		log.Fatal(err)
	}
	fmt.Println("Exported LTSV for log analysis")

	// Show what was created
	dirs := []string{"for_spreadsheet", "for_archive", "for_logs"}
	for _, dir := range dirs {
		files, err := filepath.Glob(filepath.Join(tempDir, dir, "*"))
		if err != nil {
			log.Fatal(err)
		}
		for _, file := range files {
			fmt.Printf("%s: %s\n", dir, filepath.Base(file))
		}
	}

}
Output:
Exported TSV for spreadsheet import
Exported compressed CSV for archival
Exported LTSV for log analysis
for_spreadsheet: sample.tsv
for_archive: sample.csv.gz
for_logs: sample.ltsv
Example (Deadline)

ExampleDumpDatabase_deadline exports under a deadline, which is what a handler serving a download wants: the export stops when the request it belongs to does.

package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"time"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	dir, err := os.MkdirTemp("", "filesql-dump-context")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(dir)

	source := filepath.Join(dir, "orders.csv")
	if err := os.WriteFile(source, []byte("id,total\n1,120\n2,340\n"), 0o600); err != nil {
		log.Fatal(err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	db, err := filesql.Open(ctx, source)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	out := filepath.Join(dir, "out")
	if err := filesql.DumpDatabase(ctx, db, out); err != nil {
		log.Fatal(err)
	}

	exported, err := os.ReadFile(filepath.Join(out, "orders.csv")) //nolint:gosec // Path built from this example's own temporary directory.
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(string(exported))

	// A context that is already done stops the export before it writes anything.
	done, stop := context.WithCancel(context.Background())
	stop()
	fmt.Println(errors.Is(filesql.DumpDatabase(done, db, filepath.Join(dir, "none")), context.Canceled))

}
Output:
id,total
1,120
2,340
true
Example (MultipleFormats)
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"

	"github.com/nao1215/filesql"
)

func main() {
	tempDir := filepath.Join(os.TempDir(), "filesql_formats_example")
	if err := os.MkdirAll(tempDir, 0750); err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(tempDir)

	// Open CSV file and modify data
	db, err := filesql.Open(context.Background(), filepath.Join("testdata", "sample.csv"))
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Add some data to demonstrate functionality
	_, err = db.ExecContext(context.Background(), "INSERT INTO sample (id, name, age, email) VALUES (4, 'Alice Brown', 28, 'alice@example.com')")
	if err != nil {
		log.Fatal(err)
	}

	// Demonstrate different compression options
	compressionTypes := []struct {
		name        string
		compression filesql.CompressionType
		extension   string
	}{
		{"No compression", filesql.CompressionNone, ""},
		{"Gzip compression", filesql.CompressionGZ, ".gz"},
		{"XZ compression", filesql.CompressionXZ, ".xz"},
		{"Zstd compression", filesql.CompressionZSTD, ".zst"},
	}

	for _, ct := range compressionTypes {
		fmt.Printf("%s:\n", ct.name)

		options := filesql.NewDumpOptions().
			WithFormat(filesql.OutputFormatCSV).
			WithCompression(ct.compression)

		outputDir := filepath.Join(tempDir, "compression_"+ct.compression.String())
		if err := filesql.DumpDatabase(context.Background(), db, outputDir, options); err != nil {
			log.Fatal(err)
		}

		files, err := filepath.Glob(filepath.Join(outputDir, "*"))
		if err != nil {
			log.Fatal(err)
		}
		for _, file := range files {
			fmt.Printf("  %s\n", filepath.Base(file))
		}
	}

}
Output:
No compression:
  sample.csv
Gzip compression:
  sample.csv.gz
XZ compression:
  sample.csv.xz
Zstd compression:
  sample.csv.zst
Example (WithOptions)
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"

	"github.com/nao1215/filesql"
)

func main() {
	// Create a temporary directory for output
	tempDir := filepath.Join(os.TempDir(), "filesql_dump_example")
	if err := os.MkdirAll(tempDir, 0750); err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(tempDir)

	// Open CSV file
	db, err := filesql.Open(context.Background(), filepath.Join("testdata", "sample.csv"))
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Example 1: Default CSV output (no options)
	fmt.Println("Example 1: Default CSV output")
	csvDir := filepath.Join(tempDir, "csv_output")
	if err := filesql.DumpDatabase(context.Background(), db, csvDir); err != nil {
		log.Fatal(err)
	}

	// List output files
	files1, err := filepath.Glob(filepath.Join(csvDir, "*"))
	if err != nil {
		log.Fatal(err)
	}
	for _, file := range files1 {
		fmt.Printf("Created: %s\n", filepath.Base(file))
	}

	// Example 2: TSV output with gzip compression
	fmt.Println("\nExample 2: TSV output with gzip compression")
	tsvDir := filepath.Join(tempDir, "tsv_output")
	options := filesql.NewDumpOptions().
		WithFormat(filesql.OutputFormatTSV).
		WithCompression(filesql.CompressionGZ)
	if err := filesql.DumpDatabase(context.Background(), db, tsvDir, options); err != nil {
		log.Fatal(err)
	}

	files2, err := filepath.Glob(filepath.Join(tsvDir, "*"))
	if err != nil {
		log.Fatal(err)
	}
	for _, file := range files2 {
		fmt.Printf("Created: %s\n", filepath.Base(file))
	}

	// Example 3: LTSV output with zstd compression
	fmt.Println("\nExample 3: LTSV output with zstd compression")
	ltsvDir := filepath.Join(tempDir, "ltsv_output")
	options3 := filesql.NewDumpOptions().
		WithFormat(filesql.OutputFormatLTSV).
		WithCompression(filesql.CompressionZSTD)
	if err := filesql.DumpDatabase(context.Background(), db, ltsvDir, options3); err != nil {
		log.Fatal(err)
	}

	files3, err := filepath.Glob(filepath.Join(ltsvDir, "*"))
	if err != nil {
		log.Fatal(err)
	}
	for _, file := range files3 {
		fmt.Printf("Created: %s\n", filepath.Base(file))
	}

}
Output:
Example 1: Default CSV output
Created: sample.csv

Example 2: TSV output with gzip compression
Created: sample.tsv.gz

Example 3: LTSV output with zstd compression
Created: sample.ltsv.zst

func DumpFedWire added in v0.12.0

func DumpFedWire(ctx context.Context, db *sql.DB, baseTableName, outputPath string) error

DumpFedWire exports Fedwire tables from the database back to a Fedwire file. This function reconstructs the Fedwire file from the _message table that was created when the file was loaded.

The original structure is rebuilt from the file db records as its source, so that file must still exist and be readable. A database loaded from an io.Reader has no such file; hand its bytes to DumpFedWireWithSource.

The file is written from that structure rather than patched, so a tag the caller did not edit can come back changed: tags are written in the order the format defines rather than the order the file had them, and field padding is normalized.

Parameters:

  • ctx: Context for cancellation
  • db: The database containing Fedwire tables
  • baseTableName: The base name used when the Fedwire file was loaded (e.g., "payment" for payment.fed)
  • outputPath: The path where the Fedwire file should be written

Returns an error if the export fails, or ErrSourceUnavailable if the file the tables were loaded from cannot be read.

Example

ExampleDumpFedWire loads a Fedwire file, edits the message, and writes it back.

Tags are written in the order the format defines rather than the order the file had them, so a diff after a write-back shows lines nobody edited.

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

// exampleTempDir is a directory of its own for an example to write into, so
// that no example touches a path another program may already be using.
func exampleTempDir() string {
	dir, err := os.MkdirTemp("", "filesql-api-example")
	if err != nil {
		log.Fatal(err)
	}
	return dir
}

func main() {
	dir := exampleTempDir()
	defer os.RemoveAll(dir)

	ctx := context.Background()
	db, err := filesql.Open(context.Background(), "testdata/customer-transfer.fed")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	if _, err := db.ExecContext(ctx,
		`UPDATE customer_transfer_message SET amount = '000000012500'`); err != nil {
		log.Fatal(err)
	}

	out := filepath.Join(dir, "edited.fed")
	if err := filesql.DumpFedWire(ctx, db, "customer_transfer", out); err != nil {
		log.Fatal(err)
	}

	reloaded, err := filesql.Open(context.Background(), out)
	if err != nil {
		log.Fatal(err)
	}
	defer reloaded.Close()

	var amount string
	if err := reloaded.QueryRowContext(ctx,
		`SELECT amount FROM edited_message`).Scan(&amount); err != nil {
		log.Fatal(err)
	}
	fmt.Println(amount)
}
Output:
000000012500

func DumpFedWireWithSource added in v0.55.0

func DumpFedWireWithSource(ctx context.Context, db *sql.DB, baseTableName, outputPath string, source io.Reader) error

DumpFedWireWithSource exports Fedwire tables from the database back to a Fedwire file, reading the file's original structure from source.

Use this function when the database has no source file to read the structure back from, which is the case for one loaded from an io.Reader. source must yield the same Fedwire file the database was loaded from: the file carries fields no table exposes, so the export applies the database's edits to the original rather than building a file out of the tables alone. DumpFedWire is the same export for a database that does know its source.

Parameters:

  • ctx: Context for cancellation
  • db: The database containing Fedwire tables
  • baseTableName: The base name used when the Fedwire file was loaded (e.g., "payment" for payment.fed)
  • outputPath: The path where the Fedwire file should be written
  • source: The original Fedwire file's bytes, read from the beginning

Returns an error if the export fails.

Example

ExampleDumpFedWireWithSource is ExampleDumpACHWithSource for Fedwire: a database loaded from an io.Reader is written back by handing the export the same bytes.

package main

import (
	"bytes"
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

// exampleTempDir is a directory of its own for an example to write into, so
// that no example touches a path another program may already be using.
func exampleTempDir() string {
	dir, err := os.MkdirTemp("", "filesql-api-example")
	if err != nil {
		log.Fatal(err)
	}
	return dir
}

func main() {
	dir := exampleTempDir()
	defer os.RemoveAll(dir)

	body, err := os.ReadFile("testdata/customer-transfer.fed")
	if err != nil {
		log.Fatal(err)
	}

	ctx := context.Background()
	builder := filesql.NewBuilder().
		AddReader(bytes.NewReader(body), "transfer", filesql.FileTypeFedWire)

	db, err := builder.Open(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	if _, err := db.ExecContext(ctx,
		`UPDATE transfer_message SET amount = '000000012500'`); err != nil {
		log.Fatal(err)
	}

	out := filepath.Join(dir, "transfer.fed")
	if err := filesql.DumpFedWireWithSource(ctx, db, "transfer", out, bytes.NewReader(body)); err != nil {
		log.Fatal(err)
	}

	reloaded, err := filesql.Open(context.Background(), out)
	if err != nil {
		log.Fatal(err)
	}
	defer reloaded.Close()

	var amount string
	if err := reloaded.QueryRowContext(ctx,
		`SELECT amount FROM transfer_message`).Scan(&amount); err != nil {
		log.Fatal(err)
	}
	fmt.Println(amount)
}
Output:
000000012500

func ExcelSheetTableNames added in v0.31.0

func ExcelSheetTableNames(filePath string, sheetNames []string) (tables []string, err error)

ExcelSheetTableNames maps every sheet of a workbook to the table it is loaded as, and reports the sheets that would share one table.

A workbook can name two sheets "Data" and "data", or "Q1 sales" and "Q1.sales". Sanitizing makes the first pair identical in case only and the second identical outright, and SQLite compares table names case-insensitively for ASCII, so all four end up asking for the same table. Loading them in turn means the last sheet read is the only one that survives, and the rows of the others are gone with nothing said about it.

This is the check that turns that into an error. It is exported because a caller that wants to refuse such a workbook before loading anything — rather than partway through — needs the same rule filesql applies, and a caller reimplementing the sanitizer would drift from it.

tables is parallel to sheetNames. err is non-nil when any two sheets collide, and names both the sheets and the table they would share.

filePath is what the sheets hang off, and a workbook has no file name when it arrives through AddReader: pass the table name given there instead, which is what that load uses as the base.

Example
package main

import (
	"errors"
	"fmt"
	"log"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	tables, err := filesql.ExcelSheetTableNames("book.xlsx", []string{"Sales", "Q1 sales"})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(tables)

	// "Q1 sales" and "Q1.sales" both sanitize to one identifier, so the second
	// sheet loaded would replace the first with nothing said about it. Asking
	// first is how a caller refuses the workbook before loading any of it.
	_, err = filesql.ExcelSheetTableNames("book.xlsx", []string{"Q1 sales", "Q1.sales"})
	fmt.Println(errors.Is(err, filesql.ErrDuplicateTable))
}
Output:
[book_Sales book_Q1_sales]
true

func LoadInto added in v0.13.0

func LoadInto(ctx context.Context, db *sql.DB, paths ...string) error

LoadInto loads the given file or directory paths into an existing database instead of creating a new one, and returns without closing it. This lets a caller combine file-derived tables with a database it already manages (for example a long-lived session that imports files repeatedly).

A table whose name matches a loaded file is replaced, so reloading is idempotent (last-wins for same-named inputs); other tables in db are left untouched. Each input is loaded atomically, so a file that fails partway leaves the database as it was, including the table it was replacing. For an in-memory database, pin the pool to a single connection (db.SetMaxOpenConns(1)) because SQLite ":memory:" is private per connection. See (*DBBuilder).LoadInto for the full semantics and for loading readers or filesystems.

Example:

db, _ := sql.Open("sqlite", ":memory:")
db.SetMaxOpenConns(1)
if err := filesql.LoadInto(ctx, db, "users.csv", "orders.csv"); err != nil {
	return err
}
Example
package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func createFilesqlExampleDir(files map[string]string) string {
	dir, err := os.MkdirTemp("", "filesql-api-example")
	if err != nil {
		log.Fatal(err)
	}
	for name, body := range files {
		path := filepath.Join(dir, name)
		if err := os.MkdirAll(filepath.Dir(path), 0750); err != nil {
			log.Fatal(err)
		}
		if err := os.WriteFile(path, []byte(strings.TrimLeft(body, "\n")), 0600); err != nil {
			log.Fatal(err)
		}
	}
	return dir
}

func openExampleSQLiteDB() *sql.DB {
	db, err := sql.Open("sqlite", ":memory:")
	if err != nil {
		log.Fatal(err)
	}
	db.SetMaxOpenConns(1)
	return db
}

func main() {
	dir := createFilesqlExampleDir(map[string]string{
		"users.csv": `
id,name
1,Alice
2,Bob
`,
	})
	defer os.RemoveAll(dir)

	db := openExampleSQLiteDB()
	defer db.Close()

	ctx := context.Background()

	if _, err := db.ExecContext(ctx, `CREATE TABLE notes (body TEXT)`); err != nil {
		log.Fatal(err)
	}
	if _, err := db.ExecContext(ctx, `INSERT INTO notes VALUES ('kept')`); err != nil {
		log.Fatal(err)
	}

	if err := filesql.LoadInto(ctx, db, filepath.Join(dir, "users.csv")); err != nil {
		log.Fatal(err)
	}

	var users, notes int
	if err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM users`).Scan(&users); err != nil {
		log.Fatal(err)
	}
	if err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM notes`).Scan(&notes); err != nil {
		log.Fatal(err)
	}

	fmt.Printf("users=%d notes=%d\n", users, notes)
}
Output:
users=2 notes=1
Example (DumpDatabase)

ExampleLoadInto_dumpDatabase completes the cycle a caller-managed database is for: load files into a database you already own, query across what was there and what arrived, then write the result back out.

package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func createFilesqlExampleDir(files map[string]string) string {
	dir, err := os.MkdirTemp("", "filesql-api-example")
	if err != nil {
		log.Fatal(err)
	}
	for name, body := range files {
		path := filepath.Join(dir, name)
		if err := os.MkdirAll(filepath.Dir(path), 0750); err != nil {
			log.Fatal(err)
		}
		if err := os.WriteFile(path, []byte(strings.TrimLeft(body, "\n")), 0600); err != nil {
			log.Fatal(err)
		}
	}
	return dir
}

func openExampleSQLiteDB() *sql.DB {
	db, err := sql.Open("sqlite", ":memory:")
	if err != nil {
		log.Fatal(err)
	}
	db.SetMaxOpenConns(1)
	return db
}

func main() {
	dir := createFilesqlExampleDir(map[string]string{
		"users.csv": `
id,name
1,Alice
2,Bob
`,
	})
	defer os.RemoveAll(dir)

	// openExampleSQLiteDB pins the pool to one connection, which SQLite's
	// ":memory:" requires: the database is private per connection, so a second
	// connection would not see the loaded tables.
	db := openExampleSQLiteDB()
	defer db.Close()

	ctx := context.Background()
	if err := filesql.LoadInto(ctx, db, filepath.Join(dir, "users.csv")); err != nil {
		log.Fatal(err)
	}
	if _, err := db.ExecContext(ctx, `UPDATE users SET name = 'Carol' WHERE id = 2`); err != nil {
		log.Fatal(err)
	}

	out := filepath.Join(dir, "out")
	if err := filesql.DumpDatabase(context.Background(), db, out); err != nil {
		log.Fatal(err)
	}

	saved, err := os.ReadFile(filepath.Join(out, "users.csv")) //nolint:gosec // path built from this example's own temp directory
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(string(saved))
}
Output:
id,name
1,Alice
2,Carol

func Open

func Open(ctx context.Context, paths ...string) (*sql.DB, error)

Open creates an SQL database from the files at the given paths.

db, err := filesql.Open(context.Background(), "data.csv")
if err != nil {
	return err
}
defer db.Close()

rows, err := db.Query("SELECT * FROM data WHERE age > 25")

A path is a file, a compressed file ("data.csv.gz", "archive.tsv.bz2"), or a directory, which is loaded recursively.

A file becomes a table named after it, with the extensions dropped: "users.csv" and "data.tsv.gz" become "users" and "data", "user-data.csv" becomes "user_data", and "my file.csv" becomes "my_file". Whitespace, a hyphen and a dot become an underscore and every other character an identifier cannot hold is dropped, so "a!b.csv" becomes "ab"; the package documentation states the rule in full.

The context is for a load that has to time out or be canceled: a large file, or a server that abandons the request.

ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

db, err := filesql.Open(ctx, "large-dataset.csv")

The files are never modified. Changes live in the database until DumpDatabase writes them out, or until an auto-save configured through NewBuilder does.

Example

ExampleOpen demonstrates how to use filesql.Open(context.Background(), ) with complex SQL queries. This example shows advanced SQL features including JOINs, window functions, subqueries, and aggregations on CSV data loaded into an in-memory SQLite database.

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"

	"github.com/nao1215/filesql"
)

func main() {
	// Create temporary test data files
	tmpDir := createTempTestData()
	defer os.RemoveAll(tmpDir)

	// Open the database with multiple files
	db, err := filesql.Open(context.Background(), filepath.Join(tmpDir, "employees.csv"), filepath.Join(tmpDir, "departments.csv"))
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Complex query demonstrating multiple SQL features:
	// - JOINs between tables
	// - Window functions (RANK, AVG, COUNT)
	// - Subqueries with correlated conditions
	// - CASE statements
	// - Grouping and ordering
	query := `
		SELECT 
			e.name,
			d.name as department_name,
			e.salary,
			d.budget,
			RANK() OVER (PARTITION BY e.department_id ORDER BY e.salary DESC) as salary_rank_in_dept,
			AVG(e.salary) OVER (PARTITION BY e.department_id) as dept_avg_salary,
			COUNT(*) OVER (PARTITION BY e.department_id) as dept_employee_count,
			CASE 
				WHEN e.salary > (SELECT AVG(salary) FROM employees WHERE department_id = e.department_id) * 1.2
				THEN 'High Performer'
				WHEN e.salary < (SELECT AVG(salary) FROM employees WHERE department_id = e.department_id) * 0.8  
				THEN 'Below Average'
				ELSE 'Average'
			END as performance_category,
			ROUND(e.salary / d.budget * 100, 2) as salary_budget_percentage
		FROM employees e
		JOIN departments d ON e.department_id = d.id
		WHERE e.salary > (
			SELECT AVG(salary) * 0.7
			FROM employees e2 
			WHERE e2.department_id = e.department_id
		)
		AND d.budget > 500000
		ORDER BY d.name, e.salary DESC
		LIMIT 10
	`

	rows, err := db.QueryContext(context.Background(), query)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	fmt.Println("Employee Analysis Report:")
	fmt.Println("========================")

	for rows.Next() {
		var name, deptName, perfCategory string
		var salary, budget, deptAvgSalary, salaryBudgetPct float64
		var salaryRank, deptEmpCount int

		err := rows.Scan(&name, &deptName, &salary, &budget, &salaryRank,
			&deptAvgSalary, &deptEmpCount, &perfCategory, &salaryBudgetPct)
		if err != nil {
			log.Fatal(err)
		}

		fmt.Printf("%-15s | %-12s | $%7.0f | Rank: %d/%d | %s\n",
			name, deptName, salary, salaryRank, deptEmpCount, perfCategory)
	}

	if err = rows.Err(); err != nil {
		log.Fatal(err)
	}

}

// createTempTestData creates temporary CSV files for the example
func createTempTestData() string {
	tmpDir, err := os.MkdirTemp("", "filesql_example")
	if err != nil {
		log.Fatal(err)
	}

	employeesData := `id,name,department_id,salary,hire_date
1,Alice Johnson,1,95000,2020-01-15
2,Bob Smith,1,85000,2019-03-22
3,Charlie Brown,1,80000,2021-06-10
4,David Wilson,1,75000,2022-02-28
5,Eve Davis,2,70000,2020-09-15
6,Frank Miller,2,65000,2021-11-30
7,Grace Lee,3,60000,2019-12-05
8,Henry Taylor,3,55000,2022-04-18`

	err = os.WriteFile(filepath.Join(tmpDir, "employees.csv"), []byte(employeesData), 0600)
	if err != nil {
		log.Fatal(err)
	}

	departmentsData := `id,name,budget,manager_id
1,Engineering,1000000,1
2,Marketing,800000,5
3,Sales,600000,7
4,HR,400000,9`

	err = os.WriteFile(filepath.Join(tmpDir, "departments.csv"), []byte(departmentsData), 0600)
	if err != nil {
		log.Fatal(err)
	}

	return tmpDir
}
Output:
Employee Analysis Report:
========================
Alice Johnson   | Engineering  | $  95000 | Rank: 1/4 | Average
Bob Smith       | Engineering  | $  85000 | Rank: 2/4 | Average
Charlie Brown   | Engineering  | $  80000 | Rank: 3/4 | Average
David Wilson    | Engineering  | $  75000 | Rank: 4/4 | Average
Eve Davis       | Marketing    | $  70000 | Rank: 1/2 | Average
Frank Miller    | Marketing    | $  65000 | Rank: 2/2 | Average
Grace Lee       | Sales        | $  60000 | Rank: 1/2 | Average
Henry Taylor    | Sales        | $  55000 | Rank: 2/2 | Average
Example (AdvancedSQL)

ExampleOpen_advancedSQL demonstrates advanced SQL features available in SQLite3

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/nao1215/filesql"
)

func main() {
	tmpDir := createAdvancedTestData()
	defer os.RemoveAll(tmpDir)

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	db, err := filesql.Open(ctx, tmpDir)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	fmt.Println("=== Advanced SQL Features ===")

	// Window functions with RANK() and ROW_NUMBER()
	fmt.Println("\n1. Window Functions - Employee Rankings by Department:")
	rows, err := db.QueryContext(ctx, `
		SELECT 
			e.name,
			d.name as department,
			e.salary,
			RANK() OVER (PARTITION BY e.department_id ORDER BY e.salary DESC) as salary_rank,
			ROW_NUMBER() OVER (ORDER BY e.salary DESC) as overall_rank
		FROM employees e
		JOIN departments d ON e.department_id = d.id
		ORDER BY e.department_id, salary_rank
	`)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%-15s %-12s %-8s %-10s %s\n", "Name", "Department", "Salary", "Dept Rank", "Overall Rank")
	fmt.Println(strings.Repeat("-", 65))

	for rows.Next() {
		var name, department string
		var salary float64
		var salaryRank, overallRank int

		if err := rows.Scan(&name, &department, &salary, &salaryRank, &overallRank); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%-15s %-12s $%-7.0f %-10d %d\n", name, department, salary, salaryRank, overallRank)
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
	_ = rows.Close() // Ignore close error in test cleanup

	// Common Table Expressions (CTE)
	fmt.Println("\n2. Common Table Expressions - Department Analysis:")
	rows, err = db.QueryContext(ctx, `
		WITH dept_stats AS (
			SELECT 
				d.name as department,
				COUNT(e.id) as employee_count,
				AVG(e.salary) as avg_salary,
				MAX(e.salary) as max_salary,
				MIN(e.salary) as min_salary
			FROM departments d
			LEFT JOIN employees e ON d.id = e.department_id
			GROUP BY d.id, d.name
		),
		company_avg AS (
			SELECT AVG(salary) as company_avg_salary
			FROM employees
		)
		SELECT 
			ds.department,
			ds.employee_count,
			ds.avg_salary,
			ca.company_avg_salary,
			ds.avg_salary - ca.company_avg_salary as salary_diff,
			CASE 
				WHEN ds.avg_salary > ca.company_avg_salary THEN 'Above Average'
				WHEN ds.avg_salary < ca.company_avg_salary THEN 'Below Average'
				ELSE 'At Average'
			END as comparison
		FROM dept_stats ds
		CROSS JOIN company_avg ca
		WHERE ds.employee_count > 0
		ORDER BY ds.avg_salary DESC
	`)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%-12s %-5s %-10s %-12s %-10s %s\n", "Department", "Count", "Avg Salary", "Company Avg", "Difference", "Comparison")
	fmt.Println(strings.Repeat("-", 75))

	for rows.Next() {
		var department, comparison string
		var employeeCount int
		var avgSalary, companyAvg, salaryDiff float64

		if err := rows.Scan(&department, &employeeCount, &avgSalary, &companyAvg, &salaryDiff, &comparison); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%-12s %-5d $%-9.0f $%-11.0f $%-9.0f %s\n",
			department, employeeCount, avgSalary, companyAvg, salaryDiff, comparison)
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
	_ = rows.Close() // Ignore close error in test cleanup

	// JSON operations (if data contains JSON)
	fmt.Println("\n3. Text Functions - Name Analysis:")
	rows, err = db.QueryContext(ctx, `
		SELECT 
			name,
			LENGTH(name) as name_length,
			UPPER(SUBSTR(name, 1, 1)) || LOWER(SUBSTR(name, 2)) as formatted_name,
			INSTR(name, ' ') as space_position,
			CASE 
				WHEN INSTR(name, ' ') > 0 THEN SUBSTR(name, 1, INSTR(name, ' ') - 1)
				ELSE name
			END as first_name
		FROM employees
		WHERE LENGTH(name) > 8
		ORDER BY name_length DESC
	`)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%-15s %-6s %-15s %-8s %s\n", "Name", "Length", "Formatted", "Space@", "First Name")
	fmt.Println(strings.Repeat("-", 60))

	for rows.Next() {
		var name, formattedName, firstName string
		var nameLength, spacePos int

		if err := rows.Scan(&name, &nameLength, &formattedName, &spacePos, &firstName); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%-15s %-6d %-15s %-8d %s\n", name, nameLength, formattedName, spacePos, firstName)
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
	_ = rows.Close() // Ignore close error in test cleanup

}

// createAdvancedTestData creates test data for advanced SQL examples
func createAdvancedTestData() string {
	tmpDir, err := os.MkdirTemp("", "filesql_advanced_example_*")
	if err != nil {
		log.Fatal(err)
	}

	employeesData := `id,name,department_id,salary,hire_date
1,Alice Johnson,1,95000,2023-01-15
2,Bob Smith,2,85000,2023-02-20
3,Charlie Brown,1,80000,2023-03-10
4,David Wilson,1,75000,2023-04-05
5,Eve Davis,2,65000,2023-05-15
6,Frank Miller,3,70000,2023-06-01`

	employeesFile := filepath.Join(tmpDir, "employees.csv")
	err = os.WriteFile(employeesFile, []byte(employeesData), 0600)
	if err != nil {
		log.Fatal(err)
	}

	departmentsData := `id,name,budget
1,Engineering,500000
2,Sales,300000
3,Marketing,200000
4,HR,150000`

	departmentsFile := filepath.Join(tmpDir, "departments.csv")
	err = os.WriteFile(departmentsFile, []byte(departmentsData), 0600)
	if err != nil {
		log.Fatal(err)
	}

	return tmpDir
}
Output:
=== Advanced SQL Features ===

1. Window Functions - Employee Rankings by Department:
Name            Department   Salary   Dept Rank  Overall Rank
-----------------------------------------------------------------
Alice Johnson   Engineering  $95000   1          1
Charlie Brown   Engineering  $80000   2          3
David Wilson    Engineering  $75000   3          4
Bob Smith       Sales        $85000   1          2
Eve Davis       Sales        $65000   2          6
Frank Miller    Marketing    $70000   1          5

2. Common Table Expressions - Department Analysis:
Department   Count Avg Salary Company Avg  Difference Comparison
---------------------------------------------------------------------------
Engineering  3     $83333     $78333       $5000      Above Average
Sales        2     $75000     $78333       $-3333     Below Average
Marketing    1     $70000     $78333       $-8333     Below Average

3. Text Functions - Name Analysis:
Name            Length Formatted       Space@   First Name
------------------------------------------------------------
Alice Johnson   13     Alice johnson   6        Alice
Charlie Brown   13     Charlie brown   8        Charlie
David Wilson    12     David wilson    6        David
Frank Miller    12     Frank miller    6        Frank
Bob Smith       9      Bob smith       4        Bob
Eve Davis       9      Eve davis       4        Eve
Example (CompressionSupport)

ExampleOpen_compressionSupport demonstrates working with compressed files

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/nao1215/filesql"
)

func main() {
	tmpDir := createCompressedTestData()
	defer os.RemoveAll(tmpDir)

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// Open compressed files seamlessly
	db, err := filesql.Open(ctx, tmpDir)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	fmt.Println("=== Compression Support Demo ===")
	fmt.Println("Successfully loaded compressed files:")

	// List all tables from compressed files
	rows, err := db.QueryContext(ctx, `
		SELECT name, sql 
		FROM sqlite_master 
		WHERE type='table' 
		ORDER BY name
	`)
	if err != nil {
		log.Fatal(err)
	}

	for rows.Next() {
		var tableName, createSQL string
		if err := rows.Scan(&tableName, &createSQL); err != nil {
			log.Fatal(err)
		}

		// Count records in each table
		var count int
		countQuery := "SELECT COUNT(*) FROM " + tableName
		if err := db.QueryRowContext(ctx, countQuery).Scan(&count); err != nil {
			log.Fatal(err)
		}

		fmt.Printf("- %s: %d records\n", tableName, count)
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
	_ = rows.Close() // Ignore close error in test cleanup

	// Demonstrate querying across compressed files
	fmt.Println("\nCross-file analysis from compressed data:")

	analysisRows, err := db.QueryContext(ctx, `
		SELECT 
			'logs' as source_table,
			COUNT(*) as total_records,
			MIN(timestamp) as earliest,
			MAX(timestamp) as latest
		FROM logs
		
		UNION ALL
		
		SELECT 
			'products' as source_table,
			COUNT(*) as total_records,
			'N/A' as earliest,
			'N/A' as latest
		FROM products
		
		ORDER BY source_table
	`)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%-12s %-8s %-19s %s\n", "Table", "Records", "Earliest", "Latest")
	fmt.Println(strings.Repeat("-", 60))

	for analysisRows.Next() {
		var sourceTable, earliest, latest string
		var totalRecords int

		if err := analysisRows.Scan(&sourceTable, &totalRecords, &earliest, &latest); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%-12s %-8d %-19s %s\n", sourceTable, totalRecords, earliest, latest)
	}
	if err := analysisRows.Err(); err != nil {
		log.Fatal(err)
	}
	_ = analysisRows.Close() // Ignore close error in test cleanup

}

// createCompressedTestData creates test data with compressed files
func createCompressedTestData() string {
	tmpDir, err := os.MkdirTemp("", "filesql_compressed_example_*")
	if err != nil {
		log.Fatal(err)
	}

	logsData := `timestamp,level,message,user_id
2024-01-01 10:00:00,INFO,User login,1001
2024-01-01 11:30:00,INFO,Order created,1002
2024-01-01 12:15:00,ERROR,Payment failed,1003
2024-01-01 13:45:00,INFO,User logout,1001
2024-01-01 14:00:00,INFO,System backup completed,0`

	logsFile := filepath.Join(tmpDir, "logs.csv")
	err = os.WriteFile(logsFile, []byte(logsData), 0600)
	if err != nil {
		log.Fatal(err)
	}

	productsData := `id,name,category,price,in_stock
1,Laptop Pro,Electronics,1299.99,true
2,Office Chair,Furniture,299.99,true
3,Wireless Mouse,Electronics,49.99,false`

	productsFile := filepath.Join(tmpDir, "products.csv")
	err = os.WriteFile(productsFile, []byte(productsData), 0600)
	if err != nil {
		log.Fatal(err)
	}

	return tmpDir
}
Output:
=== Compression Support Demo ===
Successfully loaded compressed files:
- logs: 5 records
- products: 3 records

Cross-file analysis from compressed data:
Table        Records  Earliest            Latest
------------------------------------------------------------
logs         5        2024-01-01 10:00:00 2024-01-01 14:00:00
products     3        N/A                 N/A
Example (Constraints)

ExampleOpen_constraints demonstrates the constraint that modifications don't affect original files

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"

	"github.com/nao1215/filesql"
)

// createTempTestData creates temporary CSV files for the example
func createTempTestData() string {
	tmpDir, err := os.MkdirTemp("", "filesql_example")
	if err != nil {
		log.Fatal(err)
	}

	employeesData := `id,name,department_id,salary,hire_date
1,Alice Johnson,1,95000,2020-01-15
2,Bob Smith,1,85000,2019-03-22
3,Charlie Brown,1,80000,2021-06-10
4,David Wilson,1,75000,2022-02-28
5,Eve Davis,2,70000,2020-09-15
6,Frank Miller,2,65000,2021-11-30
7,Grace Lee,3,60000,2019-12-05
8,Henry Taylor,3,55000,2022-04-18`

	err = os.WriteFile(filepath.Join(tmpDir, "employees.csv"), []byte(employeesData), 0600)
	if err != nil {
		log.Fatal(err)
	}

	departmentsData := `id,name,budget,manager_id
1,Engineering,1000000,1
2,Marketing,800000,5
3,Sales,600000,7
4,HR,400000,9`

	err = os.WriteFile(filepath.Join(tmpDir, "departments.csv"), []byte(departmentsData), 0600)
	if err != nil {
		log.Fatal(err)
	}

	return tmpDir
}

func main() {
	tmpDir := createTempTestData()
	defer os.RemoveAll(tmpDir)

	db, err := filesql.Open(context.Background(), filepath.Join(tmpDir, "employees.csv"))
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Show original data count
	var originalCount int
	err = db.QueryRowContext(context.Background(), "SELECT COUNT(*) FROM employees").Scan(&originalCount)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Original employee count: %d\n", originalCount)

	// Insert new data (only affects in-memory database)
	_, err = db.ExecContext(context.Background(), "INSERT INTO employees (id, name, department_id, salary, hire_date) VALUES (99, 'Test User', 1, 50000, '2023-01-01')")
	if err != nil {
		log.Fatal(err)
	}

	// Show in-memory count
	var memoryCount int
	err = db.QueryRowContext(context.Background(), "SELECT COUNT(*) FROM employees").Scan(&memoryCount)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("In-memory count after INSERT: %d\n", memoryCount)

	// Verify original file is unchanged by reopening
	db2, err := filesql.Open(context.Background(), filepath.Join(tmpDir, "employees.csv"))
	if err != nil {
		log.Fatal(err)
	}
	defer db2.Close()

	var fileCount int
	err = db2.QueryRowContext(context.Background(), "SELECT COUNT(*) FROM employees").Scan(&fileCount)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("File-based count (unchanged): %d\n", fileCount)

}
Output:
Original employee count: 8
In-memory count after INSERT: 9
File-based count (unchanged): 8
Example (CustomerInsights)

ExampleOpen_customerInsights demonstrates customer behavior analysis

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/nao1215/filesql"
)

// createSalesTestData creates test data for sales analysis examples
func createSalesTestData() string {
	tmpDir, err := os.MkdirTemp("", "filesql_sales_example")
	if err != nil {
		log.Fatal(err)
	}

	salesData := `order_id,customer_id,product_name,category,quantity,unit_price,order_date,region
1,101,Laptop Pro,Electronics,2,1299.99,2024-01-15,North
2,102,Wireless Mouse,Electronics,1,29.99,2024-01-16,South
3,103,Office Chair,Furniture,1,299.99,2024-01-17,East
4,101,USB Cable,Electronics,3,12.99,2024-01-18,North
5,104,Standing Desk,Furniture,1,599.99,2024-01-19,West
6,105,Bluetooth Speaker,Electronics,2,79.99,2024-01-20,South
7,106,Coffee Table,Furniture,1,199.99,2024-01-21,East
8,102,Keyboard,Electronics,1,89.99,2024-01-22,South
9,107,Monitor 24inch,Electronics,1,249.99,2024-01-23,North
10,103,Desk Lamp,Furniture,2,39.99,2024-01-24,East`

	err = os.WriteFile(filepath.Join(tmpDir, "sales.csv"), []byte(salesData), 0600)
	if err != nil {
		log.Fatal(err)
	}

	customersData := `customer_id,name,email,city,registration_date
101,John Doe,john@example.com,New York,2023-06-01
102,Jane Smith,jane@example.com,Los Angeles,2023-07-15
103,Bob Johnson,bob@example.com,Chicago,2023-08-20
104,Alice Brown,alice@example.com,Houston,2023-09-10
105,Charlie Wilson,charlie@example.com,Phoenix,2023-10-05
106,Diana Lee,diana@example.com,Philadelphia,2023-11-12
107,Frank Miller,frank@example.com,San Antonio,2023-12-03`

	err = os.WriteFile(filepath.Join(tmpDir, "customers.csv"), []byte(customersData), 0600)
	if err != nil {
		log.Fatal(err)
	}

	return tmpDir
}

func main() {
	tmpDir := createSalesTestData()
	defer os.RemoveAll(tmpDir)

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	db, err := filesql.Open(ctx, tmpDir)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Customer lifetime value and behavior analysis
	query := `
		SELECT 
			c.name,
			c.city,
			COUNT(s.order_id) as total_orders,
			SUM(s.quantity * s.unit_price) as lifetime_value,
			AVG(s.quantity * s.unit_price) as avg_order_value,
			MIN(s.order_date) as first_purchase,
			MAX(s.order_date) as last_purchase,
			julianday(MAX(s.order_date)) - julianday(MIN(s.order_date)) as days_active,
			COUNT(DISTINCT s.category) as categories_purchased
		FROM customers c
		JOIN sales s ON c.customer_id = s.customer_id
		GROUP BY c.customer_id, c.name, c.city
		HAVING total_orders > 1
		ORDER BY lifetime_value DESC
	`

	rows, err := db.QueryContext(ctx, query)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	fmt.Println("Customer Insights (Multi-Purchase Customers):")
	fmt.Println("===========================================")
	fmt.Printf("%-12s %-12s %-7s %-10s %-10s %-12s %-12s %-6s %s\n",
		"Name", "City", "Orders", "LTV", "Avg Order", "First Buy", "Last Buy", "Days", "Categories")
	fmt.Println(strings.Repeat("-", 100))

	for rows.Next() {
		var name, city, firstPurchase, lastPurchase string
		var totalOrders, daysActive, categoriesPurchased int
		var lifetimeValue, avgOrderValue float64

		err := rows.Scan(&name, &city, &totalOrders, &lifetimeValue, &avgOrderValue,
			&firstPurchase, &lastPurchase, &daysActive, &categoriesPurchased)
		if err != nil {
			log.Fatal(err)
		}

		fmt.Printf("%-12s %-12s %-7d $%-9.2f $%-9.2f %-12s %-12s %-6d %d\n",
			name, city, totalOrders, lifetimeValue, avgOrderValue,
			firstPurchase, lastPurchase, daysActive, categoriesPurchased)
	}

	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
}
Output:
Customer Insights (Multi-Purchase Customers):
===========================================
Name         City         Orders  LTV        Avg Order  First Buy    Last Buy     Days   Categories
----------------------------------------------------------------------------------------------------
John Doe     New York     2       $2638.95   $1319.47   2024-01-15   2024-01-18   3      1
Bob Johnson  Chicago      2       $379.97    $189.99    2024-01-17   2024-01-24   7      1
Jane Smith   Los Angeles  2       $119.98    $59.99     2024-01-16   2024-01-22   6      1
Example (ErrorHandling)

ExampleOpen_errorHandling demonstrates proper error handling patterns

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/nao1215/filesql"
)

// createTempTestData creates temporary CSV files for the example
func createTempTestData() string {
	tmpDir, err := os.MkdirTemp("", "filesql_example")
	if err != nil {
		log.Fatal(err)
	}

	employeesData := `id,name,department_id,salary,hire_date
1,Alice Johnson,1,95000,2020-01-15
2,Bob Smith,1,85000,2019-03-22
3,Charlie Brown,1,80000,2021-06-10
4,David Wilson,1,75000,2022-02-28
5,Eve Davis,2,70000,2020-09-15
6,Frank Miller,2,65000,2021-11-30
7,Grace Lee,3,60000,2019-12-05
8,Henry Taylor,3,55000,2022-04-18`

	err = os.WriteFile(filepath.Join(tmpDir, "employees.csv"), []byte(employeesData), 0600)
	if err != nil {
		log.Fatal(err)
	}

	departmentsData := `id,name,budget,manager_id
1,Engineering,1000000,1
2,Marketing,800000,5
3,Sales,600000,7
4,HR,400000,9`

	err = os.WriteFile(filepath.Join(tmpDir, "departments.csv"), []byte(departmentsData), 0600)
	if err != nil {
		log.Fatal(err)
	}

	return tmpDir
}

func main() {
	// Example 1: Handling non-existent files gracefully
	_, err := filesql.Open(context.Background(), "nonexistent.csv")
	if err != nil {
		fmt.Printf("Expected error for non-existent file: %v\n", err)
	}

	// Example 2: Context timeout handling. The deadline is already in the
	// past, so the load stops before it reads anything.
	ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
	defer cancel()

	tmpDir := createTempTestData()
	defer os.RemoveAll(tmpDir)

	_, err = filesql.Open(ctx, tmpDir)
	if err != nil {
		// Extract the core error message (context deadline exceeded)
		errMsg := err.Error()
		if strings.Contains(errMsg, "context deadline exceeded") {
			fmt.Printf("Expected timeout error: %s\n", "context deadline exceeded")
		} else {
			fmt.Printf("Expected timeout error: %v\n", err)
		}
	}

	// Example 3: Successful operation with proper error checking
	ctx2, cancel2 := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel2()

	db, err := filesql.Open(ctx2, tmpDir)
	if err != nil {
		fmt.Printf("Unexpected error: %v\n", err)
		return
	}
	defer db.Close()

	// Test query with error handling
	rows, err := db.QueryContext(ctx2, "SELECT COUNT(*) FROM employees")
	if err != nil {
		fmt.Printf("Query error: %v\n", err)
		return
	}
	defer rows.Close()

	var count int
	if rows.Next() {
		if err := rows.Scan(&count); err != nil {
			fmt.Printf("Scan error: %v\n", err)
			return
		}
		fmt.Printf("Successfully counted %d employees\n", count)
	}

	if err := rows.Err(); err != nil {
		fmt.Printf("Rows iteration error: %v\n", err)
		return
	}

}
Output:
Expected error for non-existent file: filesql: file not found: nonexistent.csv
Expected timeout error: context deadline exceeded
Successfully counted 8 employees
Example (FinancialDataAnalysis)

ExampleOpen_financialDataAnalysis demonstrates financial data processing

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/nao1215/filesql"
)

func main() {
	tmpDir := createFinancialTestData()
	defer os.RemoveAll(tmpDir)

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	db, err := filesql.Open(ctx, tmpDir)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	fmt.Println("=== Financial Data Analysis ===")

	// Monthly revenue trend
	fmt.Println("\n1. Monthly Revenue Trend:")
	rows, err := db.QueryContext(ctx, `
		SELECT 
			strftime('%Y-%m', transaction_date) as month,
			COUNT(*) as transaction_count,
			SUM(amount) as total_revenue,
			AVG(amount) as avg_transaction,
			MAX(amount) as largest_transaction
		FROM transactions 
		WHERE type = 'sale'
		GROUP BY month
		ORDER BY month
	`)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%-8s %-6s %-10s %-8s %s\n", "Month", "Count", "Revenue", "Average", "Largest")
	fmt.Println(strings.Repeat("-", 50))
	for rows.Next() {
		var month string
		var count int
		var revenue, average, largest float64
		if err := rows.Scan(&month, &count, &revenue, &average, &largest); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%-8s %-6d $%-9.2f $%-7.2f $%.2f\n", month, count, revenue, average, largest)
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
	_ = rows.Close() // Ignore close error in test cleanup

	// Expense category breakdown
	fmt.Println("\n2. Expense Categories:")
	rows, err = db.QueryContext(ctx, `
		SELECT 
			category,
			COUNT(*) as transaction_count,
			SUM(ABS(amount)) as total_expense,
			ROUND(SUM(ABS(amount)) * 100.0 / (
				SELECT SUM(ABS(amount)) FROM transactions WHERE type = 'expense'
			), 2) as percentage
		FROM transactions 
		WHERE type = 'expense'
		GROUP BY category
		ORDER BY total_expense DESC
	`)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%-15s %-6s %-12s %-10s\n", "Category", "Count", "Total", "Percentage")
	fmt.Println(strings.Repeat("-", 45))
	for rows.Next() {
		var category string
		var count int
		var expense, percentage float64
		if err := rows.Scan(&category, &count, &expense, &percentage); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%-15s %-6d $%-11.2f %-10.2f%%\n", category, count, expense, percentage)
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
	_ = rows.Close() // Ignore close error in test cleanup

	// Cash flow summary
	fmt.Println("\n3. Cash Flow Summary:")
	var totalIncome, totalExpenses, netIncome float64
	err = db.QueryRowContext(ctx, `
		SELECT 
			SUM(CASE WHEN type = 'sale' THEN amount ELSE 0 END) as total_income,
			SUM(CASE WHEN type = 'expense' THEN ABS(amount) ELSE 0 END) as total_expenses,
			SUM(CASE WHEN type = 'sale' THEN amount ELSE -ABS(amount) END) as net_income
		FROM transactions
	`).Scan(&totalIncome, &totalExpenses, &netIncome)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Total Income:  $%.2f\n", totalIncome)
	fmt.Printf("Total Expenses: $%.2f\n", totalExpenses)
	fmt.Printf("Net Income:    $%.2f\n", netIncome)
	fmt.Printf("Profit Margin: %.2f%%\n", (netIncome/totalIncome)*100)

}

// createFinancialTestData creates test data for financial analysis examples
func createFinancialTestData() string {
	tmpDir, err := os.MkdirTemp("", "filesql_financial_example_*")
	if err != nil {
		log.Fatal(err)
	}

	transactionData := `transaction_id,transaction_date,type,category,amount,description
1,2024-01-15,sale,Product Sales,1500.00,Sale of premium product
2,2024-01-20,sale,Product Sales,850.00,Sale of standard product
3,2024-01-25,sale,Service,1200.00,Consulting service
4,2024-01-10,expense,Office Supplies,-150.00,Office equipment purchase
5,2024-01-18,expense,Marketing,-250.00,Social media advertising
6,2024-02-05,sale,Product Sales,1200.00,Sale of premium product
7,2024-02-15,sale,Service,1000.00,Training service
8,2024-02-08,expense,Office Supplies,-200.00,Stationery purchase`

	transactionFile := filepath.Join(tmpDir, "transactions.csv")
	err = os.WriteFile(transactionFile, []byte(transactionData), 0600)
	if err != nil {
		log.Fatal(err)
	}

	return tmpDir
}
Output:
=== Financial Data Analysis ===

1. Monthly Revenue Trend:
Month    Count  Revenue    Average  Largest
--------------------------------------------------
2024-01  3      $3550.00   $1183.33 $1500.00
2024-02  2      $2200.00   $1100.00 $1200.00

2. Expense Categories:
Category        Count  Total        Percentage
---------------------------------------------
Office Supplies 2      $350.00      58.33     %
Marketing       1      $250.00      41.67     %

3. Cash Flow Summary:
Total Income:  $5750.00
Total Expenses: $600.00
Net Income:    $5150.00
Profit Margin: 89.57%
Example (MultipleFiles)

ExampleOpen_multipleFiles demonstrates opening multiple files and directories

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"

	"github.com/nao1215/filesql"
)

// createTempTestData creates temporary CSV files for the example
func createTempTestData() string {
	tmpDir, err := os.MkdirTemp("", "filesql_example")
	if err != nil {
		log.Fatal(err)
	}

	employeesData := `id,name,department_id,salary,hire_date
1,Alice Johnson,1,95000,2020-01-15
2,Bob Smith,1,85000,2019-03-22
3,Charlie Brown,1,80000,2021-06-10
4,David Wilson,1,75000,2022-02-28
5,Eve Davis,2,70000,2020-09-15
6,Frank Miller,2,65000,2021-11-30
7,Grace Lee,3,60000,2019-12-05
8,Henry Taylor,3,55000,2022-04-18`

	err = os.WriteFile(filepath.Join(tmpDir, "employees.csv"), []byte(employeesData), 0600)
	if err != nil {
		log.Fatal(err)
	}

	departmentsData := `id,name,budget,manager_id
1,Engineering,1000000,1
2,Marketing,800000,5
3,Sales,600000,7
4,HR,400000,9`

	err = os.WriteFile(filepath.Join(tmpDir, "departments.csv"), []byte(departmentsData), 0600)
	if err != nil {
		log.Fatal(err)
	}

	return tmpDir
}

func main() {
	tmpDir := createTempTestData()
	defer os.RemoveAll(tmpDir)

	// Open database with multiple paths (files and directories)
	db, err := filesql.Open(context.Background(), tmpDir)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Query to show all available tables
	rows, err := db.QueryContext(context.Background(), "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	fmt.Println("Available tables:")
	for rows.Next() {
		var tableName string
		if err := rows.Scan(&tableName); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("- %s\n", tableName)
	}

	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
}
Output:
Available tables:
- departments
- employees
Example (PerformanceOptimization)

ExampleOpen_performanceOptimization demonstrates techniques for handling large datasets efficiently

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"time"

	"github.com/nao1215/filesql"
)

func main() {
	tmpDir := createLargeTestData()
	defer os.RemoveAll(tmpDir)

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	db, err := filesql.Open(ctx, tmpDir)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Technique 1: Use LIMIT and OFFSET for pagination
	fmt.Println("=== Performance Optimization Techniques ===")
	fmt.Println("\n1. Pagination with LIMIT and OFFSET:")

	pageSize := 3
	offset := 0

	for page := 1; page <= 2; page++ {
		rows, err := db.QueryContext(ctx, `
			SELECT customer_id, name, total_orders 
			FROM customer_summary 
			ORDER BY total_orders DESC 
			LIMIT ? OFFSET ?
		`, pageSize, offset)
		if err != nil {
			log.Fatal(err)
		}

		fmt.Printf("Page %d:\n", page)
		for rows.Next() {
			var customerID int
			var name string
			var totalOrders int
			if err := rows.Scan(&customerID, &name, &totalOrders); err != nil {
				log.Fatal(err)
			}
			fmt.Printf("  - %s (ID: %d, Orders: %d)\n", name, customerID, totalOrders)
		}
		if err := rows.Err(); err != nil {
			log.Fatal(err)
		}
		_ = rows.Close() // Ignore close error in test cleanup
		offset += pageSize
	}

	// Technique 2: Use indexes by querying with WHERE clauses on sorted columns
	fmt.Println("\n2. Efficient filtering with indexes:")
	rows, err := db.QueryContext(ctx, `
		SELECT name, email, registration_date 
		FROM customer_summary 
		WHERE total_spent > 1000 
		ORDER BY total_spent DESC
	`)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	fmt.Println("High-value customers:")
	for rows.Next() {
		var name, email, regDate string
		if err := rows.Scan(&name, &email, &regDate); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("  - %s (%s) - Registered: %s\n", name, email, regDate)
	}

	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
	// Technique 3: Aggregate queries for summary statistics
	fmt.Println("\n3. Summary statistics:")
	var totalCustomers int
	var avgOrders, totalRevenue, avgSpent float64

	err = db.QueryRowContext(ctx, `
		SELECT 
			COUNT(*) as total_customers,
			AVG(total_orders) as avg_orders,
			SUM(total_spent) as total_revenue,
			AVG(total_spent) as avg_spent
		FROM customer_summary
	`).Scan(&totalCustomers, &avgOrders, &totalRevenue, &avgSpent)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Total customers: %d\n", totalCustomers)
	fmt.Printf("Average orders per customer: %.1f\n", avgOrders)
	fmt.Printf("Total revenue: $%.2f\n", totalRevenue)
	fmt.Printf("Average customer value: $%.2f\n", avgSpent)

}

// createLargeTestData creates test data for performance optimization examples
func createLargeTestData() string {
	tmpDir, err := os.MkdirTemp("", "filesql_large_example_*")
	if err != nil {
		log.Fatal(err)
	}

	customerData := `customer_id,name,email,registration_date,total_orders,total_spent
1001,Premium Customer A,premium.a@example.com,2023-01-15,15,1500.00
1002,Premium Customer B,premium.b@example.com,2023-02-20,12,1200.00
1003,Premium Customer C,premium.c@example.com,2023-03-10,10,1000.00
1004,Regular Customer D,regular.d@example.com,2023-04-05,8,800.00
1005,Regular Customer E,regular.e@example.com,2023-05-15,6,600.00
1006,Regular Customer F,regular.f@example.com,2023-06-20,5,500.00
1007,Budget Customer G,budget.g@example.com,2023-07-10,3,300.00
1008,Budget Customer H,budget.h@example.com,2023-08-25,2,200.00
1009,New Customer I,new.i@example.com,2023-09-30,1,100.00
1010,New Customer J,new.j@example.com,2023-10-15,1,100.00`

	customerFile := filepath.Join(tmpDir, "customer_summary.csv")
	err = os.WriteFile(customerFile, []byte(customerData), 0600)
	if err != nil {
		log.Fatal(err)
	}

	return tmpDir
}
Output:
=== Performance Optimization Techniques ===

1. Pagination with LIMIT and OFFSET:
Page 1:
  - Premium Customer A (ID: 1001, Orders: 15)
  - Premium Customer B (ID: 1002, Orders: 12)
  - Premium Customer C (ID: 1003, Orders: 10)
Page 2:
  - Regular Customer D (ID: 1004, Orders: 8)
  - Regular Customer E (ID: 1005, Orders: 6)
  - Regular Customer F (ID: 1006, Orders: 5)

2. Efficient filtering with indexes:
High-value customers:
  - Premium Customer A (premium.a@example.com) - Registered: 2023-01-15
  - Premium Customer B (premium.b@example.com) - Registered: 2023-02-20

3. Summary statistics:
Total customers: 10
Average orders per customer: 6.3
Total revenue: $6300.00
Average customer value: $630.00
Example (SalesAnalysis)

ExampleOpen_salesAnalysis demonstrates practical sales data analysis

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/nao1215/filesql"
)

// createSalesTestData creates test data for sales analysis examples
func createSalesTestData() string {
	tmpDir, err := os.MkdirTemp("", "filesql_sales_example")
	if err != nil {
		log.Fatal(err)
	}

	salesData := `order_id,customer_id,product_name,category,quantity,unit_price,order_date,region
1,101,Laptop Pro,Electronics,2,1299.99,2024-01-15,North
2,102,Wireless Mouse,Electronics,1,29.99,2024-01-16,South
3,103,Office Chair,Furniture,1,299.99,2024-01-17,East
4,101,USB Cable,Electronics,3,12.99,2024-01-18,North
5,104,Standing Desk,Furniture,1,599.99,2024-01-19,West
6,105,Bluetooth Speaker,Electronics,2,79.99,2024-01-20,South
7,106,Coffee Table,Furniture,1,199.99,2024-01-21,East
8,102,Keyboard,Electronics,1,89.99,2024-01-22,South
9,107,Monitor 24inch,Electronics,1,249.99,2024-01-23,North
10,103,Desk Lamp,Furniture,2,39.99,2024-01-24,East`

	err = os.WriteFile(filepath.Join(tmpDir, "sales.csv"), []byte(salesData), 0600)
	if err != nil {
		log.Fatal(err)
	}

	customersData := `customer_id,name,email,city,registration_date
101,John Doe,john@example.com,New York,2023-06-01
102,Jane Smith,jane@example.com,Los Angeles,2023-07-15
103,Bob Johnson,bob@example.com,Chicago,2023-08-20
104,Alice Brown,alice@example.com,Houston,2023-09-10
105,Charlie Wilson,charlie@example.com,Phoenix,2023-10-05
106,Diana Lee,diana@example.com,Philadelphia,2023-11-12
107,Frank Miller,frank@example.com,San Antonio,2023-12-03`

	err = os.WriteFile(filepath.Join(tmpDir, "customers.csv"), []byte(customersData), 0600)
	if err != nil {
		log.Fatal(err)
	}

	return tmpDir
}

func main() {
	tmpDir := createSalesTestData()
	defer os.RemoveAll(tmpDir)

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	db, err := filesql.Open(ctx, tmpDir)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Sales summary by category and region
	query := `
		SELECT 
			category,
			region,
			COUNT(*) as order_count,
			SUM(quantity * unit_price) as total_revenue,
			AVG(quantity * unit_price) as avg_order_value,
			MIN(order_date) as first_order,
			MAX(order_date) as last_order
		FROM sales 
		GROUP BY category, region
		ORDER BY total_revenue DESC
	`

	rows, err := db.QueryContext(ctx, query)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	fmt.Println("Sales Analysis by Category and Region:")
	fmt.Println("=====================================")
	fmt.Printf("%-12s %-8s %-6s %-10s %-12s %-12s %s\n",
		"Category", "Region", "Orders", "Revenue", "Avg Order", "First Order", "Last Order")
	fmt.Println(strings.Repeat("-", 80))

	for rows.Next() {
		var category, region, firstOrder, lastOrder string
		var orderCount int
		var totalRevenue, avgOrderValue float64

		err := rows.Scan(&category, &region, &orderCount, &totalRevenue, &avgOrderValue, &firstOrder, &lastOrder)
		if err != nil {
			log.Fatal(err)
		}

		fmt.Printf("%-12s %-8s %-6d $%-9.2f $%-11.2f %-12s %s\n",
			category, region, orderCount, totalRevenue, avgOrderValue, firstOrder, lastOrder)
	}

	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
}
Output:
Sales Analysis by Category and Region:
=====================================
Category     Region   Orders Revenue    Avg Order    First Order  Last Order
--------------------------------------------------------------------------------
Electronics  North    3      $2888.94   $962.98      2024-01-15   2024-01-23
Furniture    West     1      $599.99    $599.99      2024-01-19   2024-01-19
Furniture    East     3      $579.96    $193.32      2024-01-17   2024-01-24
Electronics  South    3      $279.96    $93.32       2024-01-16   2024-01-22
Example (Timeout)

ExampleOpen_timeout demonstrates opening files under a deadline, which is what the context Open takes is for.

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"time"

	"github.com/nao1215/filesql"
)

// createTempTestData creates temporary CSV files for the example
func createTempTestData() string {
	tmpDir, err := os.MkdirTemp("", "filesql_example")
	if err != nil {
		log.Fatal(err)
	}

	employeesData := `id,name,department_id,salary,hire_date
1,Alice Johnson,1,95000,2020-01-15
2,Bob Smith,1,85000,2019-03-22
3,Charlie Brown,1,80000,2021-06-10
4,David Wilson,1,75000,2022-02-28
5,Eve Davis,2,70000,2020-09-15
6,Frank Miller,2,65000,2021-11-30
7,Grace Lee,3,60000,2019-12-05
8,Henry Taylor,3,55000,2022-04-18`

	err = os.WriteFile(filepath.Join(tmpDir, "employees.csv"), []byte(employeesData), 0600)
	if err != nil {
		log.Fatal(err)
	}

	departmentsData := `id,name,budget,manager_id
1,Engineering,1000000,1
2,Marketing,800000,5
3,Sales,600000,7
4,HR,400000,9`

	err = os.WriteFile(filepath.Join(tmpDir, "departments.csv"), []byte(departmentsData), 0600)
	if err != nil {
		log.Fatal(err)
	}

	return tmpDir
}

func main() {
	tmpDir := createTempTestData()
	defer os.RemoveAll(tmpDir)

	// Create a context with timeout
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	// Open database with context
	db, err := filesql.Open(ctx, filepath.Join(tmpDir, "employees.csv"))
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Query with context support
	rows, err := db.QueryContext(ctx, `
		SELECT name, salary 
		FROM employees 
		WHERE salary > 70000 
		ORDER BY salary DESC
	`)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	fmt.Println("High earners (>$70,000):")
	for rows.Next() {
		var name string
		var salary float64
		if err := rows.Scan(&name, &salary); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("- %s: $%.0f\n", name, salary)
	}

	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
}
Output:
High earners (>$70,000):
- Alice Johnson: $95000
- Bob Smith: $85000
- Charlie Brown: $80000
- David Wilson: $75000
Example (WebLogAnalysis)

ExampleOpen_webLogAnalysis demonstrates analyzing web server logs

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/nao1215/filesql"
)

func main() {
	tmpDir := createWebLogTestData()
	defer os.RemoveAll(tmpDir)

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	db, err := filesql.Open(ctx, tmpDir)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	fmt.Println("=== Web Log Analysis ===")

	// Top pages by hits
	fmt.Println("\n1. Top Pages by Hits:")
	rows, err := db.QueryContext(ctx, `
		SELECT 
			path,
			COUNT(*) as hits,
			COUNT(DISTINCT ip_address) as unique_visitors
		FROM access_logs 
		WHERE status_code = 200
		GROUP BY path
		ORDER BY hits DESC
		LIMIT 5
	`)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%-20s %-6s %s\n", "Path", "Hits", "Unique")
	fmt.Println(strings.Repeat("-", 35))
	for rows.Next() {
		var path string
		var hits, unique int
		if err := rows.Scan(&path, &hits, &unique); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%-20s %-6d %d\n", path, hits, unique)
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
	_ = rows.Close() // Ignore close error in test cleanup

	// Error analysis
	fmt.Println("\n2. Error Analysis:")
	rows, err = db.QueryContext(ctx, `
		SELECT 
			status_code,
			COUNT(*) as error_count,
			ROUND(COUNT(*) * 100.0 / (SELECT COUNT(*) FROM access_logs), 2) as percentage
		FROM access_logs 
		WHERE status_code >= 400
		GROUP BY status_code
		ORDER BY error_count DESC
	`)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%-12s %-6s %-10s\n", "Status Code", "Count", "Percentage")
	fmt.Println(strings.Repeat("-", 30))
	for rows.Next() {
		var statusCode, errorCount int
		var percentage float64
		if err := rows.Scan(&statusCode, &errorCount, &percentage); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%-12d %-6d %-10.2f%%\n", statusCode, errorCount, percentage)
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
	_ = rows.Close() // Ignore close error in test cleanup

	// Hourly traffic pattern
	fmt.Println("\n3. Traffic by Hour:")
	rows, err = db.QueryContext(ctx, `
		SELECT 
			CAST(strftime('%H', timestamp) AS INTEGER) as hour,
			COUNT(*) as requests,
			AVG(response_time) as avg_response_time
		FROM access_logs
		GROUP BY hour
		ORDER BY hour
	`)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%-5s %-9s %-12s\n", "Hour", "Requests", "Avg Response")
	fmt.Println(strings.Repeat("-", 28))
	for rows.Next() {
		var hour, requests int
		var avgResponseTime float64
		if err := rows.Scan(&hour, &requests, &avgResponseTime); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%-5d %-9d %-12.0fms\n", hour, requests, avgResponseTime)
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
	_ = rows.Close() // Ignore close error in test cleanup

}

// createWebLogTestData creates test data for web log analysis examples
func createWebLogTestData() string {
	tmpDir, err := os.MkdirTemp("", "filesql_weblog_example_*")
	if err != nil {
		log.Fatal(err)
	}

	accessLogsData := `timestamp,ip_address,method,path,status_code,response_time,user_agent
2024-01-01 09:15:30,192.168.1.100,GET,/,200,150,Mozilla/5.0
2024-01-01 09:30:45,192.168.1.101,GET,/products,200,200,Mozilla/5.0
2024-01-01 10:05:15,192.168.1.100,GET,/,200,120,Mozilla/5.0
2024-01-01 10:20:30,192.168.1.102,GET,/about,200,180,Mozilla/5.0
2024-01-01 10:35:45,192.168.1.101,GET,/products,200,160,Mozilla/5.0
2024-01-01 11:10:15,192.168.1.103,GET,/contact,200,140,Mozilla/5.0
2024-01-01 11:25:30,192.168.1.100,GET,/,200,200,Mozilla/5.0
2024-01-01 11:40:45,192.168.1.104,GET,/missing,404,50,Mozilla/5.0
2024-01-01 14:15:30,192.168.1.105,GET,/notfound,404,100,Mozilla/5.0`

	accessLogsFile := filepath.Join(tmpDir, "access_logs.csv")
	err = os.WriteFile(accessLogsFile, []byte(accessLogsData), 0600)
	if err != nil {
		log.Fatal(err)
	}

	return tmpDir
}
Output:
=== Web Log Analysis ===

1. Top Pages by Hits:
Path                 Hits   Unique
-----------------------------------
/                    3      1
/products            2      1
/contact             1      1
/about               1      1

2. Error Analysis:
Status Code  Count  Percentage
------------------------------
404          2      22.22     %

3. Traffic by Hour:
Hour  Requests  Avg Response
----------------------------
9     2         175         ms
10    3         153         ms
11    3         130         ms
14    1         100         ms

func OpenReader added in v0.55.0

func OpenReader(path string) (io.ReadCloser, error)

OpenReader opens the file at path and returns a reader over its decompressed bytes, with the codec taken from the path's extension: "a.csv.gz" is read through gzip and "a.csv" as it is. Closing the result closes the file.

A path that is not a regular file is refused with ErrUnsupportedFormat rather than opened. Opening a named pipe for reading blocks until a writer opens the other end, inside the syscall where no deadline and no cancellation reach it, and this is the one place every read of a path in this package goes through: a load of a compressed source, the read an in-place save does for the source's compression, encoding and line terminator, and ExcelSheetsInFile. A caller who means to read a pipe opens it themselves and passes the reader to CompressionType.NewReader or to DBBuilder.AddReader, where the blocking is their own.

Example
package main

import (
	"fmt"
	"io"
	"log"
	"os"
	"path/filepath"
	"strings"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func createFilesqlExampleDir(files map[string]string) string {
	dir, err := os.MkdirTemp("", "filesql-api-example")
	if err != nil {
		log.Fatal(err)
	}
	for name, body := range files {
		path := filepath.Join(dir, name)
		if err := os.MkdirAll(filepath.Dir(path), 0750); err != nil {
			log.Fatal(err)
		}
		if err := os.WriteFile(path, []byte(strings.TrimLeft(body, "\n")), 0600); err != nil {
			log.Fatal(err)
		}
	}
	return dir
}

func main() {
	dir := createFilesqlExampleDir(map[string]string{
		"orders.csv": `
id,total
1,980
`,
	})
	defer os.RemoveAll(dir)

	reader, err := filesql.OpenReader(filepath.Join(dir, "orders.csv"))
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		if err := reader.Close(); err != nil {
			log.Fatal(err)
		}
	}()

	body, err := io.ReadAll(reader)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(string(body))
}
Output:
id,total
1,980

func RemoveCompressionExtension added in v0.55.0

func RemoveCompressionExtension(path string) string

RemoveCompressionExtension returns path without its compression extension, so "orders.csv.gz" becomes "orders.csv". A path with no compression extension is returned as it is.

Example
package main

import (
	"fmt"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	fmt.Println(filesql.RemoveCompressionExtension("orders.csv.gz"))
}
Output:
orders.csv

Types

type CompressionType added in v0.0.4

type CompressionType int

CompressionType represents the compression type

const (
	// CompressionNone represents no compression
	CompressionNone CompressionType = iota
	// CompressionGZ represents gzip compression
	CompressionGZ
	// CompressionBZ2 represents bzip2 compression
	CompressionBZ2
	// CompressionXZ represents xz compression
	CompressionXZ
	// CompressionZSTD represents zstd compression
	CompressionZSTD
	// CompressionZLIB represents zlib compression
	CompressionZLIB
	// CompressionSNAPPY represents snappy compression
	CompressionSNAPPY
	// CompressionS2 represents s2 compression
	CompressionS2
	// CompressionLZ4 represents lz4 compression
	CompressionLZ4
)

func (CompressionType) Extension added in v0.2.0

func (c CompressionType) Extension() string

Extension returns the file extension for the compression type

Example
package main

import (
	"fmt"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	fmt.Println(filesql.CompressionXZ.Extension())
}
Output:
.xz

func (CompressionType) NewReader added in v0.55.0

func (c CompressionType) NewReader(reader io.Reader) (io.ReadCloser, error)

NewReader returns a reader that decompresses reader with this codec. CompressionNone hands the stream back untouched, so a caller that does not know whether a stream is compressed can use the same call either way.

Closing the result releases the codec; it does not close reader, which is still the caller's. A stream that declares more working memory than this package will hold for it is refused with ErrCompression before any of that memory is allocated.

Example
package main

import (
	"bytes"
	"fmt"
	"io"
	"log"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	var compressed bytes.Buffer
	writer, err := filesql.CompressionGZ.NewWriter(&compressed)
	if err != nil {
		log.Fatal(err)
	}
	if _, err := io.WriteString(writer, "id,total\n1,980\n"); err != nil {
		log.Fatal(err)
	}
	if err := writer.Close(); err != nil {
		log.Fatal(err)
	}

	// The codec is named rather than guessed, which is what a caller who
	// already knows it does; OpenReader takes it from a path instead.
	reader, err := filesql.CompressionGZ.NewReader(bytes.NewReader(compressed.Bytes()))
	if err != nil {
		log.Fatal(err)
	}
	defer reader.Close()

	plain, err := io.ReadAll(reader)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Print(string(plain))
}
Output:
id,total
1,980

func (CompressionType) NewWriter added in v0.55.0

func (c CompressionType) NewWriter(writer io.Writer) (io.WriteCloser, error)

NewWriter returns a writer that compresses what is written to it with this codec and writes the result to writer. CompressionNone hands writer back untouched.

Closing the result flushes and finalizes the stream; it does not close writer, which is still the caller's. Bzip2 has no writer, and asking for one is refused with ErrUnsupportedFormat.

Example
package main

import (
	"bytes"
	"fmt"
	"io"
	"log"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	var compressed bytes.Buffer
	writer, err := filesql.CompressionGZ.NewWriter(&compressed)
	if err != nil {
		log.Fatal(err)
	}
	if _, err := io.WriteString(writer, "hello"); err != nil {
		log.Fatal(err)
	}
	// Closing finalizes the compressed stream. It does not close the
	// destination, which is still the caller's.
	if err := writer.Close(); err != nil {
		log.Fatal(err)
	}

	fmt.Println(compressed.Len() > 0)
}
Output:
true

func (CompressionType) String added in v0.2.0

func (c CompressionType) String() string

String returns the string representation of CompressionType

Example
package main

import (
	"fmt"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	fmt.Println(filesql.CompressionNone, filesql.CompressionGZ, filesql.CompressionZSTD)
}
Output:
none gz zstd

type DBBuilder added in v0.1.0

type DBBuilder struct {
	// contains filtered or unexported fields
}

DBBuilder configures and creates database connections from various data sources.

Basic usage:

db, err := filesql.NewBuilder().
	AddPath("data.csv").
	AddPath("users.tsv").
	Open(ctx)
if err != nil {
	return err
}
defer db.Close()

Supports:

  • File paths (AddPath)
  • Embedded filesystems (AddFS)
  • io.Reader streams (AddReader)
  • Auto-save functionality (EnableAutoSave)
  • Read-only mode (OpenReadOnly)

A builder can be added to and opened again: the next load reads what it holds then, including the sources and the options given since the last one. The exception is a reader handed to AddReader: a stream is read once, so a second load meets it exhausted and fails. A path and a filesystem are read again.

Example (Chaining)
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"testing/fstest"

	"github.com/nao1215/filesql"
)

func main() {
	// Create temporary files
	tempDir, _ := os.MkdirTemp("", "filesql-example")
	defer os.RemoveAll(tempDir)

	csvFile := filepath.Join(tempDir, "data1.csv")
	content1 := "id,name\n1,Alice\n2,Bob\n"
	os.WriteFile(csvFile, []byte(content1), 0644)

	tsvFile := filepath.Join(tempDir, "data2.tsv")
	content2 := "id\tproduct\n1\tLaptop\n2\tPhone\n"
	os.WriteFile(tsvFile, []byte(content2), 0644)

	// Create mock filesystem
	mockFS := fstest.MapFS{
		"logs.ltsv": &fstest.MapFile{Data: []byte("time:2024-01-01T00:00:00Z\tlevel:info\n")},
	}

	// Demonstrate method chaining
	ctx := context.Background()
	db := filesql.NewBuilder().
		AddPath(csvFile).
		AddPaths(tsvFile).
		AddFS(mockFS)

	connection, err := db.Open(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer connection.Close()

	// Count tables from different sources
	rows, err := connection.QueryContext(context.Background(), "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	var tableCount int
	for rows.Next() {
		var tableName string
		rows.Scan(&tableName)
		tableCount++
	}

	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Successfully loaded %d tables from mixed sources\n", tableCount)
}
Output:
Successfully loaded 3 tables from mixed sources
Example (ErrorHandling)
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"

	"github.com/nao1215/filesql"
)

func main() {
	ctx := context.Background()

	// Example 1: a builder with no input at all
	_, err := filesql.NewBuilder().Open(ctx)
	if err != nil {
		fmt.Printf("Expected error for no inputs: %v\n", err)
	}

	// Example 2: a file that does not exist
	_, err = filesql.NewBuilder().AddPath("nonexistent.csv").Open(ctx)
	if err != nil {
		fmt.Println("Expected error for a file that does not exist")
	}

	// Example 3: a directory that does not exist
	_, err = filesql.NewBuilder().
		AddPath(filepath.Join("nonexistent", "file.csv")).
		Open(ctx)
	if err != nil {
		fmt.Println("Expected error for non-existent file")
	}

	// Example 4: Success case
	tempDir, _ := os.MkdirTemp("", "filesql-example")
	defer os.RemoveAll(tempDir)

	csvFile := filepath.Join(tempDir, "valid.csv")
	os.WriteFile(csvFile, []byte("id,name\n1,test\n"), 0644)

	db, err := filesql.NewBuilder().AddPath(csvFile).Open(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	fmt.Println("Success: Valid file loaded correctly")

}
Output:
Expected error for no inputs: filesql: no supported files found: at least one path must be provided
Expected error for a file that does not exist
Expected error for non-existent file
Success: Valid file loaded correctly

func NewBuilder added in v0.1.0

func NewBuilder() *DBBuilder

NewBuilder creates a new database builder.

Start here when you need:

  • Multiple data sources (files, streams, embedded FS)
  • Auto-save functionality
  • Custom chunk sizes for large files
  • More control than the simple Open() function

Example:

builder := filesql.NewBuilder().
	AddPath("data.csv").
	EnableAutoSave("./backup")
Example

ExampleNewBuilder demonstrates the basic usage of the Builder pattern. This is the recommended approach for most use cases, especially when working with embedded filesystems or when you need more control over the database creation process.

package main

import (
	"fmt"

	"github.com/nao1215/filesql"
)

func main() {
	// Create a new builder - this is the starting point for all Builder pattern usage
	builder := filesql.NewBuilder()

	// The builder supports method chaining for a fluent API
	// You can add individual paths or multiple paths at once
	builder.AddPath("users.csv").AddPaths("orders.tsv", "products.ltsv")

	fmt.Printf("Builder created successfully: %t\n", builder != nil)

	// In real usage, you would continue with:
	// ctx := context.Background()
	// db, err := builder.Open(ctx)
	// if err != nil { return err }
	// defer db.Close()

}
Output:
Builder created successfully: true

func (*DBBuilder) AddFS added in v0.1.0

func (b *DBBuilder) AddFS(filesystem fs.FS) *DBBuilder

AddFS adds files from an embedded filesystem (go:embed).

Every file the filesystem holds in a format this package reads is found; the package documentation names them.

Example:

//go:embed data/*.csv data/*.tsv
var dataFS embed.FS

builder.AddFS(dataFS)

Returns self for chaining.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"testing/fstest"

	"github.com/nao1215/filesql"
)

func main() {
	// Create mock filesystem with test data
	mockFS := fstest.MapFS{
		"users.csv":    &fstest.MapFile{Data: []byte("id,name,department\n1,Alice,Engineering\n2,Bob,Sales\n")},
		"products.tsv": &fstest.MapFile{Data: []byte("id\tname\tprice\n1\tLaptop\t1000\n2\tPhone\t500\n")},
		"logs.ltsv":    &fstest.MapFile{Data: []byte("time:2024-01-01T00:00:00Z\tlevel:info\tmsg:started\n")},
		"readme.txt":   &fstest.MapFile{Data: []byte("This file will be ignored\n")}, // unsupported format
	}

	// Use builder with filesystem
	builder := filesql.NewBuilder().AddFS(mockFS)

	ctx := context.Background()

	db, err := builder.Open(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Clean up temporary files

	// List all tables that were created from the filesystem
	rows, err := db.QueryContext(context.Background(), "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	var tableCount int
	for rows.Next() {
		var tableName string
		rows.Scan(&tableName)
		tableCount++
	}

	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Created %d tables from filesystem\n", tableCount)
}
Output:
Created 3 tables from filesystem
Example (EmbedFS)
package main

import (
	"context"
	"embed"
	"fmt"
	"io/fs"
	"log"

	"github.com/nao1215/filesql"
)

//go:embed testdata/embed_test/*.csv testdata/embed_test/*.tsv
var builderExampleFS embed.FS

func main() {
	// Use embedded test filesystem
	subFS, err := fs.Sub(builderExampleFS, "testdata/embed_test")
	if err != nil {
		log.Fatal(err)
	}

	// Use builder with embedded filesystem
	builder := filesql.NewBuilder().AddFS(subFS)

	ctx := context.Background()

	db, err := builder.Open(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Clean up temporary files

	// Count the number of tables created from embedded files
	rows, err := db.QueryContext(context.Background(), "SELECT COUNT(*) FROM sqlite_master WHERE type='table'")
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	var tableCount int
	if rows.Next() {
		rows.Scan(&tableCount)
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Created %d tables from embedded files\n", tableCount)
}
Output:
Created 3 tables from embedded files

func (*DBBuilder) AddPath added in v0.1.0

func (b *DBBuilder) AddPath(path string) *DBBuilder

AddPath adds a file or directory to load.

Examples:

  • Single file: AddPath("users.csv")
  • Compressed: AddPath("data.tsv.gz")
  • Directory: AddPath("/data/") // loads every file it holds this package reads

Returns self for chaining.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"

	"github.com/nao1215/filesql"
)

func main() {
	// Create temporary CSV file for example
	tempDir, _ := os.MkdirTemp("", "filesql-example")
	defer os.RemoveAll(tempDir)

	csvFile := filepath.Join(tempDir, "users.csv")
	content := "id,name,age\n1,Alice,30\n2,Bob,25\n"
	os.WriteFile(csvFile, []byte(content), 0644)

	// Use builder to add a single file path
	builder := filesql.NewBuilder().AddPath(csvFile)

	// Build and open database
	ctx := context.Background()

	db, err := builder.Open(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Query the data
	rows, err := db.QueryContext(context.Background(), "SELECT COUNT(*) FROM users")
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	var count int
	if rows.Next() {
		rows.Scan(&count)
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Number of users: %d\n", count)
}
Output:
Number of users: 2

func (*DBBuilder) AddPaths added in v0.1.0

func (b *DBBuilder) AddPaths(paths ...string) *DBBuilder

AddPaths adds multiple files or directories at once.

Example:

builder.AddPaths("users.csv", "products.tsv", "/data/logs/")

Returns self for chaining.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"

	"github.com/nao1215/filesql"
)

func main() {
	// Create temporary files for example
	tempDir, _ := os.MkdirTemp("", "filesql-example")
	defer os.RemoveAll(tempDir)

	// Create users.csv
	usersFile := filepath.Join(tempDir, "users.csv")
	usersContent := "id,name\n1,Alice\n2,Bob\n"
	os.WriteFile(usersFile, []byte(usersContent), 0644)

	// Create products.csv
	productsFile := filepath.Join(tempDir, "products.csv")
	productsContent := "id,product_name\n1,Laptop\n2,Phone\n"
	os.WriteFile(productsFile, []byte(productsContent), 0644)

	// Use builder to add multiple file paths
	builder := filesql.NewBuilder().AddPaths(usersFile, productsFile)

	ctx := context.Background()

	db, err := builder.Open(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Query data from both tables
	rows, err := db.QueryContext(context.Background(), `
		SELECT u.name, p.product_name 
		FROM users u 
		JOIN products p ON u.id = p.id
	`)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	for rows.Next() {
		var name, product string
		rows.Scan(&name, &product)
		fmt.Printf("%s has %s\n", name, product)
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
}
Output:
Alice has Laptop
Bob has Phone

func (*DBBuilder) AddReader added in v0.2.0

func (b *DBBuilder) AddReader(reader io.Reader, tableName string, fileType FileType, opts ...ReaderOption) *DBBuilder

AddReader adds data from an io.Reader (file, network stream, etc.).

Parameters:

  • reader: Any io.Reader (file, bytes.Buffer, http.Response.Body, etc.)
  • tableName: Name for the SQL table (e.g., "users")
  • fileType: Data format (FileTypeCSV, FileTypeTSV, FileTypeLTSV, etc.)
  • opts: Per-source settings, such as WithCompression

The reader's bytes are read as fileType directly. When they are wrapped in a codec, say so with WithCompression — a reader has no path to infer it from.

Example:

resp, _ := http.Get("https://example.com/data.csv")
builder.AddReader(resp.Body, "remote_data", FileTypeCSV)

gz, _ := os.Open("users.csv.gz")
builder.AddReader(gz, "users", FileTypeCSV, WithCompression(CompressionGZ))

Returns self for chaining.

Example

ExampleDBBuilder_AddReader demonstrates using io.Reader as a data source

package main

import (
	"context"
	"fmt"
	"log"
	"strings"

	"github.com/nao1215/filesql"
)

func main() {
	// CSV data from an io.Reader (could be from network, API response, etc.)
	csvData := `id,name,department,salary
1,Alice,Engineering,95000
2,Bob,Sales,78000
3,Charlie,Engineering,102000
4,Diana,Marketing,85000`

	// Create a reader from the CSV data
	reader := strings.NewReader(csvData)

	// Build database with Reader input
	ctx := context.Background()
	builder := filesql.NewBuilder().
		AddReader(reader, "employees", filesql.FileTypeCSV). // Specify table name and type explicitly
		SetDefaultChunkSize(5000)                            // Set 5000 rows per chunk for large data

	// Build validates the input

	// Open creates the database connection
	db, err := builder.Open(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Query the data
	rows, err := db.QueryContext(context.Background(), `
		SELECT name, department, salary 
		FROM employees 
		WHERE salary > 80000 
		ORDER BY salary DESC
	`)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	// Process results
	fmt.Println("High earners (salary > 80,000):")
	for rows.Next() {
		var name, dept string
		var salary int
		if err := rows.Scan(&name, &dept, &salary); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("- %s (%s): $%d\n", name, dept, salary)
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
}
Output:
High earners (salary > 80,000):
- Charlie (Engineering): $102000
- Alice (Engineering): $95000
- Diana (Marketing): $85000
Example (Compressed)

ExampleDBBuilder_AddReader_compressed demonstrates reading compressed data from an io.Reader.

A file's name says which codec wraps it, but a reader has no name, so the codec is stated with WithCompression. The FileType stays the format itself: gzipped TSV is FileTypeTSV plus CompressionGZ.

package main

import (
	"bytes"
	"compress/gzip"
	"context"
	"fmt"
	"log"

	"github.com/nao1215/filesql"
)

func main() {
	tsvData := "product_id\tproduct_name\tprice\n1\tLaptop\t999\n2\tMouse\t25\n3\tKeyboard\t75"

	// Compress the TSV, standing in for a .tsv.gz opened from disk or fetched
	// over the network.
	var compressed bytes.Buffer
	gz := gzip.NewWriter(&compressed)
	if _, err := gz.Write([]byte(tsvData)); err != nil {
		log.Fatal(err)
	}
	if err := gz.Close(); err != nil {
		log.Fatal(err)
	}
	reader := bytes.NewReader(compressed.Bytes())

	ctx := context.Background()
	builder := filesql.NewBuilder().
		AddReader(reader, "products", filesql.FileTypeTSV, filesql.WithCompression(filesql.CompressionGZ))

	db, err := builder.Open(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Query the products
	var count int
	err = db.QueryRowContext(context.Background(), "SELECT COUNT(*) FROM products WHERE price < 100").Scan(&count)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Products under $100: %d\n", count)
}
Output:
Products under $100: 2
Example (Multiple)

ExampleDBBuilder_AddReader_multiple demonstrates combining multiple readers with files

package main

import (
	"context"
	"fmt"
	"log"
	"strings"

	"github.com/nao1215/filesql"
)

func main() {
	// First reader: Users data
	usersCSV := `user_id,name,email
1,Alice,alice@example.com
2,Bob,bob@example.com`

	// Second reader: Orders data
	ordersCSV := `order_id,user_id,amount
101,1,250
102,2,180
103,1,320`

	ctx := context.Background()
	builder := filesql.NewBuilder().
		AddReader(strings.NewReader(usersCSV), "users", filesql.FileTypeCSV).
		AddReader(strings.NewReader(ordersCSV), "orders", filesql.FileTypeCSV).
		SetDefaultChunkSize(2500) // 2500 rows per chunk

	db, err := builder.Open(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Join query across both tables
	rows, err := db.QueryContext(context.Background(), `
		SELECT u.name, SUM(o.amount) as total_spent
		FROM users u
		JOIN orders o ON u.user_id = o.user_id
		GROUP BY u.user_id, u.name
		ORDER BY total_spent DESC
	`)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	fmt.Println("Customer spending:")
	for rows.Next() {
		var name string
		var total float64
		if err := rows.Scan(&name, &total); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("- %s: $%.0f\n", name, total)
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
}
Output:
Customer spending:
- Alice: $570
- Bob: $180

func (*DBBuilder) EnableAutoSave added in v0.1.0

func (b *DBBuilder) EnableAutoSave(outputDir string, options ...DumpOptions) *DBBuilder

EnableAutoSave automatically saves changes when the database is closed.

Parameters:

  • outputDir: Where to save files
  • "" (empty): Overwrite original files
  • "./backup": Save to backup directory

Example:

builder.AddPath("data.csv").
	EnableAutoSave("") // Auto-save to original file on db.Close()

Only the empty string means the original files. A directory named with nothing but whitespace is refused with ErrEmptyPath when the builder opens, since it would be a directory of spaces in the working directory and this package refuses the same string as an input path.

Overwrite mode writes each table back to the file it was loaded from, in that file's own format, compression and line terminator; options is ignored, because all of those are what the file already has. An output directory is an export instead, and writes what options says even when the directory named is the one a source was loaded from. Only those files are written: a table created during the session has no file to be written back to and is left unsaved, so pass an output directory when you want everything in the database on disk. A source this package reads but cannot write back, by its format (JSON, JSONL) or by its compression (bzip2), is refused when the builder opens rather than written as something else.

A workbook is written onto the file it replaces: only the cells whose value changed are rewritten, so formulas, dates, styles and the sheets no table was loaded from stay as they were. Each table goes back to the sheet it was read from, under the name that sheet already had, and a table created during the session becomes a new sheet, unless its name is one a sheet already has that the sheet policy left out, which is refused rather than written over. A sheet the load read and no table remains for, which is what dropping or renaming a table leaves, refuses the save with ErrTableNotFound rather than keeping the rows it had beside the new sheet.

A save of several sources produces all of them before it replaces any, so a save the writer refuses -- a tab in a TSV value, an LTSV table the session emptied -- leaves every source holding the rows it had rather than leaving the caller a directory holding two states of one session. What is left after that is the rename of each finished file over the source it replaces, which the operating system can still refuse: one refused after an earlier one has gone through leaves the sources before it replaced, and the error names the file it would not replace.

The save runs once, when Close returns, so a database with auto-save is as safe to share across goroutines as one without it. A transaction still open at that point stops it: Close reports that the save was skipped rather than writing out rows the caller has neither committed nor rolled back.

A path that is a symbolic link is followed: the file it names receives the rows and the link stays a link. A hard link is not, because a save is staged beside its destination and renamed over it, and a rename replaces the directory entry rather than the file: the path named receives the rows, and every other name for that file keeps the ones it had and becomes a file of its own.

Returns self for chaining.

Example

ExampleDBBuilder_EnableAutoSave demonstrates automatic saving on database close. This feature automatically saves modified data when the database connection is closed, providing a convenient way to persist changes without manual intervention.

package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"
	"time"

	"github.com/nao1215/filesql"
)

func main() {
	// Create temporary directory and test file
	tempDir, _ := os.MkdirTemp("", "filesql-autosave-example")
	defer os.RemoveAll(tempDir)

	// Create sample CSV file
	csvPath := filepath.Join(tempDir, "employees.csv")
	csvContent := "name,department,salary\nAlice,Engineering,80000\nBob,Marketing,65000\n"
	_ = os.WriteFile(csvPath, []byte(csvContent), 0600)

	// Create output directory
	outputDir := filepath.Join(tempDir, "backup")
	_ = os.MkdirAll(outputDir, 0750)

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// Configure builder with auto-save on close
	builder := filesql.NewBuilder().
		AddPath(csvPath).
		EnableAutoSave(outputDir, filesql.NewDumpOptions()) // Save to backup directory on close

	db, _ := builder.Open(ctx)

	// Modify data - this will be automatically saved when db.Close() is called
	_, _ = db.ExecContext(ctx, "INSERT INTO employees (name, department, salary) VALUES ('Charlie', 'Sales', 70000)")
	_, _ = db.ExecContext(ctx, "UPDATE employees SET salary = 85000 WHERE name = 'Alice'")

	// Close database - triggers automatic save to backup directory
	_ = db.Close()

	// Verify the backup file was created and contains our changes
	backupFile := filepath.Join(outputDir, "employees.csv")
	if _, err := os.Stat(backupFile); err == nil {
		fmt.Println("Auto-save completed successfully")
	}

}
Output:
Auto-save completed successfully

func (*DBBuilder) EnableAutoSaveOnCommit added in v0.1.0

func (b *DBBuilder) EnableAutoSaveOnCommit(outputDir string, options ...DumpOptions) *DBBuilder

EnableAutoSaveOnCommit automatically saves changes after each transaction commit, and again when the database is closed.

Use this for real-time persistence. Note: May impact performance.

Example:

builder.AddPath("data.csv").
	EnableAutoSaveOnCommit("./output") // Save after each commit

Saving at close as well is what keeps a statement run outside a transaction from being lost: it is committed as soon as it runs, but no commit hook sees it. This timing therefore saves earlier and more often than EnableAutoSave, never less, and its save at close follows EnableAutoSave's rules.

Returns self for chaining.

Example

ExampleDBBuilder_EnableAutoSaveOnCommit demonstrates automatic saving on transaction commit. This provides more frequent saves but may impact performance for workloads with many commits.

package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"
	"time"

	"github.com/nao1215/filesql"
)

func main() {
	// Create temporary directory and test file
	tempDir, _ := os.MkdirTemp("", "filesql-commit-save-example")
	defer os.RemoveAll(tempDir)

	// Create sample CSV file
	csvPath := filepath.Join(tempDir, "transactions.csv")
	csvContent := "id,amount,status\n1,100.50,pending\n2,250.75,pending\n"
	_ = os.WriteFile(csvPath, []byte(csvContent), 0600)

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// Configure builder with auto-save on commit
	// Using temp directory to keep the example self-contained
	builder := filesql.NewBuilder().
		AddPath(csvPath).
		EnableAutoSaveOnCommit(tempDir, filesql.NewDumpOptions()) // Save to temp directory on each commit

	db, _ := builder.Open(ctx)
	defer func() { _ = db.Close() }()

	// Start transaction
	tx, _ := db.BeginTx(ctx, nil)

	// Process transactions within the transaction
	_, _ = tx.ExecContext(ctx, "UPDATE transactions SET status = 'completed' WHERE id = 1")
	_, _ = tx.ExecContext(ctx, "INSERT INTO transactions (id, amount, status) VALUES (3, 175.25, 'completed')")

	// Commit transaction - triggers automatic save
	_ = tx.Commit()

	fmt.Println("Transaction committed with auto-save")

}
Output:
Transaction committed with auto-save

func (*DBBuilder) LoadInto added in v0.13.0

func (b *DBBuilder) LoadInto(ctx context.Context, db *sql.DB) error

LoadInto loads the builder's configured inputs into an existing database instead of creating a new in-memory one as Open does. Use it to combine file-derived tables with a caller-managed database, such as a long-lived session or a database that already holds other tables, without copying the data through a second database.

Semantics:

  • A table whose name matches a loaded file or sheet is replaced (dropped and recreated), so reloading a file is idempotent and same-named inputs are last-wins. Other tables in db are left untouched.
  • The caller keeps ownership of db. LoadInto never closes it, even on error.
  • Each input is loaded atomically: a file that fails partway leaves the database as it was, including the table it was replacing. Inputs are not atomic with respect to each other, so when the third of three files fails the first two are loaded. Use LoadIntoTx when the whole set has to land or none of it.
  • For an in-memory database, pin the pool to one connection (db.SetMaxOpenConns(1)). SQLite ":memory:" is private per connection, so a multi-connection pool would not share the loaded tables.
  • Several goroutines may load into one database. A load that meets another load's lock waits for it -- five seconds of waiting, half a minute in all -- and then returns the error the database gave. A reader is the exception: it cannot be read a second time, so only the step before the reading is tried again.

Auto-save is not supported because the caller owns the database lifecycle; configuring it returns an error. WithDialect is refused for the same reason when it asks for a translation -- the dialect is a connector wrapping the database Open returns, so it cannot reach one the caller opened. SQLite asks for no translation and is accepted.

Example:

db, _ := sql.Open("sqlite", ":memory:")
db.SetMaxOpenConns(1)
if err := filesql.NewBuilder().AddPath("users.csv").LoadInto(ctx, db); err != nil {
	return err
}
// db now has a "users" table alongside any tables it already had.
Example
package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"
	"strings"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func openExampleSQLiteDB() *sql.DB {
	db, err := sql.Open("sqlite", ":memory:")
	if err != nil {
		log.Fatal(err)
	}
	db.SetMaxOpenConns(1)
	return db
}

func main() {
	db := openExampleSQLiteDB()
	defer db.Close()

	ctx := context.Background()

	if _, err := db.ExecContext(ctx, `CREATE TABLE notes (body TEXT)`); err != nil {
		log.Fatal(err)
	}
	if _, err := db.ExecContext(ctx, `INSERT INTO notes VALUES ('ready')`); err != nil {
		log.Fatal(err)
	}

	builder := filesql.NewBuilder().
		AddReader(strings.NewReader("id,name\n1,Alice\n2,Bob\n"), "users", filesql.FileTypeCSV)

	if err := builder.LoadInto(ctx, db); err != nil {
		log.Fatal(err)
	}

	var users, notes int
	if err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM users`).Scan(&users); err != nil {
		log.Fatal(err)
	}
	if err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM notes`).Scan(&notes); err != nil {
		log.Fatal(err)
	}

	fmt.Printf("users=%d notes=%d\n", users, notes)
}
Output:
users=2 notes=1

func (*DBBuilder) LoadIntoTx added in v0.30.1

func (b *DBBuilder) LoadIntoTx(ctx context.Context, tx *sql.Tx) error

LoadIntoTx loads the builder's inputs into an existing transaction. No transaction is started or committed by this method; the caller owns the transaction and decides whether all changes are committed or rolled back. This is intended for callers that need several files, including table replacement and empty-table creation, to be one atomic operation. Write-back metadata for ACH and Fedwire files is written inside tx, so a rollback discards it along with the tables it describes.

Each input loads under a savepoint, so an input that fails partway is rolled back to where it began: the table it was replacing stands as it was, and nothing of the failed input remains. Begin tx with a context of its own to keep it usable after such a failure, since canceling the context it was begun with ends the whole transaction.

Auto-save is refused, as it is by LoadInto, and so is a WithDialect that asks for a translation: both apply to the database Open returns, and the caller owns this one. SQLite asks for none and is accepted.

Example
package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"
	"strings"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func openExampleSQLiteDB() *sql.DB {
	db, err := sql.Open("sqlite", ":memory:")
	if err != nil {
		log.Fatal(err)
	}
	db.SetMaxOpenConns(1)
	return db
}

func main() {
	db := openExampleSQLiteDB()
	defer db.Close()

	ctx := context.Background()

	builder := filesql.NewBuilder().
		AddReader(strings.NewReader("id,name\n1,Alice\n2,Bob\n"), "users", filesql.FileTypeCSV)

	// The caller owns the transaction: the load lands only on Commit, and a
	// Rollback discards it.
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		log.Fatal(err)
	}
	if err := builder.LoadIntoTx(ctx, tx); err != nil {
		log.Fatal(err)
	}
	if err := tx.Commit(); err != nil {
		log.Fatal(err)
	}

	var users int
	if err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM users`).Scan(&users); err != nil {
		log.Fatal(err)
	}

	fmt.Printf("users=%d\n", users)
}
Output:
users=2

func (*DBBuilder) Open added in v0.1.0

func (b *DBBuilder) Open(ctx context.Context) (*sql.DB, error)

Open creates and returns a database connection using the configured inputs. It validates them first, so it can be called directly on the builder, and it creates an in-memory SQLite database and loads all configured files as tables using streaming.

Table names are derived from file names without extensions: - "users.csv" becomes table "users" - "data.tsv.gz" becomes table "data" - "user-data.csv" becomes table "user_data" (hyphens become underscores) - "my file.csv" becomes table "my_file" (spaces become underscores)

Special characters in file names are automatically sanitized for SQL safety.

The returned database connection supports the full SQLite3 SQL syntax. Auto-save functionality is supported for both file paths and reader inputs. The caller is responsible for closing the connection when done.

Returns a *sql.DB connection or an error if the database cannot be created.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"

	"github.com/nao1215/filesql"
)

func main() {
	// Create temporary CSV file
	tempDir, _ := os.MkdirTemp("", "filesql-example")
	defer os.RemoveAll(tempDir)

	csvFile := filepath.Join(tempDir, "employees.csv")
	content := "id,name,salary\n1,Alice,50000\n2,Bob,60000\n3,Charlie,55000\n"
	os.WriteFile(csvFile, []byte(content), 0644)

	// Complete builder workflow: AddPath -> Build -> Open
	builder := filesql.NewBuilder().AddPath(csvFile)

	ctx := context.Background()

	db, err := builder.Open(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Perform complex SQL query
	rows, err := db.QueryContext(context.Background(), `
		SELECT name, salary,
		       salary - (SELECT AVG(salary) FROM employees) as salary_diff
		FROM employees 
		WHERE salary > (SELECT AVG(salary) FROM employees)
		ORDER BY salary DESC
	`)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	for rows.Next() {
		var name string
		var salary, diff float64
		rows.Scan(&name, &salary, &diff)
		fmt.Printf("%s: $%.0f (+$%.0f above average)\n", name, salary, diff)
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
}
Output:
Bob: $60000 (+$5000 above average)

func (*DBBuilder) OpenReadOnly added in v0.9.0

func (b *DBBuilder) OpenReadOnly(ctx context.Context) (*sql.DB, error)

OpenReadOnly is Open for a caller who means only to read. The database it returns is an ordinary *sql.DB, and every connection it opens carries SQLite's query_only pragma, so a statement that would change the database fails in the engine rather than being turned away by this package.

That makes the refusal complete in a way inspecting the SQL could not be: a write reached through Query rather than Exec, through a prepared statement, or inside a transaction is refused the same way, and the error is the driver's -- SQLite's "attempt to write a readonly database" -- rather than a sentinel of filesql's own. A caller can still lift the restriction on a connection by running "PRAGMA query_only = 0"; the pragma guards against writing by accident, not against a caller who sets out to write.

It composes with the rest of the builder. With WithDialect the returned database still translates queries; with EnableAutoSave a close still writes the tables back out, which for a read-only handle means writing out what was loaded. The caller closes the returned database as they would any other.

Example:

db, err := filesql.NewBuilder().AddPath("payment.ach").OpenReadOnly(ctx)
if err != nil {
	return err
}
defer db.Close()

// Reads work.
rows, err := db.QueryContext(ctx, "SELECT * FROM payment_entries")

// Writes are refused by SQLite.
_, err = db.ExecContext(ctx, "DELETE FROM payment_entries")
Example
package main

import (
	"context"
	"fmt"
	"log"
	"strings"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	ctx := context.Background()

	builder := filesql.NewBuilder().
		AddReader(strings.NewReader("id,name\n1,Alice\n2,Bob\n"), "users", filesql.FileTypeCSV)

	// The result is an ordinary *sql.DB whose connections carry SQLite's
	// query_only pragma, so a write is refused by the engine rather than by
	// this package.
	db, err := builder.OpenReadOnly(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	var rows int
	if err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM users`).Scan(&rows); err != nil {
		log.Fatal(err)
	}

	_, err = db.ExecContext(ctx, `INSERT INTO users VALUES (3, 'Cora')`)
	fmt.Printf("rows=%d write_blocked=%t\n", rows, err != nil)
}
Output:
rows=2 write_blocked=true

func (*DBBuilder) SetDefaultChunkSize added in v0.2.0

func (b *DBBuilder) SetDefaultChunkSize(size int) *DBBuilder

SetDefaultChunkSize sets chunk size (number of rows) for large file processing.

Default: 1000 rows. Adjust based on available memory and processing needs. A size of zero or less is ignored and the current size is kept.

Example:

builder.SetDefaultChunkSize(5000) // 5000 rows per chunk

Returns self for chaining.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"strings"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	builder := filesql.NewBuilder().
		AddReader(strings.NewReader("id,name\n1,Alice\n2,Bob\n3,Cora\n"), "users", filesql.FileTypeCSV).
		SetDefaultChunkSize(2)

	db, err := builder.Open(context.Background())
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	ctx := context.Background()
	var rows int
	if err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM users`).Scan(&rows); err != nil {
		log.Fatal(err)
	}

	fmt.Printf("chunk=2 rows=%d\n", rows)
}
Output:
chunk=2 rows=3

func (*DBBuilder) SkippedRows added in v0.39.0

func (b *DBBuilder) SkippedRows() []SkippedRows

SkippedRows reports what WithMalformedRowPolicy(MalformedRowSkip) discarded during the most recent load, one entry per table that lost rows. A load that dropped nothing is not listed, so a non-empty result is always something worth telling a user about.

Skipping is an instruction from the caller, but an instruction that reports nothing leaves one dropped row and most of the file dropped looking exactly alike — and a write-back afterwards makes either one permanent. The counts are what lets a caller say which of the two happened before that.

A builder used again reports what that load dropped rather than the sum of every load it has run, so the counts stay counts of the file in front of the caller.

It is valid after Open, LoadInto, or LoadIntoTx have run.

Example

ExampleDBBuilder_SkippedRows shows what MalformedRowSkip discarded. The policy is an instruction from the caller, but one dropped row and most of the file dropped look alike without the counts.

package main

import (
	"context"
	"fmt"
	"log"
	"strings"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	csvData := "id,name\n1,Alice\n2\n3,Cora,extra\n4,Dave\n"

	builder := filesql.NewBuilder().
		AddReader(strings.NewReader(csvData), "users", filesql.FileTypeCSV).
		WithMalformedRowPolicy(filesql.MalformedRowSkip)

	db, err := builder.Open(context.Background())
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	for _, skipped := range builder.SkippedRows() {
		fmt.Printf("%s: %d of %d rows skipped\n", skipped.Table, skipped.Count, skipped.Total)
	}
}
Output:
users: 2 of 4 rows skipped

func (*DBBuilder) WithDialect added in v0.19.0

func (b *DBBuilder) WithDialect(d dialect.Dialect) *DBBuilder

WithDialect sets the SQL dialect accepted by the database returned from Open and OpenReadOnly. Queries are translated from the given dialect to SQLite before execution; see the dialect package for the supported translations and their limitations.

Loading data (CSV/TSV/Parquet/... ingestion) always uses SQLite internally regardless of this setting, so only the queries a caller runs are affected. The default is dialect.SQLite, which performs no translation.

Constraints (enforced when the database is opened or loaded):

  • The dialect must be one of the built-in dialects; see dialect.Dialects.
  • A non-SQLite dialect cannot be combined with auto-save; the two connector wrappers are not composed in this version.

Example:

db, err := filesql.NewBuilder().
	AddPath("users.csv").
	WithDialect(dialect.PostgreSQL).
	Open(ctx)
// ... db.Query("SELECT name::text FROM users WHERE name ILIKE 'a%'")

Returns the builder for method chaining.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"strings"

	"github.com/nao1215/filesql"
	"github.com/nao1215/filesql/dialect"

	_ "modernc.org/sqlite"
)

func main() {
	builder := filesql.NewBuilder().
		AddReader(strings.NewReader("id,shipped_at\n1,2024-12-31 09:07:00\n"), "orders", filesql.FileTypeCSV).
		WithDialect(dialect.MySQL)

	db, err := builder.Open(context.Background())
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// MySQL syntax: DATE_FORMAT with the 24-hour time and the ISO week its
	// year belongs to.
	var shipped string
	if err := db.QueryRowContext(context.Background(),
		`SELECT DATE_FORMAT(shipped_at, '%T on week %v of %x') FROM orders`).Scan(&shipped); err != nil {
		log.Fatal(err)
	}

	fmt.Println(shipped)
}
Output:
09:07:00 on week 01 of 2025

func (*DBBuilder) WithExcelSheetPolicy added in v0.32.0

func (b *DBBuilder) WithExcelSheetPolicy(policy ExcelSheetPolicy) *DBBuilder

WithExcelSheetPolicy decides which sheets of an Excel workbook this builder loads. It applies to every source: a path, a directory, an embedded filesystem, a reader, and a compressed workbook alike.

The default is ExcelSheetPolicyAll, which loads every sheet whatever the workbook says about showing it. ExcelSheetPolicyVisibleOnly loads only the sheets the workbook shows, which is what a tool presenting a workbook to someone who did not build it usually wants: a hidden sheet holds the spreadsheet's own working-out, and turning that into a queryable table surprises the reader.

Table names are worked out after the policy has run, so a hidden sheet that would sanitize to the same table as a visible one is not a collision when it is not loaded.

Example:

builder.AddPath("book.xlsx").WithExcelSheetPolicy(filesql.ExcelSheetPolicyVisibleOnly)

Returns self for chaining.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"

	"github.com/nao1215/filesql"
	"github.com/xuri/excelize/v2"

	_ "modernc.org/sqlite"
)

// exampleTempDir is a directory of its own for an example to write into, so
// that no example touches a path another program may already be using.
func exampleTempDir() string {
	dir, err := os.MkdirTemp("", "filesql-api-example")
	if err != nil {
		log.Fatal(err)
	}
	return dir
}

// exampleWorkbook writes a workbook holding one shown sheet and one hidden
// sheet, and returns its path.
func exampleWorkbook(dir string) string {
	f := excelize.NewFile()
	defer func() { _ = f.Close() }()

	for _, sheet := range []string{"Sales", "Scratch"} {
		if sheet != "Sheet1" {
			if _, err := f.NewSheet(sheet); err != nil {
				log.Fatal(err)
			}
		}
		if err := f.SetCellValue(sheet, "A1", "region"); err != nil {
			log.Fatal(err)
		}
		if err := f.SetCellValue(sheet, "A2", sheet); err != nil {
			log.Fatal(err)
		}
	}
	if err := f.DeleteSheet("Sheet1"); err != nil {
		log.Fatal(err)
	}
	if err := f.SetSheetVisible("Scratch", false); err != nil {
		log.Fatal(err)
	}

	path := filepath.Join(dir, "book.xlsx")
	if err := f.SaveAs(path); err != nil {
		log.Fatal(err)
	}
	return path
}

func main() {
	dir := exampleTempDir()
	defer os.RemoveAll(dir)

	path := exampleWorkbook(dir)

	builder := filesql.NewBuilder().
		AddPath(path).
		WithExcelSheetPolicy(filesql.ExcelSheetPolicyVisibleOnly)

	db, err := builder.Open(context.Background())
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	rows, err := db.QueryContext(context.Background(),
		`SELECT name FROM sqlite_master WHERE type='table' ORDER BY name`)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	for rows.Next() {
		var name string
		if err := rows.Scan(&name); err != nil {
			log.Fatal(err)
		}
		fmt.Println(name)
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
}
Output:
book_Sales

func (*DBBuilder) WithLogger added in v0.10.0

func (b *DBBuilder) WithLogger(logger *slog.Logger) *DBBuilder

WithLogger sets the logger this package reports its progress to: which files it collected, which table each one became, how many rows landed, and what failed. Nothing is logged by default.

The logger is a *slog.Logger, so where the records go and which levels are kept are decided by the handler the caller builds, as they are everywhere else slog is used. A nil logger leaves the current one in place.

Example:

logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}))
builder.WithLogger(logger)

Returns self for chaining.

Example
package main

import (
	"bytes"
	"context"
	"fmt"
	"log"
	"log/slog"
	"strings"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	ctx := context.Background()

	// A *slog.Logger is what the builder takes, so where the records go and
	// which levels are kept are the handler's business. This one drops the
	// timestamp so the example's output is stable.
	var buf bytes.Buffer
	logger := slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{
		Level: slog.LevelInfo,
		ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
			if attr.Key == slog.TimeKey {
				return slog.Attr{}
			}
			return attr
		},
	}))

	builder := filesql.NewBuilder().
		WithLogger(logger).
		AddReader(strings.NewReader("id,name\n1,Alice\n"), "users", filesql.FileTypeCSV)

	db, err := builder.Open(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	lines := strings.Split(strings.TrimSpace(buf.String()), "\n")
	fmt.Println(lines[0])
	fmt.Println(lines[len(lines)-1])
}
Output:
level=INFO msg="build completed" collected_paths=0 readers=1
level=INFO msg="database opened successfully"

func (*DBBuilder) WithMalformedRowPolicy added in v0.17.0

func (b *DBBuilder) WithMalformedRowPolicy(policy MalformedRowPolicy) *DBBuilder

WithMalformedRowPolicy sets how a CSV/TSV record whose field count differs from the header is handled during import.

The default is MalformedRowStop, which aborts the import with an error so a corrupt or misaligned file is not imported as partial or empty data. Use MalformedRowSkip to drop ragged rows and keep the well-formed ones, or MalformedRowFill to keep every short row by padding it with empty strings. A long row is refused whichever of the two is chosen, because truncating it would discard a cell the file holds without saying so.

The policy reaches delimited text alone. A workbook's rows are checked by the XLSX reader itself, which refuses one wider than its header whatever this is set to; LTSV pads a missing label; and Parquet and JSON/JSONL carry no per-row field count to disagree about.

Example:

builder.WithMalformedRowPolicy(filesql.MalformedRowSkip)

Returns self for chaining.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"strings"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	csvData := "id,name\n1,Alice\n2\n3,Cora,extra\n4,Dave\n"

	builder := filesql.NewBuilder().
		AddReader(strings.NewReader(csvData), "users", filesql.FileTypeCSV).
		WithMalformedRowPolicy(filesql.MalformedRowSkip)

	db, err := builder.Open(context.Background())
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	ctx := context.Background()
	var rows int
	if err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM users`).Scan(&rows); err != nil {
		log.Fatal(err)
	}

	fmt.Printf("loaded rows=%d\n", rows)
}
Output:
loaded rows=2

type DumpOptions added in v0.0.4

type DumpOptions struct {
	// Format specifies the output file format
	Format OutputFormat
	// Compression specifies the compression type
	Compression CompressionType
	// Encoding specifies the text encoding of csv, tsv, and ltsv output. It has
	// no effect on Parquet and XLSX, which carry their own.
	Encoding Encoding
	// LineEnding specifies the line terminator of csv, tsv, and ltsv output. It
	// has no effect on Parquet and XLSX, which are not line-based.
	LineEnding LineEnding
}

DumpOptions configures how database tables are exported to files.

Example:

options := NewDumpOptions().
	WithFormat(OutputFormatTSV).
	WithCompression(CompressionGZ)

err := DumpDatabase(ctx, db, "./output", options)

func NewDumpOptions added in v0.0.4

func NewDumpOptions() DumpOptions

NewDumpOptions creates default export options (CSV, no compression).

Modify with WithFormat, WithCompression, WithEncoding and WithLineEnding, each of which names the values it takes.

Example
package main

import (
	"fmt"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	opts := filesql.NewDumpOptions()
	fmt.Printf("%s %q\n", opts.Format, opts.FileExtension())
}
Output:
csv ".csv"

func (DumpOptions) FileExtension added in v0.2.0

func (o DumpOptions) FileExtension() string

FileExtension returns the complete file extension including compression

Example
package main

import (
	"fmt"

	"github.com/nao1215/filesql"
)

func main() {
	// Show how file extensions are built
	examples := []struct {
		format      filesql.OutputFormat
		compression filesql.CompressionType
	}{
		{filesql.OutputFormatCSV, filesql.CompressionNone},
		{filesql.OutputFormatTSV, filesql.CompressionGZ},
		{filesql.OutputFormatLTSV, filesql.CompressionBZ2},
		{filesql.OutputFormatCSV, filesql.CompressionXZ},
		{filesql.OutputFormatTSV, filesql.CompressionZSTD},
	}

	for _, ex := range examples {
		options := filesql.DumpOptions{
			Format:      ex.format,
			Compression: ex.compression,
		}
		fmt.Printf("Format: %-4s, Compression: %-4s -> Extension: %s\n",
			ex.format.String(),
			ex.compression.String(),
			options.FileExtension())
	}

}
Output:
Format: csv , Compression: none -> Extension: .csv
Format: tsv , Compression: gz   -> Extension: .tsv.gz
Format: ltsv, Compression: bz2  -> Extension: .ltsv.bz2
Format: csv , Compression: xz   -> Extension: .csv.xz
Format: tsv , Compression: zstd -> Extension: .tsv.zst

func (DumpOptions) WithCompression added in v0.2.0

func (o DumpOptions) WithCompression(compression CompressionType) DumpOptions

WithCompression adds compression to output files.

Options:

  • CompressionNone: No compression (default)
  • CompressionGZ: Gzip compression (.gz)
  • CompressionBZ2: Bzip2 compression (.bz2) - read only, so a save asked for it is refused with ErrUnsupportedFormat
  • CompressionXZ: XZ compression (.xz)
  • CompressionZSTD: Zstandard compression (.zst)
  • CompressionZLIB: Zlib compression (.z)
  • CompressionSNAPPY: Snappy compression (.snappy)
  • CompressionS2: S2 compression (.s2) - Snappy compatible
  • CompressionLZ4: LZ4 compression (.lz4)
Example
package main

import (
	"fmt"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	opts := filesql.NewDumpOptions().WithCompression(filesql.CompressionGZ)
	fmt.Println(opts.FileExtension())
}
Output:
.csv.gz

func (DumpOptions) WithEncoding added in v0.38.0

func (o DumpOptions) WithEncoding(enc Encoding) DumpOptions

WithEncoding sets the text encoding of csv, tsv, and ltsv output.

It exists so a caller that decoded a legacy source before loading can write one back: without it every save produced UTF-8, so an in-place save changed the file's encoding on disk and the caller's next read of the same file returned mojibake.

filesql reads UTF-8 only, so a file written in another encoding is for other tools rather than for loading back.

A value the encoding cannot write fails the save with ErrEncoding, naming the encoding, rather than being replaced — a substitution is the silent corruption the read side already refuses. ISO-2022-JP also refuses an escape, U+001B, which it reads as the start of a character-set designator: written as data it changes what the rest of the file says. Parquet and XLSX carry their own encoding and are unaffected.

Options:

  • EncodingUTF8: UTF-8 (default)
  • EncodingShiftJIS: Shift-JIS (CP932)
  • EncodingEUCJP: EUC-JP
  • EncodingISO2022JP: ISO-2022-JP
  • EncodingUTF16LE: UTF-16 little-endian, with a byte-order mark
  • EncodingUTF16BE: UTF-16 big-endian, with a byte-order mark
Example
package main

import (
	"fmt"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	// Output is UTF-8 unless asked otherwise. A value the encoding cannot write
	// fails the save rather than being replaced.
	opts := filesql.NewDumpOptions().WithEncoding(filesql.EncodingShiftJIS)
	fmt.Println(opts.Encoding)
}
Output:
shift-jis

func (DumpOptions) WithFormat added in v0.2.0

func (o DumpOptions) WithFormat(format OutputFormat) DumpOptions

WithFormat sets the output file format.

Options:

  • OutputFormatCSV: Comma-separated values
  • OutputFormatTSV: Tab-separated values
  • OutputFormatLTSV: Labeled tab-separated values
  • OutputFormatParquet: Apache Parquet columnar format
  • OutputFormatXLSX: Excel workbook

OutputFormatACH and OutputFormatFedWire are not among them: a dump writes those two for the tables loaded from such a file and refuses a request to write any other table as one.

Example
package main

import (
	"fmt"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	opts := filesql.NewDumpOptions().WithFormat(filesql.OutputFormatTSV)
	fmt.Println(opts.FileExtension())
}
Output:
.tsv

func (DumpOptions) WithLineEnding added in v0.44.0

func (o DumpOptions) WithLineEnding(lineEnding LineEnding) DumpOptions

WithLineEnding sets the line terminator of csv, tsv, and ltsv output.

It exists for the same reason WithEncoding does: a save wrote "\n" whatever the source used, so a CRLF file saved in place came back LF throughout — every line of the file changed although the caller had edited one row. Writing back in place, which is EnableAutoSave with an empty output directory, detects the file's own terminator and keeps it. Every other save is an export and writes what it is told, including one aimed at the directory a source came from, so this option is how an export is asked for CRLF.

Options:

  • LineEndingLF: "\n" (default)
  • LineEndingCRLF: "\r\n"

Parquet and XLSX are not line-based and are unaffected.

Example
package main

import (
	"fmt"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	// Output ends its records with "\n" unless asked otherwise. A save that
	// overwrites a file it loaded from a path keeps that file's own terminator
	// without being told.
	opts := filesql.NewDumpOptions().WithLineEnding(filesql.LineEndingCRLF)
	fmt.Println(opts.LineEnding)
}
Output:
crlf

type Encoding added in v0.38.0

type Encoding int

Encoding is the text encoding a save writes its output in.

A load reads UTF-8, and UTF-16 through the byte-order mark a save writes; Shift-JIS, EUC-JP and ISO-2022-JP are refused on load, so a file written in one of those is for other tools. Without a write side at all, a caller that decoded a legacy source before loading had no way to get one back, so an in-place save changed the file's encoding on disk without saying so. Compression is the same shape of decision and has had an option since the beginning; this is the one for text.

const (
	// EncodingUTF8 writes UTF-8, which is what a save wrote before this option
	// existed and remains the default.
	EncodingUTF8 Encoding = iota
	// EncodingShiftJIS writes Shift-JIS (CP932).
	EncodingShiftJIS
	// EncodingEUCJP writes EUC-JP.
	EncodingEUCJP
	// EncodingISO2022JP writes ISO-2022-JP.
	EncodingISO2022JP
	// EncodingUTF16LE writes little-endian UTF-16 with a byte-order mark.
	EncodingUTF16LE
	// EncodingUTF16BE writes big-endian UTF-16 with a byte-order mark.
	EncodingUTF16BE
)

func (Encoding) String added in v0.38.0

func (e Encoding) String() string

String returns the name a user types for the encoding.

Example
package main

import (
	"fmt"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	fmt.Println(filesql.EncodingUTF8, filesql.EncodingShiftJIS, filesql.EncodingEUCJP)
}
Output:
utf-8 shift-jis euc-jp

type ExcelSheet added in v0.32.0

type ExcelSheet struct {
	// Name is the sheet name as the workbook stores it, before any sanitizing a
	// caller applies to turn it into a table name.
	Name string
	// Visible is false for a sheet the workbook does not show, whether it is
	// hidden or very hidden.
	Visible bool
}

ExcelSheet is one sheet of a workbook and whether the workbook shows it.

func ExcelSheetsInFile added in v0.32.0

func ExcelSheetsInFile(path string) (sheets []ExcelSheet, err error)

ExcelSheetsInFile reports the sheets of the workbook at path, in the order the workbook stores them, and whether it shows each one. The path may carry a compression suffix, exactly as it may for a load.

It is exported for a caller that has to explain a load rather than only perform one: which sheets the file holds, and which of them a policy left behind. Answering that by reopening the file with a spreadsheet library would be a second implementation of the rule filesql itself applies, free to drift from it.

Example
package main

import (
	"fmt"
	"log"
	"os"
	"path/filepath"

	"github.com/nao1215/filesql"
	"github.com/xuri/excelize/v2"

	_ "modernc.org/sqlite"
)

// exampleTempDir is a directory of its own for an example to write into, so
// that no example touches a path another program may already be using.
func exampleTempDir() string {
	dir, err := os.MkdirTemp("", "filesql-api-example")
	if err != nil {
		log.Fatal(err)
	}
	return dir
}

// exampleWorkbook writes a workbook holding one shown sheet and one hidden
// sheet, and returns its path.
func exampleWorkbook(dir string) string {
	f := excelize.NewFile()
	defer func() { _ = f.Close() }()

	for _, sheet := range []string{"Sales", "Scratch"} {
		if sheet != "Sheet1" {
			if _, err := f.NewSheet(sheet); err != nil {
				log.Fatal(err)
			}
		}
		if err := f.SetCellValue(sheet, "A1", "region"); err != nil {
			log.Fatal(err)
		}
		if err := f.SetCellValue(sheet, "A2", sheet); err != nil {
			log.Fatal(err)
		}
	}
	if err := f.DeleteSheet("Sheet1"); err != nil {
		log.Fatal(err)
	}
	if err := f.SetSheetVisible("Scratch", false); err != nil {
		log.Fatal(err)
	}

	path := filepath.Join(dir, "book.xlsx")
	if err := f.SaveAs(path); err != nil {
		log.Fatal(err)
	}
	return path
}

func main() {
	dir := exampleTempDir()
	defer os.RemoveAll(dir)

	path := exampleWorkbook(dir)

	sheets, err := filesql.ExcelSheetsInFile(path)
	if err != nil {
		log.Fatal(err)
	}
	for _, sheet := range sheets {
		fmt.Printf("%s visible=%t\n", sheet.Name, sheet.Visible)
	}
}
Output:
Sales visible=true
Scratch visible=false

func ExcelSheetsInReader added in v0.32.0

func ExcelSheetsInReader(source io.Reader) (sheets []ExcelSheet, err error)

ExcelSheetsInReader is ExcelSheetsInFile for a workbook that has no path. The reader must yield the workbook's own bytes; a codec around them has to be unwrapped first, as it has no name to be detected from.

Example

ExampleExcelSheetsInReader is ExampleExcelSheetsInFile for a workbook that arrived as bytes rather than as a file.

package main

import (
	"bytes"
	"fmt"
	"log"
	"os"
	"path/filepath"

	"github.com/nao1215/filesql"
	"github.com/xuri/excelize/v2"

	_ "modernc.org/sqlite"
)

// exampleTempDir is a directory of its own for an example to write into, so
// that no example touches a path another program may already be using.
func exampleTempDir() string {
	dir, err := os.MkdirTemp("", "filesql-api-example")
	if err != nil {
		log.Fatal(err)
	}
	return dir
}

// exampleWorkbook writes a workbook holding one shown sheet and one hidden
// sheet, and returns its path.
func exampleWorkbook(dir string) string {
	f := excelize.NewFile()
	defer func() { _ = f.Close() }()

	for _, sheet := range []string{"Sales", "Scratch"} {
		if sheet != "Sheet1" {
			if _, err := f.NewSheet(sheet); err != nil {
				log.Fatal(err)
			}
		}
		if err := f.SetCellValue(sheet, "A1", "region"); err != nil {
			log.Fatal(err)
		}
		if err := f.SetCellValue(sheet, "A2", sheet); err != nil {
			log.Fatal(err)
		}
	}
	if err := f.DeleteSheet("Sheet1"); err != nil {
		log.Fatal(err)
	}
	if err := f.SetSheetVisible("Scratch", false); err != nil {
		log.Fatal(err)
	}

	path := filepath.Join(dir, "book.xlsx")
	if err := f.SaveAs(path); err != nil {
		log.Fatal(err)
	}
	return path
}

func main() {
	dir := exampleTempDir()
	defer os.RemoveAll(dir)

	path := exampleWorkbook(dir)

	// A workbook a caller holds in memory, downloaded or embedded rather than
	// read from disk. The reader must yield the workbook itself: a codec around
	// it has no name to be detected from.
	body, err := os.ReadFile(path) //nolint:gosec // path built by this example
	if err != nil {
		log.Fatal(err)
	}

	sheets, err := filesql.ExcelSheetsInReader(bytes.NewReader(body))
	if err != nil {
		log.Fatal(err)
	}
	for _, sheet := range sheets {
		fmt.Printf("%s visible=%t\n", sheet.Name, sheet.Visible)
	}
}
Output:
Sales visible=true
Scratch visible=false

type ExcelSheetPolicy added in v0.32.0

type ExcelSheetPolicy int

ExcelSheetPolicy decides which sheets of a workbook a load reads.

A workbook can hide a sheet, and hiding one is how a spreadsheet keeps scratch calculations, lookup tables and stale drafts out of the way of the sheets it means to present. Whether those belong in a database is the caller's judgment rather than something this package can decide, so which sheets to take is a setting and not a rule.

const (
	// ExcelSheetPolicyAll loads every sheet of a workbook, hidden or not. It is
	// the zero value, so a caller that names no policy keeps the behavior
	// filesql had before the setting existed.
	ExcelSheetPolicyAll ExcelSheetPolicy = iota

	// ExcelSheetPolicyVisibleOnly loads only the sheets a workbook shows.
	// Hidden and very hidden sheets are both left out: a workbook tells the two
	// apart, but a caller asking for what it presents means neither.
	ExcelSheetPolicyVisibleOnly
)

func (ExcelSheetPolicy) String added in v0.55.0

func (p ExcelSheetPolicy) String() string

String names the policy.

Example
package main

import (
	"fmt"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	fmt.Println(filesql.ExcelSheetPolicyAll)
	fmt.Println(filesql.ExcelSheetPolicyVisibleOnly)
}
Output:
all
visible-only

type FileType added in v0.2.0

type FileType int

FileType names an input format. It says nothing about compression: a gzipped CSV and a plain CSV are both FileTypeCSV, and the codec wrapping a stream is stated separately with WithCompression.

const (
	// FileTypeCSV represents CSV file type
	FileTypeCSV FileType = iota
	// FileTypeTSV represents TSV file type
	FileTypeTSV
	// FileTypeLTSV represents LTSV file type
	FileTypeLTSV
	// FileTypeParquet represents Parquet file type
	FileTypeParquet
	// FileTypeXLSX represents Excel XLSX file type
	FileTypeXLSX
	// FileTypeJSON represents JSON file type
	FileTypeJSON
	// FileTypeJSONL represents JSON Lines file type
	FileTypeJSONL
	// FileTypeACH represents ACH (NACHA) file type
	FileTypeACH
	// FileTypeFedWire represents Fedwire file type
	FileTypeFedWire

	// FileTypeUnsupported represents unsupported file type
	FileTypeUnsupported
)

func (FileType) String added in v0.6.0

func (ft FileType) String() string

String returns a human-readable string representation of the FileType.

Example
package main

import (
	"fmt"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	fmt.Println(filesql.FileTypeCSV, filesql.FileTypeLTSV, filesql.FileTypeParquet)
}
Output:
CSV LTSV Parquet

type LineEnding added in v0.44.0

type LineEnding int

LineEnding is the line terminator a save writes its records with.

A save already keeps a source's compression and its text encoding, but wrote every record with "\n" whatever the file used. A CRLF file saved in place came back LF throughout: every line of the file changed while the caller had edited one row, so the file no longer matched what a CRLF-expecting reader — or a repository configured for CRLF — had before. This is that decision made explicit, and an in-place save makes it from the file itself.

const (
	// LineEndingLF writes "\n", which is what a save wrote before this option
	// existed and remains the default.
	LineEndingLF LineEnding = iota
	// LineEndingCRLF writes "\r\n".
	LineEndingCRLF
)

func (LineEnding) String added in v0.44.0

func (l LineEnding) String() string

String returns the name a user types for the line ending.

Example
package main

import (
	"fmt"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	fmt.Println(filesql.LineEndingLF, filesql.LineEndingCRLF)
}
Output:
lf crlf

type MalformedRowPolicy added in v0.17.0

type MalformedRowPolicy int

MalformedRowPolicy controls how a record that does not fit the columns of its table is handled during import: a delimited (CSV/TSV) record whose field count differs from the header row, or an LTSV record holding a field that is not a label and a value.

A workbook's rows are checked by the XLSX reader instead, which pads a short one and refuses one wider than its header whatever this policy says, and Parquet and JSON/JSONL carry nothing per row to disagree about.

What LTSV settles itself is the missing half of the question: a record naming only some of the columns is padded, since LTSV writes its labels on every record and leaving one out is how the format says a value is absent. A field with no label is the other half, and it is this policy's: the field is data the table has no column for, so the record carrying it is one the policy decides about.

const (
	// MalformedRowStop aborts the import with an error on the first record whose
	// field count differs from the header. It is the default because a ragged
	// row usually signals a corrupt or misaligned file, and silently dropping or
	// reshaping data would hide the problem.
	MalformedRowStop MalformedRowPolicy = iota

	// MalformedRowSkip discards any record whose field count differs from the
	// header and imports the remaining well-formed records.
	MalformedRowSkip

	// MalformedRowFill keeps every short record by padding it with empty strings.
	// A long record is rejected so source data is never silently discarded --
	// filling is for a record that is missing values, and a record carrying more
	// than the header names is not that.
	MalformedRowFill
)

func (MalformedRowPolicy) String added in v0.17.0

func (p MalformedRowPolicy) String() string

String returns the lowercase name of the policy, matching the values accepted on the command line.

Example
package main

import (
	"fmt"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	fmt.Println(filesql.MalformedRowStop)
	fmt.Println(filesql.MalformedRowSkip)
	fmt.Println(filesql.MalformedRowFill)
}
Output:
stop
skip
fill

type OutputFormat added in v0.0.4

type OutputFormat int

OutputFormat represents the output file format

const (
	// OutputFormatCSV represents CSV output format
	OutputFormatCSV OutputFormat = iota
	// OutputFormatTSV represents TSV output format
	OutputFormatTSV
	// OutputFormatLTSV represents LTSV output format
	OutputFormatLTSV
	// OutputFormatParquet represents Parquet output format
	OutputFormatParquet
	// OutputFormatXLSX represents Excel XLSX output format
	OutputFormatXLSX
	// OutputFormatACH represents ACH (NACHA) output format
	OutputFormatACH
	// OutputFormatFedWire represents Fedwire output format
	OutputFormatFedWire
)

func (OutputFormat) Extension added in v0.2.0

func (f OutputFormat) Extension() string

Extension returns the file extension for the format.

A format this enumeration has no name for has no extension of its own, and a dump refuses before the path is used either way.

Example
package main

import (
	"fmt"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	fmt.Println(filesql.OutputFormatParquet.Extension())
}
Output:
.parquet

func (OutputFormat) String added in v0.2.0

func (f OutputFormat) String() string

String returns the string representation of OutputFormat.

A value this enumeration has no name for says so. It named CSV, so a refusal read "unsupported output format: csv" and sent the caller looking for a fault in a format this package writes every day.

Example
package main

import (
	"fmt"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	fmt.Println(filesql.OutputFormatCSV, filesql.OutputFormatTSV, filesql.OutputFormatXLSX)
}
Output:
csv tsv xlsx

type ParseError added in v0.33.0

type ParseError struct {
	// Source is the input that failed: a file path, or the table name of a
	// reader input, which is all a reader has to be known by.
	Source string
	// Err is what went wrong reading it.
	Err error
}

ParseError is a failure reading one input, with the input named.

Both this package and its callers want to say which file failed, and both used to. Loading one bad file produced "filesql: parsing failed: failed to stream file rm.csv: filesql: column count mismatch: row 1 has 2 fields, want 3" — two framing verbs for one event, this package's name twice — and a caller that had already named the file added a third mention of it, because there was no way to reach the cause on its own.

So the framing is a type instead of more text. Error names the source once for a caller that loaded several inputs at once and cannot otherwise tell which one failed; a caller that loads one file at a time reads Err and says the path itself.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func createFilesqlExampleDir(files map[string]string) string {
	dir, err := os.MkdirTemp("", "filesql-api-example")
	if err != nil {
		log.Fatal(err)
	}
	for name, body := range files {
		path := filepath.Join(dir, name)
		if err := os.MkdirAll(filepath.Dir(path), 0750); err != nil {
			log.Fatal(err)
		}
		if err := os.WriteFile(path, []byte(strings.TrimLeft(body, "\n")), 0600); err != nil {
			log.Fatal(err)
		}
	}
	return dir
}

func main() {
	dir := createFilesqlExampleDir(map[string]string{
		"users.csv":  "id,name\n1,alice\n",
		"orders.csv": "id,total\n1,980,extra\n",
	})
	defer os.RemoveAll(dir)

	_, err := filesql.Open(context.Background(),
		filepath.Join(dir, "users.csv"), filepath.Join(dir, "orders.csv"))
	if err == nil {
		log.Fatal("the second file should have failed to load")
	}

	// A load of several inputs says which one failed, and the cause is
	// reachable on its own for a caller that has already named the file.
	var parseErr *filesql.ParseError
	if !errors.As(err, &parseErr) {
		log.Fatalf("want a *filesql.ParseError, got %T", err)
	}

	fmt.Println(filepath.Base(parseErr.Source))
	fmt.Println(errors.Is(err, filesql.ErrParsing))
	fmt.Println(errors.Is(err, filesql.ErrColumnMismatch))
}
Output:
orders.csv
true
true

func (*ParseError) Error added in v0.33.0

func (e *ParseError) Error() string

func (*ParseError) Unwrap added in v0.33.0

func (e *ParseError) Unwrap() []error

Unwrap reports the cause and ErrParsing together, so errors.Is still finds the sentinel the message used to spell out and errors.As still reaches the cause.

type ReaderOption added in v0.30.0

type ReaderOption func(*readerInput)

ReaderOption configures one reader added with AddReader.

It is the place per-source settings go. A reader has no path, so anything a file's name would have answered — which codec wraps it — has to be stated, and stating it here keeps AddReader's ordinary three-argument call unchanged.

func WithCompression added in v0.30.0

func WithCompression(compression CompressionType) ReaderOption

WithCompression declares the codec wrapping a reader passed to AddReader.

Example:

gz, err := os.Open("users.csv.gz")
if err != nil {
	return err
}
defer gz.Close()

builder.AddReader(gz, "users", filesql.FileTypeCSV, filesql.WithCompression(filesql.CompressionGZ))
Example
package main

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"log"

	"github.com/nao1215/filesql"

	_ "modernc.org/sqlite"
)

func main() {
	var compressed bytes.Buffer
	writer, err := filesql.CompressionGZ.NewWriter(&compressed)
	if err != nil {
		log.Fatal(err)
	}
	if _, err := io.WriteString(writer, "id,total\n1,980\n2,1200\n"); err != nil {
		log.Fatal(err)
	}
	if err := writer.Close(); err != nil {
		log.Fatal(err)
	}

	// A reader carries no file name, so the codec wrapping it is declared.
	// A path does carry one, and AddPath reads the codec from it.
	ctx := context.Background()
	db, err := filesql.NewBuilder().
		AddReader(bytes.NewReader(compressed.Bytes()), "orders", filesql.FileTypeCSV,
			filesql.WithCompression(filesql.CompressionGZ)).
		Open(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	var total int
	if err := db.QueryRowContext(ctx, `SELECT SUM(total) FROM orders`).Scan(&total); err != nil {
		log.Fatal(err)
	}

	fmt.Println(total)
}
Output:
2180

type SkippedRows added in v0.39.0

type SkippedRows struct {
	// Table is the table the rows would have gone into.
	Table string
	// Count is how many data rows were dropped.
	Count int
	// Total is how many data rows the input held, dropped ones included, so a
	// caller can say "2 of 4" rather than a bare number.
	Total int
}

SkippedRows is how much of one table's input the malformed-row policy discarded.

Directories

Path Synopsis
Package dialect translates SQL written in a non-SQLite dialect (MySQL, PostgreSQL, or GoogleSQL) into SQLite SQL so it can run against the SQLite engine that backs filesql.
Package dialect translates SQL written in a non-SQLite dialect (MySQL, PostgreSQL, or GoogleSQL) into SQLite SQL so it can run against the SQLite engine that backs filesql.
internal/ast
Package ast is the typed syntax tree the parser builds and the lowering layer rewrites.
Package ast is the typed syntax tree the parser builds and the lowering layer rewrites.
internal/dialects
Package dialects holds the SQL dialect identifier.
Package dialects holds the SQL dialect identifier.
internal/lower
Package lower turns a syntax tree written in a source dialect into one that means the same thing to SQLite.
Package lower turns a syntax tree written in a source dialect into one that means the same thing to SQLite.
internal/parser
Package parser builds a typed syntax tree from SQL text.
Package parser builds a typed syntax tree from SQL text.
internal/render
Package render writes a syntax tree back as SQLite SQL.
Package render writes a syntax tree back as SQLite SQL.
internal/runtime
Package runtime holds the scalar functions this module registers with the SQLite driver, for the semantics SQL alone cannot express: a division that answers what MySQL answers, a cast that converts the way PostgreSQL converts, a date part BigQuery names.
Package runtime holds the scalar functions this module registers with the SQLite driver, for the semantics SQL alone cannot express: a division that answers what MySQL answers, a cast that converts the way PostgreSQL converts, a date part BigQuery names.
internal/sqlerr
Package sqlerr holds the sentinel errors the translation pipeline returns and the diagnostic that carries a source position with them.
Package sqlerr holds the sentinel errors the translation pipeline returns and the diagnostic that carries a source position with them.
internal/token
Package token turns SQL source text into tokens.
Package token turns SQL source text into tokens.
examples
ent module
internal
atomicwrite
Package atomicwrite stages a file's new contents beside it and puts them in place only once the whole write has succeeded.
Package atomicwrite stages a file's new contents beside it and puts them in place only once the whole write has succeeded.
codec
Package codec wraps a stream in the compression the source uses.
Package codec wraps a stream in the compression the source uses.
infer
Package infer decides what type a column of text values can be stored as.
Package infer decides what type a column of text values can be stored as.
parser
Package parser provides file parsing functionality for various tabular data formats.
Package parser provides file parsing functionality for various tabular data formats.
parser/ach
Package ach provides bidirectional conversion between ACH files and TableData.
Package ach provides bidirectional conversion between ACH files and TableData.
parser/wire
Package wire provides bidirectional conversion between Fedwire files and TableData.
Package wire provides bidirectional conversion between Fedwire files and TableData.
reader
Package reader turns a file of a supported format into the rows of a table.
Package reader turns a file of a supported format into the rows of a table.
textin
Package textin reads a text source the one way this module reads one: a leading byte-order mark decides the encoding, and what follows has to be UTF-8.
Package textin reads a text source the one way this module reads one: a leading byte-order mark decides the encoding, and what follows has to be UTF-8.
writer
Package writer turns a table's records into the bytes of a text format.
Package writer turns a table's records into the bytes of a text format.
Package prep provides preprocessing and validation for the file formats filesql reads: CSV, TSV, LTSV, JSON, JSONL, Parquet and Excel.
Package prep provides preprocessing and validation for the file formats filesql reads: CSV, TSV, LTSV, JSON, JSONL, Parquet and Excel.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL