timescale

package
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: May 8, 2025 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CreateHypertable

func CreateHypertable(ctx context.Context, db *DB, table, timeColumn string, opts ...HypertableOption) error

CreateHypertable is a helper function to create a hypertable with the given configuration options. This is exported for use by other packages.

func IsTimescaleDB

func IsTimescaleDB(config db.Config) bool

IsTimescaleDB returns true if the config is for TimescaleDB

Types

type AggregateFunction

type AggregateFunction string

AggregateFunction represents a common aggregate function

const (
	// AggrAvg calculates the average value of a column
	AggrAvg AggregateFunction = "AVG"
	// AggrSum calculates the sum of values in a column
	AggrSum AggregateFunction = "SUM"
	// AggrMin finds the minimum value in a column
	AggrMin AggregateFunction = "MIN"
	// AggrMax finds the maximum value in a column
	AggrMax AggregateFunction = "MAX"
	// AggrCount counts the number of rows
	AggrCount AggregateFunction = "COUNT"
	// AggrFirst takes the first value in a window
	AggrFirst AggregateFunction = "FIRST"
	// AggrLast takes the last value in a window
	AggrLast AggregateFunction = "LAST"
)

type ColumnAggregation

type ColumnAggregation struct {
	Function AggregateFunction
	Column   string
	Alias    string
}

ColumnAggregation represents an aggregation operation on a column

type ColumnMetadata

type ColumnMetadata struct {
	Name         string
	Type         string
	Nullable     bool
	IsPrimaryKey bool
	IsIndexed    bool
	Description  string
}

ColumnMetadata represents metadata about a column

type CompressionPolicy

type CompressionPolicy struct {
	Enabled       bool
	After         string // e.g., "7 days"
	OrderBy       string // Column to order by during compression
	SegmentBy     string // Column to segment by during compression
	CompressChunk bool   // Whether to manually compress chunks
}

CompressionPolicy defines how and when to compress data

type CompressionSettings

type CompressionSettings struct {
	HypertableName      string
	SegmentBy           string
	OrderBy             string
	ChunkTimeInterval   string
	CompressionInterval string
	CompressionEnabled  bool
}

CompressionSettings represents TimescaleDB compression settings

type ContinuousAggregateMetadata

type ContinuousAggregateMetadata struct {
	ViewName           string
	ViewSchema         string
	MaterializedOnly   bool
	RefreshInterval    string
	RefreshLag         string
	RefreshStartOffset string
	RefreshEndOffset   string
	HypertableName     string
	HypertableSchema   string
	ViewDefinition     string
}

ContinuousAggregateMetadata represents metadata about a continuous aggregate

type ContinuousAggregateOptions

type ContinuousAggregateOptions struct {
	// Required parameters
	ViewName       string // Name of the continuous aggregate view to create
	SourceTable    string // Source table with raw data
	TimeColumn     string // Time column to bucket
	BucketInterval string // Time bucket interval (e.g., '1 hour', '1 day')

	// Optional parameters
	Aggregations      []ColumnAggregation // Aggregations to include in the view
	WhereCondition    string              // WHERE condition to filter source data
	WithData          bool                // Whether to materialize data immediately (WITH DATA)
	RefreshPolicy     bool                // Whether to add a refresh policy
	RefreshInterval   string              // Refresh interval (default: '1 day')
	RefreshLookback   string              // How far back to look when refreshing (default: '1 week')
	MaterializedOnly  bool                // Whether to materialize only (no real-time)
	CreateIfNotExists bool                // Whether to use IF NOT EXISTS
}

ContinuousAggregateOptions encapsulates options for creating a continuous aggregate

type ContinuousAggregatePolicyOptions

type ContinuousAggregatePolicyOptions struct {
	ViewName         string // Name of the continuous aggregate view
	Start            string // Start offset (e.g., '-2 days')
	End              string // End offset (e.g., 'now()')
	ScheduleInterval string // Execution interval (e.g., '1 hour')
}

ContinuousAggregatePolicyOptions encapsulates options for refresh policies

