chorm

package module
v0.0.0-...-3f9387c Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2025 License: MIT Imports: 9 Imported by: 0

README

CHORM - ClickHouse ORM для Go

CHORM - это мощная ORM библиотека для работы с ClickHouse в Go, предоставляющая удобный интерфейс для маппинга структур, выполнения CRUD операций и построения сложных аналитических запросов.

Возможности

  • 🗂️ Маппинг структур - Автоматическое преобразование Go структур в таблицы ClickHouse
  • 🔄 CRUD операции - Полная поддержка Create, Read, Update, Delete операций
  • 📊 Аналитические функции - Поддержка агрегатных функций и сложных запросов
  • 🚀 Производительность - Оптимизированные массовые вставки и пул соединений
  • 🏗️ Управление схемой - Автоматическое создание таблиц и миграции
  • 🔒 Безопасность - Параметризованные запросы и TLS поддержка
  • 🎯 Кластерная поддержка - Работа с распределенными таблицами

Установка

go get github.com/AlanForester/chorm

Быстрый старт

package main

import (
    "context"
    "log"
    
    "github.com/AlanForester/chorm"
)

// Определяем структуру для маппинга
type User struct {
    ID       uint32 `ch:"id" ch_type:"UInt32"`
    Name     string `ch:"name" ch_type:"String"`
    Email    string `ch:"email" ch_type:"String"`
    Age      uint8  `ch:"age" ch_type:"UInt8"`
    Created  string `ch:"created" ch_type:"DateTime"`
}

func main() {
    // Подключаемся к ClickHouse
    db, err := chorm.Connect(context.Background(), chorm.Config{
        Host:     "localhost:9000",
        Database: "test",
        Username: "default",
        Password: "",
    })
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    // Создаем таблицу автоматически
    err = db.CreateTable(context.Background(), &User{})
    if err != nil {
        log.Fatal(err)
    }

    // Вставляем данные
    user := &User{
        ID:      1,
        Name:    "John Doe",
        Email:   "john@example.com",
        Age:     30,
        Created: "2024-01-01 10:00:00",
    }
    
    err = db.Insert(context.Background(), user)
    if err != nil {
        log.Fatal(err)
    }

    // Выполняем запрос
    var users []User
    err = db.Query(context.Background(), &users, "SELECT * FROM users WHERE age > ?", 25)
    if err != nil {
        log.Fatal(err)
    }

    log.Printf("Found %d users", len(users))
}

Документация

Полная документация доступна в docs/ директории.

Лицензия

MIT License - см. файл LICENSE для деталей.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExampleAggregations

func ExampleAggregations()

ExampleAggregations демонстрирует использование агрегатных функций

func ExampleBasicUsage

func ExampleBasicUsage()

ExampleBasicUsage демонстрирует базовое использование ORM

func ExampleBatchOperations

func ExampleBatchOperations()

ExampleBatchOperations демонстрирует массовые операции

func ExampleCluster

func ExampleCluster()

ExampleCluster демонстрирует работу с кластером

func ExampleJoins

func ExampleJoins()

ExampleJoins демонстрирует использование JOIN

func ExampleMigrations

func ExampleMigrations()

ExampleMigrations демонстрирует использование миграций

func ExampleQueryBuilder

func ExampleQueryBuilder()

ExampleQueryBuilder демонстрирует использование построителя запросов

func ExampleReplicatedTable

func ExampleReplicatedTable()

ExampleReplicatedTable демонстрирует создание реплицированной таблицы

func ExampleTransactions

func ExampleTransactions()

ExampleTransactions демонстрирует использование транзакций

func ExampleWindowFunctions

func ExampleWindowFunctions()

ExampleWindowFunctions демонстрирует оконные функции

Types

type Aggregate

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

Aggregate представляет агрегатную функцию

func (*Aggregate) All

func (a *Aggregate) All(ctx context.Context, result interface{}) error

All выполняет агрегатный запрос и возвращает все результаты

func (*Aggregate) Any

func (a *Aggregate) Any(field string) *Aggregate

Any добавляет функцию any

func (*Aggregate) ArgMax

func (a *Aggregate) ArgMax(arg, val string) *Aggregate

ArgMax добавляет функцию argMax

func (*Aggregate) ArgMin

func (a *Aggregate) ArgMin(arg, val string) *Aggregate

ArgMin добавляет функцию argMin

func (*Aggregate) Avg

func (a *Aggregate) Avg(field string) *Aggregate

