feat: 设备编号从 00000001 顺序分配

This commit is contained in:
Nixevol
2026-10-12 08:54:17 +08:00
parent 775599174b
commit c334dbc040
8 changed files with 119 additions and 29 deletions
+50 -5
View File
@@ -13,7 +13,7 @@ import (
_ "modernc.org/sqlite"
)
const schemaVersion = 1
const schemaVersion = 2
const schemaSQL = `
CREATE TABLE IF NOT EXISTS users (
@@ -68,13 +68,20 @@ CREATE TABLE IF NOT EXISTS command_logs (
result TEXT NOT NULL,
PRIMARY KEY (endpoint_id, ord)
);
CREATE TABLE IF NOT EXISTS endpoint_seq (
id INTEGER PRIMARY KEY CHECK (id = 1),
next_no INTEGER NOT NULL
);
INSERT OR IGNORE INTO endpoint_seq(id, next_no) VALUES (1, 1);
`
var (
ErrNotFound = errors.New("store: not found")
ErrConflict = errors.New("store: conflict")
ErrForbidden = errors.New("store: forbidden")
ErrLastAdmin = errors.New("store: last admin")
ErrNotFound = errors.New("store: not found")
ErrConflict = errors.New("store: conflict")
ErrForbidden = errors.New("store: forbidden")
ErrLastAdmin = errors.New("store: last admin")
ErrEndpointExhausted = errors.New("store: endpoint numbers exhausted")
)
type User struct {
@@ -175,6 +182,16 @@ func (s *Store) Migrate(ctx context.Context) error {
if _, err := tx.ExecContext(ctx, schemaSQL); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, `
UPDATE endpoint_seq SET next_no = (
SELECT MAX(endpoint_seq.next_no, COALESCE((
SELECT MAX(CAST(endpoint_id AS INTEGER)) + 1 FROM devices
WHERE length(endpoint_id) = 8
AND endpoint_id GLOB '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
), 1))
) WHERE id = 1`); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, `INSERT INTO schema_migrations(version) VALUES (?)`, schemaVersion); err != nil {
return err
}
@@ -464,6 +481,34 @@ func (s *Store) ListDevices(ctx context.Context, userID int64) ([]Device, error)
return out, rows.Err()
}
const maxEndpointNo int64 = 99999999
// AllocateEndpointID 取出下一个 8 位设备编号。从 00000001 起,用过的号不回收。
func (s *Store) AllocateEndpointID(ctx context.Context) (string, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return "", err
}
defer func() { _ = tx.Rollback() }()
var next int64
if err := tx.QueryRowContext(ctx, `SELECT next_no FROM endpoint_seq WHERE id = 1`).Scan(&next); err != nil {
return "", err
}
if next < 1 {
next = 1
}
if next > maxEndpointNo {
return "", ErrEndpointExhausted
}
if _, err := tx.ExecContext(ctx, `UPDATE endpoint_seq SET next_no = ? WHERE id = 1`, next+1); err != nil {
return "", err
}
if err := tx.Commit(); err != nil {
return "", err
}
return fmt.Sprintf("%08d", next), nil
}
func (s *Store) AddDevice(ctx context.Context, userID int64, name, endpointID, passwordHash string, groupID *int64) (Device, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {