prep

package
v0.53.0 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2026 License: MIT Imports: 26 Imported by: 0 modules, 0 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.

Documentation

Overview

Package prep re-exports parser types for backward compatibility.

Package prep provides preprocessing and validation for file formats supported by filesql (CSV, TSV, LTSV, JSON, JSONL, Parquet, Excel with gzip, bzip2, xz, zstd support).

prep complements filesql by providing data preprocessing before loading into SQLite. It uses struct tags for validation ("validate" tag) and preprocessing ("prep" tag).

Basic Usage

type Record struct {
    Name  string `prep:"trim" validate:"required"`
    Email string `prep:"trim,lowercase" validate:"email"`
    Age   int    `validate:"gte=0,lte=150"`
}

file, _ := os.Open("data.csv")
defer file.Close()

var records []Record
processor := prep.NewProcessor(prep.FileTypeCSV)
reader, result, err := processor.Process(file, &records)
if err != nil {
    log.Fatal(err)
}

// reader can be passed directly to filesql
// result.Errors contains validation errors with row/column information
// result.RowCount and result.ValidRowCount provide processing statistics

Streaming Output with ProcessToWriter

For large datasets, ProcessToWriter writes preprocessed output directly to an io.Writer, avoiding the output buffer allocation:

var buf bytes.Buffer
result, err := processor.ProcessToWriter(file, &records, &buf)

Memory Usage

prep holds the whole input in memory, so its peak scales with the size of the file rather than staying flat the way filesql's own chunked loading does. Three things are live at once: the parsed rows, one element of the struct slice per row, and, for Process, the buffer the preprocessed output is built in. ProcessToWriter removes the third of those and not the first two, since the struct slice is what the caller asked for and the rows are what a second pass over them needs.

That is the design rather than an oversight: preprocessing and validation are separate passes over the same rows, and the row a validator reports on has to be somewhere when it does. A file large enough for this to matter is better loaded with filesql, which reads it in chunks, and validated afterwards with SQL over the loaded table.

Format-specific limitations:

  • XLSX: Only the first sheet is processed
  • LTSV: Maximum line size is 10MB
  • JSON/JSONL: Data has a single "data" column containing raw JSON strings

A struct may cover a subset of the columns. A field naming a column the input does not have is refused with ErrUnknownColumn, since a zero-filled field cannot be told apart from a cell that is really empty; give such a field prep:"default=..." if it is meant to work without a column.

Supported File Formats

prep supports the same formats as filesql:

  • CSV (.csv)
  • TSV (.tsv)
  • LTSV (.ltsv)
  • JSON (.json)
  • JSONL (.jsonl)
  • Parquet (.parquet)
  • Excel (.xlsx)

All formats support compression:

  • gzip (.gz)
  • bzip2 (.bz2)
  • xz (.xz)
  • zstd (.zst)
  • zlib (.z)
  • snappy (.snappy)
  • s2 (.s2)
  • lz4 (.lz4)

Prep Tags

The "prep" tag specifies preprocessing operations applied before validation. A comma separates one tag from the next, so a tag's own parameters are separated by a colon rather than a comma:

  • trim, ltrim, rtrim: remove whitespace from both ends, the left, the right
  • collapse_space: replace each run of whitespace with one space
  • strip_newline: remove carriage returns and line feeds
  • strip_html: remove HTML tags
  • lowercase, uppercase: fold case
  • normalize_unicode: normalize to NFC
  • default=value: use value when the cell is empty
  • nullify=value: read value as an empty cell
  • prefix=value, suffix=value: add value at the front or the back
  • replace=old:new: replace every occurrence of old
  • regex_replace=pattern:replacement: replace every match of pattern
  • truncate=N: keep the first N characters
  • pad_left=N:char, pad_right=N:char: pad to N characters, with char or a space
  • trim_set=chars: remove any of chars from both ends
  • keep_digits, keep_alpha: keep only digits, or only letters
  • remove_digits, remove_alpha: remove digits, or letters
  • coerce=int|float|bool: normalize the written form of a number or a boolean. It rewrites how the value is written and not what it says, so a spelling the loader keeps as text -- a leading zero, a literal past int64, Go's own number syntax, a decimal a float64 cannot hold -- is left alone
  • fix_scheme=scheme: add scheme:// to a URL that has no scheme

A tag that needs a parameter and is given none is an invalid tag argument: WithStrictTagParsing reports it, and without that option it is ignored.

Validate Tags

The "validate" tag specifies validation rules (following the go-playground/validator dialect):

  • required: Field must not be empty
  • email: Must be a valid email address
  • url: Must be a valid URL
  • And many more...

A field tagged validate:"-" is validated by nothing, as in the dialect. Its prep tag still runs.

An empty value passes every validator except required and the required family: an empty cell is how CSV spells a missing value, so a column is optional unless one of those tags says otherwise. This is where the dialect is deliberately left — that library fails most validators on an empty value. The rule reaches the cross-field comparisons too, on either side: a comparison is skipped as soon as one of the two cells is empty, since a value has no order against a value that is not there. The required family — required_if, required_unless, required_with, required_with_all, required_without and required_without_all — is the exception: each of those tags runs on an empty cell and reports it when its condition holds, since deciding whether an empty cell is allowed is what they are for. The excluded family runs on every row for the same reason, but reads the rule the other way: it only ever reports a cell that carries a value.

The comparison tags follow the field they land on, as the dialect defines them: on a string field, eq and ne compare the string itself and gt, gte, lt, lte, min and max compare the character count, while on any other field all of them compare the numeric value and len means the value equals the parameter. Two numbers that both spell integers are compared as integers, so a pair past the point where a float64 stops spelling every integer exactly is ordered rather than rounded onto one number; anything else is compared as a float64. The cross-field tags eqfield, nefield, gtfield, gtefield, ltfield and ltefield follow the field the same way, except that on a string field they order the strings rather than measure them, so ltfield says a date range runs forwards. That is the second place this package leaves the dialect, which compares string lengths there and so cannot express a date range at all. required_if and required_unless take field and value pairs, as many as the tag names, and a value holding a space is written in single quotes: required_if=Kind paid Tier 'gold member' asks for a value only when both cells match, while required_unless=Kind paid Tier gold asks for one unless either cell matches. required_with and its three siblings take a list of field names instead: required_with fires when any of them carries a value and required_with_all when all of them do, while required_without fires when any of them is empty and required_without_all when all of them are.

excluded_if, excluded_unless, excluded_with, excluded_with_all, excluded_without and excluded_without_all negate that family: each names the condition under which the cell must be empty, and reads its parameter the way the required tag it mirrors does. excluded_if=Kind free forbids a value when every pair matches, excluded_unless=Kind paid Tier gold forbids one unless either pair matches, excluded_with=Email forbids one when any named field carries a value and excluded_without=Email when any of them is empty, with the _all spellings asking for every named field rather than any.

boolean accepts what strconv.ParseBool accepts, which is also how a bool struct field is filled. numeric accepts an optionally signed decimal and number accepts digits alone, as the dialect defines them. The dialect spells the letters-and-digits tag alphanum; alphanumeric names the same validator, because this package answered only to that spelling before.

Some validators are deliberately stricter or wider than the dialect. uri requires a scheme and something after it, so neither a relative reference such as /a/b nor a bare http:// is a URI. fqdn, hostname and hostname_rfc1123 all refuse a label ending in a hyphen, which none of the dialect's three patterns does, and all three cap a label at 63 characters and a whole name at 253, as the RFCs do and as the dialect's patterns do not. hostname reads RFC 952, so a one-character label such as a is a hostname, which the dialect's pattern refuses, and every label must begin with a letter, so 2.example is not one. ulid requires a timestamp the format can hold. uuid3 requires the variant nibble that uuid4 and uuid5 require, and all three accept upper case, as uuid does; the uuid_rfc4122, uuid3_rfc4122, uuid4_rfc4122 and uuid5_rfc4122 spellings name the same four checks, so uuid3_rfc4122 requires the variant nibble too, where the dialect leaves it unconstrained. dns_rfc1035_label is the dialect's reading of an RFC 1035 label -- a lowercase letter, then lowercase letters, digits and hyphens, not ending in a hyphen -- capped at 63 characters, which is the RFC's own limit on a label and which the dialect's pattern leaves out. The RFC's grammar admits upper case and DNS compares labels without regard to it; the lowercase reading is the dialect's and is also what Kubernetes enforces on resource names, which is where such columns come from, so a column holding mixed case wants prep:"lowercase" before this tag. iscolor passes when hexcolor, rgb, rgba, hsl or hsla does, as the dialect's alias defines it. hostname_port takes a bracketed IPv6 address and refuses a bare port. ip, ipv4 and ipv6 are the dialect's spellings of ip_addr, ip4_addr and ip6_addr and build the same checks, so an IPv4-mapped address such as ::ffff:192.0.2.1 satisfies ipv4 and not ipv6. port is defined on a numeric field in the dialect; on a cell it is ASCII digits alone naming a port from 1 to 65535, so 0080 is port 80 while +80 and 0x50 are not ports.

e164 takes the number with or without the leading plus, since the plus is a notation prefix rather than part of the number and a spreadsheet export strips it, where the dialect requires it; the first digit must be 1 through 9, so +0123456789, which the dialect accepts, is not an E.164 number.

json accepts any JSON value, so a bare number is one. timezone names an IANA zone that time.LoadLocation loads, and Local is refused in every casing, since it names the host's own zone rather than a fixed one. semver is Semantic Versioning 2.0.0, so 1.2.3 is a version and v1.2.3 is not. base32, base64, base64url and base64rawurl check the RFC 4648 alphabet before decoding, because Go's decoders skip carriage returns and line feeds, which would otherwise let a value carrying a newline through. They then decode strictly, so a value whose trailing pad bits are not zero is refused although the dialect's patterns accept it: RFC 4648 lets a decoder reject one, and no conformant encoder produces one. oneofci is oneof compared without regard to case, and reads its candidates the same way, single quotes included.

credit_card, luhn_checksum, isbn, isbn10, isbn13 and issn verify a check digit as well as a shape, which is the whole point of them: a mistyped identifier still looks plausible and only the check digit says otherwise. credit_card groups its digits with single spaces, as the dialect does, so a number written with hyphens is a column for prep:"keep_digits" first; luhn_checksum takes the digits alone; isbn10 and isbn13 remove hyphens and spaces themselves, at most as many as the width is printed with, so a value carrying more of them is not an ISBN however its digits read; and issn requires the hyphen the standard prints. md5, sha256, sha384 and sha512 are lowercase hexadecimal of exactly 32, 64, 96 and 128 characters, so an uppercase spelling is refused.

iso3166_1_alpha2, iso3166_1_alpha3 and iso3166_1_alpha_numeric look a cell up in the officially assigned ISO 3166-1 codes, and country_code passes when any of the three does. iso4217 and iso4217_numeric look it up in the active ISO 4217 currency codes, alphabetic and numeric. Every lookup is exact, as it is in the dialect, so JP is a country code and jp is not, and a numeric code keeps the leading zeros the standard prints, so 032 is Argentina, 008 is the lek, and 32 and 8 are nothing. The user-assigned range is not included, so XK, widely used for Kosovo and never assigned, is not a country code here.

unique means something different here than it does in the dialect, and deliberately: there it describes one slice, array or map field, and a row here is a flat struct, so it is read as uniqueness of a column across the rows of one processing run. The first occurrence of a value is valid and every later one is reported, naming the value and the row it first appeared on. An empty cell never counts as a duplicate, since an empty cell is a missing value and two of them are two absences rather than two equal values. The comparison is exact string equality on the value preprocessing produced, so prep:"trim,lowercase" beside it gives case-insensitive deduplication without unique needing options of its own. The seen values are held for the length of one Process call and no longer, so two calls never see each other's rows; memory grows with the number of distinct values in the column.

Importing prep embeds the IANA time zone database through time/tzdata, which the timezone tag needs on a platform that ships none, and which costs a few hundred KB of binary size. filesql itself does not import prep.

See https://pkg.go.dev/github.com/nao1215/filesql/prep for the complete list of supported validators.

Example
package main

