0

我正在尝试使用 go 实现一个小状态机,并将我的状态存储在 postgres 数据库中。

我像这样创建了我的数据库:

CREATE TABLE state_machines
(
   id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
   initial_state TEXT NOT NULL,
   "name" TEXT NOT NULL
);

CREATE TABLE state_machine_states
(
   state_machine_id uuid NOT NULL REFERENCES state_machines(id) ON DELETE CASCADE,
   "name" TEXT NOT NULL,
   PRIMARY KEY(state_machine_id, "name")
);
// StateMachine is the DB schema
type StateMachine struct {
    ID           *uuid.UUID                `pg:"id,pk,type:uuid,default:uuid_generate_v4()"`
    Name         string                    `pg:"name"`
    InitialState string                    `pg:"initial_state"`
    States       []*StateMachineState      `pg:"fk:state_machine_id"`
}

// StateMachineState is the DB schema
type StateMachineState struct {
    StateMachineID uuid.UUID `pg:"state_machine_id,fk"`
    Name           string    `pg:"name"`
}

我正在使用 go-pg 9.2,我正在尝试从“状态”关系加载状态机及其状态列表。

我加载状态机的函数如下所示:

func (cep *repository) GetStateMachines() ([]*StateMachine, error) {
    stateMachines := []*StateMachine{}

    err := cep.db.Model(&stateMachines).
        Relation("States").
        Relation("Transitions").
        Select()

    return stateMachines, err
}

如果我执行它,我总是会收到错误消息Error reading state machine: model=StateMachine does not have relation="States"

我以前做过类似的关系,他们工作了,现在,我不能让它再次工作:(

4

2 回答 2

1

尝试升级到完全支持关系的 v10:https ://pg.uptrace.dev/orm/has-many-relation/

于 2020-11-03T10:53:25.393 回答
0

查看 go-pg 中是否有 .Debug() 函数进行查询。我使用https://gorm.io/,并且有一个 Debug 函数,它返回所有 SQL 查询。当我看到发送了哪些查询时,我登录 postgresql 并手动尝试它们以查看更详细的错误。

于 2020-09-08T10:36:11.213 回答