filesql

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2025 License: MIT Imports: 6 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

Go Reference Go Report Card MultiPlatformUnitTest Coverage

日本語 | Русский | 中文 | 한국어 | Español | Français

filesql is a Go SQL driver that enables you to query CSV, TSV, and LTSV files using SQLite3 SQL syntax. Query your data files directly without any imports or transformations!

🎯 Why filesql?

This library was born from the experience of maintaining two separate CLI tools - sqly and sqluv. Both tools shared a common feature: executing SQL queries against CSV, TSV, and other file formats.

Rather than maintaining duplicate code across both projects, we extracted the core functionality into this reusable SQL driver. Now, any Go developer can leverage this capability in their own applications!

✨ Features

  • 🔍 SQLite3 SQL Interface - Use SQLite3's powerful SQL dialect to query your files
  • 📁 Multiple File Formats - Support for CSV, TSV, and LTSV files
  • 🗜️ Compression Support - Automatically handles .gz, .bz2, .xz, and .zst compressed files
  • 🚀 Zero Setup - No database server required, everything runs in-memory
  • 🌍 Cross-Platform - Works seamlessly on Linux, macOS, and Windows
  • 💾 SQLite3 Powered - Built on the robust SQLite3 engine for reliable SQL processing

📋 Supported File Formats

Extension Format Description
.csv CSV Comma-separated values
.tsv TSV Tab-separated values
.ltsv LTSV Labeled Tab-separated Values
.csv.gz, .tsv.gz, .ltsv.gz Gzip compressed Gzip compressed files
.csv.bz2, .tsv.bz2, .ltsv.bz2 Bzip2 compressed Bzip2 compressed files
.csv.xz, .tsv.xz, .ltsv.xz XZ compressed XZ compressed files
.csv.zst, .tsv.zst, .ltsv.zst Zstandard compressed Zstandard compressed files

📦 Installation

go get github.com/nao1215/filesql

🚀 Quick Start

Example codes is here.

Basic Usage
package main

import (
    "context"
    "fmt"
    "log"
    "time"
    
    "github.com/nao1215/filesql"
)

func main() {
    // Open a CSV file as a database with context
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()
    
    db, err := filesql.OpenContext(ctx, "data.csv")
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()
    
    // Execute SQL query (table name is derived from filename without extension)
    rows, err := db.QueryContext(ctx, "SELECT * FROM data WHERE age > 25 ORDER BY name")
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()
    
    // Process results
    for rows.Next() {
        var name string
        var age int
        if err := rows.Scan(&name, &age); err != nil {
            log.Fatal(err)
        }
        fmt.Printf("Name: %s, Age: %d\n", name, age)
    }
}
Opening with Context Support
// Open files with timeout control
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

db, err := filesql.OpenContext(ctx, "large_dataset.csv")
if err != nil {
    log.Fatal(err)
}
defer db.Close()

// Query with context for cancellation support
rows, err := db.QueryContext(ctx, "SELECT * FROM large_dataset WHERE status = 'active'")
Opening Multiple Files
// Open multiple files in a single database
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

db, err := filesql.OpenContext(ctx, "users.csv", "orders.tsv", "products.ltsv")
if err != nil {
    log.Fatal(err)
}
defer db.Close()

// Join data across different file formats!
rows, err := db.QueryContext(ctx, `
    SELECT u.name, o.order_date, p.product_name
    FROM users u
    JOIN orders o ON u.id = o.user_id
    JOIN products p ON o.product_id = p.id
    WHERE o.order_date > '2024-01-01'
`)
Working with Directories
// Open all supported files in a directory (recursive)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

db, err := filesql.OpenContext(ctx, "/path/to/data/directory")
if err != nil {
    log.Fatal(err)
}
defer db.Close()

// Query all loaded tables
rows, err := db.QueryContext(ctx, "SELECT name FROM sqlite_master WHERE type='table'")
Compressed Files Support
// Automatically handles compressed files
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

db, err := filesql.OpenContext(ctx, "large_dataset.csv.gz", "archive.tsv.bz2")
if err != nil {
    log.Fatal(err)
}
defer db.Close()

// Query compressed data seamlessly
rows, err := db.QueryContext(ctx, "SELECT COUNT(*) FROM large_dataset")
Table Naming Rules

filesql automatically derives table names from file paths:

// Table naming examples:
// "users.csv"           -> table name: "users"
// "data.tsv"            -> table name: "data"
// "logs.ltsv"           -> table name: "logs"
// "archive.csv.gz"      -> table name: "archive"
// "backup.tsv.bz2"      -> table name: "backup"
// "/path/to/sales.csv"  -> table name: "sales"

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

db, err := filesql.OpenContext(ctx, "employees.csv", "departments.tsv.gz")
if err != nil {
    log.Fatal(err)
}

// Use the derived table names in queries
rows, err := db.QueryContext(ctx, `
    SELECT * FROM employees 
    JOIN departments ON employees.dept_id = departments.id
`)

⚠️ Important Notes

SQL Syntax

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

  • Functions (e.g., date(), substr(), json_extract())
  • Window functions
  • Common Table Expressions (CTEs)
  • And much more!
Data Modifications
  • INSERT, UPDATE, and DELETE operations only affect the in-memory database
  • Original files remain unchanged - filesql never modifies your source files
  • This makes it safe to experiment with data transformations
Advanced SQL Features

Since filesql uses SQLite3, you can leverage its full power:

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

db, err := filesql.OpenContext(ctx, "employees.csv", "departments.csv")
if err != nil {
    log.Fatal(err)
}
defer db.Close()

// Use window functions, CTEs, and complex queries
query := `
    WITH dept_stats AS (
        SELECT 
            department_id,
            AVG(salary) as avg_salary,
            COUNT(*) as emp_count
        FROM employees
        GROUP BY department_id
    )
    SELECT 
        e.name,
        e.salary,
        d.name as department,
        ds.avg_salary as dept_avg,
        RANK() OVER (PARTITION BY e.department_id ORDER BY e.salary DESC) as rank
    FROM employees e
    JOIN departments d ON e.department_id = d.id
    JOIN dept_stats ds ON e.department_id = ds.department_id
    WHERE e.salary > ds.avg_salary * 0.8
`

rows, err := db.QueryContext(ctx, query)
Exporting Modified Data

If you need to persist changes made to the in-memory database:

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

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

// Make modifications
_, err = db.ExecContext(ctx, "UPDATE data SET status = 'processed' WHERE status = 'pending'")
if err != nil {
    log.Fatal(err)
}

// Export the modified data to a new directory
err = filesql.DumpDatabase(db, "/path/to/output/directory")
if err != nil {
    log.Fatal(err)
}

💖 Support

If you find this project useful, please consider:

  • ⭐ Giving it a star on GitHub - it helps others discover the project
  • 💝 Becoming a sponsor - your support keeps the project alive and motivates continued development

Your support, whether through stars, sponsorships, or contributions, is what drives this project forward. Thank you!

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package filesql provides file-based SQL driver implementation. It enables reading CSV, TSV, and LTSV files as SQL databases.

Index

Examples

Constants

View Source
const (
	// DriverName is the name for the filesql driver
	DriverName = "filesql"
)

Variables

This section is empty.

Functions

func DumpDatabase

func DumpDatabase(db *sql.DB, outputDir string) error

DumpDatabase is a helper function to dump a database to a directory.

Note: filesql uses SQLite3 internally as an in-memory database. Any modifications made through UPDATE, DELETE, or INSERT operations are not persisted to the original files. If you need to persist changes, use DumpDatabase to export the modified data as CSV files.

func Open

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

Open opens a database connection using the filesql driver.

The filesql driver uses SQLite3 as an in-memory database engine to provide SQL capabilities for structured text files. This allows you to query CSV, TSV, LTSV files and their compressed variants using standard SQL syntax.

Supported file formats:

  • CSV files (.csv)
  • TSV files (.tsv)
  • LTSV files (.ltsv)
  • Compressed versions of above (.gz, .bz2, .xz, .zst)

The paths parameter can be a mix of:

  • Individual files (CSV, TSV, LTSV, or their compressed versions)
  • Directories (all supported files within will be loaded recursively)

Each file will be loaded as a separate table in the database with the table name derived from the filename (without extension).

Important constraints:

  • INSERT, UPDATE, and DELETE operations are applied only to the in-memory database
  • Original input files are never modified by these operations
  • To persist changes, use the DumpDatabase function to export modified data

Example usage:

// Open a single CSV file
db, err := filesql.Open("data/users.csv")
if err != nil {
	log.Fatal(err)
}
defer db.Close()

