M
M
Michael2019-09-25 16:04:55
PostgreSQL
Michael, 2019-09-25 16:04:55

How to make pgx/pgtype friends with sqlx?

Good day!
I ask for your help. I'm trying to use github.com/jackc/pgx/pgtype from github.com/jmoiron/sqlx
but I get the error `pdateRubrica failed: sql: converting argument $1 type: unsupported type pgtype.Varchar, a struct` when saving. If you replace pgtype with normal ones, then everything works. How can you make it work?
Here is an example code:

type Rubrica struct {
  ID     pgtype.Int2    `db:"id"`
  Name   pgtype.Varchar `db:"name"`
  Weight pgtype.Int2    `db:"weight"`
}

func Connect(ctx context.Context) *TOPStore {
  d := &stdlib.DriverConfig{
    ConnConfig: pgx.ConnConfig{
      PreferSimpleProtocol: true,
      RuntimeParams: map[string]string{
        "standard_conforming_strings": "on",
      },
    },
  }
  stdlib.RegisterDriverConfig(d)

  db, err := sqlx.Connect("pgx", d.ConnectionString(connString))
  if err != nil {
    log.Fatalf("failed to sqlx Open: %v", err)
  }
  return db
}

func (s *Store) UpdateRubrica(rub *store.Rubrica) error {
  sql := `UPDATE rubricator SET name=:name, weight=:weight WHERE id=:id`
  if _, err := s.db.NamedExec(sql, rub); err != nil {
    log.Fatalf("UpdateRubrica failed: %-v\n", err)
  }
  return nil
}

func main() {
       ...
  rubrica := store.GetRubrica(1)
  store.UpdateRubrica(rubrica)
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SkipUFO, 2020-01-30
@SkipUFO

if _, err := s.db.NamedExec(sql, rub.Name, rub.Weight, rub.ID); err != nil {
    log.Fatalf("UpdateRubrica failed: %-v\n", err)
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question