importer

package
v0.42.0 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2026 License: AGPL-3.0 Imports: 36 Imported by: 0

Documentation

Overview

Package importer provides automatic file import with type detection for tinySQL.

This package supports importing structured data from various formats (CSV, TSV, JSON, XML) directly into tinySQL tables. It auto-detects delimiters, headers, encodings, and column types to minimize manual configuration.

Features:

  • Auto-detect delimiter: ',', ';', '\t', '|' (configurable)
  • Auto-detect header row (configurable override)
  • Encoding: UTF-8, UTF-8 BOM, UTF-16LE/BE (BOM-based)
  • Transparent GZIP input
  • Smart type inference (INT, FLOAT, BOOL, TEXT, TIME, JSON)
  • Streaming import with batched INSERTs
  • Optional CREATE TABLE and TRUNCATE

Example:

import "github.com/SimonWaldherr/tinySQL/internal/importer"

f, _ := os.Open("data.csv")
result, err := importer.ImportCSV(ctx, db, tenant, "mytable", f, nil)
fmt.Printf("Imported %d rows with %d columns\n", result.RowsInserted, len(result.ColumnNames))

TopoJSON v3 import: dequantize/un-delta-encode every arc once, resolve each geometry's arc-index references (including mapshaper- and topojson-server-style multi-arc-per-ring stitching, and the spec's ~i-means-reversed convention) back into plain GeoJSON coordinate arrays, then hand off to the SAME buildGeoJSONColumns/buildGeoJSONRow (geojson.go) ImportGeoJSON already uses -- both are already generic over any GeoJSON-Feature-shaped []map[string]any, so nothing there needs to change to accept a TopoJSON-derived source instead of a real GeoJSON document.

Excel (.xlsx) import. XLSX is a ZIP archive of XML parts (the Office Open XML / ECMA-376 SpreadsheetML format): a workbook listing sheets, a worksheet XML per sheet holding cell values, an optional shared-string table (repeated text is stored once and referenced by index), and an optional styles part this importer consults only to recognize date/time number formats. No third-party XLSX library is used — archive/zip and encoding/xml (both stdlib) are enough for the read path, consistent with this package's existing hand-rolled KML/OSM/Shapefile readers.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrInputTooLarge = errors.New("import input exceeds configured size limit")

ErrInputTooLarge is returned before an importer consumes data beyond the configured ImportOptions.MaxInputBytes limit.

View Source
var ErrMBTilesArtifactSQLiteUnavailable = errors.New("MBTiles import requires a build with -tags=sqliteimport")

ErrMBTilesArtifactSQLiteUnavailable reports that importing an MBTiles SQLite source needs the optional SQLite importer build tag. Opening an already published tinySQL artifact does not need SQLite on supported native targets.

View Source
var ErrTileArtifactImportUnavailable = errors.New("tile artifact import requires a native builder")

Functions

func OpenFile

func OpenFile(ctx context.Context, filePath string, opts *ImportOptions) (*storage.DB, string, error)

OpenFile opens a data file (CSV, TSV, JSON, XML) and returns a DB with the data loaded. The table name is derived from the filename unless specified in options.

This is a convenience function for quick data exploration:

db, _ := importer.OpenFile(context.Background(), "data.csv", nil)
// Now you can query it with tinySQL

Types

type ExportMBTilesOptions added in v0.26.0

type ExportMBTilesOptions struct {
	// TilesTable is the tinySQL table holding zoom_level/tile_column/tile_row/
	// tile_data. Defaults to "tiles".
	TilesTable string

	// MetadataTable holds name/value metadata rows. Defaults to
	// TilesTable + "_metadata", which is where ImportMBTiles puts it. A missing
	// table is not an error; Metadata below still applies.
	MetadataTable string

	// Metadata entries are written after the metadata table's rows, overriding
	// any key of the same name. Use it to supply or correct the keys the
	// specification requires.
	Metadata map[string]string

	// BatchSize bounds how many tiles are inserted per transaction. Zero uses a
	// default. Tiles are streamed, so a tileset larger than memory can be
	// written.
	BatchSize int

	// TileRowIsTMS declares what the source tile_row column already contains.
	// The specification stores TMS (row 0 = southernmost); if the tinySQL table
	// holds XYZ rows instead, set this false and the rows are flipped on the way
	// out. Defaults to true, matching a tileset that came from ImportMBTiles.
	TileRowIsTMS bool
}

