Рекомендации по выполнению соединения с SQLX, Squirrel

#postgresql #go #sqlx

#postgresql #Вперед #sqlx

Вопрос:

У меня есть эта модель.

 // Incident is a security incident.
type Incident struct {
    ID          string                 `json:"id" bson:"_id"`
    Title       string                 `json:"title" bson:"title"`
    Description string                 `json:"description" bson:"description"`
    Issue       *Issue                 `json:"issue" bson:"issue"`
    CreatedAt   time.Time              `json:"created_at" bson:"created_at"`
    ModifiedAt  time.Time              `json:"modified_at" bson:"modified_at"`
}

// Issue is a security issue.
type Issue struct {
    ID                         string                 `json:"id" bson:"_id"`
    Title                      string                 `json:"title" bson:"title"`
    IncidentID                 string                 `json:"incident_id"`
    Description                string                 `json:"description" bson:"description"`
}
 

У каждого инцидента есть одна проблема.

Когда я вставляю инцидент в Postgres, я добавляю только issue_id .

 type incident struct {
    ID          string    `db:"id"`
    CustomerID  string    `db:"customer_id"`
    InternalID  string    `db:"internal_id"`
    Title       string    `db:"title"`
    IssueID     string    `db:"issue_id"`
    Description string    `db:"description"`
    CreatedAt   time.Time `db:"created_at"`
    ModifiedAt  time.Time `db:"modified_at"`
}

func toIncident(model *models.Incident) (*incident, error) {
    // Create the SQL
    incident := amp;sqlIncident{
        ID:          model.ID,
        CustomerID:  model.CustomerID,
        InternalID:  model.InternalID,
        Title:       model.Title,
        Description: model.Description,
        IssueID:     "",
        CreatedAt:   model.CreatedAt,
        ModifiedAt:  model.ModifiedAt,
    }

    // Add the issue ID
    if model.Issue != nil {
        incident.IssueID = model.Issue.ID
    }

    return incident, nil
}
 

Я хотел бы иметь возможность выполнять обратную операцию с соединением по проблеме, когда я get() или list() инциденты.

Я использую "github.com/Masterminds/squirrel" и "github.com/jmoiron/sqlx" .

Приведенный ниже код будет кодом для получения инцидента.

     // Prepare query
    query := squirrel.Select(*).
        From(r.GetTableName()).
        PlaceholderFormat(squirrel.Dollar).
        Join("????????")

    // Build the SQL query
    q, args, err := query.ToSql()
    if err != nil {
        return fmt.Errorf("postgresql: unable to build query: %w", err)
    }

    // Get the session repo
    session := r.GetSession().(*sqlx.DB)

    // Prepare the statement
    stmt, err := session.PreparexContext(ctx, q)
    if err != nil {
        return fmt.Errorf("postgresql: unable to prepapre query: %w", err)
    }

    // Do the query
    err = stmt.SelectContext(ctx, result, args...)
    if err == sql.ErrNoRows {
        return repositories.ErrNoResult
    } else if err != nil {
        return fmt.Errorf("postgresql: unable to execute query: %w", err)
    }

 

Как я могу выполнить это правильно, пожалуйста?

Я чувствую, что я делаю это неправильно с issue_id полем, которое кажется бесполезным, и что я должен добавить определение проблемы в мою incident структуру SQL, что-то вроде этого ниже.

 type incident struct {
    ID          string    `db:"id"`
    CustomerID  string    `db:"customer_id"`
    InternalID  string    `db:"internal_id"`
    Title       string    `db:"title"`
    Issue       issue     `db:"issue"`
    Description string    `db:"description"`
    CreatedAt   time.Time `db:"created_at"`
    ModifiedAt  time.Time `db:"modified_at"`
}
 

Но я не вижу следующих шагов.