simpleotsgo

package module
v0.0.5-a Latest Latest
Warning

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

Go to latest
Published: Apr 13, 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 不再从环境变量读取地域
  • 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 或 export 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 --help(亦支持 -h-help

在任意项目直接使用已发布版本

如果你不在本仓库目录,也可以直接使用发布 tag 的 sync_tables

方式一:安装后长期使用(推荐)

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 -push -config ./config/tables.yaml

说明:

  • 以上命令中的 v1.0.alpha 可替换为你要使用的发布 tag
  • -config 路径相对于当前执行目录;不传时默认 ./config/tables.yaml
  • 环境变量要求与本仓库内运行一致(如 TABLESTORE_ACCESS_KEY_ID/SECRET 等);运行 SDK 时地域写在 tables.yamlregionIdsync_tables -pull 在空 YAML 场景可用 -regionIdTABLESTORE_ENDPOINT

常用参数:

  • -push:推送到远程(与 -pull 二选一,必选其一
  • -table 名称:指定目标。-push 模式可传“表名或索引名”;-pull 模式仅支持表名
  • -force:表已存在则先删后建(生产慎用
  • -config pathtables.yaml 路径(默认与 SIMPLEOTSGO_TABLES_PATH./config/tables.yaml 一致)
  • -pull:从远程拉取并写回本地 YAML(与 -push 二选一)。全量拉取时只替换本次涉及的实例(-instances 或 YAML 里出现的实例)下的表,其它实例的表定义保留;带 -table 时只替换同名那一张表
  • -instances a,b:拉取模式可选,显式指定实例列表(当本地 YAML 为空时很有用;此时请同时传 -regionId cn-hangzhou 等,或设置 TABLESTORE_ENDPOINT
  • -regionId:拉取专用;当本地 YAML 尚未包含某实例的 regionId 时用于连接远程并写回该字段(与 -instances 搭配引导空文件时常用)
  • -dry-run:演练模式——执行 DeleteTable/CreateTable覆盖 tables.yaml;拉取时会把生成的 YAML 打印到标准输出(可配合重定向保存)

拉取示例:

go run ./cmd/sync_tables -pull
go run ./cmd/sync_tables -pull -table user
go run ./cmd/sync_tables -pull -instances tec05,tec06 -regionId cn-hangzhou
go run ./cmd/sync_tables -push -table task_log_index_level

演练示例:

go run ./cmd/sync_tables -push -dry-run
go run ./cmd/sync_tables -pull -dry-run > /tmp/tables.preview.yaml

若设置 TABLESTORE_ENDPOINT,同步工具对该次任务所有实例使用该地址(多实例配置时请谨慎)。

进阶 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