Help us shape the future of Go! Take the 2026 Go Developer Survey

countries

package
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package countries supplies an ordinary typed country model and an explicitly invoked, versioned reference-data seeder. Construction never seeds a database.

Index

Constants

View Source
const (
	MigrationOrigin      migrate.Origin  = "foundry.countries"
	CreateCountries      migrate.ID      = "000001_create_countries"
	SingleDefaultCountry migrate.ID      = "000002_single_default_country"
	Introduced           migrate.Version = "v0.1.0"
)
View Source
const (
	BuiltinVersion  = "foundry-countries-v1"
	TimezoneVersion = "2026a"
	BuiltinCount    = 250
)
View Source
const MaxCountries = 1000
View Source
const SeederID seed.ID = "foundry.countries"

Variables

View Source
var Countries = orm.Define("foundry_countries", func(b orm.Builder[Country], m *Country) CountryTable {
	table := orm.TableOf(b, &m.ISO2)
	return CountryTable{Table: table,
		ISO2:                table.Key(),
		ISO3:                orm.TextOf(b, &m.ISO3),
		ISONumeric:          orm.NullableTextOf(b, &m.ISONumeric),
		Name:                orm.TextOf(b, &m.Name),
		OfficialName:        orm.NullableTextOf(b, &m.OfficialName),
		Capital:             orm.NullableTextOf(b, &m.Capital),
		Region:              orm.NullableTextOf(b, &m.Region),
		Subregion:           orm.NullableTextOf(b, &m.Subregion),
		Currencies:          orm.JSONOf(b, &m.Currencies),
		PrimaryCurrencyCode: orm.NullableTextOf(b, &m.PrimaryCurrencyCode),
		CallingCode:         orm.NullableTextOf(b, &m.CallingCode),
		CallingRoot:         orm.NullableTextOf(b, &m.CallingRoot),
		CallingSuffixes:     orm.JSONOf(b, &m.CallingSuffixes),
		TLDs:                orm.JSONOf(b, &m.TLDs),
		Timezones:           orm.JSONOf(b, &m.Timezones),
		Latitude:            orm.NullableNumberOf(b, &m.Latitude),
		Longitude:           orm.NullableNumberOf(b, &m.Longitude),
		Independent:         orm.NullableColumnOf(b, &m.Independent),
		UNMember:            orm.NullableColumnOf(b, &m.UNMember),
		FlagEmoji:           orm.NullableTextOf(b, &m.FlagEmoji),
		Status:              orm.EnumOf(b, &m.Status),
		ConversionRate:      orm.NullableColumnOf(b, &m.ConversionRate),
		IsDefault:           orm.ColumnOf(b, &m.IsDefault),
		ReferenceVersion:    orm.TextOf(b, &m.ReferenceVersion),
		CreatedAt:           orm.CreatedAtOf(b, &m.CreatedAt),
		UpdatedAt:           orm.UpdatedAtOf(b, &m.UpdatedAt),
	}
})

Countries owns the immutable Country declaration. Example: orm.First(ctx, tx, Countries.Query()).

Functions

func Default

func Default(ctx context.Context, store *extensions.Store) (value.Optional[Country], error)

Default returns the application's default country, if one is marked. The single-default migration guarantees at most one row.

func Exists

func Exists(ctx context.Context, store *extensions.Store, code Code) (bool, error)

Exists reports whether a validated country code exists in the store.

func Find

func Find(ctx context.Context, store *extensions.Store, code Code) (value.Optional[Country], error)

Find looks up a validated country code, returning an absent value when missing.

func Migrations

func Migrations() []migrate.Definition

Migrations returns the country table history. The second migration allows at most one default country. It refuses to guess when existing data already has several defaults: clear the extra is_default flags, then run it again.

func Seeder

func Seeder(store *extensions.Store) seed.Definition

Seeder plugs into the ordinary explicit transactional seeder registry. It never installs itself, migrates tables, fetches data or runs during app boot.

func SetDefault

func SetDefault(ctx context.Context, store *extensions.Store, code Code) error

SetDefault atomically moves the default flag to an existing country. The previous default is cleared first in the same transaction, so the unique single-default index never observes two defaults. A missing code returns database.NotFound and leaves the current default unchanged.

func StatusCodec

func StatusCodec() codec.Codec[Status]

StatusCodec applies the generated membership rule at both SQL boundaries. Example: StatusCodec()

Types

type Code

type Code string

Code is an uppercase alpha-2 country identifier, including user-assigned codes in the bundled reference. ParseCode normalizes explicit transport input.

func ParseCode

func ParseCode(text string) (Code, error)

ParseCode trims and uppercases text, then validates the two-letter code.

func (Code) Validate

func (c Code) Validate() error

Validate checks that the code consists of two uppercase ASCII letters.

type Country

type Country struct {
	ISO2                Code                   `foundry:"column=iso2"`
	ISO3                string                 `foundry:"column=iso3"`
	ISONumeric          value.Nullable[string] `foundry:"column=iso_numeric"`
	Name                string
	OfficialName        value.Nullable[string]
	Capital             value.Nullable[string]
	Region              value.Nullable[string]
	Subregion           value.Nullable[string]
	Currencies          value.JSON[[]Currency]
	PrimaryCurrencyCode value.Nullable[string]
	CallingCode         value.Nullable[string]
	CallingRoot         value.Nullable[string]
	CallingSuffixes     value.JSON[[]string]
	TLDs                value.JSON[[]string] `foundry:"column=tlds"`
	Timezones           value.JSON[[]string]
	Latitude            value.Nullable[float64]
	Longitude           value.Nullable[float64]
	Independent         value.Nullable[bool]
	UNMember            value.Nullable[bool] `foundry:"column=un_member"`
	FlagEmoji           value.Nullable[string]
	Status              Status
	ConversionRate      value.Nullable[decimal.Decimal]
	IsDefault           bool
	ReferenceVersion    string
	// CreatedAt preserves an explicit creation time; omitted inserts use the application clock.
	// Updates do not automatically change it. Example: Country{CreatedAt: createdAt}.
	CreatedAt temporal.DateTime
	// UpdatedAt is replaced by the application clock on writes, after before hooks and before field mutators.
	// Explicit assignments do not override this management. Example: orm.TimeDesc(Countries.UpdatedAt).
	UpdatedAt temporal.DateTime
}

Country uses an explicit ORM declaration with its natural primary key. Status, ConversionRate and IsDefault belong to the application; reference seeding never overwrites those fields on existing rows.

func All

func All(ctx context.Context, store *extensions.Store) ([]Country, error)

All lists all stored countries.

func Enabled

func Enabled(ctx context.Context, store *extensions.Store) ([]Country, error)

Enabled lists enabled stored countries.

type CountryTable

type CountryTable struct {
	// Table provides Country queries and writes. Example: Countries.Query().Limit(10).
	orm.Table[Country, Code]
	// ISO2 binds the persisted Country.ISO2 column.
	// Example: orm.KeyEq(Countries.ISO2, iSO2).
	ISO2 orm.Key[Country, Code]
	// ISO3 binds the persisted Country.ISO3 column.
	// Example: orm.TextSet(Countries.ISO3, iSO3).
	ISO3 orm.Text[Country, string]
	// ISONumeric binds the persisted Country.ISONumeric column.
	// Example: orm.NullableTextSetNull(Countries.ISONumeric).
	ISONumeric orm.NullableText[Country, string]
	// Name binds the persisted Country.Name column.
	// Example: orm.TextSet(Countries.Name, name).
	Name orm.Text[Country, string]
	// OfficialName binds the persisted Country.OfficialName column.
	// Example: orm.NullableTextSetNull(Countries.OfficialName).
	OfficialName orm.NullableText[Country, string]
	// Capital binds the persisted Country.Capital column.
	// Example: orm.NullableTextSetNull(Countries.Capital).
	Capital orm.NullableText[Country, string]
	// Region binds the persisted Country.Region column.
	// Example: orm.NullableTextSetNull(Countries.Region).
	Region orm.NullableText[Country, string]
	// Subregion binds the persisted Country.Subregion column.
	// Example: orm.NullableTextSetNull(Countries.Subregion).
	Subregion orm.NullableText[Country, string]
	// Currencies binds the persisted Country.Currencies column.
	// Example: encoded, err := value.NewJSON(currencies); if err == nil { _ = orm.JSONSet(Countries.Currencies, encoded) }.
	Currencies orm.JSON[Country, []Currency]
	// PrimaryCurrencyCode binds the persisted Country.PrimaryCurrencyCode column.
	// Example: orm.NullableTextSetNull(Countries.PrimaryCurrencyCode).
	PrimaryCurrencyCode orm.NullableText[Country, string]
	// CallingCode binds the persisted Country.CallingCode column.
	// Example: orm.NullableTextSetNull(Countries.CallingCode).
	CallingCode orm.NullableText[Country, string]
	// CallingRoot binds the persisted Country.CallingRoot column.
	// Example: orm.NullableTextSetNull(Countries.CallingRoot).
	CallingRoot orm.NullableText[Country, string]
	// CallingSuffixes binds the persisted Country.CallingSuffixes column.
	// Example: encoded, err := value.NewJSON(callingSuffixes); if err == nil { _ = orm.JSONSet(Countries.CallingSuffixes, encoded) }.
	CallingSuffixes orm.JSON[Country, []string]
	// TLDs binds the persisted Country.TLDs column.
	// Example: encoded, err := value.NewJSON([]string{".my"}); if err == nil { _ = orm.JSONSet(Countries.TLDs, encoded) }.
	TLDs orm.JSON[Country, []string]
	// Timezones binds the persisted Country.Timezones column.
	// Example: encoded, err := value.NewJSON(timezones); if err == nil { _ = orm.JSONSet(Countries.Timezones, encoded) }.
	Timezones orm.JSON[Country, []string]
	// Latitude binds the persisted Country.Latitude column.
	// Example: orm.NullableNumberSetNull(Countries.Latitude).
	Latitude orm.NullableNumber[Country, float64]
	// Longitude binds the persisted Country.Longitude column.
	// Example: orm.NullableNumberSetNull(Countries.Longitude).
	Longitude orm.NullableNumber[Country, float64]
	// Independent binds the persisted Country.Independent column.
	// Example: orm.NullableColumnSetNull(Countries.Independent).
	Independent orm.NullableColumn[Country, bool]
	// UNMember binds the persisted Country.UNMember column.
	// Example: orm.NullableColumnSetNull(Countries.UNMember).
	UNMember orm.NullableColumn[Country, bool]
	// FlagEmoji binds the persisted Country.FlagEmoji column.
	// Example: orm.NullableTextSetNull(Countries.FlagEmoji).
	FlagEmoji orm.NullableText[Country, string]
	// Status binds the persisted Country.Status column.
	// Example: orm.EnumSet(Countries.Status, status).
	Status orm.Enum[Country, Status]
	// ConversionRate binds the persisted Country.ConversionRate column.
	// Example: orm.NullableColumnSetNull(Countries.ConversionRate).
	ConversionRate orm.NullableColumn[Country, decimal.Decimal]
	// IsDefault binds the persisted Country.IsDefault column.
	// Example: orm.ColumnSet(Countries.IsDefault, isDefault).
	IsDefault orm.Column[Country, bool]
	// ReferenceVersion binds the persisted Country.ReferenceVersion column.
	// Example: orm.TextSet(Countries.ReferenceVersion, referenceVersion).
	ReferenceVersion orm.Text[Country, string]
	// CreatedAt preserves an explicitly assigned creation time; when omitted on insert, the ORM uses the application clock.
	// The insert default is applied after before hooks and before field mutators; updates do not automatically change it.
	// Example: orm.TimeSet(Countries.CreatedAt, createdAt).
	CreatedAt orm.CreatedAt[Country, temporal.DateTime]
	// UpdatedAt is managed: writes replace assigned or omitted values with the application clock after before hooks and before field mutators.
	// Example: orm.TimeDesc(Countries.UpdatedAt).
	UpdatedAt orm.UpdatedAt[Country, temporal.DateTime]
}

CountryTable binds the persisted Country columns. Example: Countries.Query().Limit(10).

type Currency

type Currency struct {
	Code       string                 `json:"code"`
	Name       value.Nullable[string] `json:"name"`
	Symbol     value.Nullable[string] `json:"symbol"`
	MinorUnits value.Nullable[int16]  `json:"minor_units"`
}

Currency describes a country's currency and optional reference metadata.

type SeedResult

type SeedResult struct {
	Version string
	Rows    int
}

SeedResult reports the reference data version and seeded row count.

func Seed

func Seed(ctx context.Context, store *extensions.Store) (SeedResult, error)

Seed seeds country reference data in a store write transaction.

func SeedIn

func SeedIn(ctx context.Context, tx *database.Tx, store *extensions.Store) (SeedResult, error)

SeedIn joins the caller's exact pool/transaction under an isolated savepoint. A successful result is provisional until the parent transaction commits.

type Status

type Status string

Status is a country's status value.

const (
	EnabledStatus  Status = "enabled"
	DisabledStatus Status = "disabled"
)

func ParseStatus

func ParseStatus(text string) (Status, error)

ParseStatus decodes and validates an enum's text representation. Example: ParseStatus(text)

func StatusValues

func StatusValues() []Status

StatusValues returns declared values in source order, with independent slice ownership. Example: StatusValues()

func (Status) EnumDescriptor

func (Status) EnumDescriptor() enum.Descriptor[Status]

EnumDescriptor describes this enum type independently of the receiver's value.

func (Status) IsValid

func (v Status) IsValid() bool

IsValid checks membership; a Go cast alone does not validate external values.

func (Status) MarshalJSON

func (v Status) MarshalJSON() ([]byte, error)

MarshalJSON encodes a validated enum as JSON.

func (Status) MarshalText

func (v Status) MarshalText() ([]byte, error)

MarshalText encodes a validated enum as text.

func (*Status) Scan

func (v *Status) Scan(source any) error

Scan changes the receiver only after successful decoding. SQL NULL is rejected.

func (*Status) UnmarshalJSON

func (v *Status) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes validated JSON and rejects null.

func (*Status) UnmarshalText

func (v *Status) UnmarshalText(data []byte) error

UnmarshalText decodes validated enum text and changes the receiver only on success.

func (Status) Validate

func (v Status) Validate() error

Validate reports invalid values without formatting the input.

func (Status) Value

func (v Status) Value() (driver.Value, error)

Value implements database/sql/driver.Valuer through the shared typed codec.

Jump to

Keyboard shortcuts

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