feat(store): integrate postgres with ent for domain management

This commit is contained in:
dalbodeule
2025-11-26 18:59:18 +09:00
parent 1d6888a45b
commit df1b4758da
24 changed files with 4399 additions and 3 deletions

View File

@@ -3,6 +3,12 @@
# 이 파일을 복사해서 `.env` 로 이름을 바꾼 뒤 값을 채워서 사용하세요.
# internal/config 패키지의 LoadServerConfigFromEnv / LoadClientConfigFromEnv 가
# .env를 먼저 읽고, 이후 환경변수로부터 설정을 구성합니다.
#
# Server-side PostgreSQL connection for admin/domain management uses:
# HOP_DB_DSN
# HOP_DB_MAX_OPEN_CONNS
# HOP_DB_MAX_IDLE_CONNS
# HOP_DB_CONN_MAX_LIFETIME
# ---- Logging / Loki ----
@@ -49,6 +55,23 @@ HOP_SERVER_PROXY_DOMAINS=api.example.com,edge.example.com
# 1. self signed localhost cert 사용여부 (debug: true -> 사용)
HOP_SERVER_DEBUG=true
# ---- PostgreSQL (server-side) ----
#
# PostgreSQL DSN (required), e.g.:
# postgres://user:pass@localhost:5432/hopgate?sslmode=disable
HOP_DB_DSN=postgres://user:pass@localhost:5432/hopgate?sslmode=disable
# Maximum number of open connections (optional, default: 10)
#HOP_DB_MAX_OPEN_CONNS=10
# Maximum number of idle connections (optional, default: 5)
#HOP_DB_MAX_IDLE_CONNS=5
# Connection max lifetime (optional, default: 30m)
# e.g. "30m", "1h"
#HOP_DB_CONN_MAX_LIFETIME=30m
# ---- Client settings ----
# DTLS 서버 주소 (host:port)

View File

@@ -8,6 +8,7 @@ import (
"github.com/dalbodeule/hop-gate/internal/config"
"github.com/dalbodeule/hop-gate/internal/dtls"
"github.com/dalbodeule/hop-gate/internal/logging"
"github.com/dalbodeule/hop-gate/internal/store"
)
func main() {
@@ -31,7 +32,22 @@ func main() {
"debug": cfg.Debug,
})
// 2. DTLS 서버 리스너 생성 (pion/dtls 기반)
// 2. PostgreSQL 연결 및 스키마 초기화 (ent 기반)
ctx := context.Background()
dbClient, err := store.OpenPostgresFromEnv(ctx, logger)
if err != nil {
logger.Error("failed to init postgres for admin/domain store", logging.Fields{
"error": err.Error(),
})
os.Exit(1)
}
defer dbClient.Close()
logger.Info("postgres connected and schema ready", logging.Fields{
"component": "store",
})
// 3. DTLS 서버 리스너 생성 (pion/dtls 기반)
//
// Debug 모드일 때는 self-signed localhost 인증서를 사용해 테스트 할 수 있도록
// internal/dtls.NewSelfSignedLocalhostConfig() 를 사용합니다.
@@ -76,8 +92,6 @@ func main() {
Logger: logger,
}
ctx := context.Background()
// 4. DTLS Accept 루프 + Handshake
for {
sess, err := dtlsServer.Accept()

341
ent/client.go Normal file
View File

@@ -0,0 +1,341 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"log"
"reflect"
"github.com/dalbodeule/hop-gate/ent/migrate"
"github.com/google/uuid"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"github.com/dalbodeule/hop-gate/ent/domain"
)
// Client is the client that holds all ent builders.
type Client struct {
config
// Schema is the client for creating, migrating and dropping schema.
Schema *migrate.Schema
// Domain is the client for interacting with the Domain builders.
Domain *DomainClient
}
// NewClient creates a new client configured with the given options.
func NewClient(opts ...Option) *Client {
client := &Client{config: newConfig(opts...)}
client.init()
return client
}
func (c *Client) init() {
c.Schema = migrate.NewSchema(c.driver)
c.Domain = NewDomainClient(c.config)
}
type (
// config is the configuration for the client and its builder.
config struct {
// driver used for executing database requests.
driver dialect.Driver
// debug enable a debug logging.
debug bool
// log used for logging on debug mode.
log func(...any)
// hooks to execute on mutations.
hooks *hooks
// interceptors to execute on queries.
inters *inters
}
// Option function to configure the client.
Option func(*config)
)
// newConfig creates a new config for the client.
func newConfig(opts ...Option) config {
cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}}
cfg.options(opts...)
return cfg
}
// options applies the options on the config object.
func (c *config) options(opts ...Option) {
for _, opt := range opts {
opt(c)
}
if c.debug {
c.driver = dialect.Debug(c.driver, c.log)
}
}
// Debug enables debug logging on the ent.Driver.
func Debug() Option {
return func(c *config) {
c.debug = true
}
}
// Log sets the logging function for debug mode.
func Log(fn func(...any)) Option {
return func(c *config) {
c.log = fn
}
}
// Driver configures the client driver.
func Driver(driver dialect.Driver) Option {
return func(c *config) {
c.driver = driver
}
}
// Open opens a database/sql.DB specified by the driver name and
// the data source name, and returns a new client attached to it.
// Optional parameters can be added for configuring the client.
func Open(driverName, dataSourceName string, options ...Option) (*Client, error) {
switch driverName {
case dialect.MySQL, dialect.Postgres, dialect.SQLite:
drv, err := sql.Open(driverName, dataSourceName)
if err != nil {
return nil, err
}
return NewClient(append(options, Driver(drv))...), nil
default:
return nil, fmt.Errorf("unsupported driver: %q", driverName)
}
}
// ErrTxStarted is returned when trying to start a new transaction from a transactional client.
var ErrTxStarted = errors.New("ent: cannot start a transaction within a transaction")
// Tx returns a new transactional client. The provided context
// is used until the transaction is committed or rolled back.
func (c *Client) Tx(ctx context.Context) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, ErrTxStarted
}
tx, err := newTx(ctx, c.driver)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
}
cfg := c.config
cfg.driver = tx
return &Tx{
ctx: ctx,
config: cfg,
Domain: NewDomainClient(cfg),
}, nil
}
// BeginTx returns a transactional client with specified options.
func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, errors.New("ent: cannot start a transaction within a transaction")
}
tx, err := c.driver.(interface {
BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error)
}).BeginTx(ctx, opts)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
}
cfg := c.config
cfg.driver = &txDriver{tx: tx, drv: c.driver}
return &Tx{
ctx: ctx,
config: cfg,
Domain: NewDomainClient(cfg),
}, nil
}
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
//
// client.Debug().
// Domain.
// Query().
// Count(ctx)
func (c *Client) Debug() *Client {
if c.debug {
return c
}
cfg := c.config
cfg.driver = dialect.Debug(c.driver, c.log)
client := &Client{config: cfg}
client.init()
return client
}
// Close closes the database connection and prevents new queries from starting.
func (c *Client) Close() error {
return c.driver.Close()
}
// Use adds the mutation hooks to all the entity clients.
// In order to add hooks to a specific client, call: `client.Node.Use(...)`.
func (c *Client) Use(hooks ...Hook) {
c.Domain.Use(hooks...)
}
// Intercept adds the query interceptors to all the entity clients.
// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`.
func (c *Client) Intercept(interceptors ...Interceptor) {
c.Domain.Intercept(interceptors...)
}
// Mutate implements the ent.Mutator interface.
func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
switch m := m.(type) {
case *DomainMutation:
return c.Domain.mutate(ctx, m)
default:
return nil, fmt.Errorf("ent: unknown mutation type %T", m)
}
}
// DomainClient is a client for the Domain schema.
type DomainClient struct {
config
}
// NewDomainClient returns a client for the Domain from the given config.
func NewDomainClient(c config) *DomainClient {
return &DomainClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `domain.Hooks(f(g(h())))`.
func (c *DomainClient) Use(hooks ...Hook) {
c.hooks.Domain = append(c.hooks.Domain, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `domain.Intercept(f(g(h())))`.
func (c *DomainClient) Intercept(interceptors ...Interceptor) {
c.inters.Domain = append(c.inters.Domain, interceptors...)
}
// Create returns a builder for creating a Domain entity.
func (c *DomainClient) Create() *DomainCreate {
mutation := newDomainMutation(c.config, OpCreate)
return &DomainCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Domain entities.
func (c *DomainClient) CreateBulk(builders ...*DomainCreate) *DomainCreateBulk {
return &DomainCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *DomainClient) MapCreateBulk(slice any, setFunc func(*DomainCreate, int)) *DomainCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &DomainCreateBulk{err: fmt.Errorf("calling to DomainClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*DomainCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &DomainCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Domain.
func (c *DomainClient) Update() *DomainUpdate {
mutation := newDomainMutation(c.config, OpUpdate)
return &DomainUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *DomainClient) UpdateOne(_m *Domain) *DomainUpdateOne {
mutation := newDomainMutation(c.config, OpUpdateOne, withDomain(_m))
return &DomainUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *DomainClient) UpdateOneID(id uuid.UUID) *DomainUpdateOne {
mutation := newDomainMutation(c.config, OpUpdateOne, withDomainID(id))
return &DomainUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Domain.
func (c *DomainClient) Delete() *DomainDelete {
mutation := newDomainMutation(c.config, OpDelete)
return &DomainDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *DomainClient) DeleteOne(_m *Domain) *DomainDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *DomainClient) DeleteOneID(id uuid.UUID) *DomainDeleteOne {
builder := c.Delete().Where(domain.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &DomainDeleteOne{builder}
}
// Query returns a query builder for Domain.
func (c *DomainClient) Query() *DomainQuery {
return &DomainQuery{
config: c.config,
ctx: &QueryContext{Type: TypeDomain},
inters: c.Interceptors(),
}
}
// Get returns a Domain entity by its id.
func (c *DomainClient) Get(ctx context.Context, id uuid.UUID) (*Domain, error) {
return c.Query().Where(domain.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *DomainClient) GetX(ctx context.Context, id uuid.UUID) *Domain {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// Hooks returns the client hooks.
func (c *DomainClient) Hooks() []Hook {
return c.hooks.Domain
}
// Interceptors returns the client interceptors.
func (c *DomainClient) Interceptors() []Interceptor {
return c.inters.Domain
}
func (c *DomainClient) mutate(ctx context.Context, m *DomainMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&DomainCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&DomainUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&DomainUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&DomainDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Domain mutation op: %q", m.Op())
}
}
// hooks and interceptors per client, for fast access.
type (
hooks struct {
Domain []ent.Hook
}
inters struct {
Domain []ent.Interceptor
}
)

151
ent/domain.go Normal file
View File

@@ -0,0 +1,151 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"github.com/dalbodeule/hop-gate/ent/domain"
"github.com/google/uuid"
)
// Domain is the model entity for the Domain schema.
type Domain struct {
config `json:"-"`
// ID of the ent.
ID uuid.UUID `json:"id,omitempty"`
// Domain holds the value of the "domain" field.
Domain string `json:"domain,omitempty"`
// ClientAPIKey holds the value of the "client_api_key" field.
ClientAPIKey string `json:"client_api_key,omitempty"`
// Memo holds the value of the "memo" field.
Memo string `json:"memo,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt time.Time `json:"updated_at,omitempty"`
selectValues sql.SelectValues
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Domain) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case domain.FieldDomain, domain.FieldClientAPIKey, domain.FieldMemo:
values[i] = new(sql.NullString)
case domain.FieldCreatedAt, domain.FieldUpdatedAt:
values[i] = new(sql.NullTime)
case domain.FieldID:
values[i] = new(uuid.UUID)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Domain fields.
func (_m *Domain) assignValues(columns []string, values []any) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case domain.FieldID:
if value, ok := values[i].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field id", values[i])
} else if value != nil {
_m.ID = *value
}
case domain.FieldDomain:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field domain", values[i])
} else if value.Valid {
_m.Domain = value.String
}
case domain.FieldClientAPIKey:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field client_api_key", values[i])
} else if value.Valid {
_m.ClientAPIKey = value.String
}
case domain.FieldMemo:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field memo", values[i])
} else if value.Valid {
_m.Memo = value.String
}
case domain.FieldCreatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
_m.CreatedAt = value.Time
}
case domain.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
_m.UpdatedAt = value.Time
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Domain.
// This includes values selected through modifiers, order, etc.
func (_m *Domain) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// Update returns a builder for updating this Domain.
// Note that you need to call Domain.Unwrap() before calling this method if this Domain
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Domain) Update() *DomainUpdateOne {
return NewDomainClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Domain entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (_m *Domain) Unwrap() *Domain {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: Domain is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Domain) String() string {
var builder strings.Builder
builder.WriteString("Domain(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("domain=")
builder.WriteString(_m.Domain)
builder.WriteString(", ")
builder.WriteString("client_api_key=")
builder.WriteString(_m.ClientAPIKey)
builder.WriteString(", ")
builder.WriteString("memo=")
builder.WriteString(_m.Memo)
builder.WriteString(", ")
builder.WriteString("created_at=")
builder.WriteString(_m.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(_m.UpdatedAt.Format(time.ANSIC))
builder.WriteByte(')')
return builder.String()
}
// Domains is a parsable slice of Domain.
type Domains []*Domain

99
ent/domain/domain.go Normal file
View File

@@ -0,0 +1,99 @@
// Code generated by ent, DO NOT EDIT.
package domain
import (
"time"
"entgo.io/ent/dialect/sql"
"github.com/google/uuid"
)
const (
// Label holds the string label denoting the domain type in the database.
Label = "domain"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldDomain holds the string denoting the domain field in the database.
FieldDomain = "domain"
// FieldClientAPIKey holds the string denoting the client_api_key field in the database.
FieldClientAPIKey = "client_api_key"
// FieldMemo holds the string denoting the memo field in the database.
FieldMemo = "memo"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
FieldUpdatedAt = "updated_at"
// Table holds the table name of the domain in the database.
Table = "domains"
)
// Columns holds all SQL columns for domain fields.
var Columns = []string{
FieldID,
FieldDomain,
FieldClientAPIKey,
FieldMemo,
FieldCreatedAt,
FieldUpdatedAt,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// DomainValidator is a validator for the "domain" field. It is called by the builders before save.
DomainValidator func(string) error
// ClientAPIKeyValidator is a validator for the "client_api_key" field. It is called by the builders before save.
ClientAPIKeyValidator func(string) error
// DefaultMemo holds the default value on creation for the "memo" field.
DefaultMemo string
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
UpdateDefaultUpdatedAt func() time.Time
// DefaultID holds the default value on creation for the "id" field.
DefaultID func() uuid.UUID
)
// OrderOption defines the ordering options for the Domain queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByDomain orders the results by the domain field.
func ByDomain(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDomain, opts...).ToFunc()
}
// ByClientAPIKey orders the results by the client_api_key field.
func ByClientAPIKey(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldClientAPIKey, opts...).ToFunc()
}
// ByMemo orders the results by the memo field.
func ByMemo(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldMemo, opts...).ToFunc()
}
// ByCreatedAt orders the results by the created_at field.
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
}
// ByUpdatedAt orders the results by the updated_at field.
func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
}

371
ent/domain/where.go Normal file
View File

@@ -0,0 +1,371 @@
// Code generated by ent, DO NOT EDIT.
package domain
import (
"time"
"entgo.io/ent/dialect/sql"
"github.com/dalbodeule/hop-gate/ent/predicate"
"github.com/google/uuid"
)
// ID filters vertices based on their ID field.
func ID(id uuid.UUID) predicate.Domain {
return predicate.Domain(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id uuid.UUID) predicate.Domain {
return predicate.Domain(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id uuid.UUID) predicate.Domain {
return predicate.Domain(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...uuid.UUID) predicate.Domain {
return predicate.Domain(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...uuid.UUID) predicate.Domain {
return predicate.Domain(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id uuid.UUID) predicate.Domain {
return predicate.Domain(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id uuid.UUID) predicate.Domain {
return predicate.Domain(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id uuid.UUID) predicate.Domain {
return predicate.Domain(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id uuid.UUID) predicate.Domain {
return predicate.Domain(sql.FieldLTE(FieldID, id))
}
// Domain applies equality check predicate on the "domain" field. It's identical to DomainEQ.
func Domain(v string) predicate.Domain {
return predicate.Domain(sql.FieldEQ(FieldDomain, v))
}
// ClientAPIKey applies equality check predicate on the "client_api_key" field. It's identical to ClientAPIKeyEQ.
func ClientAPIKey(v string) predicate.Domain {
return predicate.Domain(sql.FieldEQ(FieldClientAPIKey, v))
}
// Memo applies equality check predicate on the "memo" field. It's identical to MemoEQ.
func Memo(v string) predicate.Domain {
return predicate.Domain(sql.FieldEQ(FieldMemo, v))
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.Domain {
return predicate.Domain(sql.FieldEQ(FieldCreatedAt, v))
}
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
func UpdatedAt(v time.Time) predicate.Domain {
return predicate.Domain(sql.FieldEQ(FieldUpdatedAt, v))
}
// DomainEQ applies the EQ predicate on the "domain" field.
func DomainEQ(v string) predicate.Domain {
return predicate.Domain(sql.FieldEQ(FieldDomain, v))
}
// DomainNEQ applies the NEQ predicate on the "domain" field.
func DomainNEQ(v string) predicate.Domain {
return predicate.Domain(sql.FieldNEQ(FieldDomain, v))
}
// DomainIn applies the In predicate on the "domain" field.
func DomainIn(vs ...string) predicate.Domain {
return predicate.Domain(sql.FieldIn(FieldDomain, vs...))
}
// DomainNotIn applies the NotIn predicate on the "domain" field.
func DomainNotIn(vs ...string) predicate.Domain {
return predicate.Domain(sql.FieldNotIn(FieldDomain, vs...))
}
// DomainGT applies the GT predicate on the "domain" field.
func DomainGT(v string) predicate.Domain {
return predicate.Domain(sql.FieldGT(FieldDomain, v))
}
// DomainGTE applies the GTE predicate on the "domain" field.
func DomainGTE(v string) predicate.Domain {
return predicate.Domain(sql.FieldGTE(FieldDomain, v))
}
// DomainLT applies the LT predicate on the "domain" field.
func DomainLT(v string) predicate.Domain {
return predicate.Domain(sql.FieldLT(FieldDomain, v))
}
// DomainLTE applies the LTE predicate on the "domain" field.
func DomainLTE(v string) predicate.Domain {
return predicate.Domain(sql.FieldLTE(FieldDomain, v))
}
// DomainContains applies the Contains predicate on the "domain" field.
func DomainContains(v string) predicate.Domain {
return predicate.Domain(sql.FieldContains(FieldDomain, v))
}
// DomainHasPrefix applies the HasPrefix predicate on the "domain" field.
func DomainHasPrefix(v string) predicate.Domain {
return predicate.Domain(sql.FieldHasPrefix(FieldDomain, v))
}
// DomainHasSuffix applies the HasSuffix predicate on the "domain" field.
func DomainHasSuffix(v string) predicate.Domain {
return predicate.Domain(sql.FieldHasSuffix(FieldDomain, v))
}
// DomainEqualFold applies the EqualFold predicate on the "domain" field.
func DomainEqualFold(v string) predicate.Domain {
return predicate.Domain(sql.FieldEqualFold(FieldDomain, v))
}
// DomainContainsFold applies the ContainsFold predicate on the "domain" field.
func DomainContainsFold(v string) predicate.Domain {
return predicate.Domain(sql.FieldContainsFold(FieldDomain, v))
}
// ClientAPIKeyEQ applies the EQ predicate on the "client_api_key" field.
func ClientAPIKeyEQ(v string) predicate.Domain {
return predicate.Domain(sql.FieldEQ(FieldClientAPIKey, v))
}
// ClientAPIKeyNEQ applies the NEQ predicate on the "client_api_key" field.
func ClientAPIKeyNEQ(v string) predicate.Domain {
return predicate.Domain(sql.FieldNEQ(FieldClientAPIKey, v))
}
// ClientAPIKeyIn applies the In predicate on the "client_api_key" field.
func ClientAPIKeyIn(vs ...string) predicate.Domain {
return predicate.Domain(sql.FieldIn(FieldClientAPIKey, vs...))
}
// ClientAPIKeyNotIn applies the NotIn predicate on the "client_api_key" field.
func ClientAPIKeyNotIn(vs ...string) predicate.Domain {
return predicate.Domain(sql.FieldNotIn(FieldClientAPIKey, vs...))
}
// ClientAPIKeyGT applies the GT predicate on the "client_api_key" field.
func ClientAPIKeyGT(v string) predicate.Domain {
return predicate.Domain(sql.FieldGT(FieldClientAPIKey, v))
}
// ClientAPIKeyGTE applies the GTE predicate on the "client_api_key" field.
func ClientAPIKeyGTE(v string) predicate.Domain {
return predicate.Domain(sql.FieldGTE(FieldClientAPIKey, v))
}
// ClientAPIKeyLT applies the LT predicate on the "client_api_key" field.
func ClientAPIKeyLT(v string) predicate.Domain {
return predicate.Domain(sql.FieldLT(FieldClientAPIKey, v))
}
// ClientAPIKeyLTE applies the LTE predicate on the "client_api_key" field.
func ClientAPIKeyLTE(v string) predicate.Domain {
return predicate.Domain(sql.FieldLTE(FieldClientAPIKey, v))
}
// ClientAPIKeyContains applies the Contains predicate on the "client_api_key" field.
func ClientAPIKeyContains(v string) predicate.Domain {
return predicate.Domain(sql.FieldContains(FieldClientAPIKey, v))
}
// ClientAPIKeyHasPrefix applies the HasPrefix predicate on the "client_api_key" field.
func ClientAPIKeyHasPrefix(v string) predicate.Domain {
return predicate.Domain(sql.FieldHasPrefix(FieldClientAPIKey, v))
}
// ClientAPIKeyHasSuffix applies the HasSuffix predicate on the "client_api_key" field.
func ClientAPIKeyHasSuffix(v string) predicate.Domain {
return predicate.Domain(sql.FieldHasSuffix(FieldClientAPIKey, v))
}
// ClientAPIKeyEqualFold applies the EqualFold predicate on the "client_api_key" field.
func ClientAPIKeyEqualFold(v string) predicate.Domain {
return predicate.Domain(sql.FieldEqualFold(FieldClientAPIKey, v))
}
// ClientAPIKeyContainsFold applies the ContainsFold predicate on the "client_api_key" field.
func ClientAPIKeyContainsFold(v string) predicate.Domain {
return predicate.Domain(sql.FieldContainsFold(FieldClientAPIKey, v))
}
// MemoEQ applies the EQ predicate on the "memo" field.
func MemoEQ(v string) predicate.Domain {
return predicate.Domain(sql.FieldEQ(FieldMemo, v))
}
// MemoNEQ applies the NEQ predicate on the "memo" field.
func MemoNEQ(v string) predicate.Domain {
return predicate.Domain(sql.FieldNEQ(FieldMemo, v))
}
// MemoIn applies the In predicate on the "memo" field.
func MemoIn(vs ...string) predicate.Domain {
return predicate.Domain(sql.FieldIn(FieldMemo, vs...))
}
// MemoNotIn applies the NotIn predicate on the "memo" field.
func MemoNotIn(vs ...string) predicate.Domain {
return predicate.Domain(sql.FieldNotIn(FieldMemo, vs...))
}
// MemoGT applies the GT predicate on the "memo" field.
func MemoGT(v string) predicate.Domain {
return predicate.Domain(sql.FieldGT(FieldMemo, v))
}
// MemoGTE applies the GTE predicate on the "memo" field.
func MemoGTE(v string) predicate.Domain {
return predicate.Domain(sql.FieldGTE(FieldMemo, v))
}
// MemoLT applies the LT predicate on the "memo" field.
func MemoLT(v string) predicate.Domain {
return predicate.Domain(sql.FieldLT(FieldMemo, v))
}
// MemoLTE applies the LTE predicate on the "memo" field.
func MemoLTE(v string) predicate.Domain {
return predicate.Domain(sql.FieldLTE(FieldMemo, v))
}
// MemoContains applies the Contains predicate on the "memo" field.
func MemoContains(v string) predicate.Domain {
return predicate.Domain(sql.FieldContains(FieldMemo, v))
}
// MemoHasPrefix applies the HasPrefix predicate on the "memo" field.
func MemoHasPrefix(v string) predicate.Domain {
return predicate.Domain(sql.FieldHasPrefix(FieldMemo, v))
}
// MemoHasSuffix applies the HasSuffix predicate on the "memo" field.
func MemoHasSuffix(v string) predicate.Domain {
return predicate.Domain(sql.FieldHasSuffix(FieldMemo, v))
}
// MemoEqualFold applies the EqualFold predicate on the "memo" field.
func MemoEqualFold(v string) predicate.Domain {
return predicate.Domain(sql.FieldEqualFold(FieldMemo, v))
}
// MemoContainsFold applies the ContainsFold predicate on the "memo" field.
func MemoContainsFold(v string) predicate.Domain {
return predicate.Domain(sql.FieldContainsFold(FieldMemo, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Domain {
return predicate.Domain(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.Domain {
return predicate.Domain(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.Domain {
return predicate.Domain(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.Domain {
return predicate.Domain(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.Domain {
return predicate.Domain(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.Domain {
return predicate.Domain(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.Domain {
return predicate.Domain(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.Domain {
return predicate.Domain(sql.FieldLTE(FieldCreatedAt, v))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.Domain {
return predicate.Domain(sql.FieldEQ(FieldUpdatedAt, v))
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v time.Time) predicate.Domain {
return predicate.Domain(sql.FieldNEQ(FieldUpdatedAt, v))
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...time.Time) predicate.Domain {
return predicate.Domain(sql.FieldIn(FieldUpdatedAt, vs...))
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...time.Time) predicate.Domain {
return predicate.Domain(sql.FieldNotIn(FieldUpdatedAt, vs...))
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v time.Time) predicate.Domain {
return predicate.Domain(sql.FieldGT(FieldUpdatedAt, v))
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v time.Time) predicate.Domain {
return predicate.Domain(sql.FieldGTE(FieldUpdatedAt, v))
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v time.Time) predicate.Domain {
return predicate.Domain(sql.FieldLT(FieldUpdatedAt, v))
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v time.Time) predicate.Domain {
return predicate.Domain(sql.FieldLTE(FieldUpdatedAt, v))
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Domain) predicate.Domain {
return predicate.Domain(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Domain) predicate.Domain {
return predicate.Domain(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Domain) predicate.Domain {
return predicate.Domain(sql.NotPredicates(p))
}

312
ent/domain_create.go Normal file
View File

@@ -0,0 +1,312 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dalbodeule/hop-gate/ent/domain"
"github.com/google/uuid"
)
// DomainCreate is the builder for creating a Domain entity.
type DomainCreate struct {
config
mutation *DomainMutation
hooks []Hook
}
// SetDomain sets the "domain" field.
func (_c *DomainCreate) SetDomain(v string) *DomainCreate {
_c.mutation.SetDomain(v)
return _c
}
// SetClientAPIKey sets the "client_api_key" field.
func (_c *DomainCreate) SetClientAPIKey(v string) *DomainCreate {
_c.mutation.SetClientAPIKey(v)
return _c
}
// SetMemo sets the "memo" field.
func (_c *DomainCreate) SetMemo(v string) *DomainCreate {
_c.mutation.SetMemo(v)
return _c
}
// SetNillableMemo sets the "memo" field if the given value is not nil.
func (_c *DomainCreate) SetNillableMemo(v *string) *DomainCreate {
if v != nil {
_c.SetMemo(*v)
}
return _c
}
// SetCreatedAt sets the "created_at" field.
func (_c *DomainCreate) SetCreatedAt(v time.Time) *DomainCreate {
_c.mutation.SetCreatedAt(v)
return _c
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (_c *DomainCreate) SetNillableCreatedAt(v *time.Time) *DomainCreate {
if v != nil {
_c.SetCreatedAt(*v)
}
return _c
}
// SetUpdatedAt sets the "updated_at" field.
func (_c *DomainCreate) SetUpdatedAt(v time.Time) *DomainCreate {
_c.mutation.SetUpdatedAt(v)
return _c
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (_c *DomainCreate) SetNillableUpdatedAt(v *time.Time) *DomainCreate {
if v != nil {
_c.SetUpdatedAt(*v)
}
return _c
}
// SetID sets the "id" field.
func (_c *DomainCreate) SetID(v uuid.UUID) *DomainCreate {
_c.mutation.SetID(v)
return _c
}
// SetNillableID sets the "id" field if the given value is not nil.
func (_c *DomainCreate) SetNillableID(v *uuid.UUID) *DomainCreate {
if v != nil {
_c.SetID(*v)
}
return _c
}
// Mutation returns the DomainMutation object of the builder.
func (_c *DomainCreate) Mutation() *DomainMutation {
return _c.mutation
}
// Save creates the Domain in the database.
func (_c *DomainCreate) Save(ctx context.Context) (*Domain, error) {
_c.defaults()
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *DomainCreate) SaveX(ctx context.Context) *Domain {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *DomainCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *DomainCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_c *DomainCreate) defaults() {
if _, ok := _c.mutation.Memo(); !ok {
v := domain.DefaultMemo
_c.mutation.SetMemo(v)
}
if _, ok := _c.mutation.CreatedAt(); !ok {
v := domain.DefaultCreatedAt()
_c.mutation.SetCreatedAt(v)
}
if _, ok := _c.mutation.UpdatedAt(); !ok {
v := domain.DefaultUpdatedAt()
_c.mutation.SetUpdatedAt(v)
}
if _, ok := _c.mutation.ID(); !ok {
v := domain.DefaultID()
_c.mutation.SetID(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *DomainCreate) check() error {
if _, ok := _c.mutation.Domain(); !ok {
return &ValidationError{Name: "domain", err: errors.New(`ent: missing required field "Domain.domain"`)}
}
if v, ok := _c.mutation.Domain(); ok {
if err := domain.DomainValidator(v); err != nil {
return &ValidationError{Name: "domain", err: fmt.Errorf(`ent: validator failed for field "Domain.domain": %w`, err)}
}
}
if _, ok := _c.mutation.ClientAPIKey(); !ok {
return &ValidationError{Name: "client_api_key", err: errors.New(`ent: missing required field "Domain.client_api_key"`)}
}
if v, ok := _c.mutation.ClientAPIKey(); ok {
if err := domain.ClientAPIKeyValidator(v); err != nil {
return &ValidationError{Name: "client_api_key", err: fmt.Errorf(`ent: validator failed for field "Domain.client_api_key": %w`, err)}
}
}
if _, ok := _c.mutation.Memo(); !ok {
return &ValidationError{Name: "memo", err: errors.New(`ent: missing required field "Domain.memo"`)}
}
if _, ok := _c.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Domain.created_at"`)}
}
if _, ok := _c.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Domain.updated_at"`)}
}
return nil
}
func (_c *DomainCreate) sqlSave(ctx context.Context) (*Domain, error) {
if err := _c.check(); err != nil {
return nil, err
}
_node, _spec := _c.createSpec()
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
if _spec.ID.Value != nil {
if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
_node.ID = *id
} else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
return nil, err
}
}
_c.mutation.id = &_node.ID
_c.mutation.done = true
return _node, nil
}
func (_c *DomainCreate) createSpec() (*Domain, *sqlgraph.CreateSpec) {
var (
_node = &Domain{config: _c.config}
_spec = sqlgraph.NewCreateSpec(domain.Table, sqlgraph.NewFieldSpec(domain.FieldID, field.TypeUUID))
)
if id, ok := _c.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = &id
}
if value, ok := _c.mutation.Domain(); ok {
_spec.SetField(domain.FieldDomain, field.TypeString, value)
_node.Domain = value
}
if value, ok := _c.mutation.ClientAPIKey(); ok {
_spec.SetField(domain.FieldClientAPIKey, field.TypeString, value)
_node.ClientAPIKey = value
}
if value, ok := _c.mutation.Memo(); ok {
_spec.SetField(domain.FieldMemo, field.TypeString, value)
_node.Memo = value
}
if value, ok := _c.mutation.CreatedAt(); ok {
_spec.SetField(domain.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = value
}
if value, ok := _c.mutation.UpdatedAt(); ok {
_spec.SetField(domain.FieldUpdatedAt, field.TypeTime, value)
_node.UpdatedAt = value
}
return _node, _spec
}
// DomainCreateBulk is the builder for creating many Domain entities in bulk.
type DomainCreateBulk struct {
config
err error
builders []*DomainCreate
}
// Save creates the Domain entities in the database.
func (_c *DomainCreateBulk) Save(ctx context.Context) ([]*Domain, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*Domain, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*DomainMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (_c *DomainCreateBulk) SaveX(ctx context.Context) []*Domain {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *DomainCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *DomainCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}

88
ent/domain_delete.go Normal file
View File

@@ -0,0 +1,88 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dalbodeule/hop-gate/ent/domain"
"github.com/dalbodeule/hop-gate/ent/predicate"
)
// DomainDelete is the builder for deleting a Domain entity.
type DomainDelete struct {
config
hooks []Hook
mutation *DomainMutation
}
// Where appends a list predicates to the DomainDelete builder.
func (_d *DomainDelete) Where(ps ...predicate.Domain) *DomainDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *DomainDelete) Exec(ctx context.Context) (int, error) {
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *DomainDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *DomainDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(domain.Table, sqlgraph.NewFieldSpec(domain.FieldID, field.TypeUUID))
if ps := _d.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
_d.mutation.done = true
return affected, err
}
// DomainDeleteOne is the builder for deleting a single Domain entity.
type DomainDeleteOne struct {
_d *DomainDelete
}
// Where appends a list predicates to the DomainDelete builder.
func (_d *DomainDeleteOne) Where(ps ...predicate.Domain) *DomainDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *DomainDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{domain.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *DomainDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

528
ent/domain_query.go Normal file
View File

@@ -0,0 +1,528 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dalbodeule/hop-gate/ent/domain"
"github.com/dalbodeule/hop-gate/ent/predicate"
"github.com/google/uuid"
)
// DomainQuery is the builder for querying Domain entities.
type DomainQuery struct {
config
ctx *QueryContext
order []domain.OrderOption
inters []Interceptor
predicates []predicate.Domain
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the DomainQuery builder.
func (_q *DomainQuery) Where(ps ...predicate.Domain) *DomainQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *DomainQuery) Limit(limit int) *DomainQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *DomainQuery) Offset(offset int) *DomainQuery {
_q.ctx.Offset = &offset
return _q
}
// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (_q *DomainQuery) Unique(unique bool) *DomainQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *DomainQuery) Order(o ...domain.OrderOption) *DomainQuery {
_q.order = append(_q.order, o...)
return _q
}
// First returns the first Domain entity from the query.
// Returns a *NotFoundError when no Domain was found.
func (_q *DomainQuery) First(ctx context.Context) (*Domain, error) {
nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{domain.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *DomainQuery) FirstX(ctx context.Context) *Domain {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Domain ID from the query.
// Returns a *NotFoundError when no Domain ID was found.
func (_q *DomainQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{domain.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *DomainQuery) FirstIDX(ctx context.Context) uuid.UUID {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Domain entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Domain entity is found.
// Returns a *NotFoundError when no Domain entities are found.
func (_q *DomainQuery) Only(ctx context.Context) (*Domain, error) {
nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{domain.Label}
default:
return nil, &NotSingularError{domain.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *DomainQuery) OnlyX(ctx context.Context) *Domain {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Domain ID in the query.
// Returns a *NotSingularError when more than one Domain ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *DomainQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{domain.Label}
default:
err = &NotSingularError{domain.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *DomainQuery) OnlyIDX(ctx context.Context) uuid.UUID {
id, err := _q.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Domains.
func (_q *DomainQuery) All(ctx context.Context) ([]*Domain, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Domain, *DomainQuery]()
return withInterceptors[[]*Domain](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *DomainQuery) AllX(ctx context.Context) []*Domain {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Domain IDs.
func (_q *DomainQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
if _q.ctx.Unique == nil && _q.path != nil {
_q.Unique(true)
}
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
if err = _q.Select(domain.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *DomainQuery) IDsX(ctx context.Context) []uuid.UUID {
ids, err := _q.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (_q *DomainQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)
if err := _q.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, _q, querierCount[*DomainQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *DomainQuery) CountX(ctx context.Context) int {
count, err := _q.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (_q *DomainQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
switch _, err := _q.FirstID(ctx); {
case IsNotFound(err):
return false, nil
case err != nil:
return false, fmt.Errorf("ent: check existence: %w", err)
default:
return true, nil
}
}
// ExistX is like Exist, but panics if an error occurs.
func (_q *DomainQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the DomainQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (_q *DomainQuery) Clone() *DomainQuery {
if _q == nil {
return nil
}
return &DomainQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]domain.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Domain{}, _q.predicates...),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// Domain string `json:"domain,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Domain.Query().
// GroupBy(domain.FieldDomain).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *DomainQuery) GroupBy(field string, fields ...string) *DomainGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &DomainGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = domain.Label
grbuild.scan = grbuild.Scan
return grbuild
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// Domain string `json:"domain,omitempty"`
// }
//
// client.Domain.Query().
// Select(domain.FieldDomain).
// Scan(ctx, &v)
func (_q *DomainQuery) Select(fields ...string) *DomainSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &DomainSelect{DomainQuery: _q}
sbuild.label = domain.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a DomainSelect configured with the given aggregations.
func (_q *DomainQuery) Aggregate(fns ...AggregateFunc) *DomainSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *DomainQuery) prepareQuery(ctx context.Context) error {
for _, inter := range _q.inters {
if inter == nil {
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
}
if trv, ok := inter.(Traverser); ok {
if err := trv.Traverse(ctx, _q); err != nil {
return err
}
}
}
for _, f := range _q.ctx.Fields {
if !domain.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if _q.path != nil {
prev, err := _q.path(ctx)
if err != nil {
return err
}
_q.sql = prev
}
return nil
}
func (_q *DomainQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Domain, error) {
var (
nodes = []*Domain{}
_spec = _q.querySpec()
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Domain).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Domain{config: _q.config}
nodes = append(nodes, node)
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (_q *DomainQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *DomainQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(domain.Table, domain.Columns, sqlgraph.NewFieldSpec(domain.FieldID, field.TypeUUID))
_spec.From = _q.sql
if unique := _q.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if _q.path != nil {
_spec.Unique = true
}
if fields := _q.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, domain.FieldID)
for i := range fields {
if fields[i] != domain.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := _q.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := _q.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := _q.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := _q.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (_q *DomainQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(domain.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = domain.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// DomainGroupBy is the group-by builder for Domain entities.
type DomainGroupBy struct {
selector
build *DomainQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *DomainGroupBy) Aggregate(fns ...AggregateFunc) *DomainGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *DomainGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)
if err := _g.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*DomainQuery, *DomainGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *DomainGroupBy) sqlScan(ctx context.Context, root *DomainQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(_g.fns))
for _, fn := range _g.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*_g.flds)+len(_g.fns))
for _, f := range *_g.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*_g.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// DomainSelect is the builder for selecting fields of Domain entities.
type DomainSelect struct {
*DomainQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *DomainSelect) Aggregate(fns ...AggregateFunc) *DomainSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *DomainSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)
if err := _s.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*DomainQuery, *DomainSelect](ctx, _s.DomainQuery, _s, _s.inters, v)
}
func (_s *DomainSelect) sqlScan(ctx context.Context, root *DomainQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(_s.fns))
for _, fn := range _s.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*_s.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

340
ent/domain_update.go Normal file
View File

@@ -0,0 +1,340 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dalbodeule/hop-gate/ent/domain"
"github.com/dalbodeule/hop-gate/ent/predicate"
)
// DomainUpdate is the builder for updating Domain entities.
type DomainUpdate struct {
config
hooks []Hook
mutation *DomainMutation
}
// Where appends a list predicates to the DomainUpdate builder.
func (_u *DomainUpdate) Where(ps ...predicate.Domain) *DomainUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetClientAPIKey sets the "client_api_key" field.
func (_u *DomainUpdate) SetClientAPIKey(v string) *DomainUpdate {
_u.mutation.SetClientAPIKey(v)
return _u
}
// SetNillableClientAPIKey sets the "client_api_key" field if the given value is not nil.
func (_u *DomainUpdate) SetNillableClientAPIKey(v *string) *DomainUpdate {
if v != nil {
_u.SetClientAPIKey(*v)
}
return _u
}
// SetMemo sets the "memo" field.
func (_u *DomainUpdate) SetMemo(v string) *DomainUpdate {
_u.mutation.SetMemo(v)
return _u
}
// SetNillableMemo sets the "memo" field if the given value is not nil.
func (_u *DomainUpdate) SetNillableMemo(v *string) *DomainUpdate {
if v != nil {
_u.SetMemo(*v)
}
return _u
}
// SetCreatedAt sets the "created_at" field.
func (_u *DomainUpdate) SetCreatedAt(v time.Time) *DomainUpdate {
_u.mutation.SetCreatedAt(v)
return _u
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (_u *DomainUpdate) SetNillableCreatedAt(v *time.Time) *DomainUpdate {
if v != nil {
_u.SetCreatedAt(*v)
}
return _u
}
// SetUpdatedAt sets the "updated_at" field.
func (_u *DomainUpdate) SetUpdatedAt(v time.Time) *DomainUpdate {
_u.mutation.SetUpdatedAt(v)
return _u
}
// Mutation returns the DomainMutation object of the builder.
func (_u *DomainUpdate) Mutation() *DomainMutation {
return _u.mutation
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *DomainUpdate) Save(ctx context.Context) (int, error) {
_u.defaults()
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *DomainUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *DomainUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *DomainUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_u *DomainUpdate) defaults() {
if _, ok := _u.mutation.UpdatedAt(); !ok {
v := domain.UpdateDefaultUpdatedAt()
_u.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *DomainUpdate) check() error {
if v, ok := _u.mutation.ClientAPIKey(); ok {
if err := domain.ClientAPIKeyValidator(v); err != nil {
return &ValidationError{Name: "client_api_key", err: fmt.Errorf(`ent: validator failed for field "Domain.client_api_key": %w`, err)}
}
}
return nil
}
func (_u *DomainUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(domain.Table, domain.Columns, sqlgraph.NewFieldSpec(domain.FieldID, field.TypeUUID))
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.ClientAPIKey(); ok {
_spec.SetField(domain.FieldClientAPIKey, field.TypeString, value)
}
if value, ok := _u.mutation.Memo(); ok {
_spec.SetField(domain.FieldMemo, field.TypeString, value)
}
if value, ok := _u.mutation.CreatedAt(); ok {
_spec.SetField(domain.FieldCreatedAt, field.TypeTime, value)
}
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(domain.FieldUpdatedAt, field.TypeTime, value)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{domain.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// DomainUpdateOne is the builder for updating a single Domain entity.
type DomainUpdateOne struct {
config
fields []string
hooks []Hook
mutation *DomainMutation
}
// SetClientAPIKey sets the "client_api_key" field.
func (_u *DomainUpdateOne) SetClientAPIKey(v string) *DomainUpdateOne {
_u.mutation.SetClientAPIKey(v)
return _u
}
// SetNillableClientAPIKey sets the "client_api_key" field if the given value is not nil.
func (_u *DomainUpdateOne) SetNillableClientAPIKey(v *string) *DomainUpdateOne {
if v != nil {
_u.SetClientAPIKey(*v)
}
return _u
}
// SetMemo sets the "memo" field.
func (_u *DomainUpdateOne) SetMemo(v string) *DomainUpdateOne {
_u.mutation.SetMemo(v)
return _u
}
// SetNillableMemo sets the "memo" field if the given value is not nil.
func (_u *DomainUpdateOne) SetNillableMemo(v *string) *DomainUpdateOne {
if v != nil {
_u.SetMemo(*v)
}
return _u
}
// SetCreatedAt sets the "created_at" field.
func (_u *DomainUpdateOne) SetCreatedAt(v time.Time) *DomainUpdateOne {
_u.mutation.SetCreatedAt(v)
return _u
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (_u *DomainUpdateOne) SetNillableCreatedAt(v *time.Time) *DomainUpdateOne {
if v != nil {
_u.SetCreatedAt(*v)
}
return _u
}
// SetUpdatedAt sets the "updated_at" field.
func (_u *DomainUpdateOne) SetUpdatedAt(v time.Time) *DomainUpdateOne {
_u.mutation.SetUpdatedAt(v)
return _u
}
// Mutation returns the DomainMutation object of the builder.
func (_u *DomainUpdateOne) Mutation() *DomainMutation {
return _u.mutation
}
// Where appends a list predicates to the DomainUpdate builder.
func (_u *DomainUpdateOne) Where(ps ...predicate.Domain) *DomainUpdateOne {
_u.mutation.Where(ps...)
return _u
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (_u *DomainUpdateOne) Select(field string, fields ...string) *DomainUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated Domain entity.
func (_u *DomainUpdateOne) Save(ctx context.Context) (*Domain, error) {
_u.defaults()
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *DomainUpdateOne) SaveX(ctx context.Context) *Domain {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *DomainUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *DomainUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_u *DomainUpdateOne) defaults() {
if _, ok := _u.mutation.UpdatedAt(); !ok {
v := domain.UpdateDefaultUpdatedAt()
_u.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *DomainUpdateOne) check() error {
if v, ok := _u.mutation.ClientAPIKey(); ok {
if err := domain.ClientAPIKeyValidator(v); err != nil {
return &ValidationError{Name: "client_api_key", err: fmt.Errorf(`ent: validator failed for field "Domain.client_api_key": %w`, err)}
}
}
return nil
}
func (_u *DomainUpdateOne) sqlSave(ctx context.Context) (_node *Domain, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(domain.Table, domain.Columns, sqlgraph.NewFieldSpec(domain.FieldID, field.TypeUUID))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Domain.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := _u.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, domain.FieldID)
for _, f := range fields {
if !domain.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != domain.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.ClientAPIKey(); ok {
_spec.SetField(domain.FieldClientAPIKey, field.TypeString, value)
}
if value, ok := _u.mutation.Memo(); ok {
_spec.SetField(domain.FieldMemo, field.TypeString, value)
}
if value, ok := _u.mutation.CreatedAt(); ok {
_spec.SetField(domain.FieldCreatedAt, field.TypeTime, value)
}
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(domain.FieldUpdatedAt, field.TypeTime, value)
}
_node = &Domain{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{domain.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

608
ent/ent.go Normal file
View File

@@ -0,0 +1,608 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"reflect"
"sync"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/dalbodeule/hop-gate/ent/domain"
)
// ent aliases to avoid import conflicts in user's code.
type (
Op = ent.Op
Hook = ent.Hook
Value = ent.Value
Query = ent.Query
QueryContext = ent.QueryContext
Querier = ent.Querier
QuerierFunc = ent.QuerierFunc
Interceptor = ent.Interceptor
InterceptFunc = ent.InterceptFunc
Traverser = ent.Traverser
TraverseFunc = ent.TraverseFunc
Policy = ent.Policy
Mutator = ent.Mutator
Mutation = ent.Mutation
MutateFunc = ent.MutateFunc
)
type clientCtxKey struct{}
// FromContext returns a Client stored inside a context, or nil if there isn't one.
func FromContext(ctx context.Context) *Client {
c, _ := ctx.Value(clientCtxKey{}).(*Client)
return c
}
// NewContext returns a new context with the given Client attached.
func NewContext(parent context.Context, c *Client) context.Context {
return context.WithValue(parent, clientCtxKey{}, c)
}
type txCtxKey struct{}
// TxFromContext returns a Tx stored inside a context, or nil if there isn't one.
func TxFromContext(ctx context.Context) *Tx {
tx, _ := ctx.Value(txCtxKey{}).(*Tx)
return tx
}
// NewTxContext returns a new context with the given Tx attached.
func NewTxContext(parent context.Context, tx *Tx) context.Context {
return context.WithValue(parent, txCtxKey{}, tx)
}
// OrderFunc applies an ordering on the sql selector.
// Deprecated: Use Asc/Desc functions or the package builders instead.
type OrderFunc func(*sql.Selector)
var (
initCheck sync.Once
columnCheck sql.ColumnCheck
)
// checkColumn checks if the column exists in the given table.
func checkColumn(t, c string) error {
initCheck.Do(func() {
columnCheck = sql.NewColumnCheck(map[string]func(string) bool{
domain.Table: domain.ValidColumn,
})
})
return columnCheck(t, c)
}
// Asc applies the given fields in ASC order.
func Asc(fields ...string) func(*sql.Selector) {
return func(s *sql.Selector) {
for _, f := range fields {
if err := checkColumn(s.TableName(), f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
}
s.OrderBy(sql.Asc(s.C(f)))
}
}
}
// Desc applies the given fields in DESC order.
func Desc(fields ...string) func(*sql.Selector) {
return func(s *sql.Selector) {
for _, f := range fields {
if err := checkColumn(s.TableName(), f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
}
s.OrderBy(sql.Desc(s.C(f)))
}
}
}
// AggregateFunc applies an aggregation step on the group-by traversal/selector.
type AggregateFunc func(*sql.Selector) string
// As is a pseudo aggregation function for renaming another other functions with custom names. For example:
//
// GroupBy(field1, field2).
// Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")).
// Scan(ctx, &v)
func As(fn AggregateFunc, end string) AggregateFunc {
return func(s *sql.Selector) string {
return sql.As(fn(s), end)
}
}
// Count applies the "count" aggregation function on each group.
func Count() AggregateFunc {
return func(s *sql.Selector) string {
return sql.Count("*")
}
}
// Max applies the "max" aggregation function on the given field of each group.
func Max(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Max(s.C(field))
}
}
// Mean applies the "mean" aggregation function on the given field of each group.
func Mean(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Avg(s.C(field))
}
}
// Min applies the "min" aggregation function on the given field of each group.
func Min(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Min(s.C(field))
}
}
// Sum applies the "sum" aggregation function on the given field of each group.
func Sum(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Sum(s.C(field))
}
}
// ValidationError returns when validating a field or edge fails.
type ValidationError struct {
Name string // Field or edge name.
err error
}
// Error implements the error interface.
func (e *ValidationError) Error() string {
return e.err.Error()
}
// Unwrap implements the errors.Wrapper interface.
func (e *ValidationError) Unwrap() error {
return e.err
}
// IsValidationError returns a boolean indicating whether the error is a validation error.
func IsValidationError(err error) bool {
if err == nil {
return false
}
var e *ValidationError
return errors.As(err, &e)
}
// NotFoundError returns when trying to fetch a specific entity and it was not found in the database.
type NotFoundError struct {
label string
}
// Error implements the error interface.
func (e *NotFoundError) Error() string {
return "ent: " + e.label + " not found"
}
// IsNotFound returns a boolean indicating whether the error is a not found error.
func IsNotFound(err error) bool {
if err == nil {
return false
}
var e *NotFoundError
return errors.As(err, &e)
}
// MaskNotFound masks not found error.
func MaskNotFound(err error) error {
if IsNotFound(err) {
return nil
}
return err
}
// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database.
type NotSingularError struct {
label string
}
// Error implements the error interface.
func (e *NotSingularError) Error() string {
return "ent: " + e.label + " not singular"
}
// IsNotSingular returns a boolean indicating whether the error is a not singular error.
func IsNotSingular(err error) bool {
if err == nil {
return false
}
var e *NotSingularError
return errors.As(err, &e)
}
// NotLoadedError returns when trying to get a node that was not loaded by the query.
type NotLoadedError struct {
edge string
}
// Error implements the error interface.
func (e *NotLoadedError) Error() string {
return "ent: " + e.edge + " edge was not loaded"
}
// IsNotLoaded returns a boolean indicating whether the error is a not loaded error.
func IsNotLoaded(err error) bool {
if err == nil {
return false
}
var e *NotLoadedError
return errors.As(err, &e)
}
// ConstraintError returns when trying to create/update one or more entities and
// one or more of their constraints failed. For example, violation of edge or
// field uniqueness.
type ConstraintError struct {
msg string
wrap error
}
// Error implements the error interface.
func (e ConstraintError) Error() string {
return "ent: constraint failed: " + e.msg
}
// Unwrap implements the errors.Wrapper interface.
func (e *ConstraintError) Unwrap() error {
return e.wrap
}
// IsConstraintError returns a boolean indicating whether the error is a constraint failure.
func IsConstraintError(err error) bool {
if err == nil {
return false
}
var e *ConstraintError
return errors.As(err, &e)
}
// selector embedded by the different Select/GroupBy builders.
type selector struct {
label string
flds *[]string
fns []AggregateFunc
scan func(context.Context, any) error
}
// ScanX is like Scan, but panics if an error occurs.
func (s *selector) ScanX(ctx context.Context, v any) {
if err := s.scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (s *selector) Strings(ctx context.Context) ([]string, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (s *selector) StringsX(ctx context.Context) []string {
v, err := s.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a selector. It is only allowed when selecting one field.
func (s *selector) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = s.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (s *selector) StringX(ctx context.Context) string {
v, err := s.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (s *selector) Ints(ctx context.Context) ([]int, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (s *selector) IntsX(ctx context.Context) []int {
v, err := s.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a selector. It is only allowed when selecting one field.
func (s *selector) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = s.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (s *selector) IntX(ctx context.Context) int {
v, err := s.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (s *selector) Float64s(ctx context.Context) ([]float64, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (s *selector) Float64sX(ctx context.Context) []float64 {
v, err := s.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (s *selector) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = s.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (s *selector) Float64X(ctx context.Context) float64 {
v, err := s.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (s *selector) Bools(ctx context.Context) ([]bool, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (s *selector) BoolsX(ctx context.Context) []bool {
v, err := s.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (s *selector) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = s.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (s *selector) BoolX(ctx context.Context) bool {
v, err := s.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
// withHooks invokes the builder operation with the given hooks, if any.
func withHooks[V Value, M any, PM interface {
*M
Mutation
}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) {
if len(hooks) == 0 {
return exec(ctx)
}
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutationT, ok := any(m).(PM)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
// Set the mutation to the builder.
*mutation = *mutationT
return exec(ctx)
})
for i := len(hooks) - 1; i >= 0; i-- {
if hooks[i] == nil {
return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = hooks[i](mut)
}
v, err := mut.Mutate(ctx, mutation)
if err != nil {
return value, err
}
nv, ok := v.(V)
if !ok {
return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation)
}
return nv, nil
}
// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist.
func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context {
if ent.QueryFromContext(ctx) == nil {
qc.Op = op
ctx = ent.NewQueryContext(ctx, qc)
}
return ctx
}
func querierAll[V Value, Q interface {
sqlAll(context.Context, ...queryHook) (V, error)
}]() Querier {
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
return query.sqlAll(ctx)
})
}
func querierCount[Q interface {
sqlCount(context.Context) (int, error)
}]() Querier {
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
return query.sqlCount(ctx)
})
}
func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) {
for i := len(inters) - 1; i >= 0; i-- {
qr = inters[i].Intercept(qr)
}
rv, err := qr.Query(ctx, q)
if err != nil {
return v, err
}
vt, ok := rv.(V)
if !ok {
return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v)
}
return vt, nil
}
func scanWithInterceptors[Q1 ent.Query, Q2 interface {
sqlScan(context.Context, Q1, any) error
}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error {
rv := reflect.ValueOf(v)
var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q1)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
if err := selectOrGroup.sqlScan(ctx, query, v); err != nil {
return nil, err
}
if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() {
return rv.Elem().Interface(), nil
}
return v, nil
})
for i := len(inters) - 1; i >= 0; i-- {
qr = inters[i].Intercept(qr)
}
vv, err := qr.Query(ctx, rootQuery)
if err != nil {
return err
}
switch rv2 := reflect.ValueOf(vv); {
case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer:
case rv.Type() == rv2.Type():
rv.Elem().Set(rv2.Elem())
case rv.Elem().Type() == rv2.Type():
rv.Elem().Set(rv2)
}
return nil
}
// queryHook describes an internal hook for the different sqlAll methods.
type queryHook func(context.Context, *sqlgraph.QuerySpec)

84
ent/enttest/enttest.go Normal file
View File

@@ -0,0 +1,84 @@
// Code generated by ent, DO NOT EDIT.
package enttest
import (
"context"
"github.com/dalbodeule/hop-gate/ent"
// required by schema hooks.
_ "github.com/dalbodeule/hop-gate/ent/runtime"
"entgo.io/ent/dialect/sql/schema"
"github.com/dalbodeule/hop-gate/ent/migrate"
)
type (
// TestingT is the interface that is shared between
// testing.T and testing.B and used by enttest.
TestingT interface {
FailNow()
Error(...any)
}
// Option configures client creation.
Option func(*options)
options struct {
opts []ent.Option
migrateOpts []schema.MigrateOption
}
)
// WithOptions forwards options to client creation.
func WithOptions(opts ...ent.Option) Option {
return func(o *options) {
o.opts = append(o.opts, opts...)
}
}
// WithMigrateOptions forwards options to auto migration.
func WithMigrateOptions(opts ...schema.MigrateOption) Option {
return func(o *options) {
o.migrateOpts = append(o.migrateOpts, opts...)
}
}
func newOptions(opts []Option) *options {
o := &options{}
for _, opt := range opts {
opt(o)
}
return o
}
// Open calls ent.Open and auto-run migration.
func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Client {
o := newOptions(opts)
c, err := ent.Open(driverName, dataSourceName, o.opts...)
if err != nil {
t.Error(err)
t.FailNow()
}
migrateSchema(t, c, o)
return c
}
// NewClient calls ent.NewClient and auto-run migration.
func NewClient(t TestingT, opts ...Option) *ent.Client {
o := newOptions(opts)
c := ent.NewClient(o.opts...)
migrateSchema(t, c, o)
return c
}
func migrateSchema(t TestingT, c *ent.Client, o *options) {
tables, err := schema.CopyTables(migrate.Tables)
if err != nil {
t.Error(err)
t.FailNow()
}
if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil {
t.Error(err)
t.FailNow()
}
}

199
ent/hook/hook.go Normal file
View File

@@ -0,0 +1,199 @@
// Code generated by ent, DO NOT EDIT.
package hook
import (
"context"
"fmt"
"github.com/dalbodeule/hop-gate/ent"
)
// The DomainFunc type is an adapter to allow the use of ordinary
// function as Domain mutator.
type DomainFunc func(context.Context, *ent.DomainMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f DomainFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.DomainMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.DomainMutation", m)
}
// Condition is a hook condition function.
type Condition func(context.Context, ent.Mutation) bool
// And groups conditions with the AND operator.
func And(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
if !first(ctx, m) || !second(ctx, m) {
return false
}
for _, cond := range rest {
if !cond(ctx, m) {
return false
}
}
return true
}
}
// Or groups conditions with the OR operator.
func Or(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
if first(ctx, m) || second(ctx, m) {
return true
}
for _, cond := range rest {
if cond(ctx, m) {
return true
}
}
return false
}
}
// Not negates a given condition.
func Not(cond Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
return !cond(ctx, m)
}
}
// HasOp is a condition testing mutation operation.
func HasOp(op ent.Op) Condition {
return func(_ context.Context, m ent.Mutation) bool {
return m.Op().Is(op)
}
}
// HasAddedFields is a condition validating `.AddedField` on fields.
func HasAddedFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if _, exists := m.AddedField(field); !exists {
return false
}
for _, field := range fields {
if _, exists := m.AddedField(field); !exists {
return false
}
}
return true
}
}
// HasClearedFields is a condition validating `.FieldCleared` on fields.
func HasClearedFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if exists := m.FieldCleared(field); !exists {
return false
}
for _, field := range fields {
if exists := m.FieldCleared(field); !exists {
return false
}
}
return true
}
}
// HasFields is a condition validating `.Field` on fields.
func HasFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if _, exists := m.Field(field); !exists {
return false
}
for _, field := range fields {
if _, exists := m.Field(field); !exists {
return false
}
}
return true
}
}
// If executes the given hook under condition.
//
// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...)))
func If(hk ent.Hook, cond Condition) ent.Hook {
return func(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if cond(ctx, m) {
return hk(next).Mutate(ctx, m)
}
return next.Mutate(ctx, m)
})
}
}
// On executes the given hook only for the given operation.
//
// hook.On(Log, ent.Delete|ent.Create)
func On(hk ent.Hook, op ent.Op) ent.Hook {
return If(hk, HasOp(op))
}
// Unless skips the given hook only for the given operation.
//
// hook.Unless(Log, ent.Update|ent.UpdateOne)
func Unless(hk ent.Hook, op ent.Op) ent.Hook {
return If(hk, Not(HasOp(op)))
}
// FixedError is a hook returning a fixed error.
func FixedError(err error) ent.Hook {
return func(ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(context.Context, ent.Mutation) (ent.Value, error) {
return nil, err
})
}
}
// Reject returns a hook that rejects all operations that match op.
//
// func (T) Hooks() []ent.Hook {
// return []ent.Hook{
// Reject(ent.Delete|ent.Update),
// }
// }
func Reject(op ent.Op) ent.Hook {
hk := FixedError(fmt.Errorf("%s operation is not allowed", op))
return On(hk, op)
}
// Chain acts as a list of hooks and is effectively immutable.
// Once created, it will always hold the same set of hooks in the same order.
type Chain struct {
hooks []ent.Hook
}
// NewChain creates a new chain of hooks.
func NewChain(hooks ...ent.Hook) Chain {
return Chain{append([]ent.Hook(nil), hooks...)}
}
// Hook chains the list of hooks and returns the final hook.
func (c Chain) Hook() ent.Hook {
return func(mutator ent.Mutator) ent.Mutator {
for i := len(c.hooks) - 1; i >= 0; i-- {
mutator = c.hooks[i](mutator)
}
return mutator
}
}
// Append extends a chain, adding the specified hook
// as the last ones in the mutation flow.
func (c Chain) Append(hooks ...ent.Hook) Chain {
newHooks := make([]ent.Hook, 0, len(c.hooks)+len(hooks))
newHooks = append(newHooks, c.hooks...)
newHooks = append(newHooks, hooks...)
return Chain{newHooks}
}
// Extend extends a chain, adding the specified chain
// as the last ones in the mutation flow.
func (c Chain) Extend(chain Chain) Chain {
return c.Append(chain.hooks...)
}

64
ent/migrate/migrate.go Normal file
View File

@@ -0,0 +1,64 @@
// Code generated by ent, DO NOT EDIT.
package migrate
import (
"context"
"fmt"
"io"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql/schema"
)
var (
// WithGlobalUniqueID sets the universal ids options to the migration.
// If this option is enabled, ent migration will allocate a 1<<32 range
// for the ids of each entity (table).
// Note that this option cannot be applied on tables that already exist.
WithGlobalUniqueID = schema.WithGlobalUniqueID
// WithDropColumn sets the drop column option to the migration.
// If this option is enabled, ent migration will drop old columns
// that were used for both fields and edges. This defaults to false.
WithDropColumn = schema.WithDropColumn
// WithDropIndex sets the drop index option to the migration.
// If this option is enabled, ent migration will drop old indexes
// that were defined in the schema. This defaults to false.
// Note that unique constraints are defined using `UNIQUE INDEX`,
// and therefore, it's recommended to enable this option to get more
// flexibility in the schema changes.
WithDropIndex = schema.WithDropIndex
// WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true.
WithForeignKeys = schema.WithForeignKeys
)
// Schema is the API for creating, migrating and dropping a schema.
type Schema struct {
drv dialect.Driver
}
// NewSchema creates a new schema client.
func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} }
// Create creates all schema resources.
func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error {
return Create(ctx, s, Tables, opts...)
}
// Create creates all table resources using the given schema driver.
func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error {
migrate, err := schema.NewMigrate(s.drv, opts...)
if err != nil {
return fmt.Errorf("ent/migrate: %w", err)
}
return migrate.Create(ctx, tables...)
}
// WriteTo writes the schema changes to w instead of running them against the database.
//
// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil {
// log.Fatal(err)
// }
func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error {
return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...)
}

