duckdb

package module
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Jan 4, 2026 License: MIT Imports: 19 Imported by: 0

README

GORM DuckDB Driver

Tests Coverage Code Quality

A comprehensive DuckDB driver for GORM, featuring native array support, complete GORM v2 compliance, and enterprise-grade code quality with zero linting errors.

Features

  • Enterprise Code Quality - Zero linting errors across all categories with production-ready error handling
  • Complete GORM Compliance - Full GORM v2 interface implementation with all required methods
  • Native Array Support - First-class array types using DuckDB's native Composite[T] wrappers
  • Advanced DuckDB Types - 19 sophisticated types including JSON, Decimal, UUID, ENUM, UNION, and more
  • Production Ready - Auto-increment with sequences, comprehensive error handling, connection pooling
  • Extension Management - Built-in system for loading and managing DuckDB extensions
  • Schema Introspection - Complete metadata access with ColumnTypes() and TableType() interfaces
  • High Performance - DuckDB-optimized configurations and native type operations

Quick Start

Install

Step 1: Add dependencies to your project:

go get -u gorm.io/gorm
go get -u github.com/greysquirr3l/gorm-duckdb-driver

Step 2: Run go mod tidy:

go mod tidy

Note: Version 0.8.0+ uses the official github.com/duckdb/duckdb-go/v2 module instead of the deprecated github.com/marcboeker/go-duckdb/v2. The migration is fully backward compatible with zero breaking changes.

Connect to Database
import (
  duckdb "github.com/greysquirr3l/gorm-duckdb-driver"
  "gorm.io/gorm"
)

// In-memory database
db, err := gorm.Open(duckdb.Open(":memory:"), &gorm.Config{})

// File-based database
db, err := gorm.Open(duckdb.Open("test.db"), &gorm.Config{})

// With configuration
db, err := gorm.Open(duckdb.New(duckdb.Config{
  DSN: "test.db",
  DefaultStringSize: 256,
}), &gorm.Config{})

Native Array Support

The driver provides native DuckDB array support using duckdb.Composite[T] wrappers, offering significant performance improvements over custom implementations.

Key Features
  • Native Performance: Uses DuckDB's built-in array types with 79% code reduction (371→77 lines)
  • Type Safety: Full Go type safety with duckdb.Composite[T] wrappers
  • Array Functions: Access to DuckDB's native array functions like range(), array_length(), array_has()
  • GORM Integration: Implements GormDataType(), driver.Valuer, and sql.Scanner interfaces
Usage
// Define model with array fields
type Product struct {
    ID         uint                `gorm:"primaryKey"`
    Name       string              `gorm:"size:100"`
    Categories duckdb.StringArray  `json:"categories"`
    Scores     duckdb.FloatArray   `json:"scores"`
    ViewCounts duckdb.IntArray     `json:"view_counts"`
}

// Create arrays
product := Product{
    Categories: duckdb.NewStringArray([]string{"software", "analytics"}),
    Scores:     duckdb.NewFloatArray([]float64{4.5, 4.8, 4.2}),
    ViewCounts: duckdb.NewIntArray([]int64{1250, 890, 2340}),
}

// Insert and query using Raw SQL (recommended for arrays)
err := db.Exec(`INSERT INTO products (name, categories, scores, view_counts) VALUES (?, ?, ?, ?)`,
    product.Name, product.Categories.Get(), product.Scores.Get(), product.ViewCounts.Get()).Error

// Retrieve using Raw SQL with native array functions
var result Product
err = db.Raw(`SELECT * FROM products WHERE array_length(categories) > ?`, 1).Scan(&result).Error

// Access array data
categories := result.Categories.Get() // Returns []string
scores := result.Scores.Get()         // Returns []float64
counts := result.ViewCounts.Get()     // Returns []int64
Important Notes
  • Use Raw SQL: Native arrays work best with Raw().Scan() rather than GORM ORM methods (First(), Find())
  • Float Arrays: May return duckdb.Decimal types due to DuckDB's native behavior
  • Performance: Native implementation provides significant performance benefits over JSON serialization

Advanced DuckDB Types

The driver supports 19 advanced DuckDB types for comprehensive analytical capabilities:

Core Types
  • Arrays: StringArray, IntArray, FloatArray with native Composite[T] support
  • JSON/Document: JSONType for flexible document storage
  • Precision Math: DecimalType, HugeIntType (128-bit integers)
  • Temporal: IntervalType, TimestampTZType with timezone support
  • Identifiers: UUIDType for unique identifiers
Advanced Types
  • Structured Data: StructType, MapType, ListType for complex hierarchies
  • Variants: ENUMType, UNIONType for type-safe variants
  • Binary: BLOBType, BitStringType for binary data
  • Spatial: GEOMETRYType with WKT support
  • Performance: QueryHintType, PerformanceMetricsType for optimization
Usage Example
type AdvancedModel struct {
    ID        uint                `gorm:"primaryKey"`
    Config    duckdb.JSONType     `gorm:"type:json"`
    Price     duckdb.DecimalType  `gorm:"type:decimal(10,2)"`
    UUID      duckdb.UUIDType     `gorm:"type:uuid"`
    Tags      duckdb.StringArray  `json:"tags"`
    Location  duckdb.GEOMETRYType `gorm:"type:geometry"`
}

Extension Management

Built-in DuckDB extension management for enhanced functionality:

// Create database with extension support
db, err := gorm.Open(duckdb.OpenWithExtensions(":memory:", &duckdb.ExtensionConfig{
  AutoInstall:       true,
  PreloadExtensions: []string{"json", "parquet"},
  Timeout:           30 * time.Second,
}), &gorm.Config{})

// Get extension manager
manager, err := duckdb.GetExtensionManager(db)

// Load specific extensions
err = manager.LoadExtension("spatial")

// Use helper functions
helper := duckdb.NewExtensionHelper(manager)
err = helper.EnableAnalytics()    // json, parquet, fts, autocomplete
err = helper.EnableDataFormats()  // json, parquet, csv, excel, arrow
err = helper.EnableSpatial()      // spatial extension

Basic Usage