import (
	"fmt"
	"io"
	"strings"

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

// User represents a user record with preprocessing and validation
type User struct {
	Name  string `prep:"trim" validate:"required"`
	Email string `prep:"trim,lowercase" validate:"required"`
	Age   string
}

func main() {
	// Sample CSV data with whitespace that needs trimming
	csvData := `name,email,age
  John Doe  ,JOHN@EXAMPLE.COM,30
Jane Smith,jane@example.com,25
`

	// Create a processor for CSV files
	processor := prep.NewProcessor(prep.FileTypeCSV)

	// Prepare a slice to hold the parsed records
	var users []User

	// Process the data
	reader, result, err := processor.Process(strings.NewReader(csvData), &users)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	// Print processing results
	fmt.Printf("Processed %d rows, %d valid\n", result.RowCount, result.ValidRowCount)

	// Print parsed records (with preprocessing applied)
	for i, user := range users {
		fmt.Printf("User %d: Name=%q, Email=%q\n", i+1, user.Name, user.Email)
	}

	// The reader can be passed to filesql
	// For demonstration, we just read and show the preprocessed output
	output, err := io.ReadAll(reader)
	if err != nil {
		fmt.Printf("Error reading output: %v\n", err)
		return
	}
	fmt.Printf("Output for filesql:\n%s", output)

}
Output:
Processed 2 rows, 2 valid
User 1: Name="John Doe", Email="john@example.com"
User 2: Name="Jane Smith", Email="jane@example.com"
Output for filesql:
name,email,age
John Doe,john@example.com,30
Jane Smith,jane@example.com,25
Example (ComplexPrepAndValidation)

Example_complexPrepAndValidation demonstrates comprehensive preprocessing and validation using multiple prep tags and validation rules for realistic data processing scenarios.

package main

import (
	"fmt"
	"io"
	"strings"

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

func readAllExampleOutput(reader io.Reader) ([]byte, error) {
	return io.ReadAll(reader)
}

func main() {
	// Product represents a product record with comprehensive preprocessing and validation
	type Product struct {
		// Name: trim whitespace, require non-empty
		Name string `prep:"trim" validate:"required"`
		// SKU: trim, uppercase, require non-empty and alphanumeric
		SKU string `prep:"trim,uppercase" validate:"required,alphanumeric"`
		// Price: trim, set default if empty, validate as a decimal (numeric
		// accepts an optionally signed decimal; number would be digits only)
		Price string `prep:"trim,default=0.00" validate:"numeric"`
		// Quantity: trim, coerce to int, validate as digits only
		Quantity string `prep:"trim,coerce=int" validate:"number"`
		// Category: trim, lowercase, collapse multiple spaces
		Category string `prep:"trim,lowercase,collapse_space"`
		// Description: trim, strip HTML, truncate to 200 chars
		Description string `prep:"trim,strip_html,truncate=200"`
		// URL: trim, fix scheme (add https:// if missing)
		URL string `prep:"trim,fix_scheme=https"`
		// Tags: trim, replace semicolons with commas
		Tags string `prep:"trim,replace=;:,"`
	}

	// Sample CSV with various data quality issues
	csvData := `name,sku,price,quantity,category,description,url,tags
  Widget Pro  ,ABC123,19.99,100,  Electronics   ,<p>A <b>great</b> product!</p>,example.com/widget,tag1;tag2;tag3
 Gadget Plus ,DEF456,29.99,50,  home  goods  ,Simple description,https://example.com/gadget,electronics;sale
  ,ABC@#$,not_a_number,5,test,desc,url,tags
`

	processor := prep.NewProcessor(prep.FileTypeCSV)
	var products []Product

	reader, result, err := processor.Process(strings.NewReader(csvData), &products)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	// Show processing summary
	fmt.Printf("Processing Summary:\n")
	fmt.Printf("  Total rows: %d\n", result.RowCount)
	fmt.Printf("  Valid rows: %d\n", result.ValidRowCount)
	fmt.Printf("  Invalid rows: %d\n", result.InvalidRowCount())

	// Show validation errors
	if result.HasErrors() {
		fmt.Printf("\nValidation Errors:\n")
		for _, ve := range result.ValidationErrors() {
			fmt.Printf("  Row %d, Field %q: %s\n", ve.Row, ve.Field, ve.Message)
		}
	}

	// Show preprocessed records
	fmt.Printf("\nPreprocessed Records:\n")
	for i, p := range products {
		if p.Name != "" { // Skip invalid rows for display
			fmt.Printf("  [%d] Name=%q, SKU=%q, Price=%q, Category=%q\n",
				i+1, p.Name, p.SKU, p.Price, p.Category)
		}
	}

	// Show that URL scheme was fixed
	fmt.Printf("\nURL Examples (scheme fixed):\n")
	for i, p := range products {
		if p.URL != "" && p.Name != "" {
			fmt.Printf("  [%d] %s\n", i+1, p.URL)
		}
	}

	// The reader can be used with filesql
	if _, err := readAllExampleOutput(reader); err != nil {
		fmt.Printf("Error reading output: %v\n", err)
		return
	}

}
Output:
Processing Summary:
  Total rows: 3
  Valid rows: 2
  Invalid rows: 1

Validation Errors:
  Row 3, Field "Name": value is required
  Row 3, Field "SKU": value must contain only alphanumeric characters
  Row 3, Field "Price": value must be numeric

Preprocessed Records:
  [1] Name="Widget Pro", SKU="ABC123", Price="19.99", Category="electronics"
  [2] Name="Gadget Plus", SKU="DEF456", Price="29.99", Category="home goods"

URL Examples (scheme fixed):
  [1] https://example.com/widget
  [2] https://example.com/gadget
Example (CrossFieldValidation)

Example_crossFieldValidation demonstrates validation rules that compare values between different fields, such as password confirmation matching.

package main

import (
	"fmt"
	"strings"

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

func main() {
	// UserForm represents a user registration form with cross-field validation
	type UserForm struct {
		Username        string `prep:"trim,lowercase" validate:"required"`
		Password        string `validate:"required"`
		ConfirmPassword string `validate:"required,eqfield=Password"`
	}

	csvData := `username,password,confirm_password
  Alice  ,secret123,secret123
Bob,password1,wrongpass
`

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

	_, result, err := processor.Process(strings.NewReader(csvData), &users)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	fmt.Printf("Valid: %d/%d\n", result.ValidRowCount, result.RowCount)

	if result.HasErrors() {
		fmt.Printf("Errors:\n")
		for _, ve := range result.ValidationErrors() {
			fmt.Printf("  Row %d, Field %q: %s\n", ve.Row, ve.Field, ve.Message)
		}
	}

}
Output:
Valid: 1/2
Errors:
  Row 2, Field "ConfirmPassword": value must equal field Password
Example (DetailedErrorReporting)

Example_detailedErrorReporting demonstrates precise error information including row number, column name, and specific validation failure reason.

package main

import (
	"fmt"
	"strings"

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

func main() {
	// Order represents an order with strict validation rules. A comparison
	// follows the field it lands on: gt, gte and lte compare the number of a
	// numeric field and the character count of a string one, so the amount,
	// quantity and price are declared numeric. The third row leaves ship_date
	// empty, and an empty cell passes every validator but required, so its
	// gtfield is not reported.
	type Order struct {
		OrderID    string  `name:"order_id" validate:"required,uuid4"`
		CustomerID string  `name:"customer_id" validate:"required,numeric"`
		Email      string  `validate:"required,email"`
		Amount     float64 `validate:"required,numeric,gt=0,lte=10000"`
		Currency   string  `validate:"required,len=3,uppercase"`
		Country    string  `validate:"required,alpha,len=2"`
		OrderDate  string  `name:"order_date" validate:"required,datetime=2006-01-02"`
		ShipDate   string  `name:"ship_date" validate:"datetime=2006-01-02,gtfield=OrderDate"`
		IPAddress  string  `name:"ip_address" validate:"required,ip_addr"`
		PromoCode  string  `name:"promo_code" validate:"alphanumeric"`
		Quantity   int     `validate:"required,numeric,gte=1,lte=100"`
		UnitPrice  float64 `name:"unit_price" validate:"required,numeric,gt=0"`
		TotalCheck string  `name:"total_check" validate:"required,eqfield=Amount"`
	}

	// CSV with multiple validation errors
	csvData := `order_id,customer_id,email,amount,currency,country,order_date,ship_date,ip_address,promo_code,quantity,unit_price,total_check
550e8400-e29b-41d4-a716-446655440000,12345,alice@example.com,500.00,USD,US,2024-01-15,2024-01-20,192.168.1.1,SAVE10,2,250.00,500.00
invalid-uuid,abc,not-an-email,-100,US,USA,2024/01/15,2024-01-10,999.999.999.999,PROMO-CODE-TOO-LONG!!,0,0,999
550e8400-e29b-41d4-a716-446655440001,,bob@test,50000,EURO,J1,not-a-date,,2001:db8::1,VALID20,101,-50,50000
123e4567-e89b-42d3-a456-426614174000,99999,charlie@company.com,1500.50,JPY,JP,2024-02-28,2024-02-25,10.0.0.1,VIP,5,300.10,1500.50
`

	processor := prep.NewProcessor(prep.FileTypeCSV)
	var orders []Order

	_, result, err := processor.Process(strings.NewReader(csvData), &orders)
	if err != nil {
		fmt.Printf("Fatal error: %v\n", err)
		return
	}

	fmt.Printf("=== Validation Report ===\n")
	fmt.Printf("Total rows:     %d\n", result.RowCount)
	fmt.Printf("Valid rows:     %d\n", result.ValidRowCount)
	fmt.Printf("Invalid rows:   %d\n", result.RowCount-result.ValidRowCount)
	fmt.Printf("Total errors:   %d\n\n", len(result.ValidationErrors()))

	if result.HasErrors() {
		fmt.Println("=== Error Details ===")
		for _, e := range result.ValidationErrors() {
			fmt.Printf("Row %d, Column '%s': %s\n", e.Row, e.Column, e.Message)
		}
	}

}
Output:
=== Validation Report ===
Total rows:     4
Valid rows:     1
Invalid rows:   3
Total errors:   22

=== Error Details ===
Row 2, Column 'order_id': value must be a valid UUID version 4
Row 2, Column 'customer_id': value must be numeric
Row 2, Column 'email': value must be a valid email address
Row 2, Column 'amount': value must be greater than 0
Row 2, Column 'currency': value must have exactly 3 characters
Row 2, Column 'country': value must have exactly 2 characters
Row 2, Column 'order_date': value must be a valid datetime in format: 2006-01-02
Row 2, Column 'ip_address': value must be a valid IP address
Row 2, Column 'promo_code': value must contain only alphanumeric characters
Row 2, Column 'quantity': value must be greater than or equal to 1
Row 2, Column 'unit_price': value must be greater than 0
Row 2, Column 'ship_date': value must be greater than field OrderDate
Row 2, Column 'total_check': value must equal field Amount
Row 3, Column 'customer_id': value is required
Row 3, Column 'email': value must be a valid email address
Row 3, Column 'amount': value must be less than or equal to 10000
Row 3, Column 'currency': value must have exactly 3 characters
Row 3, Column 'country': value must contain only alphabetic characters
Row 3, Column 'order_date': value must be a valid datetime in format: 2006-01-02
Row 3, Column 'quantity': value must be less than or equal to 100
Row 3, Column 'unit_price': value must be greater than 0
Row 4, Column 'ship_date': value must be greater than field OrderDate
Example (EmployeePreprocessing)

Example_employeePreprocessing demonstrates the full power of fileprep: combining multiple preprocessors and validators to clean and validate real-world messy data.

package main

import (
	"fmt"
	"strings"

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

func main() {
	// Employee represents employee data with comprehensive preprocessing and validation
	type Employee struct {
		// ID: pad to 6 digits, must be numeric
		EmployeeID string `name:"id" prep:"trim,pad_left=6:0" validate:"required,numeric,len=6"`
		// Name: clean whitespace, required alphabetic with spaces
		FullName string `name:"name" prep:"trim,collapse_space" validate:"required,alphaspace"`
		// Email: normalize to lowercase, validate format
		Email string `prep:"trim,lowercase" validate:"required,email"`
		// Department: normalize case, must be one of allowed values
		Department string `prep:"trim,uppercase" validate:"required,oneof=ENGINEERING SALES MARKETING HR"`
		// Salary: keep only digits, validate range. Declared numeric so that
		// gte and lte compare the amount; on a string field they would count
		// characters.
		Salary int `prep:"trim,keep_digits" validate:"required,numeric,gte=30000,lte=500000"`
		// Phone: extract digits, validate E.164 format after adding country code
		Phone string `prep:"trim,keep_digits,prefix=+1" validate:"e164"`
		// Start date: validate datetime format
		StartDate string `name:"start_date" prep:"trim" validate:"required,datetime=2006-01-02"`
		// Manager ID: required only if department is not HR
		ManagerID string `name:"manager_id" prep:"trim,pad_left=6:0" validate:"required_unless=Department HR"`
		// Website: fix missing scheme, validate URL. The column is optional:
		// an empty value passes every validator except required.
		Website string `prep:"trim,lowercase,fix_scheme=https" validate:"url"`
	}

	// Messy real-world CSV data
	csvData := `id,name,email,department,salary,phone,start_date,manager_id,website
42,  John   Doe  ,JOHN.DOE@COMPANY.COM,engineering,75000,5551234567,2023-01-15,1,company.com/john
7,Jane Smith,jane@COMPANY.com,  Sales  ,120000,5559876543,2022-06-01,2,WWW.LINKEDIN.COM/in/jane
123,Bob Wilson,bob.wilson@company.com,HR,45000,5551112222,2024-03-20,,
99,Alice Brown,alice@company.com,Marketing,88500,5554443333,2023-09-10,3,https://alice.dev
`

	processor := prep.NewProcessor(prep.FileTypeCSV)
	var employees []Employee

	_, result, err := processor.Process(strings.NewReader(csvData), &employees)
	if err != nil {
		fmt.Printf("Fatal error: %v\n", err)
		return
	}

	fmt.Printf("=== Processing Result ===\n")
	fmt.Printf("Total rows: %d, Valid rows: %d\n\n", result.RowCount, result.ValidRowCount)

	for i, emp := range employees {
		fmt.Printf("Employee %d:\n", i+1)
		fmt.Printf("  ID:         %s\n", emp.EmployeeID)
		fmt.Printf("  Name:       %s\n", emp.FullName)
		fmt.Printf("  Email:      %s\n", emp.Email)
		fmt.Printf("  Department: %s\n", emp.Department)
		fmt.Printf("  Salary:     %d\n", emp.Salary)
		fmt.Printf("  Phone:      %s\n", emp.Phone)
		fmt.Printf("  Start Date: %s\n", emp.StartDate)
		fmt.Printf("  Manager ID: %s\n", emp.ManagerID)
		if emp.Website != "" {
			fmt.Printf("  Website:    %s\n\n", emp.Website)
		} else {
			fmt.Printf("  Website:    (none)\n\n")
		}
	}

}
Output:
=== Processing Result ===
Total rows: 4, Valid rows: 4

Employee 1:
  ID:         000042
  Name:       John Doe
  Email:      john.doe@company.com
  Department: ENGINEERING
  Salary:     75000
  Phone:      +15551234567
  Start Date: 2023-01-15
  Manager ID: 000001
  Website:    https://company.com/john

Employee 2:
  ID:         000007
  Name:       Jane Smith
  Email:      jane@company.com
  Department: SALES
  Salary:     120000
  Phone:      +15559876543
  Start Date: 2022-06-01
  Manager ID: 000002
  Website:    https://www.linkedin.com/in/jane

Employee 3:
  ID:         000123
  Name:       Bob Wilson
  Email:      bob.wilson@company.com
  Department: HR
  Salary:     45000
  Phone:      +15551112222
  Start Date: 2024-03-20
  Manager ID: 000000
  Website:    (none)

Employee 4:
  ID:         000099
  Name:       Alice Brown
  Email:      alice@company.com
  Department: MARKETING
  Salary:     88500
  Phone:      +15554443333
  Start Date: 2023-09-10
  Manager ID: 000003
  Website:    https://alice.dev
Example (JsonProcessing)

Example_jsonProcessing demonstrates processing JSON data. JSON arrays are parsed into rows, each containing the raw JSON element in a single "data" column.

package main

import (
	"fmt"
	"io"
	"strings"

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

func readAllExampleOutput(reader io.Reader) ([]byte, error) {
	return io.ReadAll(reader)
}

func main() {
	type Record struct {
		Data string `name:"data" validate:"required"`
	}

	jsonData := `[{"name":"Alice","age":30},{"name":"Bob","age":25}]`

	processor := prep.NewProcessor(prep.FileTypeJSON)
	var records []Record

	reader, result, err := processor.Process(strings.NewReader(jsonData), &records)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	fmt.Printf("Processed %d rows, %d valid\n", result.RowCount, result.ValidRowCount)
	for i, r := range records {
		fmt.Printf("Row %d: %s\n", i+1, r.Data)
	}

	output, err := readAllExampleOutput(reader)
	if err != nil {
		fmt.Printf("Error reading output: %v\n", err)
		return
	}
	fmt.Printf("JSONL output:\n%s", output)

}
Output:
Processed 2 rows, 2 valid
Row 1: {"name":"Alice","age":30}
Row 2: {"name":"Bob","age":25}
JSONL output:
{"name":"Alice","age":30}
{"name":"Bob","age":25}
Example (ProcessToWriter)

Example_processToWriter demonstrates ProcessToWriter, which writes preprocessed output directly to an io.Writer instead of buffering the entire output in memory.

package main

import (
	"bytes"
	"fmt"
	"strings"

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

func main() {
	type Record struct {
		Name  string `prep:"trim" validate:"required"`
		Email string `prep:"trim,lowercase"`
	}

	csvData := "name,email\n  Alice  ,ALICE@EXAMPLE.COM\n  Bob  ,BOB@EXAMPLE.COM\n"
	processor := prep.NewProcessor(prep.FileTypeCSV)
	var records []Record

	var buf bytes.Buffer
	result, err := processor.ProcessToWriter(strings.NewReader(csvData), &records, &buf)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	fmt.Printf("Processed %d rows, %d valid\n", result.RowCount, result.ValidRowCount)
	fmt.Printf("Output:\n%s", buf.String())
}
Output:
Processed 2 rows, 2 valid
Output:
name,email
Alice,alice@example.com
Bob,bob@example.com
Example (StreamSeek)
package main

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

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

func main() {
	type user struct {
		Name string
	}

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

	reader, _, err := processor.Process(strings.NewReader("name\nAlice\n"), &users)
	if err != nil {
		log.Fatal(err)
	}

	stream, ok := reader.(io.Seeker)
	if !ok {
		log.Fatalf("reader has type %T, want an io.Seeker", reader)
	}
	buf := make([]byte, 4)
	if _, err := io.ReadFull(reader, buf); err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(buf))

	if _, err := stream.Seek(0, io.SeekStart); err != nil {
		log.Fatal(err)
	}
	if _, err := io.ReadFull(reader, buf); err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(buf))
}
Output:
name
name
Example (Validation)
package main

import (
	"fmt"
	"strings"

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

// User represents a user record with preprocessing and validation
type User struct {
	Name  string `prep:"trim" validate:"required"`
	Email string `prep:"trim,lowercase" validate:"required"`
	Age   string
}

func main() {
	// CSV data with validation error (empty required name)
	csvData := `name,email,age
,john@example.com,30
Jane,jane@example.com,25
`

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

	_, result, err := processor.Process(strings.NewReader(csvData), &users)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	// Check for validation errors
	if result.HasErrors() {
		fmt.Printf("Found %d validation errors:\n", len(result.Errors))
		for _, e := range result.ValidationErrors() {
			fmt.Printf("  Row %d, Column %q: %s\n", e.Row, e.Column, e.Message)
		}
	}

	fmt.Printf("Valid rows: %d/%d\n", result.ValidRowCount, result.RowCount)

}
Output:
Found 1 validation errors:
  Row 1, Column "name": value is required
Valid rows: 1/2

Index

Examples

Constants

View Source
const (
	FileTypeCSV     = parser.CSV
	FileTypeTSV     = parser.TSV
	FileTypeLTSV    = parser.LTSV
	FileTypeParquet = parser.Parquet
	FileTypeXLSX    = parser.XLSX

	// JSON/JSONL file types (v0.5.0+)
	FileTypeJSON  = parser.JSON
	FileTypeJSONL = parser.JSONL

	FileTypeUnsupported = parser.Unsupported
)

File type constants re-exported from parser for backward compatibility.

These are every file type there is. The parser's enum used to keep a constant for each format-and-codec combination as well, which this package deliberately did not mirror; it names formats only now, so there is nothing left to leave out.

Variables

View Source
var (
	// ErrStructSlicePointer is returned when the value is not a pointer to a struct slice
	ErrStructSlicePointer = errors.New("value must be a pointer to a struct slice")
	// ErrUnsupportedFileType is returned when the file type is not supported
	ErrUnsupportedFileType = errors.New("unsupported file type")
	// ErrEmptyFile is returned when the file is empty
	ErrEmptyFile = errors.New("file is empty")
	// ErrInvalidTagFormat is returned when the tag format is invalid
	ErrInvalidTagFormat = errors.New("invalid tag format")
	// ErrInvalidJSONAfterPrep is returned when preprocessing destroys JSON structure
	// in the "data" column of a JSON/JSONL file. This is a hard error because
	// invalid JSON lines in JSONL output cause downstream parsers to fail.
	ErrInvalidJSONAfterPrep = errors.New("preprocessing produced invalid JSON")
	// ErrEmptyJSONOutput is returned when all JSON/JSONL rows are empty or invalid
	// after preprocessing, resulting in no output lines. An empty JSONL output is
	// unparseable by downstream consumers.
	ErrEmptyJSONOutput = errors.New("JSON/JSONL output has no valid rows after preprocessing")
	// ErrNilWriter is returned when a nil io.Writer is passed to ProcessToWriter.
	ErrNilWriter = errors.New("writer must not be nil")
	// ErrNilReader is returned when a nil io.Reader is passed to Process or ProcessToWriter.
	ErrNilReader = errors.New("reader must not be nil")
	// ErrUnknownColumn is returned when a struct field names a column the input
	// does not have. Such a field used to be filled with the zero value and then
	// validated, so a typo was reported as a missing value in a column that does
	// not exist, and the caller could not tell a mapping mistake from bad data.
	ErrUnknownColumn = errors.New("struct field names a column the input does not have")
)

Sentinel errors for fileprep

Functions

This section is empty.

Types

type FileType

type FileType = parser.FileType

FileType is an alias for parser.FileType for backward compatibility.

type Option

type Option func(*Processor)

Option configures a Processor.

func WithStrictTagParsing

func WithStrictTagParsing() Option

WithStrictTagParsing enables strict tag parsing mode. When enabled, invalid tag arguments (e.g., "eq=abc" where a number is expected) return an error during Process() instead of being silently ignored.

Example:

processor := prep.NewProcessor(parser.CSV, prep.WithStrictTagParsing())
Example
package main

import (
	"errors"
	"fmt"
	"strings"

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

func main() {
	// eq on a numeric field needs a numeric parameter; on a string field the
	// same tag would compare the string "abc" itself.
	type record struct {
		Value int `validate:"eq=abc"`
	}

	processor := prep.NewProcessor(prep.FileTypeCSV, prep.WithStrictTagParsing())
	var records []record

	_, _, err := processor.Process(strings.NewReader("value\ntest\n"), &records)
	fmt.Println(errors.Is(err, prep.ErrInvalidTagFormat))
}
Output:
true

func WithValidRowsOnly

func WithValidRowsOnly() Option

WithValidRowsOnly configures the Processor to include only valid rows in the output io.Reader and struct slice. Rows that fail validation are excluded from the output but still counted in ProcessResult.RowCount and reported in ProcessResult.Errors.

Example:

processor := prep.NewProcessor(parser.CSV, prep.WithValidRowsOnly())
reader, result, err := processor.Process(input, &records)
// reader contains only rows that passed all validations
// result.RowCount includes all rows, result.ValidRowCount has valid count
Example
package main

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

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

func main() {
	type user struct {
		Name  string `prep:"trim" validate:"required"`
		Email string `prep:"trim,lowercase" validate:"required,email"`
	}

	csvData := "name,email\n Alice ,ALICE@EXAMPLE.COM\n,bad-email\n Bob ,BOB@EXAMPLE.COM\n"
	processor := prep.NewProcessor(prep.FileTypeCSV, prep.WithValidRowsOnly())
	var users []user

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

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

	fmt.Printf("valid=%d invalid=%d\n", result.ValidRowCount, result.InvalidRowCount())
	fmt.Print(string(output))
}
Output:
valid=2 invalid=1
name,email
Alice,alice@example.com
Bob,bob@example.com

type PrepError

type PrepError struct {
	Row     int    // 1-based row number
	Column  string // Column name
	Field   string // Struct field name
	Tag     string // The prep tag that failed
	Message string // Human-readable error message
}

PrepError represents a preprocessing error.

Example:

for _, pe := range result.PrepErrors() {
    fmt.Printf("Row %d, Column %q: %s (tag=%q)\n",
        pe.Row, pe.Column, pe.Message, pe.Tag)
}

func (*PrepError) Error

func (e *PrepError) Error() string

Error implements the error interface

type ProcessResult

type ProcessResult struct {
	// Errors contains all validation and preprocessing errors
	Errors []error
	// RowCount is the total number of data rows processed (excluding header)
	RowCount int
	// ValidRowCount is the number of rows that passed all validations
	ValidRowCount int
	// Columns contains the column names from the header
	Columns []string
	// OriginalFormat is the file type that was processed
	OriginalFormat parser.FileType
	// OutputFormat is the format of the bytes the returned reader serves.
	// CSV, TSV and LTSV keep their format; JSON becomes JSONL; XLSX and
	// Parquet become CSV.
	OutputFormat parser.FileType
	// contains filtered or unexported fields
}

ProcessResult contains the results of processing a file.

Example:

reader, result, err := processor.Process(input, &records)
if result.HasErrors() {
    for _, ve := range result.ValidationErrors() {
        fmt.Printf("Row %d: %s\n", ve.Row, ve.Message)
    }
}
fmt.Printf("Valid: %d/%d rows\n", result.ValidRowCount, result.RowCount)

func (*ProcessResult) HasErrors

func (r *ProcessResult) HasErrors() bool

HasErrors returns true if there are any errors

Example
package main

import (
	"fmt"
	"log"
	"strings"

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

func main() {
	type user struct {
		Email string `validate:"email"`
	}

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

	_, result, err := processor.Process(strings.NewReader("email\nnot-an-email\n"), &users)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(result.HasErrors())
}
Output:
true

func (*ProcessResult) InvalidRowCount

func (r *ProcessResult) InvalidRowCount() int

InvalidRowCount returns the number of rows that failed validation

Example
package main

import (
	"fmt"
	"log"
	"strings"

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

func main() {
	type user struct {
		Email string `validate:"email"`
	}

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

	_, result, err := processor.Process(strings.NewReader("email\nbad\nok@example.com\n"), &users)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(result.InvalidRowCount())
}
Output:
1

func (*ProcessResult) PrepErrors

func (r *ProcessResult) PrepErrors() []*PrepError

PrepErrors returns only preprocessing errors

Example
package main

import (
	"fmt"
	"log"
	"strings"

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

func main() {
	type record struct {
		Data string `name:"data" prep:"nullify={}"`
	}

	processor := prep.NewProcessor(prep.FileTypeJSON)
	var records []record

	_, result, err := processor.Process(strings.NewReader(`[{}, {"id": 2}]`), &records)
	if err != nil {
		log.Fatal(err)
	}

	prepErrors := result.PrepErrors()
	fmt.Printf("%s %d\n", prepErrors[0].Tag, result.ValidRowCount)
}
Output:
empty_json_data 1

func (*ProcessResult) ValidationErrors

func (r *ProcessResult) ValidationErrors() []*ValidationError

ValidationErrors returns only validation errors

Example
package main

import (
	"fmt"
	"log"
	"strings"

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

func main() {
	type user struct {
		Email string `validate:"email"`
	}

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

	_, result, err := processor.Process(strings.NewReader("email\nnot-an-email\n"), &users)
	if err != nil {
		log.Fatal(err)
	}

	validationErrors := result.ValidationErrors()
	fmt.Printf("%s: %s\n", validationErrors[0].Column, validationErrors[0].Message)
}
Output:
email: value must be a valid email address

type Processor

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

Processor handles preprocessing and validation of file data

func NewProcessor

func NewProcessor(fileType parser.FileType, opts ...Option) *Processor

NewProcessor creates a new Processor for the specified file type. Options can be provided to configure behavior such as strict tag parsing and output filtering.

Example:

processor := prep.NewProcessor(parser.CSV)
var records []MyRecord
reader, result, err := processor.Process(input, &records)

// With options:
processor := prep.NewProcessor(parser.CSV,
    prep.WithStrictTagParsing(),
    prep.WithValidRowsOnly(),
)

func (*Processor) Process

func (p *Processor) Process(input io.Reader, structSlicePointer any) (io.Reader, *ProcessResult, error)

Process reads from the input reader, applies preprocessing and validation, populates the struct slice, and returns an io.Reader with preprocessed data.

The format the reader serves follows the format that was read, and is not always the same one:

  • CSV input → CSV output
  • TSV input → TSV output (tab-delimited)
  • LTSV input → LTSV output (label:value format)
  • JSON input → JSONL output (one JSON value per line)
  • JSONL input → JSONL output (one JSON value per line)
  • XLSX input → CSV output (tabular data)
  • Parquet input → CSV output (tabular data)

ProcessResult.OriginalFormat is the format that was read and ProcessResult.OutputFormat is the format of the bytes the reader serves. The returned io.Reader can be passed directly to filesql.AddReader, under the format the result reports rather than the format that was read:

reader, result, err := processor.Process(input, &records)
var format filesql.FileType
switch result.OutputFormat {
case prep.FileTypeTSV:
	format = filesql.FileTypeTSV
case prep.FileTypeLTSV:
	format = filesql.FileTypeLTSV
case prep.FileTypeJSONL:
	format = filesql.FileTypeJSONL
default:
	format = filesql.FileTypeCSV
}
db.AddReader(reader, "table", format)

Those four are all OutputFormat can be. Naming the input format instead reads a JSON file as one JSON document rather than as the JSONL the reader serves, and an XLSX or Parquet file as a workbook or a Parquet file rather than as the CSV it serves, so the load fails with an error about the bytes rather than about the format. The reader also satisfies io.Seeker, so it can be rewound with Seek(0, io.SeekStart) and read again.

Example:

type User struct {
    Name  string `prep:"trim" validate:"required"`
    Email string `prep:"trim,lowercase" validate:"email"`
    Age   string `validate:"numeric,min=0,max=150"`
}

csvData := "name,email,age\n  John  ,JOHN@EXAMPLE.COM,30\n"
processor := prep.NewProcessor(parser.CSV)
var users []User
reader, result, err := processor.Process(strings.NewReader(csvData), &users)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Processed %d rows, %d valid\n", result.RowCount, result.ValidRowCount)
Example
package main

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

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

func main() {
	type user struct {
		Name  string `prep:"trim" validate:"required"`
		Email string `prep:"trim,lowercase" validate:"required,email"`
	}

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

	reader, result, err := processor.Process(strings.NewReader("name,email\n Alice ,ALICE@EXAMPLE.COM\n"), &users)
	if err != nil {
		log.Fatal(err)
	}

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

	fmt.Printf("%s %d\n", users[0].Email, result.ValidRowCount)
	fmt.Print(string(output))
}
Output:
alice@example.com 1
name,email
Alice,alice@example.com
Example (ChecksummedIdentifiers)
package main

import (
	"fmt"
	"log"
	"strings"

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

func main() {
	type item struct {
		ISBN string `validate:"isbn"`
		Card string `validate:"credit_card"`
	}

	var rows []item
	_, result, err := prep.NewProcessor(prep.FileTypeCSV).Process(strings.NewReader(
		"isbn,card\n"+
			"978-0-13-110362-7,4242 4242 4242 4242\n"+
			"978-0-13-110362-8,4242 4242 4242 4243\n"), &rows)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(result.ValidRowCount)
	for _, e := range result.ValidationErrors() {
		fmt.Printf("row %d: %s %s\n", e.Row, e.Column, e.Message)
	}
}
Output:
1
row 2: isbn value must be a valid ISBN
row 2: card value must be a valid credit card number
Example (CodeColumns)
package main

import (
	"fmt"
	"log"
	"strings"

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

func main() {
	type sale struct {
		Country  string `validate:"iso3166_1_alpha2"`
		Currency string `validate:"iso4217"`
	}

	var rows []sale
	_, result, err := prep.NewProcessor(prep.FileTypeCSV).Process(strings.NewReader(
		"country,currency\n"+
			"JP,JPY\n"+
			"jp,YEN\n"), &rows)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(result.ValidRowCount)
	for _, e := range result.ValidationErrors() {
		fmt.Printf("row %d: %s %s\n", e.Row, e.Column, e.Message)
	}
}
Output:
1
row 2: country value must be an ISO 3166-1 alpha-2 country code
row 2: currency value must be an active ISO 4217 currency code
Example (ConditionalExcluded)
package main

import (
	"fmt"
	"log"
	"strings"

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

func main() {
	type account struct {
		// Forbidden as soon as the named column holds a value.
		PersonalTaxID string `validate:"excluded_with=CompanyTaxID"`
		CompanyTaxID  string
		// Forbidden unless the named column holds the value beside it.
		Coupon string `validate:"excluded_unless=Kind promo"`
		Kind   string
	}

	var rows []account
	_, result, err := prep.NewProcessor(prep.FileTypeCSV).Process(strings.NewReader(
		"personal_tax_id,company_tax_id,coupon,kind\n"+
			"P-1,C-1,,promo\n"+
			",C-1,SAVE10,regular\n"+
			",C-1,SAVE10,promo\n"), &rows)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(result.ValidRowCount)
	for _, e := range result.ValidationErrors() {
		fmt.Printf("row %d: %s %s\n", e.Row, e.Column, e.Message)
	}
}
Output:
1
row 1: personal_tax_id value must be empty when CompanyTaxID is present
row 2: coupon value must be empty unless Kind is promo
Example (ConditionalRequired)

ExampleProcessor_Process_crossField shows a comparison between two columns, which reads the cells as the field it lands on says they are: the dates are strings and compare as text, so the range runs forwards, while the quantities are numbers and compare as numbers, so 007 is not more than 7.

package main

import (
	"fmt"
	"log"
	"strings"

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

func main() {
	type order struct {
		// Required when both other columns hold the value named beside them.
		Invoice string `validate:"required_if=Kind paid Tier 'gold member'"`
		// Required as soon as either named column holds a value.
		Address string `validate:"required_with=City Zip"`
		Kind    string
		Tier    string
		City    string
		Zip     string
	}

	var rows []order
	_, result, err := prep.NewProcessor(prep.FileTypeCSV).Process(strings.NewReader(
		"invoice,address,kind,tier,city,zip\n"+
			",,paid,gold member,,\n"+
			",,paid,silver,Kyoto,\n"+
			"INV-1,1 Main St,paid,gold member,Kyoto,600-8216\n"), &rows)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(result.ValidRowCount)
	for _, e := range result.ValidationErrors() {
		fmt.Printf("row %d: %s %s\n", e.Row, e.Column, e.Message)
	}
}
Output:
1
row 1: invoice value is required when Kind is paid and Tier is gold member
row 2: address value is required when City or Zip is present
Example (CrossField)
package main

import (
	"fmt"
	"log"
	"strings"

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

func main() {
	type shipment struct {
		ShippedOn string `validate:"ltfield=DueOn"`
		DueOn     string
		Packed    int `validate:"ltefield=Ordered"`
		Ordered   int
	}

	var rows []shipment
	_, result, err := prep.NewProcessor(prep.FileTypeCSV).Process(strings.NewReader(
		"shipped_on,due_on,packed,ordered\n"+
			"2024-01-05,2024-01-31,007,7\n"+
			"2024-02-10,2024-02-01,9,7\n"), &rows)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(result.ValidRowCount)
	for _, e := range result.ValidationErrors() {
		fmt.Printf("row %d: %s %s\n", e.Row, e.Column, e.Message)
	}
}
Output:
1
row 2: shipped_on value must be less than field DueOn
row 2: packed value must be less than or equal to field Ordered
Example (DefaultForAbsentColumn)

ExampleProcessor_Process_defaultForAbsentColumn shows the field that is meant to work without a column: prep:"default=..." says where its value comes from, so it is accepted rather than refused.

package main

import (
	"fmt"
	"log"
	"strings"

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

func main() {
	type row struct {
		Comment string
		Status  string `prep:"default=active"`
	}

	var rows []row
	_, _, err := prep.NewProcessor(prep.FileTypeCSV).
		Process(strings.NewReader("comment\nhello\n"), &rows)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%+v\n", rows[0])
}
Output:
{Comment:hello Status:active}
Example (EncodedColumns)
package main

import (
	"fmt"
	"log"
	"strings"

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

func main() {
	type payload struct {
		Config   string `validate:"json"`
		Zone     string `validate:"timezone"`
		Version  string `validate:"semver"`
		Checksum string `validate:"sha256"`
	}

	var rows []payload
	_, result, err := prep.NewProcessor(prep.FileTypeCSV).Process(strings.NewReader(
		"config,zone,version,checksum\n"+
			`"{""retries"":3}",Asia/Tokyo,1.4.0,`+strings.Repeat("ab", 32)+"\n"+
			`"{""retries"":3}",JST,1.4,`+strings.ToUpper(strings.Repeat("ab", 32))+"\n"), &rows)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(result.ValidRowCount)
	for _, e := range result.ValidationErrors() {
		fmt.Printf("row %d: %s %s\n", e.Row, e.Column, e.Message)
	}
}
Output:
1
row 2: zone value must be a valid IANA time zone name
row 2: version value must be a valid semantic version
row 2: checksum value must be a valid sha256 hash
Example (IntoFilesql)

ExampleProcessor_Process_intoFilesql shows the handoff between the two packages. The format to declare is the one the result reports, which is not always the one that was read: JSON is served as JSONL here, so declaring JSON would fail on the second record.

package main

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

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

func main() {
	type record struct {
		Data string `name:"data"`
	}

	processor := prep.NewProcessor(prep.FileTypeJSON)
	var records []record
	reader, result, err := processor.Process(strings.NewReader(`[{"id":1},{"id":2}]`), &records)
	if err != nil {
		log.Fatal(err)
	}

	var format filesql.FileType
	switch result.OutputFormat {
	case prep.FileTypeTSV:
		format = filesql.FileTypeTSV
	case prep.FileTypeLTSV:
		format = filesql.FileTypeLTSV
	case prep.FileTypeJSONL:
		format = filesql.FileTypeJSONL
	default:
		format = filesql.FileTypeCSV
	}

	db, err := filesql.NewBuilder().AddReader(reader, "events", format).Open(context.Background())
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	var ids string
	if err := db.QueryRow(`SELECT group_concat(json_extract(data, '$.id'), ',') FROM events`).Scan(&ids); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("read %s, served %s, loaded ids %s\n", result.OriginalFormat, result.OutputFormat, ids)
}
Output:
read JSON, served JSONL, loaded ids 1,2
Example (Json)
package main

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

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

func main() {
	type record struct {
		Data string `name:"data" prep:"trim"`
	}

	jsonData := `[{"id":1},{"id":2}]`
	processor := prep.NewProcessor(prep.FileTypeJSON)
	var records []record

	reader, result, err := processor.Process(strings.NewReader(jsonData), &records)
	if err != nil {
		log.Fatal(err)
	}

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

	fmt.Printf("rows=%d format=%q\n", result.RowCount, string(output))
}
Output:
rows=2 format="{\"id\":1}\n{\"id\":2}\n"
Example (LabelColorAndNumericCode)
package main

import (
	"fmt"
	"log"
	"strings"

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

func main() {
	type service struct {
		Name     string `validate:"dns_rfc1035_label"`
		Badge    string `validate:"iscolor"`
		Currency string `validate:"iso4217_numeric"`
	}

	var rows []service
	_, result, err := prep.NewProcessor(prep.FileTypeCSV).Process(strings.NewReader(
		"name,badge,currency\n"+
			"web-1,#ff0000,392\n"+
			`api,"hsl(120,50%,50%)",008`+"\n"+
			"Web_1,red,32\n"), &rows)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(result.ValidRowCount)
	for _, e := range result.ValidationErrors() {
		fmt.Printf("row %d: %s %s\n", e.Row, e.Column, e.Message)
	}
}
Output:
2
row 3: name value must be a valid RFC 1035 DNS label
row 3: badge value must be a valid color
row 3: currency value must be an active ISO 4217 numeric currency code
Example (NetworkColumns)
package main

import (
	"fmt"
	"log"
	"strings"

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

func main() {
	type endpoint struct {
		Host string `validate:"ip"`
		Port string `validate:"port"`
	}

	var rows []endpoint
	_, result, err := prep.NewProcessor(prep.FileTypeCSV).Process(strings.NewReader(
		"host,port\n"+
			"192.0.2.1,0080\n"+
			"2001:db8::1,65535\n"+
			"example.com,80\n"+
			"192.0.2.1,65536\n"), &rows)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(result.ValidRowCount)
	for _, e := range result.ValidationErrors() {
		fmt.Printf("row %d: %s %s\n", e.Row, e.Column, e.Message)
	}
}
Output:
2
row 3: host value must be a valid IP address
row 4: port value must be a valid port number
Example (UniqueColumn)
package main

import (
	"fmt"
	"log"
	"strings"

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

func main() {
	type member struct {
		// prep runs before validation, so uniqueness is decided on the
		// trimmed, folded value.
		Email string `prep:"trim,lowercase" validate:"unique"`
		Name  string
	}

	var rows []member
	_, result, err := prep.NewProcessor(prep.FileTypeCSV).Process(strings.NewReader(
		"email,name\n"+
			"a@example.com,Ada\n"+
			"b@example.com,Bob\n"+
			" A@Example.com ,Ada again\n"), &rows)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(result.ValidRowCount)
	for _, e := range result.ValidationErrors() {
		fmt.Printf("row %d: %s %s\n", e.Row, e.Column, e.Message)
	}
}
Output:
2
row 3: email value "a@example.com" already appeared in row 1
Example (UnknownColumn)

ExampleProcessor_Process_unknownColumn shows what happens when a struct field names a column the input does not have. The error names the field, the column it looked for, and the columns that exist, so a typo reads as a typo rather than as a row with a missing value.

package main

import (
	"errors"
	"fmt"
	"strings"

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

func main() {
	type user struct {
		Name   string `prep:"trim"`
		Emails string // the column is "email", singular
	}

	var users []user
	_, _, err := prep.NewProcessor(prep.FileTypeCSV).
		Process(strings.NewReader("name,email\nAlice,alice@example.com\n"), &users)

	fmt.Println(errors.Is(err, prep.ErrUnknownColumn))
	fmt.Println(err)
}
Output:
true
struct field names a column the input does not have: Emails (column "emails"); the input has [name email]

func (*Processor) ProcessToWriter

func (p *Processor) ProcessToWriter(input io.Reader, structSlicePointer any, w io.Writer) (*ProcessResult, error)

ProcessToWriter works like Process but writes the preprocessed output directly to w instead of buffering it in memory. This is useful for large datasets where holding the full output buffer is undesirable.

Example:

var buf bytes.Buffer
result, err := processor.ProcessToWriter(input, &records, &buf)
Example
package main

import (
	"bytes"
	"fmt"
	"log"
	"strings"

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

func main() {
	type user struct {
		Name string `prep:"trim"`
	}

	processor := prep.NewProcessor(prep.FileTypeCSV)
	var users []user
	var buf bytes.Buffer

	result, err := processor.ProcessToWriter(strings.NewReader("name\n Alice \n"), &users, &buf)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("valid=%d output=%q\n", result.ValidRowCount, buf.String())
}
Output:
valid=1 output="name\nAlice\n"

type ValidationError

type ValidationError struct {
	Row     int    // 1-based row number (excluding header)
	Column  string // Column name
	Field   string // Struct field name
	Value   string // The value that failed validation
	Tag     string // The validation tag that failed
	Message string // Human-readable error message
}

ValidationError represents a validation error with row and column information.

Example:

for _, ve := range result.ValidationErrors() {
    fmt.Printf("Row %d, Column %q: %s (value=%q)\n",
        ve.Row, ve.Column, ve.Message, ve.Value)
}

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements the error interface

Jump to

Keyboard shortcuts

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