rows.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  1. package pgx
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "reflect"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/jackc/pgx/v5/pgconn"
  11. "github.com/jackc/pgx/v5/pgtype"
  12. )
  13. // Rows is the result set returned from *Conn.Query. Rows must be closed before
  14. // the *Conn can be used again. Rows are closed by explicitly calling Close(),
  15. // calling Next() until it returns false, or when a fatal error occurs.
  16. //
  17. // Once a Rows is closed the only methods that may be called are Close(), Err(),
  18. // and CommandTag().
  19. //
  20. // Rows is an interface instead of a struct to allow tests to mock Query. However,
  21. // adding a method to an interface is technically a breaking change. Because of this
  22. // the Rows interface is partially excluded from semantic version requirements.
  23. // Methods will not be removed or changed, but new methods may be added.
  24. type Rows interface {
  25. // Close closes the rows, making the connection ready for use again. It is safe
  26. // to call Close after rows is already closed.
  27. Close()
  28. // Err returns any error that occurred while executing a query or reading its results. Err must be called after the
  29. // Rows is closed (either by calling Close or by Next returning false) to check if the query was successful. If it is
  30. // called before the Rows is closed it may return nil even if the query failed on the server.
  31. Err() error
  32. // CommandTag returns the command tag from this query. It is only available after Rows is closed.
  33. CommandTag() pgconn.CommandTag
  34. // FieldDescriptions returns the field descriptions of the columns. It may return nil. In particular this can occur
  35. // when there was an error executing the query.
  36. FieldDescriptions() []pgconn.FieldDescription
  37. // Next prepares the next row for reading. It returns true if there is another row and false if no more rows are
  38. // available or a fatal error has occurred. It automatically closes rows upon returning false (whether due to all rows
  39. // having been read or due to an error).
  40. //
  41. // Callers should check rows.Err() after rows.Next() returns false to detect whether result-set reading ended
  42. // prematurely due to an error. See Conn.Query for details.
  43. //
  44. // For simpler error handling, consider using the higher-level pgx v5 CollectRows() and ForEachRow() helpers instead.
  45. Next() bool
  46. // Scan reads the values from the current row into dest values positionally. dest can include pointers to core types,
  47. // values implementing the Scanner interface, and nil. nil will skip the value entirely. It is an error to call Scan
  48. // without first calling Next() and checking that it returned true. Rows is automatically closed upon error.
  49. Scan(dest ...any) error
  50. // Values returns the decoded row values. As with Scan(), it is an error to
  51. // call Values without first calling Next() and checking that it returned
  52. // true.
  53. Values() ([]any, error)
  54. // RawValues returns the unparsed bytes of the row values. The returned data is only valid until the next Next
  55. // call or the Rows is closed.
  56. RawValues() [][]byte
  57. // Conn returns the underlying *Conn on which the query was executed. This may return nil if Rows did not come from a
  58. // *Conn (e.g. if it was created by RowsFromResultReader)
  59. Conn() *Conn
  60. }
  61. // Row is a convenience wrapper over Rows that is returned by QueryRow.
  62. //
  63. // Row is an interface instead of a struct to allow tests to mock QueryRow. However,
  64. // adding a method to an interface is technically a breaking change. Because of this
  65. // the Row interface is partially excluded from semantic version requirements.
  66. // Methods will not be removed or changed, but new methods may be added.
  67. type Row interface {
  68. // Scan works the same as Rows. with the following exceptions. If no
  69. // rows were found it returns ErrNoRows. If multiple rows are returned it
  70. // ignores all but the first.
  71. Scan(dest ...any) error
  72. }
  73. // RowScanner scans an entire row at a time into the RowScanner.
  74. type RowScanner interface {
  75. // ScanRows scans the row.
  76. ScanRow(rows Rows) error
  77. }
  78. // connRow implements the Row interface for Conn.QueryRow.
  79. type connRow baseRows
  80. func (r *connRow) Scan(dest ...any) (err error) {
  81. rows := (*baseRows)(r)
  82. if rows.Err() != nil {
  83. return rows.Err()
  84. }
  85. for _, d := range dest {
  86. if _, ok := d.(*pgtype.DriverBytes); ok {
  87. rows.Close()
  88. return fmt.Errorf("cannot scan into *pgtype.DriverBytes from QueryRow")
  89. }
  90. }
  91. if !rows.Next() {
  92. if rows.Err() == nil {
  93. return ErrNoRows
  94. }
  95. return rows.Err()
  96. }
  97. rows.Scan(dest...)
  98. rows.Close()
  99. return rows.Err()
  100. }
  101. // baseRows implements the Rows interface for Conn.Query.
  102. type baseRows struct {
  103. typeMap *pgtype.Map
  104. resultReader *pgconn.ResultReader
  105. values [][]byte
  106. commandTag pgconn.CommandTag
  107. err error
  108. closed bool
  109. scanPlans []pgtype.ScanPlan
  110. scanTypes []reflect.Type
  111. conn *Conn
  112. multiResultReader *pgconn.MultiResultReader
  113. queryTracer QueryTracer
  114. batchTracer BatchTracer
  115. ctx context.Context
  116. startTime time.Time
  117. sql string
  118. args []any
  119. rowCount int
  120. }
  121. func (rows *baseRows) FieldDescriptions() []pgconn.FieldDescription {
  122. return rows.resultReader.FieldDescriptions()
  123. }
  124. func (rows *baseRows) Close() {
  125. if rows.closed {
  126. return
  127. }
  128. rows.closed = true
  129. if rows.resultReader != nil {
  130. var closeErr error
  131. rows.commandTag, closeErr = rows.resultReader.Close()
  132. if rows.err == nil {
  133. rows.err = closeErr
  134. }
  135. }
  136. if rows.multiResultReader != nil {
  137. closeErr := rows.multiResultReader.Close()
  138. if rows.err == nil {
  139. rows.err = closeErr
  140. }
  141. }
  142. if rows.err != nil && rows.conn != nil && rows.sql != "" {
  143. if sc := rows.conn.statementCache; sc != nil {
  144. sc.Invalidate(rows.sql)
  145. }
  146. if sc := rows.conn.descriptionCache; sc != nil {
  147. sc.Invalidate(rows.sql)
  148. }
  149. }
  150. if rows.batchTracer != nil {
  151. rows.batchTracer.TraceBatchQuery(rows.ctx, rows.conn, TraceBatchQueryData{SQL: rows.sql, Args: rows.args, CommandTag: rows.commandTag, Err: rows.err})
  152. } else if rows.queryTracer != nil {
  153. rows.queryTracer.TraceQueryEnd(rows.ctx, rows.conn, TraceQueryEndData{rows.commandTag, rows.err})
  154. }
  155. // Zero references to other memory allocations. This allows them to be GC'd even when the Rows still referenced. In
  156. // particular, when using pgxpool GC could be delayed as pgxpool.poolRows are allocated in large slices.
  157. //
  158. // https://github.com/jackc/pgx/pull/2269
  159. rows.values = nil
  160. rows.scanPlans = nil
  161. rows.scanTypes = nil
  162. rows.ctx = nil
  163. rows.sql = ""
  164. rows.args = nil
  165. }
  166. func (rows *baseRows) CommandTag() pgconn.CommandTag {
  167. return rows.commandTag
  168. }
  169. func (rows *baseRows) Err() error {
  170. return rows.err
  171. }
  172. // fatal signals an error occurred after the query was sent to the server. It
  173. // closes the rows automatically.
  174. func (rows *baseRows) fatal(err error) {
  175. if rows.err != nil {
  176. return
  177. }
  178. rows.err = err
  179. rows.Close()
  180. }
  181. func (rows *baseRows) Next() bool {
  182. if rows.closed {
  183. return false
  184. }
  185. if rows.resultReader.NextRow() {
  186. rows.rowCount++
  187. rows.values = rows.resultReader.Values()
  188. return true
  189. } else {
  190. rows.Close()
  191. return false
  192. }
  193. }
  194. func (rows *baseRows) Scan(dest ...any) error {
  195. m := rows.typeMap
  196. fieldDescriptions := rows.FieldDescriptions()
  197. values := rows.values
  198. if len(fieldDescriptions) != len(values) {
  199. err := fmt.Errorf("number of field descriptions must equal number of values, got %d and %d", len(fieldDescriptions), len(values))
  200. rows.fatal(err)
  201. return err
  202. }
  203. if len(dest) == 1 {
  204. if rc, ok := dest[0].(RowScanner); ok {
  205. err := rc.ScanRow(rows)
  206. if err != nil {
  207. rows.fatal(err)
  208. }
  209. return err
  210. }
  211. }
  212. if len(fieldDescriptions) != len(dest) {
  213. err := fmt.Errorf("number of field descriptions must equal number of destinations, got %d and %d", len(fieldDescriptions), len(dest))
  214. rows.fatal(err)
  215. return err
  216. }
  217. if rows.scanPlans == nil {
  218. rows.scanPlans = make([]pgtype.ScanPlan, len(values))
  219. rows.scanTypes = make([]reflect.Type, len(values))
  220. for i := range dest {
  221. rows.scanPlans[i] = m.PlanScan(fieldDescriptions[i].DataTypeOID, fieldDescriptions[i].Format, dest[i])
  222. rows.scanTypes[i] = reflect.TypeOf(dest[i])
  223. }
  224. }
  225. for i, dst := range dest {
  226. if dst == nil {
  227. continue
  228. }
  229. if rows.scanTypes[i] != reflect.TypeOf(dst) {
  230. rows.scanPlans[i] = m.PlanScan(fieldDescriptions[i].DataTypeOID, fieldDescriptions[i].Format, dest[i])
  231. rows.scanTypes[i] = reflect.TypeOf(dest[i])
  232. }
  233. err := rows.scanPlans[i].Scan(values[i], dst)
  234. if err != nil {
  235. err = ScanArgError{ColumnIndex: i, FieldName: fieldDescriptions[i].Name, Err: err}
  236. rows.fatal(err)
  237. return err
  238. }
  239. }
  240. return nil
  241. }
  242. func (rows *baseRows) Values() ([]any, error) {
  243. if rows.closed {
  244. return nil, errors.New("rows is closed")
  245. }
  246. values := make([]any, 0, len(rows.FieldDescriptions()))
  247. for i := range rows.FieldDescriptions() {
  248. buf := rows.values[i]
  249. fd := &rows.FieldDescriptions()[i]
  250. if buf == nil {
  251. values = append(values, nil)
  252. continue
  253. }
  254. if dt, ok := rows.typeMap.TypeForOID(fd.DataTypeOID); ok {
  255. value, err := dt.Codec.DecodeValue(rows.typeMap, fd.DataTypeOID, fd.Format, buf)
  256. if err != nil {
  257. rows.fatal(err)
  258. }
  259. values = append(values, value)
  260. } else {
  261. switch fd.Format {
  262. case TextFormatCode:
  263. values = append(values, string(buf))
  264. case BinaryFormatCode:
  265. newBuf := make([]byte, len(buf))
  266. copy(newBuf, buf)
  267. values = append(values, newBuf)
  268. default:
  269. rows.fatal(errors.New("unknown format code"))
  270. }
  271. }
  272. if rows.Err() != nil {
  273. return nil, rows.Err()
  274. }
  275. }
  276. return values, rows.Err()
  277. }
  278. func (rows *baseRows) RawValues() [][]byte {
  279. return rows.values
  280. }
  281. func (rows *baseRows) Conn() *Conn {
  282. return rows.conn
  283. }
  284. type ScanArgError struct {
  285. ColumnIndex int
  286. FieldName string
  287. Err error
  288. }
  289. func (e ScanArgError) Error() string {
  290. if e.FieldName == "?column?" { // Don't include the fieldname if it's unknown
  291. return fmt.Sprintf("can't scan into dest[%d]: %v", e.ColumnIndex, e.Err)
  292. }
  293. return fmt.Sprintf("can't scan into dest[%d] (col: %s): %v", e.ColumnIndex, e.FieldName, e.Err)
  294. }
  295. func (e ScanArgError) Unwrap() error {
  296. return e.Err
  297. }
  298. // ScanRow decodes raw row data into dest. It can be used to scan rows read from the lower level pgconn interface.
  299. //
  300. // typeMap - OID to Go type mapping.
  301. // fieldDescriptions - OID and format of values
  302. // values - the raw data as returned from the PostgreSQL server
  303. // dest - the destination that values will be decoded into
  304. func ScanRow(typeMap *pgtype.Map, fieldDescriptions []pgconn.FieldDescription, values [][]byte, dest ...any) error {
  305. if len(fieldDescriptions) != len(values) {
  306. return fmt.Errorf("number of field descriptions must equal number of values, got %d and %d", len(fieldDescriptions), len(values))
  307. }
  308. if len(fieldDescriptions) != len(dest) {
  309. return fmt.Errorf("number of field descriptions must equal number of destinations, got %d and %d", len(fieldDescriptions), len(dest))
  310. }
  311. for i, d := range dest {
  312. if d == nil {
  313. continue
  314. }
  315. err := typeMap.Scan(fieldDescriptions[i].DataTypeOID, fieldDescriptions[i].Format, values[i], d)
  316. if err != nil {
  317. return ScanArgError{ColumnIndex: i, FieldName: fieldDescriptions[i].Name, Err: err}
  318. }
  319. }
  320. return nil
  321. }
  322. // RowsFromResultReader returns a Rows that will read from values resultReader and decode with typeMap. It can be used
  323. // to read from the lower level pgconn interface.
  324. func RowsFromResultReader(typeMap *pgtype.Map, resultReader *pgconn.ResultReader) Rows {
  325. return &baseRows{
  326. typeMap: typeMap,
  327. resultReader: resultReader,
  328. }
  329. }
  330. // ForEachRow iterates through rows. For each row it scans into the elements of scans and calls fn. If any row
  331. // fails to scan or fn returns an error the query will be aborted and the error will be returned. Rows will be closed
  332. // when ForEachRow returns.
  333. func ForEachRow(rows Rows, scans []any, fn func() error) (pgconn.CommandTag, error) {
  334. defer rows.Close()
  335. for rows.Next() {
  336. err := rows.Scan(scans...)
  337. if err != nil {
  338. return pgconn.CommandTag{}, err
  339. }
  340. err = fn()
  341. if err != nil {
  342. return pgconn.CommandTag{}, err
  343. }
  344. }
  345. if err := rows.Err(); err != nil {
  346. return pgconn.CommandTag{}, err
  347. }
  348. return rows.CommandTag(), nil
  349. }
  350. // CollectableRow is the subset of Rows methods that a RowToFunc is allowed to call.
  351. type CollectableRow interface {
  352. FieldDescriptions() []pgconn.FieldDescription
  353. Scan(dest ...any) error
  354. Values() ([]any, error)
  355. RawValues() [][]byte
  356. }
  357. // RowToFunc is a function that scans or otherwise converts row to a T.
  358. type RowToFunc[T any] func(row CollectableRow) (T, error)
  359. // AppendRows iterates through rows, calling fn for each row, and appending the results into a slice of T.
  360. //
  361. // This function closes the rows automatically on return.
  362. func AppendRows[T any, S ~[]T](slice S, rows Rows, fn RowToFunc[T]) (S, error) {
  363. defer rows.Close()
  364. for rows.Next() {
  365. value, err := fn(rows)
  366. if err != nil {
  367. return nil, err
  368. }
  369. slice = append(slice, value)
  370. }
  371. if err := rows.Err(); err != nil {
  372. return nil, err
  373. }
  374. return slice, nil
  375. }
  376. // CollectRows iterates through rows, calling fn for each row, and collecting the results into a slice of T.
  377. //
  378. // This function closes the rows automatically on return.
  379. func CollectRows[T any](rows Rows, fn RowToFunc[T]) ([]T, error) {
  380. return AppendRows([]T{}, rows, fn)
  381. }
  382. // CollectOneRow calls fn for the first row in rows and returns the result. If no rows are found returns an error where errors.Is(ErrNoRows) is true.
  383. // CollectOneRow is to CollectRows as QueryRow is to Query.
  384. //
  385. // This function closes the rows automatically on return.
  386. func CollectOneRow[T any](rows Rows, fn RowToFunc[T]) (T, error) {
  387. defer rows.Close()
  388. var value T
  389. var err error
  390. if !rows.Next() {
  391. if err = rows.Err(); err != nil {
  392. return value, err
  393. }
  394. return value, ErrNoRows
  395. }
  396. value, err = fn(rows)
  397. if err != nil {
  398. return value, err
  399. }
  400. // The defer rows.Close() won't have executed yet. If the query returned more than one row, rows would still be open.
  401. // rows.Close() must be called before rows.Err() so we explicitly call it here.
  402. rows.Close()
  403. return value, rows.Err()
  404. }
  405. // CollectExactlyOneRow calls fn for the first row in rows and returns the result.
  406. // - If no rows are found returns an error where errors.Is(ErrNoRows) is true.
  407. // - If more than 1 row is found returns an error where errors.Is(ErrTooManyRows) is true.
  408. //
  409. // This function closes the rows automatically on return.
  410. func CollectExactlyOneRow[T any](rows Rows, fn RowToFunc[T]) (T, error) {
  411. defer rows.Close()
  412. var (
  413. err error
  414. value T
  415. )
  416. if !rows.Next() {
  417. if err = rows.Err(); err != nil {
  418. return value, err
  419. }
  420. return value, ErrNoRows
  421. }
  422. value, err = fn(rows)
  423. if err != nil {
  424. return value, err
  425. }
  426. if rows.Next() {
  427. var zero T
  428. return zero, ErrTooManyRows
  429. }
  430. return value, rows.Err()
  431. }
  432. // RowTo returns a T scanned from row.
  433. func RowTo[T any](row CollectableRow) (T, error) {
  434. var value T
  435. err := row.Scan(&value)
  436. return value, err
  437. }
  438. // RowTo returns a the address of a T scanned from row.
  439. func RowToAddrOf[T any](row CollectableRow) (*T, error) {
  440. var value T
  441. err := row.Scan(&value)
  442. return &value, err
  443. }
  444. // RowToMap returns a map scanned from row.
  445. func RowToMap(row CollectableRow) (map[string]any, error) {
  446. var value map[string]any
  447. err := row.Scan((*mapRowScanner)(&value))
  448. return value, err
  449. }
  450. type mapRowScanner map[string]any
  451. func (rs *mapRowScanner) ScanRow(rows Rows) error {
  452. values, err := rows.Values()
  453. if err != nil {
  454. return err
  455. }
  456. *rs = make(mapRowScanner, len(values))
  457. for i := range values {
  458. (*rs)[string(rows.FieldDescriptions()[i].Name)] = values[i]
  459. }
  460. return nil
  461. }
  462. // RowToStructByPos returns a T scanned from row. T must be a struct. T must have the same number of public fields as row
  463. // has fields. The row and T fields will be matched by position. If the "db" struct tag is "-" then the field will be
  464. // ignored.
  465. func RowToStructByPos[T any](row CollectableRow) (T, error) {
  466. var value T
  467. err := (&positionalStructRowScanner{ptrToStruct: &value}).ScanRow(row)
  468. return value, err
  469. }
  470. // RowToAddrOfStructByPos returns the address of a T scanned from row. T must be a struct. T must have the same number a
  471. // public fields as row has fields. The row and T fields will be matched by position. If the "db" struct tag is "-" then
  472. // the field will be ignored.
  473. func RowToAddrOfStructByPos[T any](row CollectableRow) (*T, error) {
  474. var value T
  475. err := (&positionalStructRowScanner{ptrToStruct: &value}).ScanRow(row)
  476. return &value, err
  477. }
  478. type positionalStructRowScanner struct {
  479. ptrToStruct any
  480. }
  481. func (rs *positionalStructRowScanner) ScanRow(rows CollectableRow) error {
  482. typ := reflect.TypeOf(rs.ptrToStruct).Elem()
  483. fields := lookupStructFields(typ)
  484. if len(rows.RawValues()) > len(fields) {
  485. return fmt.Errorf(
  486. "got %d values, but dst struct has only %d fields",
  487. len(rows.RawValues()),
  488. len(fields),
  489. )
  490. }
  491. scanTargets := setupStructScanTargets(rs.ptrToStruct, fields)
  492. return rows.Scan(scanTargets...)
  493. }
  494. // Map from reflect.Type -> []structRowField
  495. var positionalStructFieldMap sync.Map
  496. func lookupStructFields(t reflect.Type) []structRowField {
  497. if cached, ok := positionalStructFieldMap.Load(t); ok {
  498. return cached.([]structRowField)
  499. }
  500. fieldStack := make([]int, 0, 1)
  501. fields := computeStructFields(t, make([]structRowField, 0, t.NumField()), &fieldStack)
  502. fieldsIface, _ := positionalStructFieldMap.LoadOrStore(t, fields)
  503. return fieldsIface.([]structRowField)
  504. }
  505. func computeStructFields(
  506. t reflect.Type,
  507. fields []structRowField,
  508. fieldStack *[]int,
  509. ) []structRowField {
  510. tail := len(*fieldStack)
  511. *fieldStack = append(*fieldStack, 0)
  512. for i := 0; i < t.NumField(); i++ {
  513. sf := t.Field(i)
  514. (*fieldStack)[tail] = i
  515. // Handle anonymous struct embedding, but do not try to handle embedded pointers.
  516. if sf.Anonymous && sf.Type.Kind() == reflect.Struct {
  517. fields = computeStructFields(sf.Type, fields, fieldStack)
  518. } else if sf.PkgPath == "" {
  519. dbTag, _ := sf.Tag.Lookup(structTagKey)
  520. if dbTag == "-" {
  521. // Field is ignored, skip it.
  522. continue
  523. }
  524. fields = append(fields, structRowField{
  525. path: append([]int(nil), *fieldStack...),
  526. })
  527. }
  528. }
  529. *fieldStack = (*fieldStack)[:tail]
  530. return fields
  531. }
  532. // RowToStructByName returns a T scanned from row. T must be a struct. T must have the same number of named public
  533. // fields as row has fields. The row and T fields will be matched by name. The match is case-insensitive. The database
  534. // column name can be overridden with a "db" struct tag. If the "db" struct tag is "-" then the field will be ignored.
  535. func RowToStructByName[T any](row CollectableRow) (T, error) {
  536. var value T
  537. err := (&namedStructRowScanner{ptrToStruct: &value}).ScanRow(row)
  538. return value, err
  539. }
  540. // RowToAddrOfStructByName returns the address of a T scanned from row. T must be a struct. T must have the same number
  541. // of named public fields as row has fields. The row and T fields will be matched by name. The match is
  542. // case-insensitive. The database column name can be overridden with a "db" struct tag. If the "db" struct tag is "-"
  543. // then the field will be ignored.
  544. func RowToAddrOfStructByName[T any](row CollectableRow) (*T, error) {
  545. var value T
  546. err := (&namedStructRowScanner{ptrToStruct: &value}).ScanRow(row)
  547. return &value, err
  548. }
  549. // RowToStructByNameLax returns a T scanned from row. T must be a struct. T must have greater than or equal number of named public
  550. // fields as row has fields. The row and T fields will be matched by name. The match is case-insensitive. The database
  551. // column name can be overridden with a "db" struct tag. If the "db" struct tag is "-" then the field will be ignored.
  552. func RowToStructByNameLax[T any](row CollectableRow) (T, error) {
  553. var value T
  554. err := (&namedStructRowScanner{ptrToStruct: &value, lax: true}).ScanRow(row)
  555. return value, err
  556. }
  557. // RowToAddrOfStructByNameLax returns the address of a T scanned from row. T must be a struct. T must have greater than or
  558. // equal number of named public fields as row has fields. The row and T fields will be matched by name. The match is
  559. // case-insensitive. The database column name can be overridden with a "db" struct tag. If the "db" struct tag is "-"
  560. // then the field will be ignored.
  561. func RowToAddrOfStructByNameLax[T any](row CollectableRow) (*T, error) {
  562. var value T
  563. err := (&namedStructRowScanner{ptrToStruct: &value, lax: true}).ScanRow(row)
  564. return &value, err
  565. }
  566. type namedStructRowScanner struct {
  567. ptrToStruct any
  568. lax bool
  569. }
  570. func (rs *namedStructRowScanner) ScanRow(rows CollectableRow) error {
  571. typ := reflect.TypeOf(rs.ptrToStruct).Elem()
  572. fldDescs := rows.FieldDescriptions()
  573. namedStructFields, err := lookupNamedStructFields(typ, fldDescs)
  574. if err != nil {
  575. return err
  576. }
  577. if !rs.lax && namedStructFields.missingField != "" {
  578. return fmt.Errorf("cannot find field %s in returned row", namedStructFields.missingField)
  579. }
  580. fields := namedStructFields.fields
  581. scanTargets := setupStructScanTargets(rs.ptrToStruct, fields)
  582. return rows.Scan(scanTargets...)
  583. }
  584. // Map from namedStructFieldMap -> *namedStructFields
  585. var namedStructFieldMap sync.Map
  586. type namedStructFieldsKey struct {
  587. t reflect.Type
  588. colNames string
  589. }
  590. type namedStructFields struct {
  591. fields []structRowField
  592. // missingField is the first field from the struct without a corresponding row field.
  593. // This is used to construct the correct error message for non-lax queries.
  594. missingField string
  595. }
  596. func lookupNamedStructFields(
  597. t reflect.Type,
  598. fldDescs []pgconn.FieldDescription,
  599. ) (*namedStructFields, error) {
  600. key := namedStructFieldsKey{
  601. t: t,
  602. colNames: joinFieldNames(fldDescs),
  603. }
  604. if cached, ok := namedStructFieldMap.Load(key); ok {
  605. return cached.(*namedStructFields), nil
  606. }
  607. // We could probably do two-levels of caching, where we compute the key -> fields mapping
  608. // for a type only once, cache it by type, then use that to compute the column -> fields
  609. // mapping for a given set of columns.
  610. fieldStack := make([]int, 0, 1)
  611. fields, missingField := computeNamedStructFields(
  612. fldDescs,
  613. t,
  614. make([]structRowField, len(fldDescs)),
  615. &fieldStack,
  616. )
  617. for i, f := range fields {
  618. if f.path == nil {
  619. return nil, fmt.Errorf(
  620. "struct doesn't have corresponding row field %s",
  621. fldDescs[i].Name,
  622. )
  623. }
  624. }
  625. fieldsIface, _ := namedStructFieldMap.LoadOrStore(
  626. key,
  627. &namedStructFields{fields: fields, missingField: missingField},
  628. )
  629. return fieldsIface.(*namedStructFields), nil
  630. }
  631. func joinFieldNames(fldDescs []pgconn.FieldDescription) string {
  632. switch len(fldDescs) {
  633. case 0:
  634. return ""
  635. case 1:
  636. return fldDescs[0].Name
  637. }
  638. totalSize := len(fldDescs) - 1 // Space for separator bytes.
  639. for _, d := range fldDescs {
  640. totalSize += len(d.Name)
  641. }
  642. var b strings.Builder
  643. b.Grow(totalSize)
  644. b.WriteString(fldDescs[0].Name)
  645. for _, d := range fldDescs[1:] {
  646. b.WriteByte(0) // Join with NUL byte as it's (presumably) not a valid column character.
  647. b.WriteString(d.Name)
  648. }
  649. return b.String()
  650. }
  651. func computeNamedStructFields(
  652. fldDescs []pgconn.FieldDescription,
  653. t reflect.Type,
  654. fields []structRowField,
  655. fieldStack *[]int,
  656. ) ([]structRowField, string) {
  657. var missingField string
  658. tail := len(*fieldStack)
  659. *fieldStack = append(*fieldStack, 0)
  660. for i := 0; i < t.NumField(); i++ {
  661. sf := t.Field(i)
  662. (*fieldStack)[tail] = i
  663. if sf.PkgPath != "" && !sf.Anonymous {
  664. // Field is unexported, skip it.
  665. continue
  666. }
  667. // Handle anonymous struct embedding, but do not try to handle embedded pointers.
  668. if sf.Anonymous && sf.Type.Kind() == reflect.Struct {
  669. var missingSubField string
  670. fields, missingSubField = computeNamedStructFields(
  671. fldDescs,
  672. sf.Type,
  673. fields,
  674. fieldStack,
  675. )
  676. if missingField == "" {
  677. missingField = missingSubField
  678. }
  679. } else {
  680. dbTag, dbTagPresent := sf.Tag.Lookup(structTagKey)
  681. if dbTagPresent {
  682. dbTag, _, _ = strings.Cut(dbTag, ",")
  683. }
  684. if dbTag == "-" {
  685. // Field is ignored, skip it.
  686. continue
  687. }
  688. colName := dbTag
  689. if !dbTagPresent {
  690. colName = sf.Name
  691. }
  692. fpos := fieldPosByName(fldDescs, colName, !dbTagPresent)
  693. if fpos == -1 {
  694. if missingField == "" {
  695. missingField = colName
  696. }
  697. continue
  698. }
  699. fields[fpos] = structRowField{
  700. path: append([]int(nil), *fieldStack...),
  701. }
  702. }
  703. }
  704. *fieldStack = (*fieldStack)[:tail]
  705. return fields, missingField
  706. }
  707. const structTagKey = "db"
  708. func fieldPosByName(fldDescs []pgconn.FieldDescription, field string, normalize bool) (i int) {
  709. i = -1
  710. if normalize {
  711. field = strings.ReplaceAll(field, "_", "")
  712. }
  713. for i, desc := range fldDescs {
  714. if normalize {
  715. if strings.EqualFold(strings.ReplaceAll(desc.Name, "_", ""), field) {
  716. return i
  717. }
  718. } else {
  719. if desc.Name == field {
  720. return i
  721. }
  722. }
  723. }
  724. return
  725. }
  726. // structRowField describes a field of a struct.
  727. //
  728. // TODO: It would be a bit more efficient to track the path using the pointer
  729. // offset within the (outermost) struct and use unsafe.Pointer arithmetic to
  730. // construct references when scanning rows. However, it's not clear it's worth
  731. // using unsafe for this.
  732. type structRowField struct {
  733. path []int
  734. }
  735. func setupStructScanTargets(receiver any, fields []structRowField) []any {
  736. scanTargets := make([]any, len(fields))
  737. v := reflect.ValueOf(receiver).Elem()
  738. for i, f := range fields {
  739. scanTargets[i] = v.FieldByIndex(f.path).Addr().Interface()
  740. }
  741. return scanTargets
  742. }