Define Models
type User struct {
  ID        uint      `gorm:"primaryKey"`
  Name      string    `gorm:"size:100"`
  Email     string    `gorm:"uniqueIndex"`
  Age       int
  CreatedAt time.Time
  UpdatedAt time.Time
}
CRUD Operations
// Auto-migrate schema
db.AutoMigrate(&User{})

// Create
user := User{Name: "John", Email: "john@example.com", Age: 30}
db.Create(&user)

// Read
var user User
db.First(&user, 1)
db.Where("name = ?", "John").Find(&users)

// Update
db.Model(&user).Update("age", 31)

// Delete
db.Delete(&user, 1)
Advanced Queries
// Raw SQL with arrays
var products []Product
db.Raw("SELECT * FROM products WHERE array_has(categories, ?)", "software").Scan(&products)

// Analytical queries
db.Raw(`
    SELECT 
        category,
        COUNT(*) as count,
        AVG(price) as avg_price
    FROM products, UNNEST(categories) AS t(category)
    GROUP BY category
    ORDER BY count DESC
`).Scan(&results)

Configuration Options

config := duckdb.Config{
    DSN:               "production.db",
    DefaultStringSize: 256,
}

gormConfig := &gorm.Config{
    Logger: logger.Default.LogMode(logger.Info),
}

db, err := gorm.Open(duckdb.New(config), gormConfig)

// Configure connection pool
sqlDB, _ := db.DB()
sqlDB.SetMaxIdleConns(10)
sqlDB.SetMaxOpenConns(100)
sqlDB.SetConnMaxLifetime(time.Hour)

Migration Features

The driver includes a custom migrator with DuckDB-specific optimizations:

Auto-Increment Support
type User struct {
    ID   uint   `gorm:"primaryKey"`  // Uses sequence + RETURNING
    Name string `gorm:"size:100"`
}

// Creates: CREATE SEQUENCE seq_users_id START 1
// Insert:  INSERT INTO users (...) VALUES (...) RETURNING "id"
Schema Operations
// Migrator operations
db.Migrator().CreateTable(&User{})
db.Migrator().AddColumn(&User{}, "nickname")
db.Migrator().CreateIndex(&User{}, "idx_user_email")

// Check operations
hasTable := db.Migrator().HasTable(&User{})
hasColumn := db.Migrator().HasColumn(&User{}, "email")

Error Translation

Comprehensive error handling with DuckDB-specific error patterns:

// Automatic error translation
if err := db.Create(&user).Error; err != nil {
    if duckdb.IsDuplicateKeyError(err) {
        // Handle unique constraint violation
    }
    if duckdb.IsForeignKeyError(err) {
        // Handle foreign key violation
    }
}

Examples

The repository includes comprehensive examples in the example/ directory demonstrating:

  • Basic CRUD operations
  • Array usage patterns
  • Advanced type system
  • Extension management
  • Migration best practices
  • Performance optimization

License

MIT License - see LICENSE file for details.

Contributing

Contributions are welcome! Please see CONTRIBUTING.md for guidelines.

Security

For security issues, please see SECURITY.md for reporting instructions.

Documentation

Overview

Package duckdb provides a GORM driver for DuckDB database. This file contains array support for DuckDB array operations.

Index

Constants

View Source
const (
	// Core Extensions (built-in)
	ExtensionJSON    = "json"
	ExtensionParquet = "parquet"
	ExtensionICU     = "icu"

	// Analytics Extensions
	ExtensionAutoComplete = "autocomplete"
	ExtensionFTS          = "fts"
	ExtensionTPCH         = "tpch"
	ExtensionTPCDS        = "tpcds"

	// Data Format Extensions
	ExtensionCSV    = "csv"
	ExtensionExcel  = "excel"
	ExtensionArrow  = "arrow"
	ExtensionSQLite = "sqlite"

	// Networking Extensions
	ExtensionHTTPS = "httpfs"
	ExtensionS3    = "aws"
	ExtensionAzure = "azure"

	// Geospatial Extensions
	ExtensionSpatial = "spatial"

	// Machine Learning Extensions
	ExtensionML = "ml"

	// Time Series Extensions
	ExtensionTimeSeries = "timeseries"

	// Visualization Extensions
	ExtensionVisualization = "visualization"
)

Common DuckDB extensions

Variables

View Source
var (
	ErrUniqueConstraint  = errors.New("UNIQUE constraint failed")
	ErrForeignKey        = errors.New("FOREIGN KEY constraint failed")
	ErrCheckConstraint   = errors.New("CHECK constraint failed")
	ErrNotNullConstraint = errors.New("NOT NULL constraint failed")
	ErrNoSuchTable       = errors.New("no such table")
	ErrNoSuchColumn      = errors.New("no such column")
	ErrSyntaxError       = errors.New("syntax error")
	ErrDatabaseLocked    = errors.New("database is locked")
)

Common DuckDB error patterns

Functions

func FormatSliceForDuckDB added in v0.8.0

func FormatSliceForDuckDB(value interface{}) (string, error)

FormatSliceForDuckDB converts a Go slice to DuckDB array literal syntax

func InitializeExtensions added in v0.4.0

func InitializeExtensions(db *gorm.DB) error

InitializeExtensions manually triggers preloading of configured extensions This should be called after the database connection is fully established

func IsColumnNotFoundError added in v0.4.0

func IsColumnNotFoundError(err error) bool

IsColumnNotFoundError checks if the error is a column not found error

func IsDuplicateKeyError added in v0.4.0

func IsDuplicateKeyError(err error) bool

IsDuplicateKeyError checks if the error is a duplicate key constraint violation

func IsForeignKeyError added in v0.4.0

func IsForeignKeyError(err error) bool

IsForeignKeyError checks if the error is a foreign key constraint violation

func IsNotNullError added in v0.4.0

func IsNotNullError(err error) bool

IsNotNullError checks if the error is a not null constraint violation

func IsSpecificError added in v0.4.0

func IsSpecificError(err error, target error) bool

IsSpecificError checks if an error matches a specific DuckDB error type

func IsTableNotFoundError added in v0.4.0

func IsTableNotFoundError(err error) bool

IsTableNotFoundError checks if the error is a table not found error

func New

func New(config Config) gorm.Dialector

New creates a new DuckDB dialector with the given configuration.

func NewWithExtensions

func NewWithExtensions(config Config, extensionConfig *ExtensionConfig) gorm.Dialector

NewWithExtensions creates a new dialector with extension support

func Open

func Open(dsn string) gorm.Dialector

Open creates a new DuckDB dialector with the given DSN.

func OpenWithConfig added in v0.6.0

func OpenWithConfig(dsn string, config *Config) gorm.Dialector

OpenWithConfig creates a new DuckDB dialector with the given DSN and configuration options.

func OpenWithExtensions

func OpenWithExtensions(dsn string, extensionConfig *ExtensionConfig) gorm.Dialector

OpenWithExtensions creates a dialector with extension support using DSN

func OpenWithRowCallbackWorkaround added in v0.6.0

func OpenWithRowCallbackWorkaround(dsn string, enableWorkaround bool) gorm.Dialector

OpenWithRowCallbackWorkaround creates a DuckDB dialector with explicit RowCallback workaround control. Set enableWorkaround=false if you're using a GORM version that has fixed the RowQuery callback bug.

Types

type AnalyticalFunctionType added in v0.5.2

type AnalyticalFunctionType struct {
	FunctionName string                 `json:"function_name"` // MEDIAN, MODE, PERCENTILE, etc.
	Column       string                 `json:"column"`        // Target column
	Parameters   map[string]interface{} `json:"parameters"`    // Function parameters
	WindowFrame  string                 `json:"window_frame"`  // OVER clause details
}

AnalyticalFunctionType represents advanced DuckDB analytical functions

func NewAnalyticalFunction added in v0.5.2

func NewAnalyticalFunction(functionName, column string, parameters map[string]interface{}, windowFrame string) AnalyticalFunctionType

NewAnalyticalFunction creates a new AnalyticalFunctionType

func (AnalyticalFunctionType) GormDataType added in v0.5.2

func (AnalyticalFunctionType) GormDataType() string

GormDataType implements the GormDataTypeInterface for AnalyticalFunctionType

func (*AnalyticalFunctionType) Scan added in v0.5.2

func (a *AnalyticalFunctionType) Scan(value interface{}) error

Scan implements sql.Scanner interface for AnalyticalFunctionType

func (AnalyticalFunctionType) ToSQL added in v0.5.2

func (a AnalyticalFunctionType) ToSQL() string

ToSQL generates the SQL function syntax

func (AnalyticalFunctionType) Value added in v0.5.2

Value implements driver.Valuer interface for AnalyticalFunctionType

type ArrayLiteral

type ArrayLiteral struct {
	Data interface{}
}

ArrayLiteral wraps a Go slice to be formatted as a DuckDB array literal

func (ArrayLiteral) Value

func (al ArrayLiteral) Value() (driver.Value, error)

Value implements driver.Valuer for DuckDB array literals

type BLOBType added in v0.5.2

type BLOBType struct {
	Data     []byte `json:"data"`     // Binary data content
	MimeType string `json:"mimeType"` // MIME type for content identification
	Size     int64  `json:"size"`     // Size in bytes
}

BLOBType represents a DuckDB BLOB (Binary Large Object) type Essential core type for binary data storage and manipulation

func NewBlob added in v0.5.2

func NewBlob(data []byte, mimeType string) BLOBType

NewBlob creates a new BLOBType with binary data

func (BLOBType) GetContentType added in v0.5.2

func (b BLOBType) GetContentType() string

GetContentType returns the MIME type or detects it from data

func (BLOBType) GormDataType added in v0.5.2

func (BLOBType) GormDataType() string

GormDataType implements the GormDataTypeInterface for BLOBType

func (BLOBType) IsEmpty added in v0.5.2

func (b BLOBType) IsEmpty() bool

IsEmpty returns true if the BLOB contains no data

func (*BLOBType) Scan added in v0.5.2

func (b *BLOBType) Scan(value interface{}) error

Scan implements sql.Scanner interface for BLOBType

func (BLOBType) Value added in v0.5.2

func (b BLOBType) Value() (driver.Value, error)

Value implements driver.Valuer interface for BLOBType

type BitStringType added in v0.5.2

type BitStringType struct {
	Bits   []bool `json:"bits"`   // Individual bit values
	Length int    `json:"length"` // Fixed length (0 = variable length)
}

BitStringType represents a DuckDB BIT/BITSTRING type

func NewBitString added in v0.5.2

func NewBitString(bits []bool, length int) BitStringType

NewBitString creates a new BitStringType

func NewBitStringFromString added in v0.5.2

func NewBitStringFromString(bitStr string, length int) (BitStringType, error)

NewBitStringFromString creates a BitStringType from a binary string

func (BitStringType) Count added in v0.5.2

func (b BitStringType) Count() int

Count returns the number of set bits (1s)

func (BitStringType) Get added in v0.5.2

func (b BitStringType) Get(position int) (bool, error)

Get returns the bit value at the specified position

func (BitStringType) GormDataType added in v0.5.2

func (b BitStringType) GormDataType() string

GormDataType implements the GormDataTypeInterface for BitStringType

func (*BitStringType) Scan added in v0.5.2

func (b *BitStringType) Scan(value interface{}) error

Scan implements sql.Scanner interface for BitStringType

func (*BitStringType) Set added in v0.5.2

func (b *BitStringType) Set(position int, value bool) error

Set sets the bit value at the specified position

func (BitStringType) ToBinaryString added in v0.5.2

func (b BitStringType) ToBinaryString() string

ToBinaryString returns the bit string as binary representation

func (BitStringType) ToHexString added in v0.5.2

func (b BitStringType) ToHexString() string

ToHexString returns the bit string as hexadecimal representation

func (BitStringType) Value added in v0.5.2

func (b BitStringType) Value() (driver.Value, error)

Value implements driver.Valuer interface for BitStringType

type Config

type Config struct {
	DriverName        string
	DSN               string
	Conn              gorm.ConnPool
	DefaultStringSize uint

	// RowCallbackWorkaround controls whether to apply the GORM RowQuery callback fix
	// Set to false to disable the workaround if GORM fixes the bug in the future
	// Default: true (apply workaround)
	RowCallbackWorkaround *bool
}

Config holds configuration options for the DuckDB dialector.

type ConstraintType added in v0.5.2

type ConstraintType struct {
	ConstraintType string                 `json:"constraint_type"` // CHECK, UNIQUE, FOREIGN_KEY, etc.
	Expression     string                 `json:"expression"`      // Constraint expression
	Options        map[string]interface{} `json:"options"`         // Additional constraint options
}

ConstraintType represents advanced DuckDB constraints

func NewConstraint added in v0.5.2

func NewConstraint(constraintType, expression string, options map[string]interface{}) ConstraintType

NewConstraint creates a new ConstraintType

func (ConstraintType) GormDataType added in v0.5.2

func (ConstraintType) GormDataType() string

GormDataType implements the GormDataTypeInterface for ConstraintType

func (*ConstraintType) Scan added in v0.5.2

func (c *ConstraintType) Scan(value interface{}) error

Scan implements sql.Scanner interface for ConstraintType

func (ConstraintType) ToSQL added in v0.5.2

func (c ConstraintType) ToSQL() string

ToSQL generates the SQL constraint syntax

func (ConstraintType) Value added in v0.5.2

func (c ConstraintType) Value() (driver.Value, error)

Value implements driver.Valuer interface for ConstraintType

type DecimalType added in v0.5.2

type DecimalType struct {
	Data      string // Store as string to preserve precision
	Precision int    // Total digits
	Scale     int    // Digits after decimal point
}

DecimalType represents a DuckDB DECIMAL type with precise numeric operations

func NewDecimal added in v0.5.2

func NewDecimal(value string, precision, scale int) DecimalType

NewDecimal creates a new DecimalType from a string representation

func (DecimalType) Float64 added in v0.5.2

func (d DecimalType) Float64() (float64, error)

Float64 returns the decimal value as a float64 (may lose precision)

func (DecimalType) GormDataType added in v0.5.2

func (d DecimalType) GormDataType() string

GormDataType implements the GormDataTypeInterface for DecimalType

func (*DecimalType) Scan added in v0.5.2

func (d *DecimalType) Scan(value interface{}) error

Scan implements sql.Scanner interface for DecimalType

func (DecimalType) String added in v0.5.2

func (d DecimalType) String() string

String returns the string representation of the decimal

func (DecimalType) Value added in v0.5.2

func (d DecimalType) Value() (driver.Value, error)

Value implements driver.Valuer interface for DecimalType

type Dialector

type Dialector struct {
	*Config
}

Dialector implements gorm.Dialector interface for DuckDB database.

func (Dialector) BindVarTo

func (dialector Dialector) BindVarTo(writer clause.Writer, _ *gorm.Statement, _ interface{})

BindVarTo writes the bind variable to the clause writer.

func (Dialector) DataTypeOf

func (dialector Dialector) DataTypeOf(field *schema.Field) string

DataTypeOf returns the SQL data type for a given field. nolint:gocyclo // Complex type mapping function required for comprehensive DuckDB type support

func (Dialector) DefaultValueOf

func (dialector Dialector) DefaultValueOf(field *schema.Field) clause.Expression

DefaultValueOf returns the default value clause for a field.

func (Dialector) Explain

func (dialector Dialector) Explain(sql string, vars ...interface{}) string

Explain returns an explanation of the SQL query.

func (Dialector) Initialize

func (dialector Dialector) Initialize(db *gorm.DB) error

Initialize implements gorm.Dialector

func (Dialector) Migrator

func (dialector Dialector) Migrator(db *gorm.DB) gorm.Migrator

Migrator returns a new migrator instance for DuckDB.

func (Dialector) Name

func (dialector Dialector) Name() string

Name returns the name of the dialector.

func (Dialector) QuoteTo

func (dialector Dialector) QuoteTo(writer clause.Writer, str string)

QuoteTo writes quoted identifiers to the writer.

func (Dialector) RollbackTo

func (dialector Dialector) RollbackTo(tx *gorm.DB, name string) error

RollbackTo rolls back to the given savepoint.

func (Dialector) SavePoint

func (dialector Dialector) SavePoint(tx *gorm.DB, name string) error

SavePoint creates a savepoint with the given name.

func (Dialector) Translate added in v0.5.2

func (dialector Dialector) Translate(err error) error

Translate implements ErrorTranslator interface for built-in error translation

type ENUMType added in v0.5.2

type ENUMType struct {
	Values   []string `json:"values"`   // Allowed enum values
	Selected string   `json:"selected"` // Current selected value
	Name     string   `json:"name"`     // Enum type name
}

ENUMType represents a DuckDB ENUM type with predefined allowed values

func NewEnum added in v0.5.2

func NewEnum(name string, values []string, selected string) ENUMType

NewEnum creates a new ENUMType with allowed values

func (ENUMType) GormDataType added in v0.5.2

func (e ENUMType) GormDataType() string

GormDataType implements the GormDataTypeInterface for ENUMType

func (ENUMType) IsValid added in v0.5.2

func (e ENUMType) IsValid() bool

IsValid checks if the current selected value is valid

func (*ENUMType) Scan added in v0.5.2

func (e *ENUMType) Scan(value interface{}) error

Scan implements sql.Scanner interface for ENUMType

func (ENUMType) Value added in v0.5.2

func (e ENUMType) Value() (driver.Value, error)

Value implements driver.Valuer interface for ENUMType

type ErrorTranslator added in v0.4.0

type ErrorTranslator struct{}

ErrorTranslator implements gorm.ErrorTranslator for DuckDB

func (ErrorTranslator) Translate added in v0.4.0

func (et ErrorTranslator) Translate(err error) error

Translate converts DuckDB errors to GORM errors

type Extension

type Extension struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Loaded      bool   `json:"loaded"`
	Installed   bool   `json:"installed"`
	BuiltIn     bool   `json:"built_in,omitempty"`
	Version     string `json:"version,omitempty"`
}

Extension represents a DuckDB extension with its metadata and status

type ExtensionConfig

type ExtensionConfig struct {
	// AutoInstall automatically installs extensions when loading
	AutoInstall bool

	// PreloadExtensions list of extensions to load on database connection
	PreloadExtensions []string

	// Timeout for extension operations (0 = no timeout)
	Timeout time.Duration

	// RepositoryURL custom extension repository URL
	RepositoryURL string

	// AllowUnsigned allows loading unsigned extensions (security risk)
	AllowUnsigned bool
}

ExtensionConfig holds configuration for extension management

type ExtensionHelper

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

ExtensionHelper provides convenience methods for common extension operations

func NewExtensionHelper

func NewExtensionHelper(manager *ExtensionManager) *ExtensionHelper

NewExtensionHelper creates a new extension helper

func (*ExtensionHelper) EnableAnalytics

func (h *ExtensionHelper) EnableAnalytics() error

EnableAnalytics loads common analytics extensions

func (*ExtensionHelper) EnableCloudAccess

func (h *ExtensionHelper) EnableCloudAccess() error

EnableCloudAccess loads cloud storage extensions

func (*ExtensionHelper) EnableDataFormats

func (h *ExtensionHelper) EnableDataFormats() error

EnableDataFormats loads common data format extensions

func (*ExtensionHelper) EnableMachineLearning

func (h *ExtensionHelper) EnableMachineLearning() error

EnableMachineLearning loads ML extensions

func (*ExtensionHelper) EnableSpatial

func (h *ExtensionHelper) EnableSpatial() error

EnableSpatial loads geospatial extensions

func (*ExtensionHelper) EnableTimeSeries

func (h *ExtensionHelper) EnableTimeSeries() error

EnableTimeSeries loads time series extensions

type ExtensionManager

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

ExtensionManager handles DuckDB extension operations

func GetExtensionManager

func GetExtensionManager(db *gorm.DB) (*ExtensionManager, error)

GetExtensionManager retrieves the extension manager from a database instance

func MustGetExtensionManager

func MustGetExtensionManager(db *gorm.DB) *ExtensionManager

MustGetExtensionManager retrieves the extension manager, panics if not found

func NewExtensionManager

func NewExtensionManager(db *gorm.DB, config *ExtensionConfig) *ExtensionManager

NewExtensionManager creates a new extension manager instance

func (*ExtensionManager) GetExtension

func (m *ExtensionManager) GetExtension(name string) (*Extension, error)

GetExtension returns information about a specific extension

func (*ExtensionManager) GetLoadedExtensions

func (m *ExtensionManager) GetLoadedExtensions() ([]Extension, error)

GetLoadedExtensions returns all currently loaded extensions

func (*ExtensionManager) InstallExtension

func (m *ExtensionManager) InstallExtension(name string) error

InstallExtension installs an extension from the repository

func (*ExtensionManager) IsExtensionLoaded

func (m *ExtensionManager) IsExtensionLoaded(name string) bool

IsExtensionLoaded checks if an extension is currently loaded

func (*ExtensionManager) ListExtensions

func (m *ExtensionManager) ListExtensions() ([]Extension, error)

ListExtensions returns all available extensions

func (*ExtensionManager) LoadExtension

func (m *ExtensionManager) LoadExtension(name string) error

LoadExtension loads an extension, optionally installing it first

func (*ExtensionManager) LoadExtensions

func (m *ExtensionManager) LoadExtensions(names []string) error

LoadExtensions loads multiple extensions

func (*ExtensionManager) PreloadExtensions

func (m *ExtensionManager) PreloadExtensions() error

PreloadExtensions loads all configured preload extensions

type FloatArray

type FloatArray struct {
	duckdb.Composite[[]float64]
}

FloatArray represents a DuckDB float array using native Composite type

func NewFloatArray added in v0.6.1

func NewFloatArray(values []float64) FloatArray

NewFloatArray creates a new FloatArray from a slice of float64 values.

func (FloatArray) GormDataType

func (FloatArray) GormDataType() string

GormDataType returns the GORM data type for FloatArray.

func (*FloatArray) Scan

func (a *FloatArray) Scan(value interface{}) error

Scan implements sql.Scanner interface for FloatArray.

func (FloatArray) Value

func (a FloatArray) Value() (driver.Value, error)

Value implements driver.Valuer interface for FloatArray.

type GEOMETRYType added in v0.5.2

type GEOMETRYType struct {
	WKT        string                 `json:"wkt"`        // Well-Known Text representation
	SRID       int                    `json:"srid"`       // Spatial Reference System Identifier
	GeomType   string                 `json:"geomType"`   // Geometry type (POINT, LINESTRING, POLYGON, etc.)
	Dimensions int                    `json:"dimensions"` // 2D, 3D, or 4D
	Properties map[string]interface{} `json:"properties"` // Additional spatial properties
}

GEOMETRYType represents a DuckDB GEOMETRY type for spatial data Critical core type for geospatial analysis and location-based operations

func NewGeometry added in v0.5.2

func NewGeometry(wkt string, srid int) GEOMETRYType

NewGeometry creates a new GEOMETRYType from Well-Known Text

func (GEOMETRYType) GetBounds added in v0.5.2

func (g GEOMETRYType) GetBounds() map[string]float64

GetBounds returns the bounding box of the geometry (simplified implementation)

func (GEOMETRYType) GormDataType added in v0.5.2

func (GEOMETRYType) GormDataType() string

GormDataType implements the GormDataTypeInterface for GEOMETRYType

func (GEOMETRYType) IsEmpty added in v0.5.2

func (g GEOMETRYType) IsEmpty() bool

IsEmpty returns true if the geometry has no WKT data

func (GEOMETRYType) IsPoint added in v0.5.2

func (g GEOMETRYType) IsPoint() bool

IsPoint returns true if the geometry is a POINT

func (GEOMETRYType) IsPolygon added in v0.5.2

func (g GEOMETRYType) IsPolygon() bool

IsPolygon returns true if the geometry is a POLYGON

func (*GEOMETRYType) Scan added in v0.5.2

func (g *GEOMETRYType) Scan(value interface{}) error

Scan implements sql.Scanner interface for GEOMETRYType

func (*GEOMETRYType) SetProperty added in v0.5.2

func (g *GEOMETRYType) SetProperty(key string, value interface{})

SetProperty sets a custom property for the geometry

func (GEOMETRYType) Value added in v0.5.2

func (g GEOMETRYType) Value() (driver.Value, error)

Value implements driver.Valuer interface for GEOMETRYType

type HugeIntType added in v0.5.2

type HugeIntType struct {
	Data *big.Int `json:"data"` // 128-bit integer value
}

HugeIntType represents a DuckDB HUGEINT (128-bit integer)

func NewHugeInt added in v0.5.2

func NewHugeInt(value interface{}) (HugeIntType, error)

NewHugeInt creates a new HugeIntType from various sources

func (HugeIntType) GormDataType added in v0.5.2

func (HugeIntType) GormDataType() string

GormDataType implements the GormDataTypeInterface for HugeIntType

func (HugeIntType) Int64 added in v0.5.2

func (h HugeIntType) Int64() (int64, error)

Int64 returns the value as int64 if it fits, otherwise returns an error

func (*HugeIntType) Scan added in v0.5.2

func (h *HugeIntType) Scan(value interface{}) error

Scan implements sql.Scanner interface for HugeIntType

func (HugeIntType) String added in v0.5.2

func (h HugeIntType) String() string

String returns the string representation

func (HugeIntType) Value added in v0.5.2

func (h HugeIntType) Value() (driver.Value, error)

Value implements driver.Valuer interface for HugeIntType

type Index added in v0.7.0

type Index struct {
	TableName   string
	IndexName   string
	ColumnNames []string
	IsUnique    bool
	IsPrimary   bool
	Options     string
}

Index represents a database index with its properties.

func (Index) Columns added in v0.7.0

func (idx Index) Columns() []string

Columns returns the columns that make up the index.

func (Index) Name added in v0.7.0

func (idx Index) Name() string

Name returns the name of the index.

func (Index) Option added in v0.7.0

func (idx Index) Option() string

Option returns additional options for the index.

func (Index) PrimaryKey added in v0.7.0

func (idx Index) PrimaryKey() (isPrimaryKey bool, ok bool)

PrimaryKey returns whether this index is a primary key.

func (Index) Table added in v0.7.0

func (idx Index) Table() string

Table returns the table name for the index.

func (Index) Unique added in v0.7.0

func (idx Index) Unique() (unique bool, ok bool)

Unique returns whether this index enforces uniqueness.

type IntArray

type IntArray struct {
	duckdb.Composite[[]int64]
}

IntArray represents a DuckDB integer array using native Composite type

func NewIntArray added in v0.6.1

func NewIntArray(values []int64) IntArray

NewIntArray creates a new IntArray from a slice of int64 values.

func (IntArray) GormDataType

func (IntArray) GormDataType() string

GormDataType returns the GORM data type for IntArray.

func (*IntArray) Scan

func (a *IntArray) Scan(value interface{}) error

Scan implements sql.Scanner interface for IntArray.

func (IntArray) Value

func (a IntArray) Value() (driver.Value, error)

Value implements driver.Valuer interface for IntArray.

type IntervalType added in v0.5.2

type IntervalType struct {
	Years   int
	Months  int
	Days    int
	Hours   int
	Minutes int
	Seconds int
	Micros  int
}

IntervalType represents a DuckDB INTERVAL type for time calculations

func NewInterval added in v0.5.2

func NewInterval(years, months, days, hours, minutes, seconds, micros int) IntervalType

NewInterval creates a new IntervalType

func (IntervalType) GormDataType added in v0.5.2

func (IntervalType) GormDataType() string

GormDataType implements the GormDataTypeInterface for IntervalType

func (*IntervalType) Scan added in v0.5.2

func (i *IntervalType) Scan(value interface{}) error

Scan implements sql.Scanner interface for IntervalType

func (IntervalType) ToDuration added in v0.5.2

func (i IntervalType) ToDuration() time.Duration

ToDuration converts the interval to a Go time.Duration (approximate for days/months/years)

func (IntervalType) Value added in v0.5.2

func (i IntervalType) Value() (driver.Value, error)

Value implements driver.Valuer interface for IntervalType

type JSONType added in v0.5.2

type JSONType struct {
	Data interface{} // Can hold any JSON-serializable data
}

JSONType represents a DuckDB JSON type with native JSON operations

func NewJSON added in v0.5.2

func NewJSON(data interface{}) JSONType

NewJSON creates a new JSONType from any JSON-serializable data

func (JSONType) GormDataType added in v0.5.2

func (JSONType) GormDataType() string

GormDataType implements the GormDataTypeInterface for JSONType

func (*JSONType) Scan added in v0.5.2

func (j *JSONType) Scan(value interface{}) error

Scan implements sql.Scanner interface for JSONType

func (JSONType) String added in v0.5.2

func (j JSONType) String() string

String returns the JSON as a formatted string

func (JSONType) Value added in v0.5.2

func (j JSONType) Value() (driver.Value, error)

Value implements driver.Valuer interface for JSONType

type ListType added in v0.5.2

type ListType []interface{}

ListType represents a DuckDB LIST type - dynamic arrays with variable element types

func (ListType) GormDataType added in v0.5.2

func (ListType) GormDataType() string

GormDataType implements the GormDataTypeInterface for ListType

func (*ListType) Scan added in v0.5.2

func (l *ListType) Scan(value interface{}) error

Scan implements sql.Scanner interface for ListType

func (ListType) Value added in v0.5.2

func (l ListType) Value() (driver.Value, error)

Value implements driver.Valuer interface for ListType

type MapType added in v0.5.2

type MapType map[string]interface{}

MapType represents a DuckDB MAP type - key-value pairs with typed keys and values

func (MapType) GormDataType added in v0.5.2

func (MapType) GormDataType() string

GormDataType implements the GormDataTypeInterface for MapType

func (*MapType) Scan added in v0.5.2

func (m *MapType) Scan(value interface{}) error

Scan implements sql.Scanner interface for MapType

func (MapType) Value added in v0.5.2

func (m MapType) Value() (driver.Value, error)

Value implements driver.Valuer interface for MapType

type Migrator

type Migrator struct {
	migrator.Migrator
}

Migrator implements gorm.Migrator interface for DuckDB database.

func (Migrator) AlterColumn

func (m Migrator) AlterColumn(value interface{}, field string) error

AlterColumn modifies a column definition in DuckDB, handling syntax limitations.

func (Migrator) BuildIndexOptions added in v0.5.2

func (m Migrator) BuildIndexOptions(opts []schema.IndexOption, stmt *gorm.Statement) (results []interface{})

BuildIndexOptions builds index options for DuckDB

func (Migrator) ColumnTypes added in v0.5.2

func (m Migrator) ColumnTypes(value interface{}) ([]gorm.ColumnType, error)

ColumnTypes returns comprehensive column type information for the given value

func (Migrator) CreateTable added in v0.4.0

func (m Migrator) CreateTable(values ...interface{}) error

CreateTable overrides the default CreateTable to handle DuckDB-specific auto-increment sequences

func (Migrator) CreateView

func (m Migrator) CreateView(name string, option gorm.ViewOption) error

CreateView creates a database view.

func (Migrator) CurrentDatabase

func (m Migrator) CurrentDatabase() (name string)

CurrentDatabase returns the current database name.

func (Migrator) DropConstraint

func (m Migrator) DropConstraint(value interface{}, name string) error

DropConstraint drops a constraint from the database.

func (Migrator) DropIndex

func (m Migrator) DropIndex(value interface{}, name string) error

DropIndex drops an index from the database.

func (Migrator) DropView

func (m Migrator) DropView(name string) error

DropView drops a database view.

func (Migrator) FullDataTypeOf

func (m Migrator) FullDataTypeOf(field *schema.Field) clause.Expr

FullDataTypeOf returns the full data type for a field including constraints. Override FullDataTypeOf to prevent GORM from adding duplicate PRIMARY KEY clauses

func (Migrator) GetIndexes added in v0.5.2

func (m Migrator) GetIndexes(value interface{}) ([]gorm.Index, error)

GetIndexes returns comprehensive index information for the given value

func (Migrator) GetTables

func (m Migrator) GetTables() (tableList []string, err error)

GetTables returns a list of all table names in the database.

func (Migrator) GetTypeAliases

func (m Migrator) GetTypeAliases(databaseTypeName string) []string

GetTypeAliases returns type aliases for the given database type name.

func (Migrator) HasColumn

func (m Migrator) HasColumn(value interface{}, field string) bool

HasColumn checks if a column exists in the database table.

func (Migrator) HasConstraint

func (m Migrator) HasConstraint(value interface{}, name string) bool

HasConstraint checks if a constraint exists in the database.

func (Migrator) HasIndex

func (m Migrator) HasIndex(value interface{}, name string) bool

HasIndex checks if an index exists in the database.

func (Migrator) HasTable

func (m Migrator) HasTable(value interface{}) bool

HasTable checks if a table exists in the database.

func (Migrator) RenameColumn

func (m Migrator) RenameColumn(value interface{}, oldName, newName string) error

RenameColumn renames a column in the database table.

func (Migrator) RenameIndex

func (m Migrator) RenameIndex(value interface{}, oldName, newName string) error

RenameIndex renames an index in the database.

func (Migrator) TableType added in v0.5.2

func (m Migrator) TableType(value interface{}) (gorm.TableType, error)

TableType returns comprehensive table type information

type NestedArrayType added in v0.5.2

type NestedArrayType struct {
	ElementType string        `json:"element_type"` // Type of elements (STRUCT, MAP, etc.)
	Elements    []interface{} `json:"elements"`     // Array elements
	Dimensions  int           `json:"dimensions"`   // Number of array dimensions
}

NestedArrayType represents advanced nested array operations (arrays of complex types)

func NewNestedArray added in v0.5.2

func NewNestedArray(elementType string, elements []interface{}, dimensions int) NestedArrayType

NewNestedArray creates a new NestedArrayType

func (NestedArrayType) Get added in v0.5.2

func (n NestedArrayType) Get(index int) (interface{}, error)

Get returns the element at the specified index

func (NestedArrayType) GormDataType added in v0.5.2

func (n NestedArrayType) GormDataType() string

GormDataType implements the GormDataTypeInterface for NestedArrayType

func (NestedArrayType) Length added in v0.5.2

func (n NestedArrayType) Length() int

Length returns the number of elements in the array

func (*NestedArrayType) Scan added in v0.5.2

func (n *NestedArrayType) Scan(value interface{}) error

Scan implements sql.Scanner interface for NestedArrayType

func (NestedArrayType) Slice added in v0.5.2

func (n NestedArrayType) Slice(start, end int) (NestedArrayType, error)

Slice returns a slice of the array from start to end

func (NestedArrayType) Value added in v0.5.2

func (n NestedArrayType) Value() (driver.Value, error)

Value implements driver.Valuer interface for NestedArrayType

type PerformanceMetricsType added in v0.5.2

type PerformanceMetricsType struct {
	QueryTime    float64                `json:"query_time"`    // Execution time in milliseconds
	MemoryUsage  int64                  `json:"memory_usage"`  // Memory usage in bytes
	RowsScanned  int64                  `json:"rows_scanned"`  // Number of rows scanned
	RowsReturned int64                  `json:"rows_returned"` // Number of rows returned
	Metrics      map[string]interface{} `json:"metrics"`       // Additional performance metrics
}

PerformanceMetricsType represents DuckDB performance and profiling information

func NewPerformanceMetrics added in v0.5.2

func NewPerformanceMetrics() PerformanceMetricsType

NewPerformanceMetrics creates a new PerformanceMetricsType

func (*PerformanceMetricsType) AddMetric added in v0.5.2

func (p *PerformanceMetricsType) AddMetric(key string, value interface{})

AddMetric adds a custom performance metric

func (PerformanceMetricsType) GetMetric added in v0.5.2

func (p PerformanceMetricsType) GetMetric(key string) (interface{}, bool)

GetMetric retrieves a custom performance metric

func (PerformanceMetricsType) GormDataType added in v0.5.2

func (PerformanceMetricsType) GormDataType() string

GormDataType implements the GormDataTypeInterface for PerformanceMetricsType

func (*PerformanceMetricsType) Scan added in v0.5.2

func (p *PerformanceMetricsType) Scan(value interface{}) error

Scan implements sql.Scanner interface for PerformanceMetricsType

func (PerformanceMetricsType) Summary added in v0.5.2

func (p PerformanceMetricsType) Summary() string

Summary returns a formatted summary of performance metrics

func (PerformanceMetricsType) Value added in v0.5.2

Value implements driver.Valuer interface for PerformanceMetricsType

type QueryHintType added in v0.5.2

type QueryHintType struct {
	HintType string                 `json:"hint_type"` // Type of hint (INDEX, PARTITION, etc.)
	Options  map[string]interface{} `json:"options"`   // Hint options and parameters
}

QueryHintType represents DuckDB query optimization hints

func NewQueryHint added in v0.5.2

func NewQueryHint(hintType string, options map[string]interface{}) QueryHintType

NewQueryHint creates a new QueryHintType

func (QueryHintType) GormDataType added in v0.5.2

func (QueryHintType) GormDataType() string

GormDataType implements the GormDataTypeInterface for QueryHintType

func (*QueryHintType) Scan added in v0.5.2

func (q *QueryHintType) Scan(value interface{}) error

Scan implements sql.Scanner interface for QueryHintType

func (QueryHintType) ToSQL added in v0.5.2

func (q QueryHintType) ToSQL() string

ToSQL generates the SQL hint syntax

func (QueryHintType) Value added in v0.5.2

func (q QueryHintType) Value() (driver.Value, error)

Value implements driver.Valuer interface for QueryHintType

type SimpleArrayScanner

type SimpleArrayScanner struct {
	Target interface{} // Pointer to slice
}

SimpleArrayScanner provides basic array scanning functionality

func (*SimpleArrayScanner) Scan

func (sas *SimpleArrayScanner) Scan(value interface{}) error

Scan implements sql.Scanner for basic array types

type StringArray

type StringArray struct {
	duckdb.Composite[[]string]
}

StringArray represents a DuckDB string array using native Composite type

func NewStringArray added in v0.6.1

func NewStringArray(values []string) StringArray

NewStringArray creates a new StringArray from a slice of strings.

func (StringArray) GormDataType

func (StringArray) GormDataType() string

GormDataType returns the GORM data type for StringArray. GormDataType returns the GORM data type for StringArray.

func (*StringArray) Scan

func (a *StringArray) Scan(value interface{}) error

Scan implementations for sql.Scanner interface

func (StringArray) Value

func (a StringArray) Value() (driver.Value, error)

Value implementations for driver.Valuer interface

type StructType added in v0.5.2

type StructType map[string]interface{}

StructType represents a DuckDB STRUCT type - complex nested data with named fields

func (StructType) GormDataType added in v0.5.2

func (StructType) GormDataType() string

GormDataType implements the GormDataTypeInterface for StructType

func (*StructType) Scan added in v0.5.2

func (s *StructType) Scan(value interface{}) error

Scan implements sql.Scanner interface for StructType

func (StructType) Value added in v0.5.2

func (s StructType) Value() (driver.Value, error)

Value implements driver.Valuer interface for StructType

type TimestampTZType added in v0.5.2

type TimestampTZType struct {
	Time     time.Time      `json:"time"`     // The timestamp
	Location *time.Location `json:"location"` // Timezone information
}

TimestampTZType represents a DuckDB TIMESTAMPTZ (timestamp with timezone)

func NewTimestampTZ added in v0.5.2

func NewTimestampTZ(t time.Time, location *time.Location) TimestampTZType

NewTimestampTZ creates a new TimestampTZType

func (TimestampTZType) GormDataType added in v0.5.2

func (TimestampTZType) GormDataType() string

GormDataType implements the GormDataTypeInterface for TimestampTZType

func (TimestampTZType) In added in v0.5.2

In returns the timestamp in the specified timezone

func (*TimestampTZType) Scan added in v0.5.2

func (t *TimestampTZType) Scan(value interface{}) error

Scan implements sql.Scanner interface for TimestampTZType

func (TimestampTZType) UTC added in v0.5.2

func (t TimestampTZType) UTC() time.Time

UTC returns the timestamp in UTC

func (TimestampTZType) Value added in v0.5.2

func (t TimestampTZType) Value() (driver.Value, error)

Value implements driver.Valuer interface for TimestampTZType

type UNIONType added in v0.5.2

type UNIONType struct {
	Types    []string    `json:"types"`     // Allowed type names
	Data     interface{} `json:"data"`      // Current value
	TypeName string      `json:"type_name"` // Active type name
}

UNIONType represents a DuckDB UNION type that can hold values of different types

func NewUnion added in v0.5.2

func NewUnion(types []string, value interface{}, typeName string) UNIONType

NewUnion creates a new UNIONType

func (UNIONType) GormDataType added in v0.5.2

func (UNIONType) GormDataType() string

GormDataType implements the GormDataTypeInterface for UNIONType

func (*UNIONType) Scan added in v0.5.2

func (u *UNIONType) Scan(value interface{}) error

Scan implements sql.Scanner interface for UNIONType

func (UNIONType) Value added in v0.5.2

func (u UNIONType) Value() (driver.Value, error)

Value implements driver.Valuer interface for UNIONType

type UUIDType added in v0.5.2

type UUIDType struct {
	Data string // Store UUID as string
}

UUIDType represents a DuckDB UUID type

func NewUUID added in v0.5.2

func NewUUID(uuid string) UUIDType

NewUUID creates a new UUIDType from a string

func (UUIDType) GormDataType added in v0.5.2

func (UUIDType) GormDataType() string

GormDataType implements the GormDataTypeInterface for UUIDType

func (*UUIDType) Scan added in v0.5.2

func (u *UUIDType) Scan(value interface{}) error

Scan implements sql.Scanner interface for UUIDType

func (UUIDType) String added in v0.5.2

func (u UUIDType) String() string

String returns the UUID as a string

func (UUIDType) Value added in v0.5.2

func (u UUIDType) Value() (driver.Value, error)

Value implements driver.Valuer interface for UUIDType

Directories

Path Synopsis
internal
tests/array
Package duckdb provides a GORM driver for DuckDB database.
Package duckdb provides a GORM driver for DuckDB database.

Jump to

Keyboard shortcuts

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