models

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2025 License: MIT Imports: 5 Imported by: 0

README

Porter Models Package

The models package provides core data structures and schemas used throughout the Flight SQL server, including query handling, metadata management, and Arrow schema definitions.

Design Overview

Core Components
  1. Query Models

    type QueryRequest struct {
        Query         string
        TransactionID string
        Parameters    []interface{}
        MaxRows       int64
        Timeout       time.Duration
        Properties    map[string]interface{}
    }
    
    type QueryResult struct {
        Schema        *arrow.Schema
        Records       <-chan arrow.Record
        TotalRows     int64
        ExecutionTime time.Duration
        Metadata      map[string]interface{}
    }
    
  2. Transaction Models

    type Transaction struct {
        ID             string
        IsolationLevel IsolationLevel
        ReadOnly       bool
        StartedAt      time.Time
        LastActivityAt time.Time
        State          TransactionState
    }
    
  3. Metadata Models

    type Catalog struct {
        Name        string
        Description string
        Properties  map[string]interface{}
    }
    
    type Schema struct {
        CatalogName string
        Name        string
        Owner       string
        Description string
        Properties  map[string]interface{}
    }
    
    type Table struct {
        CatalogName string
        SchemaName  string
        Name        string
        Type        string
        Description string
        Owner       string
        CreatedAt   *time.Time
        UpdatedAt   *time.Time
        RowCount    *int64
        Properties  map[string]interface{}
    }
    

Implementation Details

Query Handling
  1. Query Requests

    • SQL query string
    • Transaction context
    • Parameter binding
    • Execution limits
    • Custom properties
  2. Query Results

    • Arrow schema
    • Record streaming
    • Execution metrics
    • Result metadata
  3. Prepared Statements

    • Statement handle
    • Parameter schema
    • Result schema
    • Usage tracking
Transaction Management
  1. Transaction States

    const (
        TransactionStateActive      = "ACTIVE"
        TransactionStateCommitting  = "COMMITTING"
        TransactionStateRollingBack = "ROLLING_BACK"
        TransactionStateCommitted   = "COMMITTED"
        TransactionStateRolledBack  = "ROLLED_BACK"
    )
    
  2. Isolation Levels

    const (
        IsolationLevelDefault         = ""
        IsolationLevelReadUncommitted = "READ_UNCOMMITTED"
        IsolationLevelReadCommitted   = "READ_COMMITTED"
        IsolationLevelRepeatableRead  = "REPEATABLE_READ"
        IsolationLevelSerializable    = "SERIALIZABLE"
    )
    
Metadata Management
  1. Database Objects

    • Catalogs
    • Schemas
    • Tables
    • Columns
    • Keys
  2. Type Information

    • XDBC types
    • SQL info
    • Type mappings
    • Type properties
  3. Statistics

    • Table statistics
    • Index statistics
    • Column statistics
    • Usage metrics
Arrow Schema Integration
  1. Schema Definitions

    func GetCatalogsSchema() *arrow.Schema
    func GetDBSchemasSchema() *arrow.Schema
    func GetTablesSchema(includeSchema bool) *arrow.Schema
    func GetTableTypesSchema() *arrow.Schema
    
  2. Result Conversion

    type XdbcTypeInfoResult struct {
        Types []XdbcTypeInfo
    }
    
    func (x *XdbcTypeInfoResult) ToArrowRecord(allocator memory.Allocator) arrow.Record
    

Usage

Query Execution
// Create query request
request := models.QueryRequest{
    Query:         "SELECT * FROM users WHERE age > ?",
    Parameters:    []interface{}{18},
    MaxRows:       1000,
    Timeout:       30 * time.Second,
    Properties:    map[string]interface{}{"cache": true},
}

// Handle query result
result := models.QueryResult{
    Schema:        schema,
    Records:       records,
    TotalRows:     100,
    ExecutionTime: 50 * time.Millisecond,
    Metadata:      map[string]interface{}{"cached": true},
}
Transaction Management
// Create transaction
tx := models.Transaction{
    ID:             "tx-123",
    IsolationLevel: models.IsolationLevelReadCommitted,
    ReadOnly:       false,
    StartedAt:      time.Now(),
    State:          models.TransactionStateActive,
}

// Update transaction state
tx.State = models.TransactionStateCommitting
tx.LastActivityAt = time.Now()
Metadata Access
// Get table information
table := models.Table{
    CatalogName: "main",
    SchemaName:  "public",
    Name:        "users",
    Type:        "TABLE",
    Description: "User accounts",
    RowCount:    &rowCount,
}

// Get column information
column := models.Column{
    CatalogName:     "main",
    SchemaName:      "public",
    TableName:       "users",
    Name:            "email",
    DataType:        "VARCHAR",
    IsNullable:      false,
    CharMaxLength:   sql.NullInt64{Int64: 255, Valid: true},
}

Best Practices

  1. Query Handling

    • Use parameterized queries
    • Set appropriate timeouts
    • Handle large result sets
    • Monitor execution metrics
  2. Transaction Management

    • Choose appropriate isolation
    • Handle transaction states
    • Monitor transaction duration
    • Implement proper cleanup
  3. Metadata Usage

    • Cache metadata when possible
    • Handle null values properly
    • Validate object references
    • Track metadata changes
  4. Arrow Integration

    • Reuse schema definitions
    • Handle memory allocation
    • Manage record streaming
    • Monitor conversion overhead

Testing

The package includes comprehensive tests:

  1. Query Tests

    • Request validation
    • Result handling
    • Parameter binding
    • Error cases
  2. Transaction Tests

    • State transitions
    • Isolation levels
    • Concurrent access
    • Error handling
  3. Metadata Tests

    • Object validation
    • Type conversion
    • Null handling
    • Reference integrity

Performance Considerations

  1. Memory Usage

    • Schema caching
    • Record batching
    • Memory allocation
    • Resource cleanup
  2. CPU Impact

    • Schema validation
    • Type conversion
    • State management
    • Metadata processing
  3. Concurrency

    • State synchronization
    • Resource sharing
    • Transaction isolation
    • Cache consistency

Integration Examples

Custom Query Handler
type CustomQueryHandler struct {
    models.QueryRequest
    // Additional fields
}

func (h *CustomQueryHandler) Execute(ctx context.Context) (*models.QueryResult, error) {
    // Custom execution logic
    return &models.QueryResult{
        Schema: h.Schema,
        Records: h.Records,
    }, nil
}
Metadata Cache
type MetadataCache struct {
    catalogs map[string]*models.Catalog
    schemas  map[string]*models.Schema
    tables   map[string]*models.Table
    mu       sync.RWMutex
}

func (c *MetadataCache) GetTable(catalog, schema, table string) (*models.Table, error) {
    c.mu.RLock()
    defer c.mu.RUnlock()
    
    key := fmt.Sprintf("%s.%s.%s", catalog, schema, table)
    return c.tables[key], nil
}
Arrow Record Processor
type RecordProcessor struct {
    schema *arrow.Schema
    allocator memory.Allocator
}

func (p *RecordProcessor) ProcessRecords(records <-chan arrow.Record) <-chan arrow.Record {
    out := make(chan arrow.Record)
    go func() {
        defer close(out)
        for record := range records {
            // Process record
            out <- record
        }
    }()
    return out
}

Documentation

Overview

Package models provides data structures used throughout the Flight SQL server.

Package models provides data structures used throughout the Flight SQL server.

Package models provides data structures used throughout the Flight SQL server.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetCatalogsSchema

func GetCatalogsSchema() *arrow.Schema

GetCatalogsSchema returns the Arrow schema for catalog results.

func GetColumnsSchema

func GetColumnsSchema() *arrow.Schema

GetColumnsSchema returns the Arrow schema for column metadata results.

func GetDBSchemasSchema

func GetDBSchemasSchema() *arrow.Schema

GetDBSchemasSchema returns the Arrow schema for database schema results.

func GetExportedKeysSchema

func GetExportedKeysSchema() *arrow.Schema

GetExportedKeysSchema returns the Arrow schema for exported foreign key results.

func GetForeignKeysSchema

func GetForeignKeysSchema() *arrow.Schema

GetForeignKeysSchema returns the Arrow schema for foreign key results.

func GetImportedKeysSchema

func GetImportedKeysSchema() *arrow.Schema

GetImportedKeysSchema returns the Arrow schema for imported foreign key results.

func GetPrimaryKeysSchema

func GetPrimaryKeysSchema() *arrow.Schema

GetPrimaryKeysSchema returns the Arrow schema for primary key results.

func GetSqlInfoSchema

func GetSqlInfoSchema() *arrow.Schema

GetSqlInfoSchema returns the Arrow schema for SQL info results.

func GetTableTypesSchema

func GetTableTypesSchema() *arrow.Schema

GetTableTypesSchema returns the Arrow schema for table type results.

func GetTablesSchema

func GetTablesSchema(includeSchema bool) *arrow.Schema

GetTablesSchema returns the Arrow schema for table results.

func GetXdbcTypeInfoSchema

func GetXdbcTypeInfoSchema() *arrow.Schema

GetXdbcTypeInfoSchema returns the Arrow schema for XDBC type info results.

Types

type Catalog

type Catalog struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description,omitempty"`
	Properties  map[string]interface{} `json:"properties,omitempty"`
}

Catalog represents a database catalog.

type Column

type Column struct {
	CatalogName       string         `json:"catalog_name"`
	SchemaName        string         `json:"schema_name"`
	TableName         string         `json:"table_name"`
	Name              string         `json:"name"`
	OrdinalPosition   int            `json:"ordinal_position"`
	DataType          string         `json:"data_type"`
	IsNullable        bool           `json:"is_nullable"`
	DefaultValue      sql.NullString `json:"default_value,omitempty"`
	CharMaxLength     sql.NullInt64  `json:"char_max_length,omitempty"`
	NumericPrecision  sql.NullInt64  `json:"numeric_precision,omitempty"`
	NumericScale      sql.NullInt64  `json:"numeric_scale,omitempty"`
	DateTimePrecision sql.NullInt64  `json:"datetime_precision,omitempty"`
	CharSet           sql.NullString `json:"char_set,omitempty"`
	Collation         sql.NullString `json:"collation,omitempty"`
	Comment           sql.NullString `json:"comment,omitempty"`
}

Column represents a database column.

type CrossTableRef

type CrossTableRef struct {
	PKRef TableRef `json:"pk_ref"`
	FKRef TableRef `json:"fk_ref"`
}

CrossTableRef represents a cross-table reference for foreign key lookups.

type FKRule

type FKRule int32

FKRule represents a foreign key update/delete rule.

const (
	// FKRuleCascade indicates CASCADE rule.
	FKRuleCascade FKRule = 0
	// FKRuleRestrict indicates RESTRICT rule.
	FKRuleRestrict FKRule = 1
	// FKRuleSetNull indicates SET NULL rule.
	FKRuleSetNull FKRule = 2
	// FKRuleNoAction indicates NO ACTION rule.
	FKRuleNoAction FKRule = 3
	// FKRuleSetDefault indicates SET DEFAULT rule.
	FKRuleSetDefault FKRule = 4
)

type ForeignKey

type ForeignKey struct {
	PKCatalogName string `json:"pk_catalog_name"`
	PKSchemaName  string `json:"pk_schema_name"`
	PKTableName   string `json:"pk_table_name"`
	PKColumnName  string `json:"pk_column_name"`
	FKCatalogName string `json:"fk_catalog_name"`
	FKSchemaName  string `json:"fk_schema_name"`
	FKTableName   string `json:"fk_table_name"`
	FKColumnName  string `json:"fk_column_name"`
	KeySequence   int32  `json:"key_sequence"`
	PKKeyName     string `json:"pk_key_name,omitempty"`
	FKKeyName     string `json:"fk_key_name,omitempty"`
	UpdateRule    FKRule `json:"update_rule"`
	DeleteRule    FKRule `json:"delete_rule"`
}

ForeignKey represents a foreign key relationship.

type GetTablesOptions

type GetTablesOptions struct {
	Catalog                *string  `json:"catalog,omitempty"`
	SchemaFilterPattern    *string  `json:"schema_filter_pattern,omitempty"`
	TableNameFilterPattern *string  `json:"table_name_filter_pattern,omitempty"`
	TableTypes             []string `json:"table_types,omitempty"`
	IncludeSchema          bool     `json:"include_schema,omitempty"`
}

GetTablesOptions represents options for getting tables.

type IsolationLevel

type IsolationLevel string

IsolationLevel represents the transaction isolation level.

const (
	// IsolationLevelDefault uses the database default isolation level.
	IsolationLevelDefault IsolationLevel = ""
	// IsolationLevelReadUncommitted allows dirty reads.
	IsolationLevelReadUncommitted IsolationLevel = "READ_UNCOMMITTED"
	// IsolationLevelReadCommitted prevents dirty reads.
	IsolationLevelReadCommitted IsolationLevel = "READ_COMMITTED"
	// IsolationLevelRepeatableRead prevents dirty reads and non-repeatable reads.
	IsolationLevelRepeatableRead IsolationLevel = "REPEATABLE_READ"
	// IsolationLevelSerializable provides the highest isolation level.
	IsolationLevelSerializable IsolationLevel = "SERIALIZABLE"
)

type Key

type Key struct {
	CatalogName string `json:"catalog_name"`
	SchemaName  string `json:"schema_name"`
	TableName   string `json:"table_name"`
	ColumnName  string `json:"column_name"`
	KeySequence int32  `json:"key_sequence"`
	KeyName     string `json:"key_name,omitempty"`
}

Key represents a primary key.

type PreparedStatement

type PreparedStatement struct {
	Handle            string          `json:"handle"`
	Query             string          `json:"query"`
	ParameterSchema   *arrow.Schema   `json:"-"`
	ResultSetSchema   *arrow.Schema   `json:"-"`
	BoundParameters   [][]interface{} `json:"-"`
	CreatedAt         time.Time       `json:"created_at"`
	LastUsedAt        time.Time       `json:"last_used_at"`
	ExecutionCount    int64           `json:"execution_count"`
	TransactionID     string          `json:"transaction_id,omitempty"`
	IsResultSetUpdate bool            `json:"is_result_set_update"`
}

PreparedStatement represents a prepared SQL statement.

type QueryRequest

type QueryRequest struct {
	Query         string                 `json:"query"`
	TransactionID string                 `json:"transaction_id,omitempty"`
	Parameters    []interface{}          `json:"parameters,omitempty"`
	MaxRows       int64                  `json:"max_rows,omitempty"`
	Timeout       time.Duration          `json:"timeout,omitempty"`
	Properties    map[string]interface{} `json:"properties,omitempty"`
}

QueryRequest represents a query execution request.

type QueryResult

type QueryResult struct {
	Schema        *arrow.Schema          `json:"-"`
	Records       <-chan arrow.Record    `json:"-"`
	TotalRows     int64                  `json:"total_rows"`
	ExecutionTime time.Duration          `json:"execution_time"`
	Metadata      map[string]interface{} `json:"metadata,omitempty"`
}

QueryResult represents the result of a query execution.

type SQLInfo

type SQLInfo struct {
	InfoName uint32      `json:"info_name"`
	Value    interface{} `json:"value"`
}

SQLInfo represents SQL feature information.

type Schema

type Schema struct {
	CatalogName string                 `json:"catalog_name"`
	Name        string                 `json:"name"`
	Owner       string                 `json:"owner,omitempty"`
	Description string                 `json:"description,omitempty"`
	Properties  map[string]interface{} `json:"properties,omitempty"`
}

Schema represents a database schema.

type SqlInfoResult

type SqlInfoResult struct {
	Info []SQLInfo
}

SqlInfoResult holds SQL info for conversion to Arrow.

func (*SqlInfoResult) ToArrowRecord

func (s *SqlInfoResult) ToArrowRecord(allocator memory.Allocator) arrow.Record

ToArrowRecord converts SqlInfo results to an Arrow record.

type Table

type Table struct {
	CatalogName string                 `json:"catalog_name"`
	SchemaName  string                 `json:"schema_name"`
	Name        string                 `json:"name"`
	Type        string                 `json:"type"`
	Description string                 `json:"description,omitempty"`
	Owner       string                 `json:"owner,omitempty"`
	CreatedAt   *time.Time             `json:"created_at,omitempty"`
	UpdatedAt   *time.Time             `json:"updated_at,omitempty"`
	RowCount    *int64                 `json:"row_count,omitempty"`
	Properties  map[string]interface{} `json:"properties,omitempty"`
}

Table represents a database table.

type TableRef

type TableRef struct {
	Catalog  *string `json:"catalog,omitempty"`
	DBSchema *string `json:"db_schema,omitempty"`
	Table    string  `json:"table"`
}

TableRef represents a reference to a table.

type Transaction

type Transaction struct {
	ID             string           `json:"id"`
	IsolationLevel IsolationLevel   `json:"isolation_level"`
	ReadOnly       bool             `json:"read_only"`
	StartedAt      time.Time        `json:"started_at"`
	LastActivityAt time.Time        `json:"last_activity_at"`
	State          TransactionState `json:"state"`
}

Transaction represents an active database transaction.

type TransactionOptions

type TransactionOptions struct {
	IsolationLevel IsolationLevel         `json:"isolation_level,omitempty"`
	ReadOnly       bool                   `json:"read_only,omitempty"`
	Timeout        time.Duration          `json:"timeout,omitempty"`
	Properties     map[string]interface{} `json:"properties,omitempty"`
}

TransactionOptions represents options for creating a transaction.

type TransactionState

type TransactionState string

TransactionState represents the state of a transaction.

const (
	// TransactionStateActive indicates an active transaction.
	TransactionStateActive TransactionState = "ACTIVE"
	// TransactionStateCommitting indicates a transaction being committed.
	TransactionStateCommitting TransactionState = "COMMITTING"
	// TransactionStateRollingBack indicates a transaction being rolled back.
	TransactionStateRollingBack TransactionState = "ROLLING_BACK"
	// TransactionStateCommitted indicates a committed transaction.
	TransactionStateCommitted TransactionState = "COMMITTED"
	// TransactionStateRolledBack indicates a rolled back transaction.
	TransactionStateRolledBack TransactionState = "ROLLED_BACK"
)

type UpdateRequest

type UpdateRequest struct {
	Statement     string                 `json:"statement"`
	TransactionID string                 `json:"transaction_id,omitempty"`
	Parameters    []interface{}          `json:"parameters,omitempty"`
	Timeout       time.Duration          `json:"timeout,omitempty"`
	Properties    map[string]interface{} `json:"properties,omitempty"`
}

UpdateRequest represents an update execution request.

type UpdateResult

type UpdateResult struct {
	RowsAffected  int64                  `json:"rows_affected"`
	ExecutionTime time.Duration          `json:"execution_time"`
	Metadata      map[string]interface{} `json:"metadata,omitempty"`
}

UpdateResult represents the result of an update execution.

type XdbcTypeInfo

type XdbcTypeInfo struct {
	TypeName          string         `json:"type_name"`
	DataType          int32          `json:"data_type"`
	ColumnSize        sql.NullInt32  `json:"column_size"`
	LiteralPrefix     sql.NullString `json:"literal_prefix"`
	LiteralSuffix     sql.NullString `json:"literal_suffix"`
	CreateParams      sql.NullString `json:"create_params"`
	Nullable          int32          `json:"nullable"`
	CaseSensitive     bool           `json:"case_sensitive"`
	Searchable        int32          `json:"searchable"`
	UnsignedAttribute sql.NullBool   `json:"unsigned_attribute"`
	FixedPrecScale    bool           `json:"fixed_prec_scale"`
	AutoIncrement     sql.NullBool   `json:"auto_increment"`
	LocalTypeName     sql.NullString `json:"local_type_name"`
	MinimumScale      sql.NullInt32  `json:"minimum_scale"`
	MaximumScale      sql.NullInt32  `json:"maximum_scale"`
	SQLDataType       int32          `json:"sql_data_type"`
	DatetimeSubcode   sql.NullInt32  `json:"datetime_subcode"`
	NumPrecRadix      sql.NullInt32  `json:"num_prec_radix"`
	IntervalPrecision sql.NullInt32  `json:"interval_precision"`
}

XdbcTypeInfo represents XDBC type information.

type XdbcTypeInfoResult

type XdbcTypeInfoResult struct {
	Types []XdbcTypeInfo
}

XdbcTypeInfoResult holds XDBC type information for conversion to Arrow.

func (*XdbcTypeInfoResult) ToArrowRecord

func (x *XdbcTypeInfoResult) ToArrowRecord(allocator memory.Allocator) arrow.Record

ToArrowRecord converts XdbcTypeInfo results to an Arrow record.

Jump to

Keyboard shortcuts

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