pgdate

package
v0.23.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 12, 2024 License: Apache-2.0 Imports: 19 Imported by: 2

Documentation

Overview

Package pgdate contains parsing functions and types for dates and times in a manner that is compatible with PostgreSQL.

The implementation here is inspired by the following https://github.com/postgres/postgres/blob/REL_10_5/src/backend/utils/adt/datetime.c

The general approach is to take each input string and break it into contiguous runs of alphanumeric characters. Then, we attempt to interpret the input in order to populate a collection of date/time fields. We track which fields have been set in order to be able to apply various parsing heuristics to map the input chunks into date/time fields.

Index

Constants

This section is empty.

Variables

View Source
var (
	TimeEpoch = timeutil.Unix(0, 0)
	// TimeInfinity represents the "highest" possible time.
	// TODO (#41564): this should actually behave as infinity, i.e. any operator
	// leaves this as infinity. This time should always be greater than any other time.
	// We should probably use the next microsecond after this value, i.e. timeutil.Unix(9224318016000, 0).
	// Postgres uses math.MaxInt64 microseconds as the infinity value.
	// See: https://github.com/postgres/postgres/blob/42aa1f0ab321fd43cbfdd875dd9e13940b485900/src/include/datatype/timestamp.h#L107.
	TimeInfinity = timeutil.Unix(9224318016000-1, 999999000)
	// TimeNegativeInfinity represents the "lowest" possible time.
	// TODO (#41564): this should actually behave as -infinity, i.e. any operator
	// leaves this as -infinity. This time should always be less than any other time.
	// We should probably use the next microsecond before this value, i.e. timeutil.Unix(9224318016000-1, 999999000).
	// Postgres uses math.MinInt64 microseconds as the -infinity value.
	// See: https://github.com/postgres/postgres/blob/42aa1f0ab321fd43cbfdd875dd9e13940b485900/src/include/datatype/timestamp.h#L107.
	TimeNegativeInfinity = timeutil.Unix(-210866803200, 0)
)

These are sentinel values for handling special values: https://www.postgresql.org/docs/10/static/datatype-datetime.html#DATATYPE-DATETIME-SPECIAL-TABLE

View Source
var (
	// LowDate is the lowest non-infinite Date.
	LowDate = Date{/* contains filtered or unexported fields */}
	// HighDate is the highest non-infinite Date.
	HighDate = Date{/* contains filtered or unexported fields */}
	// PosInfDate is the positive infinity Date.
	PosInfDate = Date{/* contains filtered or unexported fields */}
	// NegInfDate is the negative infinity date.
	NegInfDate = Date{/* contains filtered or unexported fields */}
)
View Source
var (
	ErrInvalidLengthPgdate        = fmt.Errorf("proto: negative length found during unmarshaling")
	ErrIntOverflowPgdate          = fmt.Errorf("proto: integer overflow")
	ErrUnexpectedEndOfGroupPgdate = fmt.Errorf("proto: unexpected end of group")
)
View Source
var Order_name = map[int32]string{
	0: "MDY",
	1: "DMY",
	2: "YMD",
}
View Source
var Order_value = map[string]int32{
	"MDY": 0,
	"DMY": 1,
	"YMD": 2,
}
View Source
var Style_name = map[int32]string{
	0: "ISO",
	1: "SQL",
	2: "POSTGRES",
	3: "GERMAN",
}
View Source
var Style_value = map[string]int32{
	"ISO":      0,
	"SQL":      1,
	"POSTGRES": 2,
	"GERMAN":   3,
}

Functions

func AllowedDateStyles

func AllowedDateStyles() []string

AllowedDateStyles returns the list of allowed date styles.

func DateToJulianDay

func DateToJulianDay(year int, month int, day int) int

DateToJulianDay is based on the date2j function in PostgreSQL 10.5.

func ParseTime

func ParseTime(
	now time.Time, dateStyle DateStyle, s string, h *ParseHelper,
) (_ time.Time, dependsOnContext bool, _ error)

ParseTime converts a string into a time value on the epoch day.

The dependsOnContext return value indicates if we had to consult the given `now` value (either for the time or the local timezone).

Memory allocations can be avoided by passing ParseHelper which can be re-used across calls for batch parsing purposes, otherwise it can be nil.

func ParseTimeWithoutTimezone

func ParseTimeWithoutTimezone(
	now time.Time, dateStyle DateStyle, s string,
) (_ time.Time, dependsOnContext bool, _ error)

ParseTimeWithoutTimezone converts a string into a time value on the epoch day, dropping any timezone information. The returned time always has UTC location.

Any specified timezone is inconsequential. Examples:

  • "now": parses to the local time of day (in the current timezone)
  • "01:09:15.511971" and "01:09:15.511971-05" parse to the same result

The dependsOnContext return value indicates if we had to consult the given `now` value (either for the time or the local timezone).

func ParseTimestamp

func ParseTimestamp(
	now time.Time, dateStyle DateStyle, s string,
) (_ time.Time, dependsOnContext bool, _ error)

ParseTimestamp converts a string into a timestamp.

The dependsOnContext return value indicates if we had to consult the given `now` value (either for the time or the local timezone).

func ParseTimestampWithoutTimezone

func ParseTimestampWithoutTimezone(
	now time.Time, dateStyle DateStyle, s string,
) (_ time.Time, dependsOnContext bool, _ error)

ParseTimestampWithoutTimezone converts a string into a timestamp, stripping away any timezone information. Any specified timezone is inconsequential. The returned time always has UTC location.

For example, all these inputs return 2020-06-26 01:02:03 +0000 UTC:

  • '2020-06-26 01:02:03';
  • '2020-06-26 01:02:03+04';
  • 'now', if the local time (in the current timezone) is 2020-06-26 01:02:03. Note that this does not represent the same time instant, but the one that "reads" the same in UTC.

The dependsOnContext return value indicates if we had to consult the given `now` value (either for the time or the local timezone).

Types

type Date

type Date struct {
	// contains filtered or unexported fields
}

Date is a postgres-compatible date implementation. It stores the number of days from the postgres epoch (2000-01-01). Its properties are unexported so that it cannot be misused by external packages. This package takes care to prevent silent problems like overflow that can occur when adding days or converting to and from a time.Time.

func MakeCompatibleDateFromDisk

func MakeCompatibleDateFromDisk(unixDays int64) Date

MakeCompatibleDateFromDisk creates a Date from the number of days since the Unix epoch. If it is out of range of LowDate and HighDate, positive or negative infinity dates are returned. This function should be used only by the on-disk decoder to maintain backward compatibility. It retains the origin days argument which is returned by UnixEpochDaysWithOrig.

func MakeDateFromPGEpoch

func MakeDateFromPGEpoch(days int32) (Date, error)

MakeDateFromPGEpoch creates a Date from the number of days since 2000-01-01. MaxInt32 or MinInt32 represent the positive and negative infinity dates.

func MakeDateFromPGEpochClampFinite

func MakeDateFromPGEpochClampFinite(days int32) Date

MakeDateFromPGEpochClampFinite creates a Date from the number of days since 2000-01-01, clamping to LowDate or HighDate if outside those bounds.

func MakeDateFromTime

func MakeDateFromTime(t time.Time) (Date, error)

MakeDateFromTime creates a Date from the specified time. The timezone-relative date is used.

func MakeDateFromUnixEpoch

func MakeDateFromUnixEpoch(days int64) (Date, error)

MakeDateFromUnixEpoch creates a Date from the number of days since the Unix epoch.

func ParseDate

func ParseDate(
	now time.Time, dateStyle DateStyle, s string, h *ParseHelper,
) (_ Date, dependsOnContext bool, _ error)

ParseDate converts a string into Date.

Any specified timezone is inconsequential. Examples:

  • "now": parses to the local date (in the current timezone)
  • "2020-06-26 01:09:15.511971": parses to '2020-06-26'
  • "2020-06-26 01:09:15.511971-05": parses to '2020-06-26'

The dependsOnContext return value indicates if we had to consult the given `now` value (either for the time or the local timezone).

Memory allocations can be avoided by passing ParseHelper which can be re-used across calls for batch parsing purposes, otherwise it can be nil.

func (Date) AddDays

func (d Date) AddDays(days int64) (Date, error)

AddDays adds days to d with overflow and bounds checking.

func (Date) Compare

func (d Date) Compare(other Date) int

Compare compares two dates.

func (Date) Format

func (d Date) Format(buf *bytes.Buffer)

Format formats d as a string.

func (Date) IsFinite

func (d Date) IsFinite() bool

IsFinite returns whether d is finite.

func (Date) PGEpochDays

func (d Date) PGEpochDays() int32

PGEpochDays returns the number of days since 2001-01-01. This value can also be MinInt32 or MaxInt32, indicating negative or positive infinity.

func (Date) String

func (d Date) String() string

func (Date) SubDays

func (d Date) SubDays(days int64) (Date, error)

SubDays subtracts days from d with overflow and bounds checking.

func (Date) ToTime

func (d Date) ToTime() (time.Time, error)

ToTime returns d as a time.Time. Non finite dates return an error.

func (Date) UnixEpochDays

func (d Date) UnixEpochDays() int64

UnixEpochDays returns the number of days since the Unix epoch. Infinite dates are converted to MinInt64 or MaxInt64.

func (Date) UnixEpochDaysWithOrig

func (d Date) UnixEpochDaysWithOrig() int64

UnixEpochDaysWithOrig returns the original on-disk representation if present, otherwise UnixEpochDays().

type DateStyle

type DateStyle struct {
	// Style refers to the style to print output dates.
	Style Style `protobuf:"varint,1,opt,name=style,proto3,enum=cockroach.util.timeutil.pgdate.Style" json:"style,omitempty"`
	// Order refers to the order of day, month and year components.
	Order Order `protobuf:"varint,2,opt,name=order,proto3,enum=cockroach.util.timeutil.pgdate.Order" json:"order,omitempty"`
}

DateStyle refers to the PostgreSQL DateStyle allowed variables.

func DefaultDateStyle

func DefaultDateStyle() DateStyle

DefaultDateStyle returns the default datestyle for Postgres.

func ParseDateStyle

func ParseDateStyle(s string, existingDateStyle DateStyle) (DateStyle, error)

ParseDateStyle parses a given DateStyle, modifying the existingDateStyle as appropriate. This is because specifying just Style or Order will leave the other field unchanged.

func (*DateStyle) Descriptor

func (*DateStyle) Descriptor() ([]byte, []int)

func (*DateStyle) Marshal

func (m *DateStyle) Marshal() (dAtA []byte, err error)

func (*DateStyle) MarshalTo

func (m *DateStyle) MarshalTo(dAtA []byte) (int, error)

func (*DateStyle) MarshalToSizedBuffer

func (m *DateStyle) MarshalToSizedBuffer(dAtA []byte) (int, error)

func (*DateStyle) ProtoMessage

func (*DateStyle) ProtoMessage()

func (*DateStyle) Reset

func (m *DateStyle) Reset()

func (DateStyle) SQLString

func (ds DateStyle) SQLString() string

SQLString formats DateStyle into a SQL format.

func (*DateStyle) Size

func (m *DateStyle) Size() (n int)

func (*DateStyle) String

func (m *DateStyle) String() string

func (*DateStyle) Unmarshal

func (m *DateStyle) Unmarshal(dAtA []byte) error

func (*DateStyle) XXX_DiscardUnknown

func (m *DateStyle) XXX_DiscardUnknown()

func (*DateStyle) XXX_Marshal

func (m *DateStyle) XXX_Marshal(b []byte, deterministic bool) ([]byte, error)

func (*DateStyle) XXX_Merge

func (m *DateStyle) XXX_Merge(src proto.Message)

func (*DateStyle) XXX_Size

func (m *DateStyle) XXX_Size() int

func (*DateStyle) XXX_Unmarshal

func (m *DateStyle) XXX_Unmarshal(b []byte) error

type Order

type Order int32

Order refers to the Order component of a DateStyle.

const (
	Order_MDY Order = 0
	Order_DMY Order = 1
	Order_YMD Order = 2
)

func (Order) EnumDescriptor

func (Order) EnumDescriptor() ([]byte, []int)

func (Order) String

func (x Order) String() string

type ParseHelper

type ParseHelper struct {
	// contains filtered or unexported fields
}

type Style

type Style int32

Style refers to the Style component of a DateStyle.

const (
	Style_ISO      Style = 0
	Style_SQL      Style = 1
	Style_POSTGRES Style = 2
	Style_GERMAN   Style = 3
)

func (Style) EnumDescriptor

func (Style) EnumDescriptor() ([]byte, []int)

func (Style) SQLString

func (s Style) SQLString() string

SQLString formats the Style into a SQL string.

func (Style) String

func (x Style) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL