Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

447
Views
¿Cómo obtengo un segmento de una matriz de Postgres en Golang?

Digamos que tengo una consulta postgres como:

 SELECT id, ARRAY_AGG(code) AS code FROM codes WHERE id = '9252781' GROUP BY id;

Mi regreso se parece a:

 id | codes -----------+------------- 9252781 | {H01,H02}

Tanto id como los codes son varchar .

En Golang, cuando escaneo a lo largo de las filas para obtener mi resultado, simplemente se congela. Ningún error, nada.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Si está utilizando el controlador de postgres github.com/lib/pq , puede usar su función auxiliar pq.Array para escanear y almacenar matrices de postgres.

 var id string var arr []string row := db.QueryRow(`SELECT '9252781', ARRAY['H01','H02']`) if err := row.Scan(&id, pq.Array(&arr)); err != nil { log.Fatal(err) } log.Println(id, arr) // 9252781 [H01 H02]
over 4 years ago · Santiago Trujillo Report

0

No quiero usar un controlador adicional ( github.com/lib/pq ), y no encontré ninguna forma pgx de hacerlo que no sea crear mi propio tipo.

Así que hice uno:

 type Tags []string func (t *Tags) Scan(v interface{}) error { if v == nil { *t = Tags{} return nil } s, ok := v.(string) if !ok { return fmt.Errorf("Scan is expected to receive a string from database, but got [%+v]", v) } s = strings.TrimPrefix(s, "{") s = strings.TrimSuffix(s, "}") *t = strings.Split(s, ",") return nil } func (t *Tags) Value() (driver.Value, error) { s := fmt.Sprintf("{%v}", strings.Join(([]string)(*t), ",")) return s, nil }

luego puede escanear la fila devuelta desde la base de datos como:

 ... err := rows.Scan( ... &Tags, ... )

y puede usarlo directamente en sus consultas de Exec .

Este código funciona bien con constantes en matrices, pero necesita más trabajo si desea usarlo entre comas y corchetes.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!