Avg добавляет функцию AVG

func (*Aggregate) Corr

func (a *Aggregate) Corr(x, y string) *Aggregate

Corr добавляет функцию корреляции

func (*Aggregate) Count

func (a *Aggregate) Count(field string) *Aggregate

Count добавляет функцию COUNT

func (*Aggregate) CountDistinct

func (a *Aggregate) CountDistinct(field string) *Aggregate

CountDistinct добавляет функцию COUNT DISTINCT

func (*Aggregate) CovarPop

func (a *Aggregate) CovarPop(x, y string) *Aggregate

CovarPop добавляет функцию ковариации

func (*Aggregate) CovarSamp

func (a *Aggregate) CovarSamp(x, y string) *Aggregate

CovarSamp добавляет функцию выборочной ковариации

func (*Aggregate) Entropy

func (a *Aggregate) Entropy(field string) *Aggregate

Entropy добавляет функцию энтропии

func (*Aggregate) GeometricMean

func (a *Aggregate) GeometricMean(field string) *Aggregate

GeometricMean добавляет функцию геометрического среднего

func (*Aggregate) Get

func (a *Aggregate) Get(ctx context.Context, result interface{}) error

Get выполняет агрегатный запрос и возвращает результат

func (*Aggregate) GroupArray

func (a *Aggregate) GroupArray(field string) *Aggregate

GroupArray добавляет функцию groupArray

func (*Aggregate) GroupUniqArray

func (a *Aggregate) GroupUniqArray(field string) *Aggregate

GroupUniqArray добавляет функцию groupUniqArray

func (*Aggregate) HarmonicMean

func (a *Aggregate) HarmonicMean(field string) *Aggregate

HarmonicMean добавляет функцию гармонического среднего

func (*Aggregate) Histogram

func (a *Aggregate) Histogram(bins int, field string) *Aggregate

Histogram добавляет функцию histogram

func (*Aggregate) KurtPop

func (a *Aggregate) KurtPop(field string) *Aggregate

KurtPop добавляет функцию эксцесса

func (*Aggregate) Max

func (a *Aggregate) Max(field string) *Aggregate

Max добавляет функцию MAX

func (*Aggregate) Median

func (a *Aggregate) Median(field string) *Aggregate

Median добавляет функцию median

func (*Aggregate) Min

func (a *Aggregate) Min(field string) *Aggregate

Min добавляет функцию MIN

func (*Aggregate) Quantile

func (a *Aggregate) Quantile(level float64, field string) *Aggregate

Quantile добавляет функцию quantile

func (*Aggregate) SkewPop

func (a *Aggregate) SkewPop(field string) *Aggregate

SkewPop добавляет функцию асимметрии

func (*Aggregate) StdDev

func (a *Aggregate) StdDev(field string) *Aggregate

StdDev добавляет функцию stddev

func (*Aggregate) Sum

func (a *Aggregate) Sum(field string) *Aggregate

Sum добавляет функцию SUM

func (*Aggregate) TopK

func (a *Aggregate) TopK(k int, field string) *Aggregate

TopK добавляет функцию topK

func (*Aggregate) TopKWeighted

func (a *Aggregate) TopKWeighted(k int, field, weight string) *Aggregate

TopKWeighted добавляет функцию topKWeighted

func (*Aggregate) Uniq

func (a *Aggregate) Uniq(field string) *Aggregate

Uniq добавляет функцию uniq (ClickHouse специфичная)

func (*Aggregate) UniqExact

func (a *Aggregate) UniqExact(field string) *Aggregate

UniqExact добавляет функцию uniqExact

func (*Aggregate) Variance

func (a *Aggregate) Variance(field string) *Aggregate

Variance добавляет функцию variance

type ClickHouseType

type ClickHouseType string

ClickHouseType представляет типы данных ClickHouse

const (
	// Базовые типы
	TypeUInt8       ClickHouseType = "UInt8"
	TypeUInt16      ClickHouseType = "UInt16"
	TypeUInt32      ClickHouseType = "UInt32"
	TypeUInt64      ClickHouseType = "UInt64"
	TypeInt8        ClickHouseType = "Int8"
	TypeInt16       ClickHouseType = "Int16"
	TypeInt32       ClickHouseType = "Int32"
	TypeInt64       ClickHouseType = "Int64"
	TypeFloat32     ClickHouseType = "Float32"
	TypeFloat64     ClickHouseType = "Float64"
	TypeString      ClickHouseType = "String"
	TypeFixedString ClickHouseType = "FixedString"
	TypeDate        ClickHouseType = "Date"
	TypeDateTime    ClickHouseType = "DateTime"
	TypeDateTime64  ClickHouseType = "DateTime64"
	TypeBoolean     ClickHouseType = "Boolean"
	TypeUUID        ClickHouseType = "UUID"

	// Сложные типы
	TypeArray          ClickHouseType = "Array"
	TypeNullable       ClickHouseType = "Nullable"
	TypeLowCardinality ClickHouseType = "LowCardinality"
	TypeEnum           ClickHouseType = "Enum"
	TypeNested         ClickHouseType = "Nested"
	TypeTuple          ClickHouseType = "Tuple"
	TypeMap            ClickHouseType = "Map"
)

type Cluster

type Cluster struct {
	Name  string
	Nodes []*ClusterNode
	// contains filtered or unexported fields
}

Cluster представляет кластер ClickHouse

func NewCluster

func NewCluster(name string) *Cluster

NewCluster создает новый кластер

func (*Cluster) AddNode

func (c *Cluster) AddNode(node *ClusterNode)

AddNode добавляет узел в кластер

func (*Cluster) GetHealthyNodes

func (c *Cluster) GetHealthyNodes() []*ClusterNode

GetHealthyNodes возвращает здоровые узлы

func (*Cluster) GetNodeByWeight

func (c *Cluster) GetNodeByWeight() *ClusterNode

GetNodeByWeight возвращает узел по весу (для балансировки)

func (*Cluster) HealthCheck

func (c *Cluster) HealthCheck(ctx context.Context)

HealthCheck проверяет здоровье узлов кластера

func (*Cluster) RemoveNode

func (c *Cluster) RemoveNode(host string, port int)

RemoveNode удаляет узел из кластера

type ClusterDB

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

ClusterDB представляет подключение к кластеру

func ConnectToCluster

func ConnectToCluster(cluster *Cluster, config Config) (*ClusterDB, error)

ConnectToCluster подключается к кластеру

func NewClusterDB

func NewClusterDB(cluster *Cluster, config Config) *ClusterDB

NewClusterDB создает новое подключение к кластеру

func (*ClusterDB) CreateDistributedTable

func (cdb *ClusterDB) CreateDistributedTable(ctx context.Context, tableName, clusterName, localTableName string, shardingKey string) error

CreateDistributedTable создает распределенную таблицу

func (*ClusterDB) Exec

func (cdb *ClusterDB) Exec(ctx context.Context, query string, args ...interface{}) (Result, error)

Exec выполняет команду на случайном узле кластера

func (*ClusterDB) GetConnection

func (cdb *ClusterDB) GetConnection(ctx context.Context) (*DB, error)

GetConnection получает подключение к случайному здоровому узлу

func (*ClusterDB) InsertIntoDistributed

func (cdb *ClusterDB) InsertIntoDistributed(ctx context.Context, tableName string, data interface{}) error

InsertIntoDistributed вставляет данные в распределенную таблицу

func (*ClusterDB) Query

func (cdb *ClusterDB) Query(ctx context.Context, result interface{}, query string, args ...interface{}) error

Query выполняет запрос на случайном узле кластера

type ClusterNode

type ClusterNode struct {
	Host     string
	Port     int
	Database string
	Username string
	Password string
	Weight   int // Вес для балансировки
	Healthy  bool
	LastPing time.Time
}

ClusterNode представляет узел кластера

type Config

type Config struct {
	Host            string
	Port            int
	Database        string
	Username        string
	Password        string
	MaxOpenConns    int
	MaxIdleConns    int
	ConnMaxLifetime time.Duration
	TLS             bool
	Compression     bool
	Debug           bool
}

Config представляет конфигурацию подключения к ClickHouse

type DB

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

DB представляет основное соединение с ClickHouse

func Connect

func Connect(ctx context.Context, config Config) (*DB, error)

Connect создает подключение к ClickHouse

func (*DB) Begin

func (db *DB) Begin(ctx context.Context) (*Tx, error)

Begin начинает транзакцию

func (*DB) Close

func (db *DB) Close() error

Close закрывает соединение с базой данных

func (*DB) CreateTable

func (db *DB) CreateTable(ctx context.Context, model interface{}) error

CreateTable создает таблицу на основе структуры

func (*DB) Exec

func (db *DB) Exec(ctx context.Context, query string, args ...interface{}) (Result, error)

Exec выполняет запрос без возврата результата

func (*DB) Insert

func (db *DB) Insert(ctx context.Context, model interface{}) error

Insert вставляет одну запись

func (*DB) InsertBatch

func (db *DB) InsertBatch(ctx context.Context, models []interface{}) error

InsertBatch вставляет множество записей

func (*DB) NewQuery

func (db *DB) NewQuery() *Query

NewQuery создает новый построитель запросов

func (*DB) Query

func (db *DB) Query(ctx context.Context, result interface{}, query string, args ...interface{}) error

Query выполняет запрос и заполняет результат в slice

func (*DB) QueryRow

func (db *DB) QueryRow(ctx context.Context, result interface{}, query string, args ...interface{}) error

QueryRow выполняет запрос и возвращает одну строку

type Engine

type Engine string

Engine представляет движки таблиц ClickHouse

const (
	EngineMergeTree                    Engine = "MergeTree"
	EngineReplacingMergeTree           Engine = "ReplacingMergeTree"
	EngineSummingMergeTree             Engine = "SummingMergeTree"
	EngineAggregatingMergeTree         Engine = "AggregatingMergeTree"
	EngineCollapsingMergeTree          Engine = "CollapsingMergeTree"
	EngineVersionedCollapsingMergeTree Engine = "VersionedCollapsingMergeTree"
	EngineGraphiteMergeTree            Engine = "GraphiteMergeTree"
	EngineTinyLog                      Engine = "TinyLog"
	EngineLog                          Engine = "Log"
	EngineMemory                       Engine = "Memory"
	EngineSet                          Engine = "Set"
	EngineJoin                         Engine = "Join"
	EngineBuffer                       Engine = "Buffer"
	EngineMaterializedView             Engine = "MaterializedView"
)

type Error

type Error struct {
	Code    int
	Message string
	Query   string
}

Error представляет ошибку ORM

func (*Error) Error

func (e *Error) Error() string

type FieldInfo

type FieldInfo struct {
	Name     string
	Type     string
	Tag      string
	IsPK     bool
	IsAuto   bool
	Nullable bool
}

FieldInfo содержит информацию о поле структуры

type Mapper

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

Mapper представляет маппер для работы со структурами

func NewMapper

func NewMapper() *Mapper

NewMapper создает новый маппер

func (*Mapper) BuildCreateTableSQL

func (m *Mapper) BuildCreateTableSQL(info *TableInfo) string

BuildCreateTableSQL строит SQL для создания таблицы

func (*Mapper) GetFieldValue

func (m *Mapper) GetFieldValue(model interface{}, fieldName string) (interface{}, error)

GetFieldValue получает значение поля из структуры

func (*Mapper) GetPrimaryKey

func (m *Mapper) GetPrimaryKey(model interface{}) (string, interface{}, error)

GetPrimaryKey получает первичный ключ из структуры

func (*Mapper) ParseStruct

func (m *Mapper) ParseStruct(model interface{}) (*TableInfo, error)

ParseStruct парсит структуру и возвращает информацию о таблице

func (*Mapper) SetFieldValue

func (m *Mapper) SetFieldValue(model interface{}, fieldName string, value interface{}) error

SetFieldValue устанавливает значение поля в структуре

type Migration

type Migration struct {
	ID        int64     `ch:"id" ch_type:"UInt64"`
	Name      string    `ch:"name" ch_type:"String"`
	AppliedAt time.Time `ch:"applied_at" ch_type:"DateTime"`
	Checksum  string    `ch:"checksum" ch_type:"String"`
}

Migration представляет миграцию

func (*Migration) TableName

func (m *Migration) TableName() string

TableName возвращает имя таблицы для миграций

type MigrationFunc

type MigrationFunc func(ctx context.Context, db *DB) error

MigrationFunc представляет функцию миграции

type MigrationRecord

type MigrationRecord struct {
	Name     string
	Up       MigrationFunc
	Down     MigrationFunc
	Checksum string
}

MigrationRecord представляет запись о миграции

type Migrator

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

Migrator представляет мигратор

func NewMigrator

func NewMigrator(db *DB) *Migrator

NewMigrator создает новый мигратор

func (*Migrator) AddMigration

func (m *Migrator) AddMigration(name string, up, down MigrationFunc) *Migrator

AddMigration добавляет миграцию

func (*Migrator) ApplyMigration

func (m *Migrator) ApplyMigration(ctx context.Context, migration MigrationRecord) error

ApplyMigration применяет миграцию

func (*Migrator) CreateMigrationsTable

func (m *Migrator) CreateMigrationsTable(ctx context.Context) error

CreateMigrationsTable создает таблицу для отслеживания миграций

func (*Migrator) GetAppliedMigrations

func (m *Migrator) GetAppliedMigrations(ctx context.Context) ([]Migration, error)

GetAppliedMigrations получает список примененных миграций

func (*Migrator) IsMigrationApplied

func (m *Migrator) IsMigrationApplied(ctx context.Context, name string) (bool, error)

IsMigrationApplied проверяет, применена ли миграция

func (*Migrator) Migrate

func (m *Migrator) Migrate(ctx context.Context) error

Migrate применяет все непримененные миграции

func (*Migrator) Rollback

func (m *Migrator) Rollback(ctx context.Context) error

Rollback откатывает последнюю миграцию

func (*Migrator) RollbackMigration

func (m *Migrator) RollbackMigration(ctx context.Context, name string) error

RollbackMigration откатывает миграцию

func (*Migrator) Status

func (m *Migrator) Status(ctx context.Context) error

Status показывает статус миграций

type Model

type Model interface {
	TableName() string
}

Model представляет интерфейс для моделей

type Order

type Order struct {
	ID        uint32    `ch:"id" ch_type:"UInt32" ch_pk:"true"`
	UserID    uint32    `ch:"user_id" ch_type:"UInt32"`
	ProductID uint32    `ch:"product_id" ch_type:"UInt32"`
	Quantity  uint16    `ch:"quantity" ch_type:"UInt16"`
	Price     float64   `ch:"price" ch_type:"Float64"`
	Total     float64   `ch:"total" ch_type:"Float64"`
	Status    string    `ch:"status" ch_type:"String"`
	Created   time.Time `ch:"created" ch_type:"DateTime"`
	Completed time.Time `ch:"completed" ch_type:"DateTime"`
}

Order представляет заказ

func (*Order) TableName

func (o *Order) TableName() string

TableName возвращает имя таблицы

type Product

type Product struct {
	ID          uint32    `ch:"id" ch_type:"UInt32" ch_pk:"true"`
	Name        string    `ch:"name" ch_type:"String"`
	Description string    `ch:"description" ch_type:"String"`
	Price       float64   `ch:"price" ch_type:"Float64"`
	Category    string    `ch:"category" ch_type:"String"`
	InStock     bool      `ch:"in_stock" ch_type:"Boolean"`
	Created     time.Time `ch:"created" ch_type:"DateTime"`
}

Product представляет продукт

func (*Product) TableName

func (p *Product) TableName() string

TableName возвращает имя таблицы

type Query

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

Query представляет построитель запросов

func (*Query) All

func (q *Query) All(ctx context.Context, result interface{}) error

All выполняет запрос и возвращает все записи

func (*Query) Count

func (q *Query) Count(ctx context.Context) (int64, error)

Count выполняет запрос COUNT

func (*Query) Delete

func (q *Query) Delete(ctx context.Context) (Result, error)

Delete выполняет DELETE запрос

func (*Query) Distinct

func (q *Query) Distinct() *Query

Distinct добавляет DISTINCT к запросу

func (*Query) Exists

func (q *Query) Exists(ctx context.Context) (bool, error)

Exists проверяет существование записей

func (*Query) First

func (q *Query) First(ctx context.Context, result interface{}) error

First выполняет запрос и возвращает первую запись

func (*Query) Get

func (q *Query) Get(ctx context.Context, result interface{}) error

Get выполняет запрос и возвращает одну запись

func (*Query) GroupBy

func (q *Query) GroupBy(fields ...string) *Query

GroupBy добавляет GROUP BY

func (*Query) Having

func (q *Query) Having(condition string, args ...interface{}) *Query

Having добавляет HAVING

func (*Query) Join

func (q *Query) Join(table, condition string, args ...interface{}) *Query

Join добавляет JOIN

func (*Query) Last

func (q *Query) Last(ctx context.Context, result interface{}) error

Last выполняет запрос и возвращает последнюю запись

func (*Query) LeftJoin

func (q *Query) LeftJoin(table, condition string, args ...interface{}) *Query

LeftJoin добавляет LEFT JOIN

func (*Query) Limit

func (q *Query) Limit(limit int) *Query

Limit устанавливает LIMIT

func (*Query) NewAggregate

func (q *Query) NewAggregate() *Aggregate

NewAggregate создает новый агрегат

func (*Query) NewWindow

func (q *Query) NewWindow() *Window

NewWindow создает новую оконную функцию

func (*Query) Offset

func (q *Query) Offset(offset int) *Query

Offset устанавливает OFFSET

func (*Query) OrderBy

func (q *Query) OrderBy(field string, direction ...string) *Query

OrderBy добавляет ORDER BY

func (*Query) OrderByAsc

func (q *Query) OrderByAsc(field string) *Query

OrderByAsc добавляет ORDER BY ASC

func (*Query) OrderByDesc

func (q *Query) OrderByDesc(field string) *Query

OrderByDesc добавляет ORDER BY DESC

func (*Query) Paginate

func (q *Query) Paginate(ctx context.Context, page, perPage int, result interface{}) (int64, error)

Paginate выполняет пагинацию

func (*Query) RightJoin

func (q *Query) RightJoin(table, condition string, args ...interface{}) *Query

RightJoin добавляет RIGHT JOIN

func (*Query) Select

func (q *Query) Select(fields ...string) *Query

Select устанавливает поля для выборки

func (*Query) Table

func (q *Query) Table(table string) *Query

Table устанавливает таблицу для запроса

func (*Query) Update

func (q *Query) Update(ctx context.Context, data map[string]interface{}) (Result, error)

Update выполняет UPDATE запрос

func (*Query) Where

func (q *Query) Where(condition string, args ...interface{}) *Query

Where добавляет условие WHERE

func (*Query) WhereBetween

func (q *Query) WhereBetween(field string, start, end interface{}) *Query

WhereBetween добавляет условие WHERE BETWEEN

func (*Query) WhereIn

func (q *Query) WhereIn(field string, values []interface{}) *Query

WhereIn добавляет условие WHERE IN

func (*Query) WhereLike

func (q *Query) WhereLike(field, pattern string) *Query

WhereLike добавляет условие WHERE LIKE

func (*Query) WhereNotIn

func (q *Query) WhereNotIn(field string, values []interface{}) *Query

WhereNotIn добавляет условие WHERE NOT IN

func (*Query) WhereNotNull

func (q *Query) WhereNotNull(field string) *Query

WhereNotNull добавляет условие WHERE IS NOT NULL

func (*Query) WhereNull

func (q *Query) WhereNull(field string) *Query

WhereNull добавляет условие WHERE IS NULL

type QueryBuilder

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

QueryBuilder представляет построитель запросов

type ReplicatedTable

type ReplicatedTable struct {
	Name          string
	ClusterName   string
	Database      string
	Engine        string
	ReplicaPath   string
	ReplicaName   string
	ZooKeeperPath string
	Columns       []string
	PartitionBy   string
	OrderBy       string
	PrimaryKey    string
	SampleBy      string
	TTL           string
	Settings      map[string]string
}

ReplicatedTable представляет реплицированную таблицу

func NewReplicatedTable

func NewReplicatedTable(name, clusterName, database string) *ReplicatedTable

NewReplicatedTable создает новую реплицированную таблицу

func (*ReplicatedTable) AddColumn

func (rt *ReplicatedTable) AddColumn(name, dataType string) *ReplicatedTable

AddColumn добавляет колонку в реплицированную таблицу

func (*ReplicatedTable) AddSetting

func (rt *ReplicatedTable) AddSetting(key, value string) *ReplicatedTable

AddSetting добавляет настройку

func (*ReplicatedTable) BuildCreateSQL

func (rt *ReplicatedTable) BuildCreateSQL() string

BuildCreateSQL строит SQL для создания реплицированной таблицы

func (*ReplicatedTable) Create

func (rt *ReplicatedTable) Create(ctx context.Context, db *DB) error

Create создает реплицированную таблицу

func (*ReplicatedTable) SetOrderBy

func (rt *ReplicatedTable) SetOrderBy(expr string) *ReplicatedTable

SetOrderBy устанавливает ORDER BY

func (*ReplicatedTable) SetPartitionBy

func (rt *ReplicatedTable) SetPartitionBy(expr string) *ReplicatedTable

SetPartitionBy устанавливает PARTITION BY

func (*ReplicatedTable) SetPrimaryKey

func (rt *ReplicatedTable) SetPrimaryKey(expr string) *ReplicatedTable

SetPrimaryKey устанавливает PRIMARY KEY

func (*ReplicatedTable) SetReplicaName

func (rt *ReplicatedTable) SetReplicaName(name string) *ReplicatedTable

SetReplicaName устанавливает имя реплики

func (*ReplicatedTable) SetReplicaPath

func (rt *ReplicatedTable) SetReplicaPath(path string) *ReplicatedTable

SetReplicaPath устанавливает путь реплики

func (*ReplicatedTable) SetSampleBy

func (rt *ReplicatedTable) SetSampleBy(expr string) *ReplicatedTable

SetSampleBy устанавливает SAMPLE BY

func (*ReplicatedTable) SetTTL

func (rt *ReplicatedTable) SetTTL(expr string) *ReplicatedTable

SetTTL устанавливает TTL

func (*ReplicatedTable) SetZooKeeperPath

func (rt *ReplicatedTable) SetZooKeeperPath(path string) *ReplicatedTable

SetZooKeeperPath устанавливает путь в ZooKeeper

type Result

type Result struct {
	LastInsertID int64
	RowsAffected int64
}

Result представляет результат выполнения запроса

type Row

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

Row представляет строку результата

func (*Row) Get

func (r *Row) Get(key string) interface{}

Get возвращает значение по ключу

func (*Row) GetBool

func (r *Row) GetBool(key string) bool

GetBool возвращает булево значение

func (*Row) GetFloat

func (r *Row) GetFloat(key string) float64

GetFloat возвращает значение с плавающей точкой

func (*Row) GetInt

func (r *Row) GetInt(key string) int64

GetInt возвращает целочисленное значение

func (*Row) GetString

func (r *Row) GetString(key string) string

GetString возвращает строковое значение

func (*Row) GetTime

func (r *Row) GetTime(key string) time.Time

GetTime возвращает временное значение

type Schema

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

Schema представляет схему базы данных

func NewSchema

func NewSchema(db *DB) *Schema

NewSchema создает новый объект схемы

func (*Schema) AddColumn

func (s *Schema) AddColumn(ctx context.Context, tableName, columnName, columnType string) error

AddColumn добавляет колонку

func (*Schema) CreateDatabase

func (s *Schema) CreateDatabase(ctx context.Context, name string) error

CreateDatabase создает базу данных

func (*Schema) CreateIndex

func (s *Schema) CreateIndex(ctx context.Context, indexName, tableName string, columns []string) error

CreateIndex создает индекс

func (*Schema) CreateMaterializedView

func (s *Schema) CreateMaterializedView(ctx context.Context, viewName, tableName, selectQuery string) error

CreateMaterializedView создает материализованное представление

func (*Schema) CreateTable

func (s *Schema) CreateTable(ctx context.Context, tableName string, columns []string, engine string, options map[string]string) error

CreateTable создает таблицу

func (*Schema) DropColumn

func (s *Schema) DropColumn(ctx context.Context, tableName, columnName string) error

DropColumn удаляет колонку

func (*Schema) DropDatabase

func (s *Schema) DropDatabase(ctx context.Context, name string) error

DropDatabase удаляет базу данных

func (*Schema) DropIndex

func (s *Schema) DropIndex(ctx context.Context, indexName, tableName string) error

DropIndex удаляет индекс

func (*Schema) DropMaterializedView

func (s *Schema) DropMaterializedView(ctx context.Context, viewName string) error

DropMaterializedView удаляет материализованное представление

func (*Schema) DropTable

func (s *Schema) DropTable(ctx context.Context, tableName string) error

DropTable удаляет таблицу

func (*Schema) GetDatabases

func (s *Schema) GetDatabases(ctx context.Context) ([]string, error)

GetDatabases получает список баз данных

func (*Schema) GetTableInfo

func (s *Schema) GetTableInfo(ctx context.Context, tableName string) (map[string]interface{}, error)

GetTableInfo получает информацию о таблице

func (*Schema) GetTables

func (s *Schema) GetTables(ctx context.Context) ([]string, error)

GetTables получает список таблиц

func (*Schema) ModifyColumn

func (s *Schema) ModifyColumn(ctx context.Context, tableName, columnName, newType string) error

ModifyColumn изменяет тип колонки

func (*Schema) RenameColumn

func (s *Schema) RenameColumn(ctx context.Context, tableName, oldName, newName string) error

RenameColumn переименовывает колонку

func (*Schema) RenameTable

func (s *Schema) RenameTable(ctx context.Context, oldName, newName string) error

RenameTable переименовывает таблицу

func (*Schema) TruncateTable

func (s *Schema) TruncateTable(ctx context.Context, tableName string) error

TruncateTable очищает таблицу

type ShardManager

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

ShardManager представляет менеджер шардов

func NewShardManager

func NewShardManager(cluster *Cluster) *ShardManager

NewShardManager создает новый менеджер шардов

func (*ShardManager) BalanceLoad

func (sm *ShardManager) BalanceLoad(ctx context.Context) error

BalanceLoad балансирует нагрузку между шардами

func (*ShardManager) GetShardInfo

func (sm *ShardManager) GetShardInfo(ctx context.Context) (map[string]interface{}, error)

GetShardInfo получает информацию о шардах

func (*ShardManager) GetShardNodes

func (sm *ShardManager) GetShardNodes(ctx context.Context, clusterName string) ([]map[string]interface{}, error)

GetShardNodes получает узлы шарда

type TableInfo

type TableInfo struct {
	Name    string
	Fields  []FieldInfo
	Engine  string
	Options map[string]string
}

TableInfo содержит информацию о таблице

type Tx

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

Tx представляет транзакцию

func (*Tx) Commit

func (tx *Tx) Commit() error

Commit подтверждает транзакцию

func (*Tx) Exec

func (tx *Tx) Exec(ctx context.Context, query string, args ...interface{}) (Result, error)

Exec выполняет запрос в транзакции

func (*Tx) Rollback

func (tx *Tx) Rollback() error

Rollback откатывает транзакцию

type User

type User struct {
	ID       uint32    `ch:"id" ch_type:"UInt32" ch_pk:"true"`
	Name     string    `ch:"name" ch_type:"String"`
	Email    string    `ch:"email" ch_type:"String"`
	Age      uint8     `ch:"age" ch_type:"UInt8"`
	Created  time.Time `ch:"created" ch_type:"DateTime"`
	Updated  time.Time `ch:"updated" ch_type:"DateTime"`
	IsActive bool      `ch:"is_active" ch_type:"Boolean"`
	Score    float64   `ch:"score" ch_type:"Float64"`
}

User представляет пользователя

func (*User) TableName

func (u *User) TableName() string

TableName возвращает имя таблицы

type UserStats

type UserStats struct {
	UserID       uint32  `ch:"user_id" ch_type:"UInt32"`
	TotalOrders  uint32  `ch:"total_orders" ch_type:"UInt32"`
	TotalSpent   float64 `ch:"total_spent" ch_type:"Float64"`
	AvgOrderSize float64 `ch:"avg_order_size" ch_type:"Float64"`
	LastOrder    string  `ch:"last_order" ch_type:"String"`
}

UserStats представляет статистику пользователей

func (*UserStats) TableName

func (us *UserStats) TableName() string

TableName возвращает имя таблицы

type Window

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

Window представляет оконную функцию

func (*Window) AddToQuery

func (w *Window) AddToQuery() *Query

AddToQuery добавляет оконную функцию к запросу

func (*Window) As

func (w *Window) As(alias string) *Window

As устанавливает алиас

func (*Window) Build

func (w *Window) Build() string

Build строит оконную функцию

func (*Window) CumeDist

func (w *Window) CumeDist() *Window

CumeDist добавляет CUME_DIST()

func (*Window) DenseRank

func (w *Window) DenseRank() *Window

DenseRank добавляет DENSE_RANK()

func (*Window) FirstValue

func (w *Window) FirstValue(field string) *Window

FirstValue добавляет FIRST_VALUE()

func (*Window) Lag

func (w *Window) Lag(field string, offset int) *Window

Lag добавляет LAG()

func (*Window) LastValue

func (w *Window) LastValue(field string) *Window

LastValue добавляет LAST_VALUE()

func (*Window) Lead

func (w *Window) Lead(field string, offset int) *Window

Lead добавляет LEAD()

func (*Window) NthValue

func (w *Window) NthValue(field string, n int) *Window

NthValue добавляет NTH_VALUE()

func (*Window) Ntile

func (w *Window) Ntile(buckets int) *Window

Ntile добавляет NTILE()

func (*Window) Over

func (w *Window) Over(partitionBy, orderBy string) *Window

Over устанавливает OVER clause

func (*Window) PercentRank

func (w *Window) PercentRank() *Window

PercentRank добавляет PERCENT_RANK()

func (*Window) Rank

func (w *Window) Rank() *Window

Rank добавляет RANK()

func (*Window) RowNumber

func (w *Window) RowNumber() *Window

RowNumber добавляет ROW_NUMBER()

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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