Working with PostgreSQL arrays

pgdialect supports PostgreSQL one-dimensional arrays using array struct field tag:

  1. type Article struct {
  2. ID int64
  3. Tags []string `bun:",array"`
  4. }

To scan a PostgreSQL array into a variable, use pgdialect.Array:

  1. import "github.com/uptrace/bun/dialect/pgdialect"
  2. var tags []string
  3. err := db.NewSelect().
  4. Model((*Article)(nil)).
  5. ColumnExpr("tags").
  6. Where("id = 1").
  7. Scan(ctx, pgdialect.Array(&tags))

You can also use pgdialect.Array to insert/update arrays:

  1. res, err := db.NewUpdate().
  2. Model(&article).
  3. Set("tags = ?", pgdialect.Array([]string{"foo", "bar"})).
  4. WherePK().
  5. Exec(ctx)

Or in Where clause:

  1. q.Where("tags @> ?", pgdialect.Array([]string{"foo"}))