40
ent/migrate/schema.go Normal file
View File

@@ -0,0 +1,40 @@
// Code generated by ent, DO NOT EDIT.
package migrate
import (
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/schema/field"
)
var (
// DomainsColumns holds the columns for the "domains" table.
DomainsColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID},
{Name: "domain", Type: field.TypeString, Unique: true},
{Name: "client_api_key", Type: field.TypeString, Size: 64},
{Name: "memo", Type: field.TypeString, Default: ""},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
}
// DomainsTable holds the schema information for the "domains" table.
DomainsTable = &schema.Table{
Name: "domains",
Columns: DomainsColumns,
PrimaryKey: []*schema.Column{DomainsColumns[0]},
Indexes: []*schema.Index{
{
Name: "domain_client_api_key",
Unique: true,
Columns: []*schema.Column{DomainsColumns[2]},
},
},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
DomainsTable,
}
)
func init() {
}

577
ent/mutation.go Normal file
View File

@@ -0,0 +1,577 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"sync"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"github.com/dalbodeule/hop-gate/ent/domain"
"github.com/dalbodeule/hop-gate/ent/predicate"
"github.com/google/uuid"
)
const (
// Operation types.
OpCreate = ent.OpCreate
OpDelete = ent.OpDelete
OpDeleteOne = ent.OpDeleteOne
OpUpdate = ent.OpUpdate
OpUpdateOne = ent.OpUpdateOne
// Node types.
TypeDomain = "Domain"
)
// DomainMutation represents an operation that mutates the Domain nodes in the graph.
type DomainMutation struct {
config
op Op
typ string
id *uuid.UUID
domain *string
client_api_key *string
memo *string
created_at *time.Time
updated_at *time.Time
clearedFields map[string]struct{}
done bool
oldValue func(context.Context) (*Domain, error)
predicates []predicate.Domain
}
var _ ent.Mutation = (*DomainMutation)(nil)
// domainOption allows management of the mutation configuration using functional options.
type domainOption func(*DomainMutation)
// newDomainMutation creates new mutation for the Domain entity.
func newDomainMutation(c config, op Op, opts ...domainOption) *DomainMutation {
m := &DomainMutation{
config: c,
op: op,
typ: TypeDomain,
clearedFields: make(map[string]struct{}),
}
for _, opt := range opts {
opt(m)
}
return m
}
// withDomainID sets the ID field of the mutation.
func withDomainID(id uuid.UUID) domainOption {
return func(m *DomainMutation) {
var (
err error
once sync.Once
value *Domain
)
m.oldValue = func(ctx context.Context) (*Domain, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().Domain.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withDomain sets the old Domain of the mutation.
func withDomain(node *Domain) domainOption {
return func(m *DomainMutation) {
m.oldValue = func(context.Context) (*Domain, error) {
return node, nil
}
m.id = &node.ID
}
}
// Client returns a new `ent.Client` from the mutation. If the mutation was
// executed in a transaction (ent.Tx), a transactional client is returned.
func (m DomainMutation) Client() *Client {
client := &Client{config: m.config}
client.init()
return client
}
// Tx returns an `ent.Tx` for mutations that were executed in transactions;
// it returns an error otherwise.
func (m DomainMutation) Tx() (*Tx, error) {
if _, ok := m.driver.(*txDriver); !ok {
return nil, errors.New("ent: mutation is not running in a transaction")
}
tx := &Tx{config: m.config}
tx.init()
return tx, nil
}
// SetID sets the value of the id field. Note that this
// operation is only accepted on creation of Domain entities.
func (m *DomainMutation) SetID(id uuid.UUID) {
m.id = &id
}
// ID returns the ID value in the mutation. Note that the ID is only available
// if it was provided to the builder or after it was returned from the database.
func (m *DomainMutation) ID() (id uuid.UUID, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// IDs queries the database and returns the entity ids that match the mutation's predicate.
// That means, if the mutation is applied within a transaction with an isolation level such
// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated
// or updated by the mutation.
func (m *DomainMutation) IDs(ctx context.Context) ([]uuid.UUID, error) {
switch {
case m.op.Is(OpUpdateOne | OpDeleteOne):
id, exists := m.ID()
if exists {
return []uuid.UUID{id}, nil
}
fallthrough
case m.op.Is(OpUpdate | OpDelete):
return m.Client().Domain.Query().Where(m.predicates...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
}
}
// SetDomain sets the "domain" field.
func (m *DomainMutation) SetDomain(s string) {
m.domain = &s
}
// Domain returns the value of the "domain" field in the mutation.
func (m *DomainMutation) Domain() (r string, exists bool) {
v := m.domain
if v == nil {
return
}
return *v, true
}
// OldDomain returns the old "domain" field's value of the Domain entity.
// If the Domain object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *DomainMutation) OldDomain(ctx context.Context) (v string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldDomain is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldDomain requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldDomain: %w", err)
}
return oldValue.Domain, nil
}
// ResetDomain resets all changes to the "domain" field.
func (m *DomainMutation) ResetDomain() {
m.domain = nil
}
// SetClientAPIKey sets the "client_api_key" field.
func (m *DomainMutation) SetClientAPIKey(s string) {
m.client_api_key = &s
}
// ClientAPIKey returns the value of the "client_api_key" field in the mutation.
func (m *DomainMutation) ClientAPIKey() (r string, exists bool) {
v := m.client_api_key
if v == nil {
return
}
return *v, true
}
// OldClientAPIKey returns the old "client_api_key" field's value of the Domain entity.
// If the Domain object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *DomainMutation) OldClientAPIKey(ctx context.Context) (v string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldClientAPIKey is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldClientAPIKey requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldClientAPIKey: %w", err)
}
return oldValue.ClientAPIKey, nil
}
// ResetClientAPIKey resets all changes to the "client_api_key" field.
func (m *DomainMutation) ResetClientAPIKey() {
m.client_api_key = nil
}
// SetMemo sets the "memo" field.
func (m *DomainMutation) SetMemo(s string) {
m.memo = &s
}
// Memo returns the value of the "memo" field in the mutation.
func (m *DomainMutation) Memo() (r string, exists bool) {
v := m.memo
if v == nil {
return
}
return *v, true
}
// OldMemo returns the old "memo" field's value of the Domain entity.
// If the Domain object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *DomainMutation) OldMemo(ctx context.Context) (v string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldMemo is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldMemo requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldMemo: %w", err)
}
return oldValue.Memo, nil
}
// ResetMemo resets all changes to the "memo" field.
func (m *DomainMutation) ResetMemo() {
m.memo = nil
}
// SetCreatedAt sets the "created_at" field.
func (m *DomainMutation) SetCreatedAt(t time.Time) {
m.created_at = &t
}
// CreatedAt returns the value of the "created_at" field in the mutation.
func (m *DomainMutation) CreatedAt() (r time.Time, exists bool) {
v := m.created_at
if v == nil {
return
}
return *v, true
}
// OldCreatedAt returns the old "created_at" field's value of the Domain entity.
// If the Domain object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *DomainMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldCreatedAt requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err)
}
return oldValue.CreatedAt, nil
}
// ResetCreatedAt resets all changes to the "created_at" field.
func (m *DomainMutation) ResetCreatedAt() {
m.created_at = nil
}
// SetUpdatedAt sets the "updated_at" field.
func (m *DomainMutation) SetUpdatedAt(t time.Time) {
m.updated_at = &t
}
// UpdatedAt returns the value of the "updated_at" field in the mutation.
func (m *DomainMutation) UpdatedAt() (r time.Time, exists bool) {
v := m.updated_at
if v == nil {
return
}
return *v, true
}
// OldUpdatedAt returns the old "updated_at" field's value of the Domain entity.
// If the Domain object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *DomainMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldUpdatedAt requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err)
}
return oldValue.UpdatedAt, nil
}
// ResetUpdatedAt resets all changes to the "updated_at" field.
func (m *DomainMutation) ResetUpdatedAt() {
m.updated_at = nil
}
// Where appends a list predicates to the DomainMutation builder.
func (m *DomainMutation) Where(ps ...predicate.Domain) {
m.predicates = append(m.predicates, ps...)
}
// WhereP appends storage-level predicates to the DomainMutation builder. Using this method,
// users can use type-assertion to append predicates that do not depend on any generated package.
func (m *DomainMutation) WhereP(ps ...func(*sql.Selector)) {
p := make([]predicate.Domain, len(ps))
for i := range ps {
p[i] = ps[i]
}
m.Where(p...)
}
// Op returns the operation name.
func (m *DomainMutation) Op() Op {
return m.op
}
// SetOp allows setting the mutation operation.
func (m *DomainMutation) SetOp(op Op) {
m.op = op
}
// Type returns the node type of this mutation (Domain).
func (m *DomainMutation) Type() string {
return m.typ
}
// Fields returns all fields that were changed during this mutation. Note that in
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *DomainMutation) Fields() []string {
fields := make([]string, 0, 5)
if m.domain != nil {
fields = append(fields, domain.FieldDomain)
}
if m.client_api_key != nil {
fields = append(fields, domain.FieldClientAPIKey)
}
if m.memo != nil {
fields = append(fields, domain.FieldMemo)
}
if m.created_at != nil {
fields = append(fields, domain.FieldCreatedAt)
}
if m.updated_at != nil {
fields = append(fields, domain.FieldUpdatedAt)
}
return fields
}
// Field returns the value of a field with the given name. The second boolean
// return value indicates that this field was not set, or was not defined in the
// schema.
func (m *DomainMutation) Field(name string) (ent.Value, bool) {
switch name {
case domain.FieldDomain:
return m.Domain()
case domain.FieldClientAPIKey:
return m.ClientAPIKey()
case domain.FieldMemo:
return m.Memo()
case domain.FieldCreatedAt:
return m.CreatedAt()
case domain.FieldUpdatedAt:
return m.UpdatedAt()
}
return nil, false
}
// OldField returns the old value of the field from the database. An error is
// returned if the mutation operation is not UpdateOne, or the query to the
// database failed.
func (m *DomainMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case domain.FieldDomain:
return m.OldDomain(ctx)
case domain.FieldClientAPIKey:
return m.OldClientAPIKey(ctx)
case domain.FieldMemo:
return m.OldMemo(ctx)
case domain.FieldCreatedAt:
return m.OldCreatedAt(ctx)
case domain.FieldUpdatedAt:
return m.OldUpdatedAt(ctx)
}
return nil, fmt.Errorf("unknown Domain field %s", name)
}
// SetField sets the value of a field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *DomainMutation) SetField(name string, value ent.Value) error {
switch name {
case domain.FieldDomain:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetDomain(v)
return nil
case domain.FieldClientAPIKey:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetClientAPIKey(v)
return nil
case domain.FieldMemo:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetMemo(v)
return nil
case domain.FieldCreatedAt:
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetCreatedAt(v)
return nil
case domain.FieldUpdatedAt:
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetUpdatedAt(v)
return nil
}
return fmt.Errorf("unknown Domain field %s", name)
}
// AddedFields returns all numeric fields that were incremented/decremented during
// this mutation.
func (m *DomainMutation) AddedFields() []string {
return nil
}
// AddedField returns the numeric value that was incremented/decremented on a field
// with the given name. The second boolean return value indicates that this field
// was not set, or was not defined in the schema.
func (m *DomainMutation) AddedField(name string) (ent.Value, bool) {
return nil, false
}
// AddField adds the value to the field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *DomainMutation) AddField(name string, value ent.Value) error {
switch name {
}
return fmt.Errorf("unknown Domain numeric field %s", name)
}
// ClearedFields returns all nullable fields that were cleared during this
// mutation.
func (m *DomainMutation) ClearedFields() []string {
return nil
}
// FieldCleared returns a boolean indicating if a field with the given name was
// cleared in this mutation.
func (m *DomainMutation) FieldCleared(name string) bool {
_, ok := m.clearedFields[name]
return ok
}
// ClearField clears the value of the field with the given name. It returns an
// error if the field is not defined in the schema.
func (m *DomainMutation) ClearField(name string) error {
return fmt.Errorf("unknown Domain nullable field %s", name)
}
// ResetField resets all changes in the mutation for the field with the given name.
// It returns an error if the field is not defined in the schema.
func (m *DomainMutation) ResetField(name string) error {
switch name {
case domain.FieldDomain:
m.ResetDomain()
return nil
case domain.FieldClientAPIKey:
m.ResetClientAPIKey()
return nil
case domain.FieldMemo:
m.ResetMemo()
return nil
case domain.FieldCreatedAt:
m.ResetCreatedAt()
return nil
case domain.FieldUpdatedAt:
m.ResetUpdatedAt()
return nil
}
return fmt.Errorf("unknown Domain field %s", name)
}
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *DomainMutation) AddedEdges() []string {
edges := make([]string, 0, 0)
return edges
}
// AddedIDs returns all IDs (to other nodes) that were added for the given edge
// name in this mutation.
func (m *DomainMutation) AddedIDs(name string) []ent.Value {
return nil
}
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *DomainMutation) RemovedEdges() []string {
edges := make([]string, 0, 0)
return edges
}
// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
// the given name in this mutation.
func (m *DomainMutation) RemovedIDs(name string) []ent.Value {
return nil
}
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *DomainMutation) ClearedEdges() []string {
edges := make([]string, 0, 0)
return edges
}
// EdgeCleared returns a boolean which indicates if the edge with the given name
// was cleared in this mutation.
func (m *DomainMutation) EdgeCleared(name string) bool {
return false
}
// ClearEdge clears the value of the edge with the given name. It returns an error
// if that edge is not defined in the schema.
func (m *DomainMutation) ClearEdge(name string) error {
return fmt.Errorf("unknown Domain unique edge %s", name)
}
// ResetEdge resets all changes to the edge with the given name in this mutation.
// It returns an error if the edge is not defined in the schema.
func (m *DomainMutation) ResetEdge(name string) error {
return fmt.Errorf("unknown Domain edge %s", name)
}

View File

@@ -0,0 +1,10 @@
// Code generated by ent, DO NOT EDIT.
package predicate
import (
"entgo.io/ent/dialect/sql"
)
// Domain is the predicate function for domain builders.
type Domain func(*sql.Selector)

59
ent/runtime.go Normal file
View File

@@ -0,0 +1,59 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"time"
"github.com/dalbodeule/hop-gate/ent/domain"
"github.com/dalbodeule/hop-gate/ent/schema"
"github.com/google/uuid"
)
// The init function reads all schema descriptors with runtime code
// (default values, validators, hooks and policies) and stitches it
// to their package variables.
func init() {
domainFields := schema.Domain{}.Fields()
_ = domainFields
// domainDescDomain is the schema descriptor for domain field.
domainDescDomain := domainFields[1].Descriptor()
// domain.DomainValidator is a validator for the "domain" field. It is called by the builders before save.
domain.DomainValidator = domainDescDomain.Validators[0].(func(string) error)
// domainDescClientAPIKey is the schema descriptor for client_api_key field.
domainDescClientAPIKey := domainFields[2].Descriptor()
// domain.ClientAPIKeyValidator is a validator for the "client_api_key" field. It is called by the builders before save.
domain.ClientAPIKeyValidator = func() func(string) error {
validators := domainDescClientAPIKey.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(client_api_key string) error {
for _, fn := range fns {
if err := fn(client_api_key); err != nil {
return err
}
}
return nil
}
}()
// domainDescMemo is the schema descriptor for memo field.
domainDescMemo := domainFields[3].Descriptor()
// domain.DefaultMemo holds the default value on creation for the memo field.
domain.DefaultMemo = domainDescMemo.Default.(string)
// domainDescCreatedAt is the schema descriptor for created_at field.
domainDescCreatedAt := domainFields[4].Descriptor()
// domain.DefaultCreatedAt holds the default value on creation for the created_at field.
domain.DefaultCreatedAt = domainDescCreatedAt.Default.(func() time.Time)
// domainDescUpdatedAt is the schema descriptor for updated_at field.
domainDescUpdatedAt := domainFields[5].Descriptor()
// domain.DefaultUpdatedAt holds the default value on creation for the updated_at field.
domain.DefaultUpdatedAt = domainDescUpdatedAt.Default.(func() time.Time)
// domain.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
domain.UpdateDefaultUpdatedAt = domainDescUpdatedAt.UpdateDefault.(func() time.Time)
// domainDescID is the schema descriptor for id field.
domainDescID := domainFields[0].Descriptor()
// domain.DefaultID holds the default value on creation for the id field.
domain.DefaultID = domainDescID.Default.(func() uuid.UUID)
}