type DB

type DB struct {
	db.Database // Embed standard Database interface
	// contains filtered or unexported fields
}

DB represents a TimescaleDB database connection

func NewTimescaleDB

func NewTimescaleDB(config DBConfig) (*DB, error)

NewTimescaleDB creates a new TimescaleDB connection

func (*DB) AddCompressionPolicy

func (t *DB) AddCompressionPolicy(ctx context.Context, tableName, interval, segmentBy, orderBy string) error

AddCompressionPolicy adds a compression policy to a hypertable

func (*DB) AddContinuousAggregatePolicy

func (t *DB) AddContinuousAggregatePolicy(ctx context.Context, options ContinuousAggregatePolicyOptions) error

AddContinuousAggregatePolicy adds a refresh policy to a continuous aggregate

func (*DB) AddDimension

func (t *DB) AddDimension(ctx context.Context, tableName, columnName string, numPartitions int) error

AddDimension adds a new dimension (partitioning key) to a hypertable

func (*DB) AddRetentionPolicy

func (t *DB) AddRetentionPolicy(ctx context.Context, tableName, interval string) error

AddRetentionPolicy adds a data retention policy to a hypertable

func (*DB) AnalyzeTimeSeries

func (t *DB) AnalyzeTimeSeries(ctx context.Context, table, timeColumn string,
	startTime, endTime time.Time) (map[string]interface{}, error)

AnalyzeTimeSeries performs analysis on time-series data

func (*DB) ApplyConfig

func (t *DB) ApplyConfig() error

ApplyConfig applies TimescaleDB-specific configuration options

func (*DB) CheckIfHypertable

func (t *DB) CheckIfHypertable(ctx context.Context, tableName string) (bool, error)

CheckIfHypertable checks if a table is a hypertable

func (*DB) Close

func (t *DB) Close() error

Close closes the database connection

func (*DB) CompressChunks

func (t *DB) CompressChunks(ctx context.Context, tableName, olderThan string) error

CompressChunks compresses chunks for a hypertable

func (*DB) Connect

func (t *DB) Connect() error

Connect establishes a connection and verifies TimescaleDB availability

func (*DB) CreateContinuousAggregate

func (t *DB) CreateContinuousAggregate(ctx context.Context, options ContinuousAggregateOptions) error

CreateContinuousAggregate creates a new continuous aggregate view

func (*DB) CreateHypertable

func (t *DB) CreateHypertable(ctx context.Context, config HypertableConfig) error

CreateHypertable converts a regular PostgreSQL table to a TimescaleDB hypertable

func (*DB) DecompressChunks

func (t *DB) DecompressChunks(ctx context.Context, tableName, newerThan string) error

DecompressChunks decompresses chunks for a hypertable

func (*DB) DetectTimescaleDBVersion

func (t *DB) DetectTimescaleDBVersion(ctx context.Context) (string, error)

DetectTimescaleDBVersion checks if TimescaleDB is installed and returns its version

func (*DB) DisableCompression

func (t *DB) DisableCompression(ctx context.Context, tableName string) error

DisableCompression disables compression on a hypertable

func (*DB) DownsampleTimeSeries

func (t *DB) DownsampleTimeSeries(ctx context.Context, options DownsampleOptions) error

DownsampleTimeSeries creates downsampled time-series data

func (*DB) DropContinuousAggregate

func (t *DB) DropContinuousAggregate(ctx context.Context, viewName string, cascade bool) error

DropContinuousAggregate drops a continuous aggregate

func (*DB) DropHypertable

func (t *DB) DropHypertable(ctx context.Context, tableName string, cascade bool) error

DropHypertable drops a hypertable

func (*DB) EnableCompression

func (t *DB) EnableCompression(ctx context.Context, tableName string, afterInterval string) error

EnableCompression enables compression on a hypertable

func (*DB) ExecuteSQL

func (t *DB) ExecuteSQL(ctx context.Context, query string, args ...interface{}) (interface{}, error)

ExecuteSQL executes a SQL query with parameters and returns a result

func (*DB) ExecuteSQLWithoutParams

func (t *DB) ExecuteSQLWithoutParams(ctx context.Context, query string) (interface{}, error)

ExecuteSQLWithoutParams executes a SQL query without parameters and returns a result

func (*DB) ExtVersion

func (t *DB) ExtVersion() string

ExtVersion returns the TimescaleDB extension version

func (*DB) GenerateHypertableSchema

func (t *DB) GenerateHypertableSchema(ctx context.Context, tableName string) (string, error)

GenerateHypertableSchema generates CREATE TABLE and CREATE HYPERTABLE statements for a hypertable

func (*DB) GetChunkCompressionStats

func (t *DB) GetChunkCompressionStats(ctx context.Context, tableName string) (interface{}, error)

GetChunkCompressionStats gets compression statistics for a hypertable

func (*DB) GetCommonTimeIntervals

func (t *DB) GetCommonTimeIntervals() []string

GetCommonTimeIntervals returns a list of supported time bucket intervals

func (*DB) GetCompressionSettings

func (t *DB) GetCompressionSettings(ctx context.Context, tableName string) (*CompressionSettings, error)

GetCompressionSettings gets the compression settings for a hypertable

func (*DB) GetContinuousAggregate

func (t *DB) GetContinuousAggregate(ctx context.Context, viewName string) (*ContinuousAggregateMetadata, error)

GetContinuousAggregate gets metadata about a specific continuous aggregate

func (*DB) GetContinuousAggregateInfo

func (t *DB) GetContinuousAggregateInfo(ctx context.Context, viewName string) (map[string]interface{}, error)

GetContinuousAggregateInfo gets detailed information about a continuous aggregate

func (*DB) GetDatabaseSize

func (t *DB) GetDatabaseSize(ctx context.Context) (map[string]string, error)

GetDatabaseSize gets size information about the database

func (*DB) GetHypertable

func (t *DB) GetHypertable(ctx context.Context, tableName string) (*Hypertable, error)

GetHypertable gets information about a specific hypertable

func (*DB) GetHypertableMetadata

func (t *DB) GetHypertableMetadata(ctx context.Context, tableName string) (*HypertableMetadata, error)

GetHypertableMetadata returns detailed metadata about a hypertable

func (*DB) GetRetentionSettings

func (t *DB) GetRetentionSettings(ctx context.Context, tableName string) (*RetentionSettings, error)

GetRetentionSettings gets the retention settings for a hypertable

func (*DB) GetTableColumns

func (t *DB) GetTableColumns(ctx context.Context, tableName string) ([]ColumnMetadata, error)

GetTableColumns returns metadata about columns in a table

func (*DB) IsTimescaleDB

func (t *DB) IsTimescaleDB() bool

IsTimescaleDB returns true if the database has TimescaleDB extension installed

func (*DB) ListContinuousAggregates

func (t *DB) ListContinuousAggregates(ctx context.Context) ([]ContinuousAggregateMetadata, error)

ListContinuousAggregates lists all continuous aggregates

func (*DB) ListHypertables

func (t *DB) ListHypertables(ctx context.Context) ([]Hypertable, error)

ListHypertables returns a list of all hypertables in the database

func (*DB) RecentChunks

func (t *DB) RecentChunks(ctx context.Context, tableName string, limit int) (interface{}, error)

RecentChunks returns information about the most recent chunks

func (*DB) RefreshContinuousAggregate

func (t *DB) RefreshContinuousAggregate(ctx context.Context, viewName, startTime, endTime string) error

RefreshContinuousAggregate refreshes a continuous aggregate for a specific time range

func (*DB) RemoveCompressionPolicy

func (t *DB) RemoveCompressionPolicy(ctx context.Context, tableName string) error

RemoveCompressionPolicy removes a compression policy from a hypertable

func (*DB) RemoveContinuousAggregatePolicy

func (t *DB) RemoveContinuousAggregatePolicy(ctx context.Context, viewName string) error

RemoveContinuousAggregatePolicy removes a refresh policy from a continuous aggregate

func (*DB) RemoveRetentionPolicy

func (t *DB) RemoveRetentionPolicy(ctx context.Context, tableName string) error

RemoveRetentionPolicy removes a data retention policy from a hypertable

func (*DB) TimeSeriesQuery

func (t *DB) TimeSeriesQuery(ctx context.Context, options TimeSeriesQueryOptions) ([]map[string]interface{}, error)

TimeSeriesQuery executes a time-series query with the given options

type DBConfig

type DBConfig struct {
	// Inherit PostgreSQL config
	PostgresConfig db.Config

	// TimescaleDB-specific settings
	ChunkTimeInterval string             // Default chunk time interval (e.g., "7 days")
	RetentionPolicy   *RetentionPolicy   // Data retention configuration
	CompressionPolicy *CompressionPolicy // Compression configuration
	UseTimescaleDB    bool               // Enable TimescaleDB features (default: true)
}

DBConfig extends PostgreSQL configuration with TimescaleDB-specific options

func FromDBConfig

func FromDBConfig(config db.Config) DBConfig

FromDBConfig converts a standard db.Config to a DBConfig

func NewDefaultTimescaleDBConfig

func NewDefaultTimescaleDBConfig(pgConfig db.Config) DBConfig

NewDefaultTimescaleDBConfig creates a DBConfig with default values

type DownsampleOptions

type DownsampleOptions struct {
	SourceTable       string
	DestTable         string
	TimeColumn        string
	BucketInterval    string
	Aggregations      []ColumnAggregation
	WhereCondition    string
	CreateTable       bool
	ChunkTimeInterval string
}

DownsampleOptions describes options for downsampling time-series data

type Hypertable

type Hypertable struct {
	TableName          string
	SchemaName         string
	TimeColumn         string
	SpaceColumn        string
	NumDimensions      int
	CompressionEnabled bool
	RetentionEnabled   bool
}

Hypertable represents a TimescaleDB hypertable

type HypertableConfig

type HypertableConfig struct {
	TableName          string
	TimeColumn         string
	ChunkTimeInterval  string
	PartitioningColumn string
	CreateIfNotExists  bool
	SpacePartitions    int  // Number of space partitions (for multi-dimensional partitioning)
	IfNotExists        bool // If true, don't error if table is already a hypertable
	MigrateData        bool // If true, migrate existing data to chunks
}

HypertableConfig defines configuration for creating a hypertable

type HypertableMetadata

type HypertableMetadata struct {
	TableName         string
	SchemaName        string
	Owner             string
	NumDimensions     int
	TimeDimension     string
	TimeDimensionType string
	SpaceDimensions   []string
	ChunkTimeInterval string
	Compression       bool
	RetentionPolicy   bool
	TotalSize         string
	TotalRows         int64
	Chunks            int
}

HypertableMetadata represents metadata about a TimescaleDB hypertable

type HypertableOption

type HypertableOption func(*HypertableConfig)

HypertableOption is a functional option for CreateHypertable

func WithChunkInterval

func WithChunkInterval(interval string) HypertableOption

WithChunkInterval sets the chunk time interval

func WithIfNotExists

func WithIfNotExists(ifNotExists bool) HypertableOption

WithIfNotExists sets the if_not_exists flag

func WithMigrateData

func WithMigrateData(migrateData bool) HypertableOption

WithMigrateData sets the migrate_data flag

func WithPartitioningColumn

func WithPartitioningColumn(column string) HypertableOption

WithPartitioningColumn sets the space partitioning column

type RetentionPolicy

type RetentionPolicy struct {
	Enabled    bool
	Duration   string // e.g., "90 days"
	DropChunks bool   // Whether to physically drop chunks (vs logical deletion)
}

RetentionPolicy defines how long to keep data in TimescaleDB

type RetentionSettings

type RetentionSettings struct {
	HypertableName    string
	RetentionInterval string
	RetentionEnabled  bool
}

RetentionSettings represents TimescaleDB retention settings

type TimeBucket

type TimeBucket struct {
	Interval string // e.g., '1 hour', '1 day', '1 month'
	Column   string // Time column to bucket
	Alias    string // Optional alias for the bucket column
}

TimeBucket represents a time bucket for time-series aggregation

type TimeRange

type TimeRange struct {
	Start time.Time
	End   time.Time
}

TimeRange represents a common time range for queries

func PredefinedTimeRange

func PredefinedTimeRange(name string) (*TimeRange, error)

PredefinedTimeRange returns a TimeRange for common time ranges

type TimeSeriesQueryOptions

type TimeSeriesQueryOptions struct {
	// Required parameters
	Table          string // The table to query
	TimeColumn     string // The time column
	BucketInterval string // Time bucket interval (e.g., '1 hour', '1 day')

	// Optional parameters
	BucketColumnName string              // Name for the bucket column (defaults to "time_bucket")
	SelectColumns    []string            // Additional columns to select
	Aggregations     []ColumnAggregation // Aggregations to perform
	WindowFunctions  []WindowFunction    // Window functions to apply
	StartTime        time.Time           // Start of time range
	EndTime          time.Time           // End of time range
	WhereCondition   string              // Additional WHERE conditions
	GroupByColumns   []string            // Additional GROUP BY columns
	OrderBy          string              // ORDER BY clause
	Limit            int                 // LIMIT clause
	Offset           int                 // OFFSET clause
}

TimeSeriesQueryOptions encapsulates options for time-series queries

type TimeseriesQueryBuilder

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

TimeseriesQueryBuilder helps build optimized time-series queries

func NewTimeseriesQueryBuilder

func NewTimeseriesQueryBuilder(table string) *TimeseriesQueryBuilder

NewTimeseriesQueryBuilder creates a new builder for a specific table

func (*TimeseriesQueryBuilder) Aggregate

func (b *TimeseriesQueryBuilder) Aggregate(function AggregateFunction, column, alias string) *TimeseriesQueryBuilder

Aggregate adds an aggregation function to a column

func (*TimeseriesQueryBuilder) Build

func (b *TimeseriesQueryBuilder) Build() (string, []interface{})

Build constructs the SQL query and args

func (*TimeseriesQueryBuilder) Execute

func (b *TimeseriesQueryBuilder) Execute(ctx context.Context, db *DB) ([]map[string]interface{}, error)

Execute runs the query against the database

func (*TimeseriesQueryBuilder) GroupBy

GroupBy adds columns to the GROUP BY clause

func (*TimeseriesQueryBuilder) Limit

Limit sets the LIMIT clause

func (*TimeseriesQueryBuilder) Offset

Offset sets the OFFSET clause

func (*TimeseriesQueryBuilder) OrderBy

OrderBy adds columns to the ORDER BY clause

func (*TimeseriesQueryBuilder) Select

Select adds columns to the SELECT clause

func (*TimeseriesQueryBuilder) Where

func (b *TimeseriesQueryBuilder) Where(clause string, args ...interface{}) *TimeseriesQueryBuilder

Where adds a WHERE condition

func (*TimeseriesQueryBuilder) WhereTimeRange

func (b *TimeseriesQueryBuilder) WhereTimeRange(column string, start, end time.Time) *TimeseriesQueryBuilder

WhereTimeRange adds a time range condition

func (*TimeseriesQueryBuilder) WithTimeBucket

func (b *TimeseriesQueryBuilder) WithTimeBucket(interval, column, alias string) *TimeseriesQueryBuilder

WithTimeBucket adds a time bucket to the query

type WindowFunction

type WindowFunction struct {
	Function    string // e.g. LAG, LEAD, ROW_NUMBER
	Expression  string // Expression to apply function to
	Alias       string // Result column name
	PartitionBy string // PARTITION BY column(s)
	OrderBy     string // ORDER BY column(s)
	Frame       string // Window frame specification
}

WindowFunction represents a SQL window function

Jump to

Keyboard shortcuts

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