zealql

package module
v0.0.0-...-0eca2fd Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 14 Imported by: 1 module, 1 package

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

ZealQL

ZealQL is a lightweight Go library that provides an in-memory SQLite wrapper with automatic schema inference. It allows you to transform unstructured or semi-structured data (like slices of maps) into fully functional relational tables instantly.

Features

  • Automatic Schema Inference: Just pass a slice of map[string]any and ZealQL will determine the best SQLite types for your columns.
  • Type Promotion: Safely handles mixed data types (e.g., promoting a column from INTEGER to REAL if decimal values are encountered).
  • Strict Schema Validation: Subsequent calls to Insert for the same table validate that the new data structure is identical to the existing schema, preventing accidental data corruption.
  • Embedded JSON Support: Complex Go structures (maps, slices) are automatically marshaled to JSON strings for storage.
  • JSON Schema Documentation: Automatically generates and embeds JSON Schemas as SQL comments in the CREATE TABLE statement for structured columns.
  • Deep Clonability: Efficiently clone an entire database instance (data + schema) into a new isolated instance using SQLite's serialization API.
  • Pointer Handling: Correctly dereferences pointers during inference and ingestion.
  • Fluent Querying: Simplifies common SQLite operations while maintaining the power of standard SQL.

Installation

go get github.com/fragshq/zealql

Note: ZealQL uses modernc.org/sqlite, a pure Go SQLite implementation, so no CGO is required.

Quick Start

package main

import (
	"fmt"
	"log"
	"github.com/fragshq/zealql"
)

func main() {
	// 1. Initialize an in-memory database
	db, _ := zealql.NewDatabase()
	defer db.Close()

	// 2. Prepare semi-structured data
	data := []map[string]any{
		{
			"id": 1, 
			"name": "Alice", 
			"meta": map[string]any{"age": 30, "tags": []string{"go", "sql"}},
		},
		{
			"id": 2, 
			"name": "Bob", 
			"meta": map[string]any{"age": 25, "active": true},
		},
	}

	// 3. Create table (infers schema and inserts data automatically)
	table, _ := db.Insert("users", data)

	// Print the inferred SQL schema
	fmt.Println(table.ToSQL())

	// 4. Query with JSON extraction
	query := "SELECT name, meta ->> '$.age' as age FROM users WHERE id = 1"
	results, _ := db.Query(query)

	for _, row := range results {
		fmt.Printf("User: %s, Age: %v\n", row["name"], row["age"])
	}
}

How It Works

Schema Inference

ZealQL scans your data to find the most specific common type for every key.

  • int -> INTEGER
  • float64 -> REAL
  • string -> TEXT
  • bool -> INTEGER (0 or 1)
  • time.Time -> DATETIME
  • map/slice -> TEXT (stored as JSON)
Appending Data

When you call db.Insert on a table that already exists, ZealQL:

  1. Infers the schema of the new data.
  2. Compares it against the existing table schema.
  3. If the schemas are identical (same keys and types), the data is appended.
  4. If the schemas differ (extra keys, missing keys, or type mismatches), an error is returned.
JSON Schema Comments

When a column is inferred as a JSON field, ZealQL generates a JSON Schema representing the structure of that data and attaches it as a SQL comment:

CREATE TABLE IF NOT EXISTS users (
  id INTEGER,
  name TEXT,
  meta TEXT /* JSON Schema: {"type":"object","properties":{"age":{"type":"integer"},...}} */
);

License

MIT

Documentation

Overview

Package zealql provides a lightweight in-memory SQLite wrapper that automatically infers schemas from map data and supports JSON columns with embedded JSON Schema comments.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Column

type Column struct {
	Name       string
	Type       SQLType
	JSONSchema *jsonschema.Schema // Optional: Schema for structured JSON data in TEXT columns.
}

Column represents a single database column with an optional inferred JSON Schema.

type Database

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

Database represents an in-memory data manipulation database that tracks inferred table schemas.

func NewDatabase

func NewDatabase() (*Database, error)

NewDatabase initializes a new in-memory SQLite database. It returns an error if the database driver is not available or fails to initialize.

func (*Database) Clone

func (d *Database) Clone() (*Database, error)

Clone creates a complete deep copy of the database, including all tables, data, and inferred schema metadata.

func (*Database) Close

func (d *Database) Close() error

Close closes the underlying SQLite database connection.

func (*Database) GetTable

func (d *Database) GetTable(name string) (*Table, bool)

GetTable returns a table definition by its name if it was created via Insert.

func (*Database) Insert

func (d *Database) Insert(name string, data any) (*Table, error)

Insert infers a table schema from data (a slice of maps), creates the table if it doesn't exist yet and inserts the rows. If the table already exists, the inferred schema must be compatible with the existing one. The whole operation is atomic: either the table is created and all rows are inserted, or nothing changes. It is safe for concurrent use.

func (*Database) ListTables

func (d *Database) ListTables() []string

func (*Database) Query

func (d *Database) Query(query string, args ...any) ([]map[string]any, error)

Query executes a SQL query against the database and returns the results as a slice of maps. It automatically handles basic SQLite type conversion and attempts to unmarshal JSON strings back into Go structures.

type Preparer

type Preparer interface {
	Prepare(query string) (*sql.Stmt, error)
}

Preparer is satisfied by *sql.DB, *sql.Tx and *sql.Conn.

type SQLType

type SQLType string

SQLType represents a standard SQLite data type.

const (
	Integer  SQLType = "INTEGER"
	Real     SQLType = "REAL"
	Text     SQLType = "TEXT"
	Blob     SQLType = "BLOB"
	DateTime SQLType = "DATETIME"
	Null     SQLType = "NULL"
	JSON     SQLType = "JSON"
)

type Table

type Table struct {
	Name    string
	Columns []Column
}

Table represents a SQLite table definition, including its columns and logic for SQL generation and data ingestion.

func InferTable

func InferTable(tableName string, data []map[string]any) (*Table, error)

InferTable analyzes a slice of map data to determine the most appropriate SQLite table schema. It handles type promotion and JSON schema inference for structured fields.

func (*Table) Compatible

func (t *Table) Compatible(other *Table) bool

Compatible checks if the provided table has an identical schema (column names and types) to the current table. It assumes columns in both tables are sorted by name.

func (*Table) GenerateInsertSQL

func (t *Table) GenerateInsertSQL() string

GenerateInsertSQL creates an INSERT INTO statement template with question mark (?) placeholders for all table columns.

func (*Table) Insert

func (t *Table) Insert(db Preparer, data []map[string]any) error

Insert executes the insertion of multiple rows of data into the provided database, transaction or connection. It automatically marshals maps, structs, slices and arrays to JSON strings, and dereferences pointers.

func (*Table) ToSQL

func (t *Table) ToSQL() string

ToSQL generates a CREATE TABLE statement for the table. If a column has an inferred JSON schema, it is included as a SQL comment.

Jump to

Keyboard shortcuts

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