10
ent/runtime/runtime.go Normal file
View File

@@ -0,0 +1,10 @@
// Code generated by ent, DO NOT EDIT.
package runtime
// The schema-stitching logic is generated in github.com/dalbodeule/hop-gate/ent/runtime.go
const (
Version = "v0.14.5" // Version of ent codegen.
Sum = "h1:Rj2WOYJtCkWyFo6a+5wB3EfBRP0rnx1fMk6gGA0UUe4=" // Sum of ent codegen.
)

210
ent/tx.go Normal file
View File

@@ -0,0 +1,210 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"sync"
"entgo.io/ent/dialect"
)
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
// Domain is the client for interacting with the Domain builders.
Domain *DomainClient
// lazily loaded.
client *Client
clientOnce sync.Once
// ctx lives for the life of the transaction. It is
// the same context used by the underlying connection.
ctx context.Context
}
type (
// Committer is the interface that wraps the Commit method.
Committer interface {
Commit(context.Context, *Tx) error
}
// The CommitFunc type is an adapter to allow the use of ordinary
// function as a Committer. If f is a function with the appropriate
// signature, CommitFunc(f) is a Committer that calls f.
CommitFunc func(context.Context, *Tx) error
// CommitHook defines the "commit middleware". A function that gets a Committer
// and returns a Committer. For example:
//
// hook := func(next ent.Committer) ent.Committer {
// return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error {
// // Do some stuff before.
// if err := next.Commit(ctx, tx); err != nil {
// return err
// }
// // Do some stuff after.
// return nil
// })
// }
//
CommitHook func(Committer) Committer
)
// Commit calls f(ctx, m).
func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error {
return f(ctx, tx)
}
// Commit commits the transaction.
func (tx *Tx) Commit() error {
txDriver := tx.config.driver.(*txDriver)
var fn Committer = CommitFunc(func(context.Context, *Tx) error {
return txDriver.tx.Commit()
})
txDriver.mu.Lock()
hooks := append([]CommitHook(nil), txDriver.onCommit...)
txDriver.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
return fn.Commit(tx.ctx, tx)
}
// OnCommit adds a hook to call on commit.
func (tx *Tx) OnCommit(f CommitHook) {
txDriver := tx.config.driver.(*txDriver)
txDriver.mu.Lock()
txDriver.onCommit = append(txDriver.onCommit, f)
txDriver.mu.Unlock()
}
type (
// Rollbacker is the interface that wraps the Rollback method.
Rollbacker interface {
Rollback(context.Context, *Tx) error
}
// The RollbackFunc type is an adapter to allow the use of ordinary
// function as a Rollbacker. If f is a function with the appropriate
// signature, RollbackFunc(f) is a Rollbacker that calls f.
RollbackFunc func(context.Context, *Tx) error
// RollbackHook defines the "rollback middleware". A function that gets a Rollbacker
// and returns a Rollbacker. For example:
//
// hook := func(next ent.Rollbacker) ent.Rollbacker {
// return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error {
// // Do some stuff before.
// if err := next.Rollback(ctx, tx); err != nil {
// return err
// }
// // Do some stuff after.
// return nil
// })
// }
//
RollbackHook func(Rollbacker) Rollbacker
)
// Rollback calls f(ctx, m).
func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error {
return f(ctx, tx)
}
// Rollback rollbacks the transaction.
func (tx *Tx) Rollback() error {
txDriver := tx.config.driver.(*txDriver)
var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error {
return txDriver.tx.Rollback()
})
txDriver.mu.Lock()
hooks := append([]RollbackHook(nil), txDriver.onRollback...)
txDriver.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
return fn.Rollback(tx.ctx, tx)
}
// OnRollback adds a hook to call on rollback.
func (tx *Tx) OnRollback(f RollbackHook) {
txDriver := tx.config.driver.(*txDriver)
txDriver.mu.Lock()
txDriver.onRollback = append(txDriver.onRollback, f)
txDriver.mu.Unlock()
}
// Client returns a Client that binds to current transaction.
func (tx *Tx) Client() *Client {
tx.clientOnce.Do(func() {
tx.client = &Client{config: tx.config}
tx.client.init()
})
return tx.client
}
func (tx *Tx) init() {
tx.Domain = NewDomainClient(tx.config)
}
// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation.
// The idea is to support transactions without adding any extra code to the builders.
// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance.
// Commit and Rollback are nop for the internal builders and the user must call one
// of them in order to commit or rollback the transaction.
//
// If a closed transaction is embedded in one of the generated entities, and the entity
// applies a query, for example: Domain.QueryXXX(), the query will be executed
// through the driver which created this transaction.
//
// Note that txDriver is not goroutine safe.
type txDriver struct {
// the driver we started the transaction from.
drv dialect.Driver
// tx is the underlying transaction.
tx dialect.Tx
// completion hooks.
mu sync.Mutex
onCommit []CommitHook
onRollback []RollbackHook
}
// newTx creates a new transactional driver.
func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) {
tx, err := drv.Tx(ctx)
if err != nil {
return nil, err
}
return &txDriver{tx: tx, drv: drv}, nil
}
// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls
// from the internal builders. Should be called only by the internal builders.
func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil }
// Dialect returns the dialect of the driver we started the transaction from.
func (tx *txDriver) Dialect() string { return tx.drv.Dialect() }
// Close is a nop close.
func (*txDriver) Close() error { return nil }
// Commit is a nop commit for the internal builders.
// User must call `Tx.Commit` in order to commit the transaction.
func (*txDriver) Commit() error { return nil }
// Rollback is a nop rollback for the internal builders.
// User must call `Tx.Rollback` in order to rollback the transaction.
func (*txDriver) Rollback() error { return nil }
// Exec calls tx.Exec.
func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error {
return tx.tx.Exec(ctx, query, args, v)
}
// Query calls tx.Query.
func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error {
return tx.tx.Query(ctx, query, args, v)
}
var _ dialect.Driver = (*txDriver)(nil)

13
go.mod
View File

@@ -5,13 +5,26 @@ go 1.25.4
require (
entgo.io/ent v0.14.5
github.com/google/uuid v1.3.0
github.com/lib/pq v1.10.9
github.com/pion/dtls/v3 v3.0.7
golang.org/x/net v0.47.0
)
require (
ariga.io/atlas v0.32.1-0.20250325101103-175b25e1c1b9 // indirect
github.com/agext/levenshtein v1.2.3 // indirect
github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect
github.com/bmatcuk/doublestar v1.3.4 // indirect
github.com/go-openapi/inflect v0.19.0 // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/hashicorp/hcl/v2 v2.18.1 // indirect
github.com/mitchellh/go-wordwrap v1.0.1 // indirect
github.com/pion/logging v0.2.4 // indirect
github.com/pion/transport/v3 v3.0.7 // indirect
github.com/rogpeppe/go-internal v1.14.1 // indirect
github.com/zclconf/go-cty v1.14.4 // indirect
github.com/zclconf/go-cty-yaml v1.1.0 // indirect
golang.org/x/crypto v0.44.0 // indirect
golang.org/x/mod v0.29.0 // indirect
golang.org/x/text v0.31.0 // indirect
)

40
go.sum
View File

@@ -1,9 +1,39 @@
ariga.io/atlas v0.32.1-0.20250325101103-175b25e1c1b9 h1:E0wvcUXTkgyN4wy4LGtNzMNGMytJN8afmIWXJVMi4cc=
ariga.io/atlas v0.32.1-0.20250325101103-175b25e1c1b9/go.mod h1:Oe1xWPuu5q9LzyrWfbZmEZxFYeu4BHTyzfjeW2aZp/w=
entgo.io/ent v0.14.5 h1:Rj2WOYJtCkWyFo6a+5wB3EfBRP0rnx1fMk6gGA0UUe4=
entgo.io/ent v0.14.5/go.mod h1:zTzLmWtPvGpmSwtkaayM2cm5m819NdM7z7tYPq3vN0U=
github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60=
github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM=
github.com/agext/levenshtein v1.2.3 h1:YB2fHEn0UJagG8T1rrWknE3ZQzWM06O8AMAatNn7lmo=
github.com/agext/levenshtein v1.2.3/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558=
github.com/apparentlymart/go-textseg/v15 v15.0.0 h1:uYvfpb3DyLSCGWnctWKGj857c6ew1u1fNQOlOtuGxQY=
github.com/apparentlymart/go-textseg/v15 v15.0.0/go.mod h1:K8XmNZdhEBkdlyDdvbmmsvpAG721bKi0joRfFdHIWJ4=
github.com/bmatcuk/doublestar v1.3.4 h1:gPypJ5xD31uhX6Tf54sDPUOBXTqKH4c9aPY66CyQrS0=
github.com/bmatcuk/doublestar v1.3.4/go.mod h1:wiQtGV+rzVYxB7WIlirSN++5HPtPlXEo9MEoZQC/PmE=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-openapi/inflect v0.19.0 h1:9jCH9scKIbHeV9m12SmPilScz6krDxKRasNNSNPXu/4=
github.com/go-openapi/inflect v0.19.0/go.mod h1:lHpZVlpIQqLyKwJ4N+YSc9hchQy/i12fJykb83CRBH4=
github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68=
github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/hcl/v2 v2.18.1 h1:6nxnOJFku1EuSawSD81fuviYUV8DxFr3fp2dUi3ZYSo=
github.com/hashicorp/hcl/v2 v2.18.1/go.mod h1:ThLC89FV4p9MPW804KVbe/cEXoQ8NZEh+JtMeeGErHE=
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mattn/go-sqlite3 v1.14.17 h1:mCRHCLDUBXgpKAqIKsaAaAsrAlbkeomtRFKXh2L6YIM=
github.com/mattn/go-sqlite3 v1.14.17/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0=
github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0=
github.com/pion/dtls/v3 v3.0.7 h1:bItXtTYYhZwkPFk4t1n3Kkf5TDrfj6+4wG+CZR8uI9Q=
github.com/pion/dtls/v3 v3.0.7/go.mod h1:uDlH5VPrgOQIw59irKYkMudSFprY9IEFCqz/eTz16f8=
github.com/pion/logging v0.2.4 h1:tTew+7cmQ+Mc1pTBLKH2puKsOvhm32dROumOZ655zB8=
@@ -12,10 +42,20 @@ github.com/pion/transport/v3 v3.0.7 h1:iRbMH05BzSNwhILHoBoAPxoB9xQgOaJk+591KC9P1
github.com/pion/transport/v3 v3.0.7/go.mod h1:YleKiTZ4vqNxVwh77Z0zytYi7rXHl7j6uPLGhhz9rwo=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8=
github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/zclconf/go-cty v1.14.4 h1:uXXczd9QDGsgu0i/QFR/hzI5NYCHLf6NQw/atrbnhq8=
github.com/zclconf/go-cty v1.14.4/go.mod h1:VvMs5i0vgZdhYawQNq5kePSpLAoz8u1xvZgrPIxfnZE=
github.com/zclconf/go-cty-yaml v1.1.0 h1:nP+jp0qPHv2IhUVqmQSzjvqAWcObN0KBkUl2rWBdig0=
github.com/zclconf/go-cty-yaml v1.1.0/go.mod h1:9YLUH4g7lOhVWqUbctnVlZ5KLpg7JAprQNgxSZ1Gyxs=
golang.org/x/crypto v0.44.0 h1:A97SsFvM3AIwEEmTBiaxPPTYpDC47w720rdiiUvgoAU=
golang.org/x/crypto v0.44.0/go.mod h1:013i+Nw79BMiQiMsOPcVCB5ZIJbYkerPrGnOa00tvmc=
golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA=
golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=

170
internal/store/postgres.go Normal file
View File

@@ -0,0 +1,170 @@
package store
import (
"context"
"database/sql"
"fmt"
"os"
"strings"
"time"
entsql "entgo.io/ent/dialect/sql"
"github.com/dalbodeule/hop-gate/ent"
"github.com/dalbodeule/hop-gate/internal/logging"
_ "github.com/lib/pq"
)
// Config holds PostgreSQL connection and pool settings.
type Config struct {
DSN string // PostgreSQL DSN, e.g. postgres://user:pass@host:5432/db?sslmode=disable
MaxOpenConns int // maximum number of open connections
MaxIdleConns int // maximum number of idle connections
ConnMaxLifetime time.Duration // maximum connection lifetime
}
// defaultConfig returns reasonable defaults for local development.
func defaultConfig() Config {
return Config{
MaxOpenConns: 10,
MaxIdleConns: 5,
ConnMaxLifetime: 30 * time.Minute,
}
}
// ConfigFromEnv builds a Config from environment variables.
//
// Environment variables:
// - HOP_DB_DSN : required, PostgreSQL DSN
// - HOP_DB_MAX_OPEN_CONNS : optional, int, default 10
// - HOP_DB_MAX_IDLE_CONNS : optional, int, default 5
// - HOP_DB_CONN_MAX_LIFETIME : optional, duration (e.g. "30m"), default 30m
func ConfigFromEnv() (Config, error) {
cfg := defaultConfig()
dsn := strings.TrimSpace(os.Getenv("HOP_DB_DSN"))
if dsn == "" {
return Config{}, fmt.Errorf("HOP_DB_DSN is required")
}
cfg.DSN = dsn
if v := strings.TrimSpace(os.Getenv("HOP_DB_MAX_OPEN_CONNS")); v != "" {
if n, err := parseInt(v); err == nil && n > 0 {
cfg.MaxOpenConns = n
}
}
if v := strings.TrimSpace(os.Getenv("HOP_DB_MAX_IDLE_CONNS")); v != "" {
if n, err := parseInt(v); err == nil && n >= 0 {
cfg.MaxIdleConns = n
}
}
if v := strings.TrimSpace(os.Getenv("HOP_DB_CONN_MAX_LIFETIME")); v != "" {
if d, err := time.ParseDuration(v); err == nil && d > 0 {
cfg.ConnMaxLifetime = d
}
}
return cfg, nil
}
func parseInt(s string) (int, error) {
var n int
_, err := fmt.Sscanf(s, "%d", &n)
return n, err
}
// OpenPostgres opens an ent.Client backed by PostgreSQL, configures the pool,
// verifies the connection, and runs schema migrations (DB init).
//
// This will create tables if they do not exist, based on ent schema definitions.
func OpenPostgres(ctx context.Context, logger logging.Logger, cfg Config) (*ent.Client, error) {
if strings.TrimSpace(cfg.DSN) == "" {
return nil, fmt.Errorf("postgres DSN is empty")
}
// Open a *sql.DB using the standard library, then wrap it with ent's SQL driver.
db, err := sql.Open("postgres", cfg.DSN)
if err != nil {
return nil, fmt.Errorf("open postgres db: %w", err)
}
// If anything fails after this, close db explicitly.
if err := configurePool(db, cfg); err != nil {
_ = db.Close()
return nil, fmt.Errorf("configure db pool: %w", err)
}
if err := ping(ctx, db); err != nil {
_ = db.Close()
return nil, fmt.Errorf("ping postgres: %w", err)
}
// Wrap the *sql.DB with the ent SQL driver and create the ent client.
//
// From this point on, ent owns the underlying *sql.DB; callers should close
// the ent.Client when shutting down.
entDrv := entsql.OpenDB("postgres", db)
client := ent.NewClient(ent.Driver(entDrv))
// Auto-migrate schema: creates tables if they do not exist.
if err := client.Schema.Create(ctx); err != nil {
_ = client.Close()
return nil, fmt.Errorf("ent schema create: %w", err)
}
logger.Info("connected to postgres and applied schema", logging.Fields{
"dsn_masked": maskDSN(cfg.DSN),
})
return client, nil
}
func configurePool(db *sql.DB, cfg Config) error {
if db == nil {
return fmt.Errorf("db is nil")
}
if cfg.MaxOpenConns > 0 {
db.SetMaxOpenConns(cfg.MaxOpenConns)
}
if cfg.MaxIdleConns >= 0 {
db.SetMaxIdleConns(cfg.MaxIdleConns)
}
if cfg.ConnMaxLifetime > 0 {
db.SetConnMaxLifetime(cfg.ConnMaxLifetime)
}
return nil
}
func ping(ctx context.Context, db *sql.DB) error {
if db == nil {
return fmt.Errorf("db is nil")
}
if ctx == nil {
ctx = context.Background()
}
return db.PingContext(ctx)
}
// OpenPostgresFromEnv is a convenience helper that reads configuration
// from environment variables and opens a PostgreSQL ent client.
//
// It is intended to be called from the server side at startup.
func OpenPostgresFromEnv(ctx context.Context, logger logging.Logger) (*ent.Client, error) {
cfg, err := ConfigFromEnv()
if err != nil {
return nil, err
}
return OpenPostgres(ctx, logger, cfg)
}
// maskDSN hides password in DSN for safe logging.
func maskDSN(dsn string) string {
// Very simple masking: do not log full DSN.
if dsn == "" {
return ""
}
return "***"
}

45
tools/gen_ent.sh Executable file
View File

@@ -0,0 +1,45 @@
#!/usr/bin/env bash
set -euo pipefail
# 프로젝트 루트 기준으로 실행한다고 가정.
# 이 스크립트를 프로젝트 루트에서 실행하지 않는다면,
# 아래 BASE_DIR 를 적절히 조정하거나 `cd`를 추가하세요.
BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$BASE_DIR"
echo "[ent] project root: $BASE_DIR"
# 1. ent 바이너리 체크
if ! command -v ent >/dev/null 2>&1; then
echo "[ent] 'ent' CLI 가 설치되어 있지 않습니다."
echo " 설치: go install entgo.io/ent/cmd/ent@latest"
exit 1
fi
# 2. ./ent/schema/*.go 존재 확인
SCHEMA_DIR="$BASE_DIR/ent/schema"
if [ ! -d "$SCHEMA_DIR" ]; then
echo "[ent] 스키마 디렉터리가 없습니다: $SCHEMA_DIR"
exit 1
fi
shopt -s nullglob
SCHEMA_FILES=("$SCHEMA_DIR"/*.go)
shopt -u nullglob
if [ ${#SCHEMA_FILES[@]} -eq 0 ]; then
echo "[ent] 스키마 파일(./ent/schema/*.go)이 없습니다."
exit 1
fi
echo "[ent] schema files:"
for f in "${SCHEMA_FILES[@]}"; do
echo " - $f"
done
# 3. ent 코드 생성
echo "[ent] generating ent client from ./ent/schema"
ent generate ./ent/schema
echo "[ent] ent code generation complete."
echo "[ent] done."