ExportMBTilesOptions configures a tileset export.

type ExportMBTilesResult added in v0.26.0

type ExportMBTilesResult struct {
	TilesWritten    int64
	MetadataWritten int64
	// MinZoom and MaxZoom are the observed zoom range, also written to metadata
	// when the caller supplied neither. Both are -1 for an empty tileset.
	MinZoom int
	MaxZoom int
}

ExportMBTilesResult reports what was written.

func ExportMBTiles added in v0.26.0

func ExportMBTiles(
	ctx context.Context,
	db *storage.DB,
	tenant string,
	filePath string,
	opts *ExportMBTilesOptions,
) (*ExportMBTilesResult, error)

ExportMBTiles reports that MBTiles export requires the sqliteimport build tag.

type FuzzyImportOptions added in v0.3.1

type FuzzyImportOptions struct {
	*ImportOptions

	// SkipInvalidRows skips rows that don't match the expected column count (default true)
	SkipInvalidRows bool

	// TrimWhitespace aggressively trims whitespace from all values (default true)
	TrimWhitespace bool

	// FixQuotes attempts to fix unmatched quotes in CSV data (default true)
	FixQuotes bool

	// CoerceTypes attempts to coerce invalid values to the expected type (default true)
	CoerceTypes bool

	// MaxSkippedRows maximum number of rows to skip before giving up (default 100)
	MaxSkippedRows int

	// AllowMixedTypes allows columns to have mixed types (converts to TEXT) (default true)
	AllowMixedTypes bool

	// FuzzyJSON attempts to parse malformed JSON (default true)
	FuzzyJSON bool

	// RemoveInvalidChars removes invalid UTF-8 characters (default true)
	RemoveInvalidChars bool

	// AutoFixDelimiters tries to detect and fix inconsistent delimiters (default true)
	AutoFixDelimiters bool
}

FuzzyImportOptions extends ImportOptions with fuzzy parsing capabilities

type ImportOptions

type ImportOptions struct {
	// MaxInputBytes rejects input that exceeds this size. Zero leaves the source
	// unbounded, which preserves the historic library behavior. Set this for
	// network and user-supplied input. For gzip CSV, the limit applies after
	// decompression.
	MaxInputBytes int64

	// MaxRecordBytes caps an individual NDJSON record. Zero uses the scanner's
	// standard limit. CSV records remain governed by encoding/csv.
	MaxRecordBytes int

	// Encoding selects the source text encoding. Empty or "auto" accepts a
	// UTF BOM when present and otherwise requires UTF-8. Legacy single-byte
	// encodings are opt-in: iso-8859-1, iso-8859-2, iso-8859-15, and
	// windows-1252. tinySQL always stores resulting TEXT as UTF-8.
	Encoding string

	// BatchSize controls how many rows are buffered before executing INSERT (default 1000).
	BatchSize int

	// NullLiterals are treated as SQL NULL (case-insensitive, trimmed).
	// Defaults: "", "null", "na", "n/a", "none", "#n/a"
	NullLiterals []string

	// CreateTable creates the table if it doesn't exist using inferred column types (default true).
	// Disable this if you want to create the table manually with specific types/constraints.
	CreateTable bool

	// Truncate clears the table before import (default false).
	Truncate bool

	// HeaderMode controls header detection:
	//   "auto" (default)  → heuristic decides based on data analysis
	//   "present"         → first row is always treated as header
	//   "absent"          → first row is data, synthetic column names generated (col_1, col_2, ...)
	HeaderMode string

	// DelimiterCandidates tested during auto-detection. Default: , ; \t |
	// Override to force specific delimiter(s).
	DelimiterCandidates []rune

	// TableName overrides the target table name (useful when importing from stdin/pipes).
	TableName string

	// SampleBytes caps the amount of data used for detection (default 128KB).
	SampleBytes int

	// SampleRecords caps the number of records analyzed for detection (default 500).
	SampleRecords int

	// TypeInference controls automatic type detection (default true).
	// When enabled, analyzes sample data to determine INT, FLOAT, BOOL, TIME, or TEXT.
	// When disabled, all columns default to TEXT type.
	TypeInference bool

	// DateTimeFormats lists custom datetime formats to try during type detection.
	// Defaults include RFC3339, ISO8601, common US/EU formats.
	DateTimeFormats []string

	// StrictTypes when true causes import to fail if data doesn't match detected types (default false).
	// When false, falls back to TEXT on type conversion errors.
	StrictTypes bool

	// TopoJSONObject selects a single top-level "objects" key when importing
	// a TopoJSON Topology (ImportTopoJSON). Empty imports every object; if
	// more than one object key exists in that case, each resulting row gets
	// an added "topo_object" property naming its source object, so a
	// multi-object Topology's provenance isn't silently lost. Ignored by
	// every other importer.
	TopoJSONObject string

	// XLSXSheet selects a single worksheet by name when importing an Excel
	// workbook (ImportXLSX). Empty selects the workbook's first sheet in
	// declared order. Ignored by every other importer.
	XLSXSheet string
}

ImportOptions configures the importer behavior. All fields are optional.

type ImportResult

type ImportResult struct {
	RowsInserted int64             // Total rows successfully inserted
	RowsSkipped  int64             // Rows skipped due to errors (if StrictTypes=false)
	Delimiter    rune              // Detected or configured delimiter
	HadHeader    bool              // Whether a header row was detected/configured
	Encoding     string            // Detected encoding: "utf-8", "utf-8-bom", "utf-16le", "utf-16be"
	LineEnding   string            // Detected line ending: "\n" or "\r\n"
	ColumnNames  []string          // Final column names used
	ColumnTypes  []storage.ColType // Detected column types
	Errors       []string          // Non-fatal errors encountered during import
}

ImportResult returns metadata about the import operation.

func FuzzyImportCSV added in v0.3.1

func FuzzyImportCSV(
	ctx context.Context,
	db *storage.DB,
	tenant string,
	tableName string,
	src io.Reader,
	opts *FuzzyImportOptions,
) (*ImportResult, error)

FuzzyImportCSV is a more forgiving version of ImportCSV that handles malformed data

func FuzzyImportJSON added in v0.3.1

func FuzzyImportJSON(
	ctx context.Context,
	db *storage.DB,
	tenant string,
	tableName string,
	src io.Reader,
	opts *FuzzyImportOptions,
) (*ImportResult, error)

FuzzyImportJSON imports JSON after applying the configured recovery rules.

func ImportCSV

func ImportCSV(
	ctx context.Context,
	db *storage.DB,
	tenant string,
	tableName string,
	src io.Reader,
	opts *ImportOptions,
) (*ImportResult, error)

ImportCSV imports delimited data (CSV/TSV) from a reader into a tinySQL table.

This function auto-detects the file format, creates the table if needed, and streams data insertion with batching for performance. It handles various encodings, compressed input (gzip), and performs smart type inference.

Parameters:

  • ctx: Context for cancellation
  • db: Target database instance
  • tenant: Tenant/schema name (use "default" for single-tenant mode)
  • tableName: Target table name (can be overridden via opts.TableName)
  • src: Input reader (file, network stream, stdin, etc.)
  • opts: Optional configuration (nil uses sensible defaults)

Returns ImportResult with metadata and any error encountered.

ImportCSV is the entrypoint for CSV/TSV imports. It orchestrates detection, decoding, sampling, type inference and insertion while delegating detailed tasks to smaller helpers to keep cyclomatic complexity low.

func ImportFile

func ImportFile(
	ctx context.Context,
	db *storage.DB,
	tenant string,
	tableName string,
	filePath string,
	opts *ImportOptions,
) (*ImportResult, error)

ImportFile detects the file format and imports it into a tinySQL table. Supports: CSV, TSV, JSON, XML and common map data formats (GeoJSON, KML, Shapefile, OSM XML, MBTiles, routing graph JSON/CSV/NDJSON).

Parameters:

  • ctx: Context for cancellation
  • db: Target database instance
  • tenant: Tenant/schema name (use "default" for single-tenant mode)
  • tableName: Target table name (if empty, derived from filename)
  • filePath: Path to the file to import
  • opts: Optional configuration (nil uses sensible defaults)

Returns ImportResult with metadata and any error encountered.

Example (Xml)
ctx := context.Background()
db := storage.NewDB()
xmlData := `<root>
  <record id="1" name="Alice" />
  <record id="2" name="Bob" />
</root>`

result, err := ImportXML(ctx, db, "default", "people", strings.NewReader(xmlData),
	&ImportOptions{CreateTable: true, TypeInference: true})
if err != nil {
	panic(err)
}

fmt.Println(result.RowsInserted)
Output:
2
Example (Yaml)
ctx := context.Background()
db := storage.NewDB()
yamlData := "- id: 1\n  name: Alice\n- id: 2\n  name: Bob\n"

result, err := ImportYAML(ctx, db, "default", "people", strings.NewReader(yamlData),
	&ImportOptions{CreateTable: true, TypeInference: true})
if err != nil {
	panic(err)
}

fmt.Println(result.RowsInserted)
Output:
2

func ImportGeoJSON added in v0.6.0

func ImportGeoJSON(
	ctx context.Context,
	db *storage.DB,
	tenant string,
	tableName string,
	src io.Reader,
	opts *ImportOptions,
) (*ImportResult, error)

ImportGeoJSON imports a GeoJSON file. It supports FeatureCollection and individual Feature objects. Properties become table columns; geometry is stored in a `geometry` column with type GeometryType.

func ImportJSON

func ImportJSON(
	ctx context.Context,
	db *storage.DB,
	tenant string,
	tableName string,
	src io.Reader,
	opts *ImportOptions,
) (*ImportResult, error)

ImportJSON imports JSON records from src into tableName for tenant.

func ImportKML added in v0.6.0

func ImportKML(
	ctx context.Context,
	db *storage.DB,
	tenant string,
	tableName string,
	src io.Reader,
	opts *ImportOptions,
) (*ImportResult, error)

ImportKML imports KML Placemarks into a tinySQL table. Names/descriptions become properties.

func ImportMBTiles added in v0.14.0

func ImportMBTiles(
	ctx context.Context,
	db *storage.DB,
	tenant string,
	tableName string,
	filePath string,
	opts *ImportOptions,
) (*ImportResult, error)

ImportMBTiles reports that MBTiles import requires the sqliteimport build tag.

func ImportMBTilesReader added in v0.14.0

func ImportMBTilesReader(
	ctx context.Context,
	db *storage.DB,
	tenant string,
	tableName string,
	src io.Reader,
	opts *ImportOptions,
) (*ImportResult, error)

ImportMBTilesReader reports that MBTiles import requires the sqliteimport build tag.

func ImportOSM added in v0.14.0

func ImportOSM(
	ctx context.Context,
	db *storage.DB,
	tenant string,
	tableName string,
	src io.Reader,
	opts *ImportOptions,
) (*ImportResult, error)

ImportOSM imports OSM XML (.osm or .osm.xml) into one table. Nodes, ways and relations share a normalized row shape; ways get GeoJSON LineString/Polygon geometry when referenced node coordinates are present earlier in the file.

func ImportRoutingGraph added in v0.14.0

func ImportRoutingGraph(
	ctx context.Context,
	db *storage.DB,
	tenant string,
	tableName string,
	src io.Reader,
	opts *ImportOptions,
) (*ImportResult, error)

ImportRoutingGraph imports routing graph data from JSON or CSV. JSON may be either {"nodes":[...],"edges":[...]} or a plain edge array. CSV is treated as an edge list using common source/target/cost/distance/duration/mode columns.

func ImportShapefile added in v0.6.0

func ImportShapefile(ctx context.Context, db *storage.DB, tenant, tableName, filePath string, opts *ImportOptions) (*ImportResult, error)

ImportShapefile is available only in builds that opt into the optional shapefile dependency: go build -tags=shapefile ./...

func ImportShapefileZip added in v0.14.0

func ImportShapefileZip(ctx context.Context, db *storage.DB, tenant, tableName string, src io.Reader, opts *ImportOptions) (*ImportResult, error)

ImportShapefileZip is available only in builds that opt into the optional shapefile dependency: go build -tags=shapefile ./...

func ImportTopoJSON added in v0.27.0

func ImportTopoJSON(
	ctx context.Context,
	db *storage.DB,
	tenant string,
	tableName string,
	src io.Reader,
	opts *ImportOptions,
) (*ImportResult, error)

ImportTopoJSON imports a TopoJSON Topology file. Arc references are resolved to absolute coordinates before rows are built; see extractTopoJSONFeatures. Properties become table columns; geometry is stored in a `geometry` column with type GeometryType, identically to ImportGeoJSON -- whose buildGeoJSONColumns/buildGeoJSONRow this reuses unmodified.

func ImportXLSX added in v0.27.0

func ImportXLSX(
	ctx context.Context,
	db *storage.DB,
	tenant string,
	tableName string,
	src io.Reader,
	opts *ImportOptions,
) (*ImportResult, error)

ImportXLSX imports the first worksheet (or opts.XLSXSheet, if set) of an Excel workbook from src into a tinySQL table.

Cell values are read with their native Excel type: numbers stay numeric, booleans stay boolean, and a numeric cell styled with a recognized date/time number format is converted from its Excel serial date to a timestamp — all fed through the same sample-based type inference and insertion path ImportCSV uses, so column typing behaves identically whether the source was a spreadsheet or a delimited file.

func ImportXML

func ImportXML(
	ctx context.Context,
	db *storage.DB,
	tenant string,
	tableName string,
	src io.Reader,
	opts *ImportOptions,
) (*ImportResult, error)

ImportXML imports XML data from a reader into a tinySQL table. Supports simple row-based XML like:

<root>
  <record id="1" name="Alice" />
  <record id="2" name="Bob" />
</root>

or:

<root>
  <record><id>1</id><name>Alice</name></record>
  <record><id>2</id><name>Bob</name></record>
</root>

func ImportYAML added in v0.5.5

func ImportYAML(
	ctx context.Context,
	db *storage.DB,
	tenant string,
	tableName string,
	src io.Reader,
	opts *ImportOptions,
) (*ImportResult, error)

ImportYAML provides basic YAML -> table import. It supports a YAML list of mappings or a single mapping. This is a convenience helper and does not attempt to support every YAML feature; it converts YAML to Go maps and processes them similarly to JSON imports.

type MBTilesArtifactIndex added in v0.27.1

type MBTilesArtifactIndex struct {
	Name    string   `json:"name"`
	Columns []string `json:"columns"`
	Unique  bool     `json:"unique"`
}

type MBTilesArtifactManifest added in v0.27.1

type MBTilesArtifactManifest struct {
	FormatVersion  int                     `json:"format_version"`
	TinySQLVersion string                  `json:"tinysql_version"`
	Schema         MBTilesArtifactSchema   `json:"schema"`
	CreatedAt      time.Time               `json:"created_at"`
	Source         string                  `json:"source"`
	SourceBytes    int64                   `json:"source_bytes"`
	Resources      MBTilesResourceEstimate `json:"resources"`
	Provenance     map[string]any          `json:"provenance,omitempty"`
	Tables         []MBTilesArtifactTable  `json:"tables"`
	IndexConfig    map[string]any          `json:"index_config"`
	Checksums      map[string]string       `json:"checksums"`
}

MBTilesArtifactManifest is the signed-by-checksum description of a published artifact. The JSON itself is included in checksums.sha256.

func OpenMBTilesArtifact added in v0.27.1

func OpenMBTilesArtifact(ctx context.Context, artifactPath string, maxMemoryBytes int64) (*storage.DB, *MBTilesArtifactManifest, error)

func ValidateMBTilesArtifact added in v0.27.1

func ValidateMBTilesArtifact(ctx context.Context, artifactPath string) (*MBTilesArtifactManifest, error)

type MBTilesArtifactOptions added in v0.27.1

type MBTilesArtifactOptions struct {
	Schema         MBTilesArtifactSchema
	BatchSize      int
	MaxMemoryBytes int64
	MinFreeBytes   int64
	// Provenance is optional caller-supplied, JSON-compatible source context.
	// tinySQL preserves it in the checksummed manifest but does not interpret
	// application-specific fields such as an OSM generator configuration.
	Provenance      map[string]any
	Progress        func(MBTilesProgress)
	ProgressEvery   time.Duration
	ReplaceExisting bool
}

MBTilesArtifactOptions controls a bounded, publish-on-success import.

type MBTilesArtifactResult added in v0.27.1

type MBTilesArtifactResult struct {
	ArtifactPath string
	Manifest     MBTilesArtifactManifest
	Estimate     MBTilesResourceEstimate
}

MBTilesArtifactResult is returned only after validation and atomic publish.

func ImportMBTilesArtifact added in v0.27.1

func ImportTileArtifact added in v0.29.0

func ImportTileArtifact(ctx context.Context, source TileArtifactSource, artifactPath string, opts *MBTilesArtifactOptions) (*MBTilesArtifactResult, error)

ImportTileArtifact streams a repeatable tile source directly into a validated, atomically published artifact. It never creates or opens an intermediate SQLite/MBTiles database.

type MBTilesArtifactSchema added in v0.27.1

type MBTilesArtifactSchema string

MBTilesArtifactSchema selects the physical representation used in a dataset.tinysql artifact.

const (
	MBTilesSchemaAuto       MBTilesArtifactSchema = "auto"
	MBTilesSchemaFlat       MBTilesArtifactSchema = "flat"
	MBTilesSchemaNormalized MBTilesArtifactSchema = "normalized"
)

type MBTilesArtifactTable added in v0.27.1

type MBTilesArtifactTable struct {
	Name    string                 `json:"name"`
	Columns []string               `json:"columns"`
	Rows    int64                  `json:"rows"`
	Indexes []MBTilesArtifactIndex `json:"indexes,omitempty"`
}

MBTilesArtifactTable describes one persisted table in the manifest.

type MBTilesProgress added in v0.27.1

type MBTilesProgress struct {
	Phase        string
	RowsRead     int64
	RowsWritten  int64
	BytesRead    int64
	BytesWritten int64
	TotalRows    int64
	BatchSize    int
	Estimate     *MBTilesResourceEstimate
}

MBTilesProgress is emitted after resource planning and after each flushed batch. The callback is never called while a source row is being retained.

type MBTilesReader added in v0.27.1

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

MBTilesReader is a validated, read-only tile reader. Each reader owns one pager handle; separate readers are safe to use concurrently.

func OpenMBTilesReader added in v0.27.1

func OpenMBTilesReader(ctx context.Context, artifactPath string, maxMemoryBytes int64) (*MBTilesReader, error)

OpenMBTilesReader validates the complete artifact before returning a reader.

func (*MBTilesReader) Close added in v0.28.0

func (r *MBTilesReader) Close() error

func (*MBTilesReader) LookupMetadata added in v0.28.0

func (r *MBTilesReader) LookupMetadata(ctx context.Context, name string) (string, bool, error)

LookupMetadata returns one MBTiles metadata value by its standard name. Metadata is indexed separately from tiles, so callers do not need to scan the tile catalogue for ordinary fields such as format or bounds.

func (*MBTilesReader) LookupTile added in v0.28.0

func (r *MBTilesReader) LookupTile(ctx context.Context, z, x, y int) ([]byte, bool, error)

LookupTile performs one exact TMS lookup. The returned BLOB is owned by the caller: the pager decoder has already copied it out of its page cache, so no second defensive payload copy is necessary here.

func (*MBTilesReader) LookupTileFunc added in v0.28.0

func (r *MBTilesReader) LookupTileFunc(ctx context.Context, z, x, y int, fn func(data []byte) error) (bool, error)

LookupTileFunc is the allocation-conscious exact lookup API. fn receives a caller-owned decoded payload and may retain it. Unlike LookupTile, it does not need an additional result slice or a second BLOB copy.

func (*MBTilesReader) Manifest added in v0.28.0

func (r *MBTilesReader) Manifest() *MBTilesArtifactManifest

func (*MBTilesReader) ScanMetadata added in v0.28.0

func (r *MBTilesReader) ScanMetadata(ctx context.Context, fn func(name, value string) error) error

ScanMetadata streams the complete metadata table in the artifact's stable import order. Metadata is intentionally scanned through the paged table reader rather than collected from a query result: a serving application may copy this small set at open time without ever materializing its tile rows.

func (*MBTilesReader) ScanTileRange added in v0.28.0

func (r *MBTilesReader) ScanTileRange(ctx context.Context, z, xMin, xMax, yMin, yMax int, fn func(z, x, y int, data []byte) bool) error

ScanTileRange streams a TMS rectangle. A z/x/y B+Tree cannot express a rectangular y bound across multiple x values as one contiguous key range, so scan one tightly bounded y interval per x. This avoids decoding every tile in the selected columns for the common small map-window workload.

type MBTilesResourceEstimate added in v0.27.1

type MBTilesResourceEstimate struct {
	SourceBytes     int64 `json:"source_bytes"`
	TileCount       int64 `json:"tile_count"`
	MapRows         int64 `json:"map_rows,omitempty"`
	ImageRows       int64 `json:"image_rows,omitempty"`
	MetadataRows    int64 `json:"metadata_rows"`
	EstimatedMemory int64 `json:"estimated_memory"`
	EstimatedDisk   int64 `json:"estimated_disk"`
	AvailableDisk   int64 `json:"available_disk"`
	BatchSize       int   `json:"batch_size"`
}

MBTilesResourceEstimate is the preflight result printed/reported before the first destination file is created.

type OpenMBTilesOptions added in v0.26.0

type OpenMBTilesOptions struct {
	// TilesTable and MetadataTable name the tinySQL tables the tileset is
	// exposed as. They default to "tiles" and "tiles_metadata".
	TilesTable    string
	MetadataTable string

	// MaxTiles bounds how many tiles are admitted, guarding against
	// accidentally materializing a continental tileset. Zero means unlimited.
	MaxTiles int64

	// Zooms restricts the import to these zoom levels. Empty means all. This is
	// the practical way to work with a large tileset in place: overview zooms
	// are a tiny fraction of the tile count.
	Zooms []int

	// WithoutTileData omits tile_data, keeping only the addressing columns and
	// per-tile size/hash. A tile *index* of even a huge tileset is small, which
	// makes coverage and integrity queries cheap.
	WithoutTileData bool
}

OpenMBTilesOptions configures opening an .mbtiles file for querying in place.

type OpenMBTilesResult added in v0.26.0

type OpenMBTilesResult struct {
	TilesExposed    int64
	MetadataExposed int64
	MinZoom         int
	MaxZoom         int
	// Truncated is true when MaxTiles stopped the read before the source was
	// exhausted, so the exposed table is a partial view.
	Truncated bool
}

OpenMBTilesResult reports what an in-place open exposed.

func OpenMBTiles added in v0.26.0

func OpenMBTiles(
	ctx context.Context,
	db *storage.DB,
	tenant string,
	filePath string,
	opts *OpenMBTilesOptions,
) (*OpenMBTilesResult, error)

OpenMBTiles reports that querying an .mbtiles in place requires the sqliteimport build tag.

type TileArtifactInfo added in v0.29.0

type TileArtifactInfo struct {
	Name         string
	SourceBytes  int64
	TileCount    int64
	TileBytes    int64
	MaxTileBytes int64
	Metadata     map[string]string
}

TileArtifactInfo describes a repeatable tile stream before an artifact is created. The importer verifies the declared counts while consuming it.

type TileArtifactSource added in v0.29.0

type TileArtifactSource interface {
	Info(context.Context) (TileArtifactInfo, error)
	ScanTiles(context.Context, func(TileArtifactTile) error) error
}

TileArtifactSource is a repeatable source for direct artifact generation. ScanTiles may emit keys in any order. Data remains source-owned for the duration of the callback.

type TileArtifactTile added in v0.29.0

type TileArtifactTile struct {
	Z, X, Y int
	Data    []byte
}

TileArtifactTile is one TMS tile emitted by TileArtifactSource.

type XMLRecord

type XMLRecord struct {
	XMLName xml.Name
	Attrs   []xml.Attr  `xml:",any,attr"`
	Content string      `xml:",chardata"`
	Nodes   []XMLRecord `xml:",any"`
}

XMLRecord represents a generic XML element for table import.

Jump to

Keyboard shortcuts

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