// Complex query with JOINs, aggregation, and window functions
rows, err := db.Query(`
	SELECT
		u.name,
		u.department,
		u.salary,
		AVG(u.salary) OVER (PARTITION BY u.department) as dept_avg_salary,
		RANK() OVER (PARTITION BY u.department ORDER BY u.salary DESC) as salary_rank,
		COUNT(*) OVER (PARTITION BY u.department) as dept_size
	FROM users u
	WHERE u.salary > (
		SELECT AVG(salary) * 0.8
		FROM users
		WHERE department = u.department
	)
	ORDER BY u.department, u.salary DESC
`)
if err != nil {
	log.Fatal(err)
}
defer rows.Close()

// Process results
for rows.Next() {
	var name, dept string
	var salary, deptAvg float64
	var rank, deptSize int
	if err := rows.Scan(&name, &dept, &salary, &deptAvg, &rank, &deptSize); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s (%s): $%.2f (Rank: %d/%d, Dept Avg: $%.2f)\n",
		name, dept, salary, rank, deptSize, deptAvg)
}
Example

ExampleOpen demonstrates how to use filesql.Open() 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(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), 0644)
	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), 0644)
	if err != nil {
		log.Fatal(err)
	}

	return tmpDir
}
Output:
Employee Analysis Report:
========================
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 (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), 0644)
	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), 0644)
	if err != nil {
		log.Fatal(err)
	}

	return tmpDir
}

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

	db, err := filesql.Open(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(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 (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), 0644)
	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), 0644)
	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(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)
	}

}
Output:
Available tables:
- departments
- employees

func OpenContext added in v0.0.2

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

OpenContext opens a database connection using the filesql driver with context support.

The filesql driver uses SQLite3 as an in-memory database engine to provide SQL capabilities for structured text files. This allows you to query CSV, TSV, LTSV files and their compressed variants using standard SQL syntax.

Supported file formats:

  • CSV files (.csv)
  • TSV files (.tsv)
  • LTSV files (.ltsv)
  • Compressed versions of above (.gz, .bz2, .xz, .zst)

The paths parameter can be a mix of:

  • Individual files (CSV, TSV, LTSV, or their compressed versions)
  • Directories (all supported files within will be loaded recursively)

Each file will be loaded as a separate table in the database with the table name derived from the filename (without extension).

Important constraints:

  • INSERT, UPDATE, and DELETE operations are applied only to the in-memory database
  • Original input files are never modified by these operations
  • To persist changes, use the DumpDatabase function to export modified data

Example usage:

// Open a single CSV file with timeout
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
db, err := filesql.OpenContext(ctx, "data/users.csv")
if err != nil {
	log.Fatal(err)
}
defer db.Close()

// Complex query with JOINs, aggregation, and window functions
rows, err := db.QueryContext(ctx, `
	SELECT
		u.name,
		u.department,
		u.salary,
		AVG(u.salary) OVER (PARTITION BY u.department) as dept_avg_salary,
		RANK() OVER (PARTITION BY u.department ORDER BY u.salary DESC) as salary_rank,
		COUNT(*) OVER (PARTITION BY u.department) as dept_size
	FROM users u
	WHERE u.salary > (
		SELECT AVG(salary) * 0.8
		FROM users
		WHERE department = u.department
	)
	ORDER BY u.department, u.salary DESC
`)
if err != nil {
	log.Fatal(err)
}
defer rows.Close()

// Process results
for rows.Next() {
	var name, dept string
	var salary, deptAvg float64
	var rank, deptSize int
	if err := rows.Scan(&name, &dept, &salary, &deptAvg, &rank, &deptSize); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s (%s): $%.2f (Rank: %d/%d, Dept Avg: $%.2f)\n",
		name, dept, salary, rank, deptSize, deptAvg)
}
Example

ExampleOpenContext demonstrates opening files with context support for timeout and cancellation

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), 0644)
	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), 0644)
	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.OpenContext(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)
	}

}
Output:
High earners (>$70,000):
- Alice Johnson: $95000
- Bob Smith: $85000
- Charlie Brown: $80000
- David Wilson: $75000

func Register

func Register()

Register registers the filesql driver with database/sql

Types

This section is empty.

Directories

Path Synopsis
domain
model
Package model provides domain model for filesql
Package model provides domain model for filesql
Package driver provides file SQL driver implementation.
Package driver provides file SQL driver implementation.
examples
ent module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL