...

Source file src/github.com/jackc/pgtype/oid.go

Documentation: github.com/jackc/pgtype

     1  package pgtype
     2  
     3  import (
     4  	"database/sql/driver"
     5  	"encoding/binary"
     6  	"fmt"
     7  	"strconv"
     8  
     9  	"github.com/jackc/pgio"
    10  )
    11  
    12  // OID (Object Identifier Type) is, according to
    13  // https://www.postgresql.org/docs/current/static/datatype-oid.html, used
    14  // internally by PostgreSQL as a primary key for various system tables. It is
    15  // currently implemented as an unsigned four-byte integer. Its definition can be
    16  // found in src/include/postgres_ext.h in the PostgreSQL sources. Because it is
    17  // so frequently required to be in a NOT NULL condition OID cannot be NULL. To
    18  // allow for NULL OIDs use OIDValue.
    19  type OID uint32
    20  
    21  func (dst *OID) DecodeText(ci *ConnInfo, src []byte) error {
    22  	if src == nil {
    23  		return fmt.Errorf("cannot decode nil into OID")
    24  	}
    25  
    26  	n, err := strconv.ParseUint(string(src), 10, 32)
    27  	if err != nil {
    28  		return err
    29  	}
    30  
    31  	*dst = OID(n)
    32  	return nil
    33  }
    34  
    35  func (dst *OID) DecodeBinary(ci *ConnInfo, src []byte) error {
    36  	if src == nil {
    37  		return fmt.Errorf("cannot decode nil into OID")
    38  	}
    39  
    40  	if len(src) != 4 {
    41  		return fmt.Errorf("invalid length: %v", len(src))
    42  	}
    43  
    44  	n := binary.BigEndian.Uint32(src)
    45  	*dst = OID(n)
    46  	return nil
    47  }
    48  
    49  func (src OID) EncodeText(ci *ConnInfo, buf []byte) ([]byte, error) {
    50  	return append(buf, strconv.FormatUint(uint64(src), 10)...), nil
    51  }
    52  
    53  func (src OID) EncodeBinary(ci *ConnInfo, buf []byte) ([]byte, error) {
    54  	return pgio.AppendUint32(buf, uint32(src)), nil
    55  }
    56  
    57  // Scan implements the database/sql Scanner interface.
    58  func (dst *OID) Scan(src interface{}) error {
    59  	if src == nil {
    60  		return fmt.Errorf("cannot scan NULL into %T", src)
    61  	}
    62  
    63  	switch src := src.(type) {
    64  	case int64:
    65  		*dst = OID(src)
    66  		return nil
    67  	case string:
    68  		return dst.DecodeText(nil, []byte(src))
    69  	case []byte:
    70  		srcCopy := make([]byte, len(src))
    71  		copy(srcCopy, src)
    72  		return dst.DecodeText(nil, srcCopy)
    73  	}
    74  
    75  	return fmt.Errorf("cannot scan %T", src)
    76  }
    77  
    78  // Value implements the database/sql/driver Valuer interface.
    79  func (src OID) Value() (driver.Value, error) {
    80  	return int64(src), nil
    81  }
    82  

View as plain text