Created
November 11, 2023 15:52
-
-
Save stevelizcano/cfe5663dc9c1dcd3869fdf84316e7a5a to your computer and use it in GitHub Desktop.
A PG TypeID type that can be used with SQLC and the package typeID. It allows you to specify this type and parse the tuple returned from postgres into a typeid.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| type PGTypeID string | |
| // ConvertToTypeID converts the PGTypeID to the typeid.TypeID. | |
| func (p PGTypeID) ConvertToTypeID() (typeid.TypeID, error) { | |
| str := string(p) | |
| if !strings.HasPrefix(str, "(") || !strings.HasSuffix(str, ")") { | |
| return typeid.Nil, errors.New("invalid type id format") | |
| } | |
| // Remove the surrounding parentheses and replace the comma with an underscore | |
| // to match the format expected by FromString | |
| trimmed := strings.TrimSuffix(strings.TrimPrefix(str, "("), ")") | |
| trimmed = strings.Replace(trimmed, ",", "_", 1) | |
| // Use FromString to convert the trimmed string to TypeID | |
| return typeid.FromString(trimmed) | |
| } | |
| // Scan implements the sql.Scanner interface for PGTypeID. | |
| func (p *PGTypeID) Scan(value interface{}) error { | |
| strVal, ok := value.(string) | |
| if !ok { | |
| return errors.New("PGTypeID must be a string") | |
| } | |
| *p = PGTypeID(strVal) | |
| return nil | |
| } | |
| // Value implements the driver.Valuer interface for PGTypeID. | |
| func (p PGTypeID) Value() (driver.Value, error) { | |
| return string(p), nil | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment