simpleotsgo

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2026 License: MIT Imports: 8 Imported by: 0

README

SimpleOTSGo

简单好用的 Go TableStore SDK。
你只需要 AccessKey + SecretKey,然后按表名获取操作器即可 CRUD。

安装

go get github.com/izut/simple-ots-go

1 分钟上手(推荐)

package main

import (
	"fmt"
	"os"

	"github.com/izut/simple-ots-go"
)

func main() {
	// 地域在 tables.yaml 各表的 regionId 中配置(本示例假设已配置 cn-hangzhou 等)。
	// 开发模式走公网,生产模式走 VPC。
	_ = os.Setenv("APP_ENV", "development")
	// 可选:指定 tables.yaml,默认 ./config/tables.yaml。
	_ = os.Setenv("SIMPLEOTSGO_TABLES_PATH", "./config/tables.yaml")
	// 需提供 AK/SK(两组选其一)。
	_ = os.Setenv("TABLESTORE_ACCESS_KEY_ID", "your-access-key")
	_ = os.Setenv("TABLESTORE_ACCESS_KEY_SECRET", "your-secret-key")

	// AK/SK 从环境变量读取;instanceName 与 regionId 均从 tables.yaml 读取(未写 regionId 且未设 TABLESTORE_ENDPOINT 将无法连接)。
	userTable, err := simpleotsgo.Table("user")
	if err != nil {
		panic(err)
	}

	// Create
	_, err = userTable.PutRow(map[string]interface{}{
		"uid":       "user_00001",
		"user_name": "张三",
		"email":     "zhangsan@example.com",
		"status":    int64(1),
	}, nil)
	if err != nil {
		panic(err)
	}

	// Read
	row, err := userTable.GetRow(map[string]interface{}{"uid": "user_00001"}, nil, 0)
	if err != nil {
		panic(err)
	}
	fmt.Printf("row=%+v\n", row)

	// Update:RowData 含主键与待 Put 列;可选 DeleteColumns、IncrementColumns;第二个参数为 RowCondition,nil 表示默认「行须已存在」。
	err = userTable.UpdateRow(simpleotsgo.UpdateData{
		RowData: map[string]interface{}{
			"uid":       "user_00001",
			"user_name": "张三-已更新",
		},
	}, nil)
	if err != nil {
		panic(err)
	}

	// Delete:返回 DeleteRowResponse(CU、RequestId 等),不需要时可 `_` 丢弃。
	_, err = userTable.DeleteRow(map[string]interface{}{"uid": "user_00001"})
	if err != nil {
		panic(err)
	}
}

关键规则(必看)

  • instanceName 来自 tables.yaml 中对应表配置
  • 每张表须在 tables.yaml 中配置 regionId(地域 ID,如 cn-hangzhou),SDK 不再从环境变量读取地域
  • 主表可选 dataLifeCycle(单位:秒),默认 -1(永不过期);该参数仅作用于主表 CreateTable.TableOption.TimeToAlive
  • APP_ENV=development 使用公网 endpoint
  • APP_ENV=production 使用 VPC endpoint
  • GO_ENV=productionSIMPLEOTSGO_RUN_MODE=productionAPP_ENV=production 等价参与判定(与常见 Go 项目习惯一致)
  • 显式设置 TABLESTORE_ENDPOINT 时,优先使用显式值

同步表结构(CLI)

支持双向同步(必须二选一):

  • -pushtables.yaml -> TableStore(建表/补列/补索引)
  • -pullTableStore -> tables.yaml(回写远程结构)
环境准备
export APP_ENV=development     # 生产环境改 production(或 GO_ENV=production)
export TABLESTORE_ACCESS_KEY_ID=...
export TABLESTORE_ACCESS_KEY_SECRET=...
# 或使用:TABLESTORE_ACCESS_KEY + TABLESTORE_SECRET_KEY
快速用法
# 推送全部表
go run ./cmd/sync_tables -push

# 拉取全部表
go run ./cmd/sync_tables -pull

查看完整参数:go run ./cmd/sync_tables --help(同样支持 -h / -help

参数说明(新版)
  • -push / -pull:方向互斥,且必须指定一个
  • -table <name|*>
    • -table "*":表示全部表(在 -push / -pull 都生效)
    • -push 时可传索引名:仅执行该索引 CreateIndex
    • -pull 时仅支持主表名(不支持按索引名)
  • -instance <name>:单实例别名,等价 -instances <name>
  • -instances a,b:按实例过滤;在 -push / -pull 都生效
  • -regionId:拉取时地域回退(本地 YAML 缺该实例 regionId 时使用)
  • -regionid-regionId 的全小写别名
  • -force-push 模式下先删后建(高风险)
  • -dry-run:演练模式(不改远程、不写本地文件)
  • -config <path>tables.yaml 路径(默认 SIMPLEOTSGO_TABLES_PATH./config/tables.yaml
行为规则(重点)
  • -table "*" 与不传 -table 等价,都是“全部表”
  • 指定 -instance/-instances 时,只处理这些实例下的表(push/pull 都一样)
  • -pull 合并策略:
    • 指定 -table:只替换同名表,其他表保留
    • 全量(未指定具体表):只替换本次涉及实例下的表,其他实例保留
  • 若设置 TABLESTORE_ENDPOINT,本次任务的所有实例都会共用该 endpoint(多实例请谨慎)
与数据生命周期配合

主表支持 dataLifeCycle(秒)字段,默认 -1(永不过期):

tables:
  - name: task_log
    instanceName: bigots
    regionId: cn-hangzhou
    dataLifeCycle: -1
  • -push 时用于 CreateTable.TableOption.TimeToAlive
  • -pull 时会把远端 TimeToAlive 回填到 tables.yaml
常用示例
# 推送某实例全部表
go run ./cmd/sync_tables -push -table "*" -instances tec05

# 推送单表
go run ./cmd/sync_tables -push -table task_log

# 推送单索引(仅 push 支持)
go run ./cmd/sync_tables -push -table task_log_index_level

# 拉取某实例全部表(本地空 YAML 场景)
go run ./cmd/sync_tables -pull -table "*" -instance tec05 -regionid cn-hangzhou

# 拉取单表
go run ./cmd/sync_tables -pull -table user

# 演练模式
go run ./cmd/sync_tables -push -dry-run
go run ./cmd/sync_tables -pull -dry-run > /tmp/tables.preview.yaml
在任意项目使用发布版本
# 安装后长期使用
go install github.com/izut/simple-ots-go/cmd/sync_tables@v1.0.alpha
sync_tables -push -config ./config/tables.yaml

# 单次运行
go run github.com/izut/simple-ots-go/cmd/sync_tables@v1.0.alpha -pull -table "*" -instances tec05 -regionId cn-hangzhou
  • v1.0.alpha 可替换为你要使用的 tag
  • -config 为执行目录相对路径(不传默认 ./config/tables.yaml

进阶 API(可选)

// 显式指定 endpoint(覆盖自动拼接)
op, err := simpleotsgo.NewWithEndpoint("ak", "sk", "https://xxx.cn-hangzhou.ots.aliyuncs.com")

// 显式指定 endpoint + tables.yaml 路径
op, err := simpleotsgo.NewWithConfig("ak", "sk", "https://xxx", "/data/config/tables.yaml")

// 调整重试参数
simpleotsgo.SetDefaultRetryConfig(simpleotsgo.RetryConfig{
	MaxRetries:     2,
	InitialBackoff: 100 * time.Millisecond,
	MaxBackoff:     2 * time.Second,
	Multiplier:     2,
})

License

MIT,详见 LICENSE

Documentation

Index

Constants

View Source
const (
	// EndpointModeDevelopment 表示开发模式:使用公网 endpoint。
	EndpointModeDevelopment = otscore.EndpointModeDevelopment
	// EndpointModeProduction 表示生产模式:使用 VPC endpoint。
	EndpointModeProduction = otscore.EndpointModeProduction

	// FORWARD 表示正向扫描,BACKWARD 表示反向扫描
	FORWARD  = tablestore.FORWARD
	BACKWARD = tablestore.BACKWARD

	// INF_MIN 表示无穷小,INF_MAX 表示无穷大
	INF_MIN = tablestore.MIN
	INF_MAX = tablestore.MAX

	// RT_NONE 表示不返回行数据体
	RT_NONE = tablestore.ReturnType_RT_NONE
	// RT_PK 表示返回主键
	RT_PK = tablestore.ReturnType_RT_PK
	// RT_ALT 表示返回修改列
	RT_ALT = tablestore.ReturnType_RT_AFTER_MODIFY
)

Variables

View Source
var (

	// EXPECT_EXIST 表示期望存在
	EXPECT_EXIST = &tablestore.RowCondition{
		RowExistenceExpectation: tablestore.RowExistenceExpectation_EXPECT_EXIST,
	}
	// EXPECT_NOT_EXIST 表示期望不存在
	EXPECT_NOT_EXIST = &tablestore.RowCondition{
		RowExistenceExpectation: tablestore.RowExistenceExpectation_EXPECT_NOT_EXIST,
	}
	// IGNORE 表示忽略
	IGNORE = &tablestore.RowCondition{
		RowExistenceExpectation: tablestore.RowExistenceExpectation_IGNORE,
	}
)

Functions

func BuildTableStoreEndpoint

func BuildTableStoreEndpoint(instanceName, regionID, mode string) (string, error)

BuildTableStoreEndpoint 根据实例名、地域 ID(与 YAML regionId 一致)与运行模式拼接 TableStore endpoint。 供同步工具等场景与 SDK 内部共用,规则与 New 系列一致。

func BuildUpdateRowChange

func BuildUpdateRowChange(table string, pk *tablestore.PrimaryKey, mut *UpdateMutation, cond *tablestore.RowCondition) (*tablestore.UpdateRowChange, error)

BuildUpdateRowChange 由 UpdateMutation 生成 UpdateRowChange,可与 BatchWriteRowChanges 组合使用。

func ConvertTablesConfig

func ConvertTablesConfig(cfg *config.TablesConfig) (map[string]*TableConfig, error)

ConvertTablesConfig 将 config 包中的 YAML 结构转换为运行时表配置。 转换过程中会校验字段类型是否合法,确保错误尽早暴露在初始化阶段。

func DefaultTablesConfigPath

func DefaultTablesConfigPath() string

DefaultTablesConfigPath 返回默认配置路径。 解析顺序: 1. 优先读取环境变量 SIMPLEOTSGO_TABLES_PATH; 2. 未设置时回落到当前工作目录下的 config/tables.yaml。

func NewPrimaryKey

func NewPrimaryKey(entries ...PKEntry) *tablestore.PrimaryKey

NewPrimaryKey 按表定义顺序构造 *tablestore.PrimaryKey。

func PrepareRowMapForTableStore

func PrepareRowMapForTableStore(data map[string]interface{}) (map[string]interface{}, error)

PrepareRowMapForTableStore 写入前编码 *_json 列(与 PutRow 行为一致,供直连底层 SDK 时使用)。

func PrimaryKeyToMap

func PrimaryKeyToMap(pk *tablestore.PrimaryKey) map[string]interface{}

PrimaryKeyToMap 将 PrimaryKey 转为 map(无序;续扫分页请使用 *tablestore.PrimaryKey)。

func ResetForTesting

func ResetForTesting()

ResetForTesting 重置所有全局缓存与初始化状态,仅供测试使用。 生产代码不应调用此函数;它使同一进程内的不同测试用例可以独立初始化。

func RowMapFromTableStore

func RowMapFromTableStore(raw map[string]interface{}) map[string]interface{}

RowMapFromTableStore 将含 *_json 字符串列的 map 解析为嵌套 map/slice(与 GetRow 系列行为一致)。

func RowToMap

func RowToMap(row *tablestore.Row) map[string]interface{}

RowToMap 将 *tablestore.Row 转为 map,并自动解析 *_json 列为对象/数组。

func SetDefaultRetryConfig

func SetDefaultRetryConfig(cfg RetryConfig)

SetDefaultRetryConfig 设置全局重试配置。

func SyncTableStoreEndpoint

func SyncTableStoreEndpoint(instanceName string) (string, error)

SyncTableStoreEndpoint 解析同步工具连接用的 endpoint。 若已设置 TABLESTORE_ENDPOINT,则全实例共用该地址(多实例 YAML 时请慎用); 否则须由调用方传入从 tables.yaml 解析出的 regionId,并结合运行模式拼接。

func SyncTableStoreEndpointWithRegionId

func SyncTableStoreEndpointWithRegionId(instanceName, regionID string) (string, error)

SyncTableStoreEndpointWithRegionId 解析同步工具连接 endpoint;regionID 须来自 tables.yaml(同实例下各表 regionId 应一致)。 优先级:TABLESTORE_ENDPOINT > 传入 regionID(环境变量不再作为地域来源)。

Types

type BatchGetRowItem

type BatchGetRowItem = otscore.BatchGetRowItem

type BatchWriteAction

type BatchWriteAction = otscore.BatchWriteAction

type Client

type Client = otscore.Client

Client 对外暴露客户端类型,保持与核心实现一致。

func NewClient

func NewClient(opts ...Option) (*Client, error)

NewClient 创建单实例直连客户端(适合已知 endpoint + instance 的场景)。

type ColumnVersionDelete

type ColumnVersionDelete = otscore.ColumnVersionDelete

type GetRangeOptions

type GetRangeOptions = otscore.GetRangeOptions

type GetRangePage

type GetRangePage = otscore.GetRangePage

type GetRowOptions

type GetRowOptions = otscore.GetRowOptions

GetRowOptions、BatchGetRowItem、GetRangeOptions、GetRangePage(可选的已解码分页视图)等为行级读写相关类型。

type Operator

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

Operator 是面向业务层的简化入口。 设计目标是只要求 AccessKey/SecretKey,表结构与实例信息由 tables.yaml 决定。

func New

func New(accessKey, secretKey string) (*Operator, error)

New 创建最简 SDK 操作入口。 1. 自动加载 tables.yaml(按默认或 SIMPLEOTSGO_TABLES_PATH 解析的绝对路径;与上次已成功加载的路径相同时跳过重复读,否则重新加载); 2. 自动读取 TABLESTORE_ENDPOINT(可选;未设置时依赖各表 regionId 拼接 endpoint); 3. 返回可按表名获取操作器的 Operator。

func NewWithConfig

func NewWithConfig(accessKey, secretKey, endpoint, tablesPath string) (*Operator, error)

NewWithConfig 创建可完全自定义初始化参数的入口。 tablesPath 为空时会走 DefaultTablesConfigPath;不为空时使用传入路径。 与当前进程已成功注册的 YAML 绝对路径不一致时会重新读取并替换全局表配置(同进程多文件场景)。

func NewWithEndpoint

func NewWithEndpoint(accessKey, secretKey, endpoint string) (*Operator, error)

NewWithEndpoint 在代码中显式指定 endpoint。 当调用方不想依赖环境变量时,建议使用该函数。

func (*Operator) Table

func (op *Operator) Table(tableName string) (*SimpleTableOperator, error)

Table 根据表名获取表操作器。 SDK 会从已加载的 tables.yaml 中解析该表的 instanceName 与主键结构。

type Option

type Option = otscore.Option

Option 对外暴露客户端配置 Option 类型。

func WithAccessKey

func WithAccessKey(accessKey string) Option

WithAccessKey 设置 AccessKey。

func WithEndpoint

func WithEndpoint(endpoint string) Option

WithEndpoint 设置 Endpoint。

func WithInstance

func WithInstance(instance string) Option

WithInstance 设置 Instance 名称。

func WithSecretKey

func WithSecretKey(secretKey string) Option

WithSecretKey 设置 SecretKey。

type PKEntry

type PKEntry = otscore.PKEntry

PKEntry 主键列项(有序),与 NewPrimaryKey 配合用于联合主键、BatchGet、GetRange 边界等。

type PrimaryKey

type PrimaryKey = tablestore.PrimaryKey

type RetryConfig

type RetryConfig = otscore.RetryConfig

RetryConfig 对外暴露重试配置类型,保持与核心实现一致。

type Row

type Row = tablestore.Row

type RowCondition

type RowCondition = tablestore.RowCondition

type SimpleTableOperator

type SimpleTableOperator = otscore.SimpleTableOperator

SimpleTableOperator 对外暴露操作器类型,保持与核心实现一致。

func Table

func Table(tableName string) (*SimpleTableOperator, error)

Table 提供“零实例化”快捷入口:用户无需显式创建 Operator,直接按表名获取操作器。 凭证来源:优先 TABLESTORE_ACCESS_KEY_ID/TABLESTORE_ACCESS_KEY_SECRET,回退 TABLESTORE_ACCESS_KEY/TABLESTORE_SECRET_KEY。

type TableConfig

type TableConfig = otscore.TableConfig

TableConfig 对外暴露表配置类型,保持与核心实现一致。

type UpdateData

type UpdateData = otscore.UpdateData

UpdateData 为 UpdateRow 的入参结构体(RowData / DeleteColumns / IncrementColumns),与 internal/otscore 定义一致。

type UpdateMutation

type UpdateMutation = otscore.UpdateMutation

Directories

Path Synopsis
cmd
sync_tables command
incremental_push 实现推送模式下「表已存在」时的增量 DDL: 在不动主键、不删列的前提下,用 AddDefinedColumn 补齐本地 YAML 中多出的预定义列。
incremental_push 实现推送模式下「表已存在」时的增量 DDL: 在不动主键、不删列的前提下,用 AddDefinedColumn 补齐本地 YAML 中多出的预定义列。
internal

Jump to

Keyboard shortcuts

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