File: oid.go

package info (click to toggle)
golang-github-jackc-pgtype 1.10.0-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 1,656 kB
  • sloc: sh: 32; makefile: 4
file content (81 lines) | stat: -rw-r--r-- 1,988 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package pgtype

import (
	"database/sql/driver"
	"encoding/binary"
	"fmt"
	"strconv"

	"github.com/jackc/pgio"
)

// OID (Object Identifier Type) is, according to
// https://www.postgresql.org/docs/current/static/datatype-oid.html, used
// internally by PostgreSQL as a primary key for various system tables. It is
// currently implemented as an unsigned four-byte integer. Its definition can be
// found in src/include/postgres_ext.h in the PostgreSQL sources. Because it is
// so frequently required to be in a NOT NULL condition OID cannot be NULL. To
// allow for NULL OIDs use OIDValue.
type OID uint32

func (dst *OID) DecodeText(ci *ConnInfo, src []byte) error {
	if src == nil {
		return fmt.Errorf("cannot decode nil into OID")
	}

	n, err := strconv.ParseUint(string(src), 10, 32)
	if err != nil {
		return err
	}

	*dst = OID(n)
	return nil
}

func (dst *OID) DecodeBinary(ci *ConnInfo, src []byte) error {
	if src == nil {
		return fmt.Errorf("cannot decode nil into OID")
	}

	if len(src) != 4 {
		return fmt.Errorf("invalid length: %v", len(src))
	}

	n := binary.BigEndian.Uint32(src)
	*dst = OID(n)
	return nil
}

func (src OID) EncodeText(ci *ConnInfo, buf []byte) ([]byte, error) {
	return append(buf, strconv.FormatUint(uint64(src), 10)...), nil
}

func (src OID) EncodeBinary(ci *ConnInfo, buf []byte) ([]byte, error) {
	return pgio.AppendUint32(buf, uint32(src)), nil
}

// Scan implements the database/sql Scanner interface.
func (dst *OID) Scan(src interface{}) error {
	if src == nil {
		return fmt.Errorf("cannot scan NULL into %T", src)
	}

	switch src := src.(type) {
	case int64:
		*dst = OID(src)
		return nil
	case string:
		return dst.DecodeText(nil, []byte(src))
	case []byte:
		srcCopy := make([]byte, len(src))
		copy(srcCopy, src)
		return dst.DecodeText(nil, srcCopy)
	}

	return fmt.Errorf("cannot scan %T", src)
}

// Value implements the database/sql/driver Valuer interface.
func (src OID) Value() (driver.Value, error) {
	return int64(src), nil
}