sequence

package
v0.20.0 Latest Latest
Warning

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

Go to latest
Published: Mar 9, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Index

Constants

View Source
const DBStoreTableName = "sys_sequence_rule"

Variables

View Source
var (
	// ErrRuleNotFound indicates the sequence rule was not found or is inactive.
	ErrRuleNotFound = errors.New("sequence rule not found or inactive")
	// ErrSequenceOverflow indicates the sequence value has exceeded its configured MaxValue.
	ErrSequenceOverflow = errors.New("sequence value exceeded max value")
	// ErrInvalidCount indicates the requested count is invalid (must be >= 1).
	ErrInvalidCount = errors.New("sequence generate count must be >= 1")
)

Functions

func FormatDate

func FormatDate(dt timex.DateTime, format string) string

FormatDate formats a datetime according to a user-friendly format string. Supported placeholders: yyyy, yy, MM, dd, HH, mm, ss. Returns an empty string if the format is empty.

Types

type DBStore

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

DBStore implements Store using a relational database. Table name is fixed to sys_sequence_rule.

func (*DBStore) Init

func (s *DBStore) Init(ctx context.Context) error

Init creates the sys_sequence_rule table if it does not exist. Implements contract.Initializer.

func (*DBStore) Reserve

func (s *DBStore) Reserve(ctx context.Context, key string, count int, now timex.DateTime) (*Rule, int, error)

type Generator

type Generator interface {
	// Generate generates a new serial number for the given rule key.
	Generate(ctx context.Context, key string) (string, error)
	// GenerateN generates N serial numbers for the given rule key in a single atomic operation.
	GenerateN(ctx context.Context, key string, count int) ([]string, error)
}

Generator provides serial number generation.

type MemoryStore

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

MemoryStore implements Store using in-memory storage. Suitable for single-instance deployments, development, and testing.

func (*MemoryStore) Register

func (s *MemoryStore) Register(rules ...*Rule)

Register preloads rules into the memory store. Existing rules with the same key will be overwritten. A deep copy of each rule is stored to prevent external mutation.

func (*MemoryStore) Reserve

func (s *MemoryStore) Reserve(_ context.Context, key string, count int, now timex.DateTime) (*Rule, int, error)

type OverflowStrategy

type OverflowStrategy string

OverflowStrategy defines the behavior when the sequence value exceeds MaxValue.

const (
	// OverflowError returns ErrSequenceOverflow when MaxValue is exceeded. This is the default strategy.
	OverflowError OverflowStrategy = "error"
	// OverflowReset automatically resets the counter to StartValue when MaxValue is exceeded.
	OverflowReset OverflowStrategy = "reset"
	// OverflowExtend allows the sequence number to exceed SeqLength (more digits than configured).
	OverflowExtend OverflowStrategy = "extend"
)

type RedisStore

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

RedisStore implements Store using Redis for distributed deployments.

func (*RedisStore) RegisterRule

func (s *RedisStore) RegisterRule(ctx context.Context, rule *Rule) error

RegisterRule stores a rule in Redis as a hash. This is a helper for setting up rules in Redis.

func (*RedisStore) Reserve

func (s *RedisStore) Reserve(ctx context.Context, key string, count int, now timex.DateTime) (*Rule, int, error)

type ResetCycle

type ResetCycle string

ResetCycle defines when the sequence counter should be reset.

const (
	ResetNone      ResetCycle = "N"
	ResetDaily     ResetCycle = "D"
	ResetWeekly    ResetCycle = "W"
	ResetMonthly   ResetCycle = "M"
	ResetQuarterly ResetCycle = "Q"
	ResetYearly    ResetCycle = "Y"
)

type Rule

type Rule struct {
	Key              string
	Name             string
	Prefix           string           // empty = no prefix
	Suffix           string           // empty = no suffix
	DateFormat       string           // e.g. "yyyyMMdd", empty = no date part
	SeqLength        int              // zero-padded width
	SeqStep          int              // increment per generation
	StartValue       int              // value after reset (first generated = StartValue + Step)
	MaxValue         int              // upper limit (0 = unlimited)
	OverflowStrategy OverflowStrategy // behavior when MaxValue is reached
	ResetCycle       ResetCycle       // N/D/W/M/Q/Y
	CurrentValue     int              // current counter value
	LastResetAt      *timex.DateTime  // nil = never reset
	IsActive         bool             // whether the rule is active
}

Rule defines the configuration for serial number generation.

func (*Rule) Clone

func (r *Rule) Clone() *Rule

Clone returns a deep copy of the Rule.

type RuleModel

type RuleModel struct {
	orm.BaseModel `bun:"table:sys_sequence_rule,alias:ssr"`
	orm.Model

	Key              string           `bun:"key,notnull,unique"`
	Name             string           `bun:"name,notnull"`
	Prefix           *string          `bun:"prefix,type:varchar(32)"`
	Suffix           *string          `bun:"suffix,type:varchar(32)"`
	DateFormat       *string          `bun:"date_format,type:varchar(32)"`
	SeqLength        int16            `bun:"seq_length,notnull,default:4"`
	SeqStep          int16            `bun:"seq_step,notnull,default:1"`
	StartValue       int              `bun:"start_value,notnull,default:0"`
	MaxValue         int              `bun:"max_value,notnull,default:0"`
	OverflowStrategy OverflowStrategy `bun:"overflow_strategy,notnull,default:'error'"`
	ResetCycle       ResetCycle       `bun:"reset_cycle,notnull,default:'N'"`
	CurrentValue     int              `bun:"current_value,notnull,default:0"`
	LastResetAt      *timex.DateTime  `bun:"last_reset_at,type:timestamp"`
	IsActive         bool             `bun:"is_active,notnull,default:true"`
	Remark           *string          `bun:"remark,type:varchar(256)"`
}

RuleModel is the internal ORM model for the sys_sequence_rule table.

type Store

type Store interface {
	// Reserve reserves count sequence values for key based on rule policy at now.
	// It returns the rule snapshot used for generation and the final counter value in the reserved batch.
	Reserve(ctx context.Context, key string, count int, now timex.DateTime) (rule *Rule, newValue int, err error)
}

Store abstracts rule persistence and atomic counter operations. Implementations must guarantee atomicity of Reserve (read-modify-write must be serialized per key).

func NewDBStore

func NewDBStore(db orm.DB) Store

NewDBStore creates a new database-backed sequence store.

func NewMemoryStore

func NewMemoryStore() Store

NewMemoryStore creates a new in-memory sequence store.

func NewRedisStore

func NewRedisStore(client *redis.Client) Store

NewRedisStore creates a new Redis-backed sequence store.

Jump to

Keyboard shortcuts

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