Documentation
¶
Overview ¶
Package schema provides functionality for the TDTP framework.
Index ¶
- func FormatTimeOfDay(t time.Time) string
- func FormatTimestamp(t time.Time) string
- func GetDefaultPrecision() int
- func GetDefaultScale() int
- func GetDefaultTimezone() string
- func IsBlobType(t DataType) bool
- func IsBooleanType(t DataType) bool
- func IsDateTimeType(t DataType) bool
- func IsNumericType(t DataType) bool
- func IsTextType(t DataType) bool
- func IsValidType(t DataType) bool
- type Builder
- func (b *Builder) AddBlob(name string) *Builder
- func (b *Builder) AddBoolean(name string) *Builder
- func (b *Builder) AddDate(name string) *Builder
- func (b *Builder) AddDatetime(name, timezone string) *Builder
- func (b *Builder) AddDecimal(name string, precision, scale int) *Builder
- func (b *Builder) AddField(field packet.Field) *Builder
- func (b *Builder) AddInteger(name string, key bool) *Builder
- func (b *Builder) AddReal(name string) *Builder
- func (b *Builder) AddText(name string, length int) *Builder
- func (b *Builder) AddTimestamp(name string) *Builder
- func (b *Builder) Build() packet.Schema
- func (b *Builder) FieldCount() int
- func (b *Builder) HasKeyField() bool
- func (b *Builder) Reset() *Builder
- type Converter
- type DataType
- type FieldDef
- type TypedValue
- type ValidationError
- type Validator
- func (v *Validator) GetFieldByName(schema packet.Schema, name string) (*packet.Field, error)
- func (v *Validator) GetKeyFields(schema packet.Schema) []packet.Field
- func (v *Validator) ValidateDataPacket(pkt *packet.DataPacket) error
- func (v *Validator) ValidatePrimaryKey(rows [][]string, schema packet.Schema) error
- func (v *Validator) ValidateRow(row []string, schema packet.Schema) error
- func (v *Validator) ValidateRows(rows [][]string, schema packet.Schema) []error
- func (v *Validator) ValidateSchema(schema packet.Schema) error
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func FormatTimeOfDay ¶
FormatTimeOfDay renders a TIME value (PostgreSQL `time`, subtype "time") as plain time of day. Trailing zeros in the fraction are trimmed and the dot disappears entirely when there is none, so a whole-second value formats as "14:38:11" — the same bytes the previous %02d:%02d:%02d formatting produced, while microseconds now survive instead of being cut off.
func FormatTimestamp ¶
FormatTimestamp renders a DATETIME/TIMESTAMP value in TDTP's canonical form. It is the single definition of that format: adapters converting a driver value and FormatValue re-formatting a parsed one must agree, or the second pass silently undoes the first.
RFC3339Nano rather than RFC3339, because RFC3339 formats to whole seconds and every database this framework talks to stores more: Postgres `timestamp` keeps microseconds, MSSQL `datetime2` up to 100ns. Exporting through RFC3339 discarded that, and a round-trip could not give it back.
The loss was not only cosmetic. --sync-incremental derives its watermark from the exported data, so against a microsecond column the watermark could never represent the row it stood for: `last_updated > '11:38:11Z'` still matches the row at 11:38:11.52877, and the sync re-sent that row on every run forever. Neither > nor >= converges when the watermark is coarser than the values it is compared against.
Compatibility rests on two measured properties:
- A value with no sub-second component formats byte-identically under both layouts, so packets for such data — and their checksums — do not change.
- time.Parse with the RFC3339 layout already accepts a fractional part, so every existing reader takes the longer string unchanged. datetimeFormats above leads with exactly that layout.
One caveat: RFC3339Nano trims trailing zeros, so widths differ between rows and "…:11.5Z" sorts before "…:11Z" as raw text. Nothing here compares these as text — tdtql's comparator compares parsed times, the SQL generator hands the value to the database, and sync's watermark comparison parses first — but a caller sorting the raw strings would be wrong to.
func GetDefaultPrecision ¶
func GetDefaultPrecision() int
GetDefaultPrecision возвращает точность по умолчанию для DECIMAL
func GetDefaultScale ¶
func GetDefaultScale() int
GetDefaultScale возвращает масштаб по умолчанию для DECIMAL
func GetDefaultTimezone ¶
func GetDefaultTimezone() string
GetDefaultTimezone возвращает таймзону по умолчанию
func IsBooleanType ¶
IsBooleanType проверяет является ли тип логическим
func IsDateTimeType ¶
IsDateTimeType проверяет является ли тип временным
func IsNumericType ¶
IsNumericType проверяет является ли тип числовым
Types ¶
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder помогает строить схемы
func (*Builder) AddBoolean ¶
AddBoolean добавляет BOOLEAN поле
func (*Builder) AddDatetime ¶
AddDatetime добавляет DATETIME поле
func (*Builder) AddDecimal ¶
AddDecimal добавляет DECIMAL поле
func (*Builder) AddInteger ¶
AddInteger добавляет INTEGER поле
func (*Builder) AddTimestamp ¶
AddTimestamp добавляет TIMESTAMP поле
func (*Builder) FieldCount ¶
FieldCount возвращает количество полей
func (*Builder) HasKeyField ¶
HasKeyField проверяет наличие первичного ключа
type Converter ¶
type Converter struct{}
Converter отвечает за конвертацию значений
func (*Converter) FormatValue ¶
func (c *Converter) FormatValue(tv *TypedValue) string
FormatValue форматирует типизированное значение обратно в строку
func (*Converter) ParseValue ¶
func (c *Converter) ParseValue(rawValue string, field FieldDef) (*TypedValue, error)
ParseValue парсит строковое значение согласно типу поля
type DataType ¶
type DataType string
DataType представляет тип данных поля
const ( TypeInteger DataType = "INTEGER" TypeInt DataType = "INT" TypeReal DataType = "REAL" TypeFloat DataType = "FLOAT" TypeDouble DataType = "DOUBLE" TypeDecimal DataType = "DECIMAL" TypeText DataType = "TEXT" TypeVarchar DataType = "VARCHAR" TypeChar DataType = "CHAR" TypeString DataType = "STRING" TypeBoolean DataType = "BOOLEAN" TypeBool DataType = "BOOL" TypeDate DataType = "DATE" TypeDatetime DataType = "DATETIME" TypeTimestamp DataType = "TIMESTAMP" TypeBlob DataType = "BLOB" )
Поддерживаемые типы данных согласно спецификации TDTP
func NormalizeType ¶
NormalizeType нормализует синонимы типов
type FieldDef ¶
type FieldDef struct {
Name string
Type DataType
Subtype string // e.g., "time", "jsonb", "uuid"
Length int
Precision int
Scale int
Timezone string
Key bool
Nullable bool
}
FieldDef расширенное определение поля с валидацией
type TypedValue ¶
type TypedValue struct {
Type DataType
// Subtype повторяет FieldDef.Subtype ("time", "jsonb", "uuid", ...).
// Нужен FormatValue и TypedValueToSQL: без него TIME из PostgreSQL
// неотличим от TIMESTAMP и печатается как "0000-01-01T14:38:11Z" —
// значение, которое PostgreSQL обратно в колонку time уже не примет.
Subtype string
// Precision повторяет FieldDef.Precision. Для DATETIME/TIMESTAMP это
// разрядность дробной части: адаптер обязан отдать в колонку ровно
// столько знаков, сколько она вмещает, иначе БД округлит сама.
Precision int
RawValue string
IsNull bool
IntValue *int64
FloatValue *float64
// DecimalValue is the exact decimal text of a DECIMAL value — no
// exponent, no float rounding. FloatValue is still set for DECIMAL as a
// convenience, but float64 keeps ~16 significant digits: writers and
// formatters must use DecimalValue, or 1234567890123450.1234 becomes
// 1234567890123450 and 9007199254740993 becomes …992.
DecimalValue *string
StringValue *string
BoolValue *bool
TimeValue *time.Time
BlobValue []byte
}
TypedValue представляет типизированное значение
type ValidationError ¶
ValidationError ошибка валидации
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
type Validator ¶
type Validator struct {
// contains filtered or unexported fields
}
Validator валидирует схемы и данные
func (*Validator) GetFieldByName ¶
GetFieldByName находит поле по имени
func (*Validator) GetKeyFields ¶
GetKeyFields возвращает поля первичного ключа
func (*Validator) ValidateDataPacket ¶
func (v *Validator) ValidateDataPacket(pkt *packet.DataPacket) error
ValidateDataPacket проверяет весь DataPacket
func (*Validator) ValidatePrimaryKey ¶
ValidatePrimaryKey проверяет уникальность первичного ключа
func (*Validator) ValidateRow ¶
ValidateRow проверяет соответствие строки данных схеме
func (*Validator) ValidateRows ¶
ValidateRows проверяет множество строк