diff --git a/README.md b/README.md index 223b73d..d8038cc 100644 --- a/README.md +++ b/README.md @@ -2,10 +2,21 @@ ### 로컬 DB 실행 ```bash -./dev-db.sh +./script/dev-db.sh ``` ### 테스트용 DB 실행 ```bash -./test-db.sh +./script/test-db.sh ``` + +## DB 마이그레이션 + +[ent, atlas migration 가이드](https://entgo.io/docs/versioned-migrations#generating-versioned-migration-files) + +schema 작성 후 아래 스크립트 실행 +```bash +./script/create_migration.sh +``` +- atlas 설치 필요 +- migration파일 생성 후 필요에 따라 migratin 파일 수정시 atlas migrate hash로 적용 필요 diff --git a/cmd/main.go b/cmd/main.go index e3d00c3..98ce422 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -2,22 +2,34 @@ package main import ( "fmt" - "os" + "log" + + "github.com/techbloghub/server/config" + _ "github.com/techbloghub/server/ent/runtime" + "github.com/techbloghub/server/internal/database" "github.com/gin-gonic/gin" - "github.com/joho/godotenv" + _ "github.com/lib/pq" ) func main() { - godotenv.Load(".env") + cfg, cfgErr := config.NewConfig() + if cfgErr != nil { + log.Fatalf("failed to load config: %v", cfgErr) + } + + // DB 연결 + client, errPg := database.ConnectDatabase(cfg) + if errPg != nil { + log.Fatalf("failed to connect database: %v", errPg) + } + defer client.Close() - // PORT 환경변수에서 가져오기 - // 후에 이런 config값 관리할것들 많아지면 후에 Config struct등으로 분리 고려 - port := getEnvWithDefault("PORT", "8080") + // 서버 실행 r := setRouter() - err := r.Run(":" + port) - if err != nil { - fmt.Println("Error while running server: ", err) + routerErr := r.Run(":" + cfg.ServerConfig.Port) + if routerErr != nil { + fmt.Println("Error while running server: ", cfgErr) return } } @@ -29,10 +41,3 @@ func setRouter() *gin.Engine { }) return r } - -func getEnvWithDefault(key, defaultValue string) string { - if value := os.Getenv(key); value != "" { - return value - } - return defaultValue -} diff --git a/config/config.go b/config/config.go new file mode 100644 index 0000000..be2095c --- /dev/null +++ b/config/config.go @@ -0,0 +1,97 @@ +package config + +import ( + "fmt" + "log" + "os" + + "github.com/joho/godotenv" +) + +type Config struct { + PostgresConfig + ServerConfig +} + +type PostgresConfig struct { + Host string + Port string + User string + Password string + Db string +} + +type ServerConfig struct { + Port string + Env string +} + +func (cfg *PostgresConfig) ToMap() map[string]string { + return map[string]string{ + "HOST": cfg.Host, + "PORT": cfg.Port, + "USER": cfg.User, + "PASSWORD": cfg.Password, + "DB": cfg.Db, + } +} + +func (cfg *ServerConfig) ToMap() map[string]string { + return map[string]string{ + "PORT": cfg.Port, + "ENV": cfg.Env, + } +} + +func NewConfig() (*Config, error) { + errEnv := godotenv.Load(".env") + if errEnv != nil { + log.Print("failed to reading .env", errEnv) + } + + postgresConf := PostgresConfig{ + Host: os.Getenv("POSTGRES_HOST"), + Port: os.Getenv("POSTGRES_PORT"), + User: os.Getenv("POSTGRES_USER"), + Password: os.Getenv("POSTGRES_PASSWORD"), + Db: os.Getenv("POSTGRES_DB"), + } + + serverConf := ServerConfig{ + Port: os.Getenv("PORT"), + Env: os.Getenv("ENV"), + } + + cfg := &Config{ + PostgresConfig: postgresConf, + ServerConfig: serverConf, + } + + if err := validateEnvs(cfg); err != nil { + return nil, err + } + + return cfg, nil +} + +func validateEnvs(cfg *Config) error { + missingEnvs := []string{} + + missingEnvs = append(missingEnvs, findEmptyValueKeys(cfg.PostgresConfig.ToMap())...) + missingEnvs = append(missingEnvs, findEmptyValueKeys(cfg.ServerConfig.ToMap())...) + + if len(missingEnvs) > 0 { + return fmt.Errorf("missing envs: %v", missingEnvs) + } + return nil +} + +func findEmptyValueKeys(m map[string]string) []string { + keys := []string{} + for k, v := range m { + if v == "" { + keys = append(keys, k) + } + } + return keys +} diff --git a/ent/client.go b/ent/client.go new file mode 100644 index 0000000..68b4126 --- /dev/null +++ b/ent/client.go @@ -0,0 +1,342 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "log" + "reflect" + + "github.com/techbloghub/server/ent/migrate" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "github.com/techbloghub/server/ent/company" +) + +// 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 + // Company is the client for interacting with the Company builders. + Company *CompanyClient +} + +// 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.Company = NewCompanyClient(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, + Company: NewCompanyClient(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, + Company: NewCompanyClient(cfg), + }, nil +} + +// Debug returns a new debug-client. It's used to get verbose logging on specific operations. +// +// client.Debug(). +// Company. +// 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.Company.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.Company.Intercept(interceptors...) +} + +// Mutate implements the ent.Mutator interface. +func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { + switch m := m.(type) { + case *CompanyMutation: + return c.Company.mutate(ctx, m) + default: + return nil, fmt.Errorf("ent: unknown mutation type %T", m) + } +} + +// CompanyClient is a client for the Company schema. +type CompanyClient struct { + config +} + +// NewCompanyClient returns a client for the Company from the given config. +func NewCompanyClient(c config) *CompanyClient { + return &CompanyClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `company.Hooks(f(g(h())))`. +func (c *CompanyClient) Use(hooks ...Hook) { + c.hooks.Company = append(c.hooks.Company, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `company.Intercept(f(g(h())))`. +func (c *CompanyClient) Intercept(interceptors ...Interceptor) { + c.inters.Company = append(c.inters.Company, interceptors...) +} + +// Create returns a builder for creating a Company entity. +func (c *CompanyClient) Create() *CompanyCreate { + mutation := newCompanyMutation(c.config, OpCreate) + return &CompanyCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Company entities. +func (c *CompanyClient) CreateBulk(builders ...*CompanyCreate) *CompanyCreateBulk { + return &CompanyCreateBulk{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 *CompanyClient) MapCreateBulk(slice any, setFunc func(*CompanyCreate, int)) *CompanyCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &CompanyCreateBulk{err: fmt.Errorf("calling to CompanyClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*CompanyCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &CompanyCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Company. +func (c *CompanyClient) Update() *CompanyUpdate { + mutation := newCompanyMutation(c.config, OpUpdate) + return &CompanyUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *CompanyClient) UpdateOne(co *Company) *CompanyUpdateOne { + mutation := newCompanyMutation(c.config, OpUpdateOne, withCompany(co)) + return &CompanyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *CompanyClient) UpdateOneID(id int) *CompanyUpdateOne { + mutation := newCompanyMutation(c.config, OpUpdateOne, withCompanyID(id)) + return &CompanyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Company. +func (c *CompanyClient) Delete() *CompanyDelete { + mutation := newCompanyMutation(c.config, OpDelete) + return &CompanyDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *CompanyClient) DeleteOne(co *Company) *CompanyDeleteOne { + return c.DeleteOneID(co.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *CompanyClient) DeleteOneID(id int) *CompanyDeleteOne { + builder := c.Delete().Where(company.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &CompanyDeleteOne{builder} +} + +// Query returns a query builder for Company. +func (c *CompanyClient) Query() *CompanyQuery { + return &CompanyQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeCompany}, + inters: c.Interceptors(), + } +} + +// Get returns a Company entity by its id. +func (c *CompanyClient) Get(ctx context.Context, id int) (*Company, error) { + return c.Query().Where(company.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *CompanyClient) GetX(ctx context.Context, id int) *Company { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *CompanyClient) Hooks() []Hook { + hooks := c.hooks.Company + return append(hooks[:len(hooks):len(hooks)], company.Hooks[:]...) +} + +// Interceptors returns the client interceptors. +func (c *CompanyClient) Interceptors() []Interceptor { + inters := c.inters.Company + return append(inters[:len(inters):len(inters)], company.Interceptors[:]...) +} + +func (c *CompanyClient) mutate(ctx context.Context, m *CompanyMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&CompanyCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&CompanyUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&CompanyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&CompanyDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Company mutation op: %q", m.Op()) + } +} + +// hooks and interceptors per client, for fast access. +type ( + hooks struct { + Company []ent.Hook + } + inters struct { + Company []ent.Interceptor + } +) diff --git a/ent/company.go b/ent/company.go new file mode 100644 index 0000000..197bba5 --- /dev/null +++ b/ent/company.go @@ -0,0 +1,179 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "net/url" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/techbloghub/server/ent/company" +) + +// Company is the model entity for the Company schema. +type Company struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // CreateTime holds the value of the "create_time" field. + CreateTime time.Time `json:"create_time,omitempty"` + // UpdateTime holds the value of the "update_time" field. + UpdateTime time.Time `json:"update_time,omitempty"` + // DeleteTime holds the value of the "delete_time" field. + DeleteTime time.Time `json:"delete_time,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // LogoURL holds the value of the "logo_url" field. + LogoURL *url.URL `json:"logo_url,omitempty"` + // BlogURL holds the value of the "blog_url" field. + BlogURL *url.URL `json:"blog_url,omitempty"` + // RssURL holds the value of the "rss_url" field. + RssURL *url.URL `json:"rss_url,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Company) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case company.FieldID: + values[i] = new(sql.NullInt64) + case company.FieldName: + values[i] = new(sql.NullString) + case company.FieldCreateTime, company.FieldUpdateTime, company.FieldDeleteTime: + values[i] = new(sql.NullTime) + case company.FieldLogoURL: + values[i] = company.ValueScanner.LogoURL.ScanValue() + case company.FieldBlogURL: + values[i] = company.ValueScanner.BlogURL.ScanValue() + case company.FieldRssURL: + values[i] = company.ValueScanner.RssURL.ScanValue() + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Company fields. +func (c *Company) 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 company.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + c.ID = int(value.Int64) + case company.FieldCreateTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field create_time", values[i]) + } else if value.Valid { + c.CreateTime = value.Time + } + case company.FieldUpdateTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field update_time", values[i]) + } else if value.Valid { + c.UpdateTime = value.Time + } + case company.FieldDeleteTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field delete_time", values[i]) + } else if value.Valid { + c.DeleteTime = value.Time + } + case company.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + c.Name = value.String + } + case company.FieldLogoURL: + if value, err := company.ValueScanner.LogoURL.FromValue(values[i]); err != nil { + return err + } else { + c.LogoURL = value + } + case company.FieldBlogURL: + if value, err := company.ValueScanner.BlogURL.FromValue(values[i]); err != nil { + return err + } else { + c.BlogURL = value + } + case company.FieldRssURL: + if value, err := company.ValueScanner.RssURL.FromValue(values[i]); err != nil { + return err + } else { + c.RssURL = value + } + default: + c.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Company. +// This includes values selected through modifiers, order, etc. +func (c *Company) Value(name string) (ent.Value, error) { + return c.selectValues.Get(name) +} + +// Update returns a builder for updating this Company. +// Note that you need to call Company.Unwrap() before calling this method if this Company +// was returned from a transaction, and the transaction was committed or rolled back. +func (c *Company) Update() *CompanyUpdateOne { + return NewCompanyClient(c.config).UpdateOne(c) +} + +// Unwrap unwraps the Company 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 (c *Company) Unwrap() *Company { + _tx, ok := c.config.driver.(*txDriver) + if !ok { + panic("ent: Company is not a transactional entity") + } + c.config.driver = _tx.drv + return c +} + +// String implements the fmt.Stringer. +func (c *Company) String() string { + var builder strings.Builder + builder.WriteString("Company(") + builder.WriteString(fmt.Sprintf("id=%v, ", c.ID)) + builder.WriteString("create_time=") + builder.WriteString(c.CreateTime.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("update_time=") + builder.WriteString(c.UpdateTime.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("delete_time=") + builder.WriteString(c.DeleteTime.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("name=") + builder.WriteString(c.Name) + builder.WriteString(", ") + builder.WriteString("logo_url=") + builder.WriteString(fmt.Sprintf("%v", c.LogoURL)) + builder.WriteString(", ") + builder.WriteString("blog_url=") + builder.WriteString(fmt.Sprintf("%v", c.BlogURL)) + builder.WriteString(", ") + builder.WriteString("rss_url=") + builder.WriteString(fmt.Sprintf("%v", c.RssURL)) + builder.WriteByte(')') + return builder.String() +} + +// Companies is a parsable slice of Company. +type Companies []*Company diff --git a/ent/company/company.go b/ent/company/company.go new file mode 100644 index 0000000..ff7d1d1 --- /dev/null +++ b/ent/company/company.go @@ -0,0 +1,122 @@ +// Code generated by ent, DO NOT EDIT. + +package company + +import ( + "net/url" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/schema/field" +) + +const ( + // Label holds the string label denoting the company type in the database. + Label = "company" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldCreateTime holds the string denoting the create_time field in the database. + FieldCreateTime = "create_time" + // FieldUpdateTime holds the string denoting the update_time field in the database. + FieldUpdateTime = "update_time" + // FieldDeleteTime holds the string denoting the delete_time field in the database. + FieldDeleteTime = "delete_time" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldLogoURL holds the string denoting the logo_url field in the database. + FieldLogoURL = "logo_url" + // FieldBlogURL holds the string denoting the blog_url field in the database. + FieldBlogURL = "blog_url" + // FieldRssURL holds the string denoting the rss_url field in the database. + FieldRssURL = "rss_url" + // Table holds the table name of the company in the database. + Table = "companies" +) + +// Columns holds all SQL columns for company fields. +var Columns = []string{ + FieldID, + FieldCreateTime, + FieldUpdateTime, + FieldDeleteTime, + FieldName, + FieldLogoURL, + FieldBlogURL, + FieldRssURL, +} + +// 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 +} + +// Note that the variables below are initialized by the runtime +// package on the initialization of the application. Therefore, +// it should be imported in the main as follows: +// +// import _ "github.com/techbloghub/server/ent/runtime" +var ( + Hooks [1]ent.Hook + Interceptors [1]ent.Interceptor + // DefaultCreateTime holds the default value on creation for the "create_time" field. + DefaultCreateTime func() time.Time + // DefaultUpdateTime holds the default value on creation for the "update_time" field. + DefaultUpdateTime func() time.Time + // UpdateDefaultUpdateTime holds the default value on update for the "update_time" field. + UpdateDefaultUpdateTime func() time.Time + // ValueScanner of all Company fields. + ValueScanner struct { + LogoURL field.TypeValueScanner[*url.URL] + BlogURL field.TypeValueScanner[*url.URL] + RssURL field.TypeValueScanner[*url.URL] + } +) + +// OrderOption defines the ordering options for the Company 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() +} + +// ByCreateTime orders the results by the create_time field. +func ByCreateTime(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreateTime, opts...).ToFunc() +} + +// ByUpdateTime orders the results by the update_time field. +func ByUpdateTime(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdateTime, opts...).ToFunc() +} + +// ByDeleteTime orders the results by the delete_time field. +func ByDeleteTime(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDeleteTime, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByLogoURL orders the results by the logo_url field. +func ByLogoURL(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLogoURL, opts...).ToFunc() +} + +// ByBlogURL orders the results by the blog_url field. +func ByBlogURL(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBlogURL, opts...).ToFunc() +} + +// ByRssURL orders the results by the rss_url field. +func ByRssURL(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRssURL, opts...).ToFunc() +} diff --git a/ent/company/where.go b/ent/company/where.go new file mode 100644 index 0000000..f29e241 --- /dev/null +++ b/ent/company/where.go @@ -0,0 +1,647 @@ +// Code generated by ent, DO NOT EDIT. + +package company + +import ( + "fmt" + "net/url" + "time" + + "entgo.io/ent/dialect/sql" + "github.com/techbloghub/server/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.Company { + return predicate.Company(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.Company { + return predicate.Company(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.Company { + return predicate.Company(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.Company { + return predicate.Company(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.Company { + return predicate.Company(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.Company { + return predicate.Company(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.Company { + return predicate.Company(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.Company { + return predicate.Company(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.Company { + return predicate.Company(sql.FieldLTE(FieldID, id)) +} + +// CreateTime applies equality check predicate on the "create_time" field. It's identical to CreateTimeEQ. +func CreateTime(v time.Time) predicate.Company { + return predicate.Company(sql.FieldEQ(FieldCreateTime, v)) +} + +// UpdateTime applies equality check predicate on the "update_time" field. It's identical to UpdateTimeEQ. +func UpdateTime(v time.Time) predicate.Company { + return predicate.Company(sql.FieldEQ(FieldUpdateTime, v)) +} + +// DeleteTime applies equality check predicate on the "delete_time" field. It's identical to DeleteTimeEQ. +func DeleteTime(v time.Time) predicate.Company { + return predicate.Company(sql.FieldEQ(FieldDeleteTime, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.Company { + return predicate.Company(sql.FieldEQ(FieldName, v)) +} + +// LogoURL applies equality check predicate on the "logo_url" field. It's identical to LogoURLEQ. +func LogoURL(v *url.URL) predicate.Company { + vc, err := ValueScanner.LogoURL.Value(v) + return predicate.CompanyOrErr(sql.FieldEQ(FieldLogoURL, vc), err) +} + +// BlogURL applies equality check predicate on the "blog_url" field. It's identical to BlogURLEQ. +func BlogURL(v *url.URL) predicate.Company { + vc, err := ValueScanner.BlogURL.Value(v) + return predicate.CompanyOrErr(sql.FieldEQ(FieldBlogURL, vc), err) +} + +// RssURL applies equality check predicate on the "rss_url" field. It's identical to RssURLEQ. +func RssURL(v *url.URL) predicate.Company { + vc, err := ValueScanner.RssURL.Value(v) + return predicate.CompanyOrErr(sql.FieldEQ(FieldRssURL, vc), err) +} + +// CreateTimeEQ applies the EQ predicate on the "create_time" field. +func CreateTimeEQ(v time.Time) predicate.Company { + return predicate.Company(sql.FieldEQ(FieldCreateTime, v)) +} + +// CreateTimeNEQ applies the NEQ predicate on the "create_time" field. +func CreateTimeNEQ(v time.Time) predicate.Company { + return predicate.Company(sql.FieldNEQ(FieldCreateTime, v)) +} + +// CreateTimeIn applies the In predicate on the "create_time" field. +func CreateTimeIn(vs ...time.Time) predicate.Company { + return predicate.Company(sql.FieldIn(FieldCreateTime, vs...)) +} + +// CreateTimeNotIn applies the NotIn predicate on the "create_time" field. +func CreateTimeNotIn(vs ...time.Time) predicate.Company { + return predicate.Company(sql.FieldNotIn(FieldCreateTime, vs...)) +} + +// CreateTimeGT applies the GT predicate on the "create_time" field. +func CreateTimeGT(v time.Time) predicate.Company { + return predicate.Company(sql.FieldGT(FieldCreateTime, v)) +} + +// CreateTimeGTE applies the GTE predicate on the "create_time" field. +func CreateTimeGTE(v time.Time) predicate.Company { + return predicate.Company(sql.FieldGTE(FieldCreateTime, v)) +} + +// CreateTimeLT applies the LT predicate on the "create_time" field. +func CreateTimeLT(v time.Time) predicate.Company { + return predicate.Company(sql.FieldLT(FieldCreateTime, v)) +} + +// CreateTimeLTE applies the LTE predicate on the "create_time" field. +func CreateTimeLTE(v time.Time) predicate.Company { + return predicate.Company(sql.FieldLTE(FieldCreateTime, v)) +} + +// UpdateTimeEQ applies the EQ predicate on the "update_time" field. +func UpdateTimeEQ(v time.Time) predicate.Company { + return predicate.Company(sql.FieldEQ(FieldUpdateTime, v)) +} + +// UpdateTimeNEQ applies the NEQ predicate on the "update_time" field. +func UpdateTimeNEQ(v time.Time) predicate.Company { + return predicate.Company(sql.FieldNEQ(FieldUpdateTime, v)) +} + +// UpdateTimeIn applies the In predicate on the "update_time" field. +func UpdateTimeIn(vs ...time.Time) predicate.Company { + return predicate.Company(sql.FieldIn(FieldUpdateTime, vs...)) +} + +// UpdateTimeNotIn applies the NotIn predicate on the "update_time" field. +func UpdateTimeNotIn(vs ...time.Time) predicate.Company { + return predicate.Company(sql.FieldNotIn(FieldUpdateTime, vs...)) +} + +// UpdateTimeGT applies the GT predicate on the "update_time" field. +func UpdateTimeGT(v time.Time) predicate.Company { + return predicate.Company(sql.FieldGT(FieldUpdateTime, v)) +} + +// UpdateTimeGTE applies the GTE predicate on the "update_time" field. +func UpdateTimeGTE(v time.Time) predicate.Company { + return predicate.Company(sql.FieldGTE(FieldUpdateTime, v)) +} + +// UpdateTimeLT applies the LT predicate on the "update_time" field. +func UpdateTimeLT(v time.Time) predicate.Company { + return predicate.Company(sql.FieldLT(FieldUpdateTime, v)) +} + +// UpdateTimeLTE applies the LTE predicate on the "update_time" field. +func UpdateTimeLTE(v time.Time) predicate.Company { + return predicate.Company(sql.FieldLTE(FieldUpdateTime, v)) +} + +// DeleteTimeEQ applies the EQ predicate on the "delete_time" field. +func DeleteTimeEQ(v time.Time) predicate.Company { + return predicate.Company(sql.FieldEQ(FieldDeleteTime, v)) +} + +// DeleteTimeNEQ applies the NEQ predicate on the "delete_time" field. +func DeleteTimeNEQ(v time.Time) predicate.Company { + return predicate.Company(sql.FieldNEQ(FieldDeleteTime, v)) +} + +// DeleteTimeIn applies the In predicate on the "delete_time" field. +func DeleteTimeIn(vs ...time.Time) predicate.Company { + return predicate.Company(sql.FieldIn(FieldDeleteTime, vs...)) +} + +// DeleteTimeNotIn applies the NotIn predicate on the "delete_time" field. +func DeleteTimeNotIn(vs ...time.Time) predicate.Company { + return predicate.Company(sql.FieldNotIn(FieldDeleteTime, vs...)) +} + +// DeleteTimeGT applies the GT predicate on the "delete_time" field. +func DeleteTimeGT(v time.Time) predicate.Company { + return predicate.Company(sql.FieldGT(FieldDeleteTime, v)) +} + +// DeleteTimeGTE applies the GTE predicate on the "delete_time" field. +func DeleteTimeGTE(v time.Time) predicate.Company { + return predicate.Company(sql.FieldGTE(FieldDeleteTime, v)) +} + +// DeleteTimeLT applies the LT predicate on the "delete_time" field. +func DeleteTimeLT(v time.Time) predicate.Company { + return predicate.Company(sql.FieldLT(FieldDeleteTime, v)) +} + +// DeleteTimeLTE applies the LTE predicate on the "delete_time" field. +func DeleteTimeLTE(v time.Time) predicate.Company { + return predicate.Company(sql.FieldLTE(FieldDeleteTime, v)) +} + +// DeleteTimeIsNil applies the IsNil predicate on the "delete_time" field. +func DeleteTimeIsNil() predicate.Company { + return predicate.Company(sql.FieldIsNull(FieldDeleteTime)) +} + +// DeleteTimeNotNil applies the NotNil predicate on the "delete_time" field. +func DeleteTimeNotNil() predicate.Company { + return predicate.Company(sql.FieldNotNull(FieldDeleteTime)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.Company { + return predicate.Company(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.Company { + return predicate.Company(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.Company { + return predicate.Company(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.Company { + return predicate.Company(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.Company { + return predicate.Company(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.Company { + return predicate.Company(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.Company { + return predicate.Company(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.Company { + return predicate.Company(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.Company { + return predicate.Company(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.Company { + return predicate.Company(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.Company { + return predicate.Company(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.Company { + return predicate.Company(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.Company { + return predicate.Company(sql.FieldContainsFold(FieldName, v)) +} + +// LogoURLEQ applies the EQ predicate on the "logo_url" field. +func LogoURLEQ(v *url.URL) predicate.Company { + vc, err := ValueScanner.LogoURL.Value(v) + return predicate.CompanyOrErr(sql.FieldEQ(FieldLogoURL, vc), err) +} + +// LogoURLNEQ applies the NEQ predicate on the "logo_url" field. +func LogoURLNEQ(v *url.URL) predicate.Company { + vc, err := ValueScanner.LogoURL.Value(v) + return predicate.CompanyOrErr(sql.FieldNEQ(FieldLogoURL, vc), err) +} + +// LogoURLIn applies the In predicate on the "logo_url" field. +func LogoURLIn(vs ...*url.URL) predicate.Company { + var ( + err error + v = make([]any, len(vs)) + ) + for i := range v { + if v[i], err = ValueScanner.LogoURL.Value(vs[i]); err != nil { + break + } + } + return predicate.CompanyOrErr(sql.FieldIn(FieldLogoURL, v...), err) +} + +// LogoURLNotIn applies the NotIn predicate on the "logo_url" field. +func LogoURLNotIn(vs ...*url.URL) predicate.Company { + var ( + err error + v = make([]any, len(vs)) + ) + for i := range v { + if v[i], err = ValueScanner.LogoURL.Value(vs[i]); err != nil { + break + } + } + return predicate.CompanyOrErr(sql.FieldNotIn(FieldLogoURL, v...), err) +} + +// LogoURLGT applies the GT predicate on the "logo_url" field. +func LogoURLGT(v *url.URL) predicate.Company { + vc, err := ValueScanner.LogoURL.Value(v) + return predicate.CompanyOrErr(sql.FieldGT(FieldLogoURL, vc), err) +} + +// LogoURLGTE applies the GTE predicate on the "logo_url" field. +func LogoURLGTE(v *url.URL) predicate.Company { + vc, err := ValueScanner.LogoURL.Value(v) + return predicate.CompanyOrErr(sql.FieldGTE(FieldLogoURL, vc), err) +} + +// LogoURLLT applies the LT predicate on the "logo_url" field. +func LogoURLLT(v *url.URL) predicate.Company { + vc, err := ValueScanner.LogoURL.Value(v) + return predicate.CompanyOrErr(sql.FieldLT(FieldLogoURL, vc), err) +} + +// LogoURLLTE applies the LTE predicate on the "logo_url" field. +func LogoURLLTE(v *url.URL) predicate.Company { + vc, err := ValueScanner.LogoURL.Value(v) + return predicate.CompanyOrErr(sql.FieldLTE(FieldLogoURL, vc), err) +} + +// LogoURLContains applies the Contains predicate on the "logo_url" field. +func LogoURLContains(v *url.URL) predicate.Company { + vc, err := ValueScanner.LogoURL.Value(v) + vcs, ok := vc.(string) + if err == nil && !ok { + err = fmt.Errorf("logo_url value is not a string: %T", vc) + } + return predicate.CompanyOrErr(sql.FieldContains(FieldLogoURL, vcs), err) +} + +// LogoURLHasPrefix applies the HasPrefix predicate on the "logo_url" field. +func LogoURLHasPrefix(v *url.URL) predicate.Company { + vc, err := ValueScanner.LogoURL.Value(v) + vcs, ok := vc.(string) + if err == nil && !ok { + err = fmt.Errorf("logo_url value is not a string: %T", vc) + } + return predicate.CompanyOrErr(sql.FieldHasPrefix(FieldLogoURL, vcs), err) +} + +// LogoURLHasSuffix applies the HasSuffix predicate on the "logo_url" field. +func LogoURLHasSuffix(v *url.URL) predicate.Company { + vc, err := ValueScanner.LogoURL.Value(v) + vcs, ok := vc.(string) + if err == nil && !ok { + err = fmt.Errorf("logo_url value is not a string: %T", vc) + } + return predicate.CompanyOrErr(sql.FieldHasSuffix(FieldLogoURL, vcs), err) +} + +// LogoURLEqualFold applies the EqualFold predicate on the "logo_url" field. +func LogoURLEqualFold(v *url.URL) predicate.Company { + vc, err := ValueScanner.LogoURL.Value(v) + vcs, ok := vc.(string) + if err == nil && !ok { + err = fmt.Errorf("logo_url value is not a string: %T", vc) + } + return predicate.CompanyOrErr(sql.FieldEqualFold(FieldLogoURL, vcs), err) +} + +// LogoURLContainsFold applies the ContainsFold predicate on the "logo_url" field. +func LogoURLContainsFold(v *url.URL) predicate.Company { + vc, err := ValueScanner.LogoURL.Value(v) + vcs, ok := vc.(string) + if err == nil && !ok { + err = fmt.Errorf("logo_url value is not a string: %T", vc) + } + return predicate.CompanyOrErr(sql.FieldContainsFold(FieldLogoURL, vcs), err) +} + +// BlogURLEQ applies the EQ predicate on the "blog_url" field. +func BlogURLEQ(v *url.URL) predicate.Company { + vc, err := ValueScanner.BlogURL.Value(v) + return predicate.CompanyOrErr(sql.FieldEQ(FieldBlogURL, vc), err) +} + +// BlogURLNEQ applies the NEQ predicate on the "blog_url" field. +func BlogURLNEQ(v *url.URL) predicate.Company { + vc, err := ValueScanner.BlogURL.Value(v) + return predicate.CompanyOrErr(sql.FieldNEQ(FieldBlogURL, vc), err) +} + +// BlogURLIn applies the In predicate on the "blog_url" field. +func BlogURLIn(vs ...*url.URL) predicate.Company { + var ( + err error + v = make([]any, len(vs)) + ) + for i := range v { + if v[i], err = ValueScanner.BlogURL.Value(vs[i]); err != nil { + break + } + } + return predicate.CompanyOrErr(sql.FieldIn(FieldBlogURL, v...), err) +} + +// BlogURLNotIn applies the NotIn predicate on the "blog_url" field. +func BlogURLNotIn(vs ...*url.URL) predicate.Company { + var ( + err error + v = make([]any, len(vs)) + ) + for i := range v { + if v[i], err = ValueScanner.BlogURL.Value(vs[i]); err != nil { + break + } + } + return predicate.CompanyOrErr(sql.FieldNotIn(FieldBlogURL, v...), err) +} + +// BlogURLGT applies the GT predicate on the "blog_url" field. +func BlogURLGT(v *url.URL) predicate.Company { + vc, err := ValueScanner.BlogURL.Value(v) + return predicate.CompanyOrErr(sql.FieldGT(FieldBlogURL, vc), err) +} + +// BlogURLGTE applies the GTE predicate on the "blog_url" field. +func BlogURLGTE(v *url.URL) predicate.Company { + vc, err := ValueScanner.BlogURL.Value(v) + return predicate.CompanyOrErr(sql.FieldGTE(FieldBlogURL, vc), err) +} + +// BlogURLLT applies the LT predicate on the "blog_url" field. +func BlogURLLT(v *url.URL) predicate.Company { + vc, err := ValueScanner.BlogURL.Value(v) + return predicate.CompanyOrErr(sql.FieldLT(FieldBlogURL, vc), err) +} + +// BlogURLLTE applies the LTE predicate on the "blog_url" field. +func BlogURLLTE(v *url.URL) predicate.Company { + vc, err := ValueScanner.BlogURL.Value(v) + return predicate.CompanyOrErr(sql.FieldLTE(FieldBlogURL, vc), err) +} + +// BlogURLContains applies the Contains predicate on the "blog_url" field. +func BlogURLContains(v *url.URL) predicate.Company { + vc, err := ValueScanner.BlogURL.Value(v) + vcs, ok := vc.(string) + if err == nil && !ok { + err = fmt.Errorf("blog_url value is not a string: %T", vc) + } + return predicate.CompanyOrErr(sql.FieldContains(FieldBlogURL, vcs), err) +} + +// BlogURLHasPrefix applies the HasPrefix predicate on the "blog_url" field. +func BlogURLHasPrefix(v *url.URL) predicate.Company { + vc, err := ValueScanner.BlogURL.Value(v) + vcs, ok := vc.(string) + if err == nil && !ok { + err = fmt.Errorf("blog_url value is not a string: %T", vc) + } + return predicate.CompanyOrErr(sql.FieldHasPrefix(FieldBlogURL, vcs), err) +} + +// BlogURLHasSuffix applies the HasSuffix predicate on the "blog_url" field. +func BlogURLHasSuffix(v *url.URL) predicate.Company { + vc, err := ValueScanner.BlogURL.Value(v) + vcs, ok := vc.(string) + if err == nil && !ok { + err = fmt.Errorf("blog_url value is not a string: %T", vc) + } + return predicate.CompanyOrErr(sql.FieldHasSuffix(FieldBlogURL, vcs), err) +} + +// BlogURLEqualFold applies the EqualFold predicate on the "blog_url" field. +func BlogURLEqualFold(v *url.URL) predicate.Company { + vc, err := ValueScanner.BlogURL.Value(v) + vcs, ok := vc.(string) + if err == nil && !ok { + err = fmt.Errorf("blog_url value is not a string: %T", vc) + } + return predicate.CompanyOrErr(sql.FieldEqualFold(FieldBlogURL, vcs), err) +} + +// BlogURLContainsFold applies the ContainsFold predicate on the "blog_url" field. +func BlogURLContainsFold(v *url.URL) predicate.Company { + vc, err := ValueScanner.BlogURL.Value(v) + vcs, ok := vc.(string) + if err == nil && !ok { + err = fmt.Errorf("blog_url value is not a string: %T", vc) + } + return predicate.CompanyOrErr(sql.FieldContainsFold(FieldBlogURL, vcs), err) +} + +// RssURLEQ applies the EQ predicate on the "rss_url" field. +func RssURLEQ(v *url.URL) predicate.Company { + vc, err := ValueScanner.RssURL.Value(v) + return predicate.CompanyOrErr(sql.FieldEQ(FieldRssURL, vc), err) +} + +// RssURLNEQ applies the NEQ predicate on the "rss_url" field. +func RssURLNEQ(v *url.URL) predicate.Company { + vc, err := ValueScanner.RssURL.Value(v) + return predicate.CompanyOrErr(sql.FieldNEQ(FieldRssURL, vc), err) +} + +// RssURLIn applies the In predicate on the "rss_url" field. +func RssURLIn(vs ...*url.URL) predicate.Company { + var ( + err error + v = make([]any, len(vs)) + ) + for i := range v { + if v[i], err = ValueScanner.RssURL.Value(vs[i]); err != nil { + break + } + } + return predicate.CompanyOrErr(sql.FieldIn(FieldRssURL, v...), err) +} + +// RssURLNotIn applies the NotIn predicate on the "rss_url" field. +func RssURLNotIn(vs ...*url.URL) predicate.Company { + var ( + err error + v = make([]any, len(vs)) + ) + for i := range v { + if v[i], err = ValueScanner.RssURL.Value(vs[i]); err != nil { + break + } + } + return predicate.CompanyOrErr(sql.FieldNotIn(FieldRssURL, v...), err) +} + +// RssURLGT applies the GT predicate on the "rss_url" field. +func RssURLGT(v *url.URL) predicate.Company { + vc, err := ValueScanner.RssURL.Value(v) + return predicate.CompanyOrErr(sql.FieldGT(FieldRssURL, vc), err) +} + +// RssURLGTE applies the GTE predicate on the "rss_url" field. +func RssURLGTE(v *url.URL) predicate.Company { + vc, err := ValueScanner.RssURL.Value(v) + return predicate.CompanyOrErr(sql.FieldGTE(FieldRssURL, vc), err) +} + +// RssURLLT applies the LT predicate on the "rss_url" field. +func RssURLLT(v *url.URL) predicate.Company { + vc, err := ValueScanner.RssURL.Value(v) + return predicate.CompanyOrErr(sql.FieldLT(FieldRssURL, vc), err) +} + +// RssURLLTE applies the LTE predicate on the "rss_url" field. +func RssURLLTE(v *url.URL) predicate.Company { + vc, err := ValueScanner.RssURL.Value(v) + return predicate.CompanyOrErr(sql.FieldLTE(FieldRssURL, vc), err) +} + +// RssURLContains applies the Contains predicate on the "rss_url" field. +func RssURLContains(v *url.URL) predicate.Company { + vc, err := ValueScanner.RssURL.Value(v) + vcs, ok := vc.(string) + if err == nil && !ok { + err = fmt.Errorf("rss_url value is not a string: %T", vc) + } + return predicate.CompanyOrErr(sql.FieldContains(FieldRssURL, vcs), err) +} + +// RssURLHasPrefix applies the HasPrefix predicate on the "rss_url" field. +func RssURLHasPrefix(v *url.URL) predicate.Company { + vc, err := ValueScanner.RssURL.Value(v) + vcs, ok := vc.(string) + if err == nil && !ok { + err = fmt.Errorf("rss_url value is not a string: %T", vc) + } + return predicate.CompanyOrErr(sql.FieldHasPrefix(FieldRssURL, vcs), err) +} + +// RssURLHasSuffix applies the HasSuffix predicate on the "rss_url" field. +func RssURLHasSuffix(v *url.URL) predicate.Company { + vc, err := ValueScanner.RssURL.Value(v) + vcs, ok := vc.(string) + if err == nil && !ok { + err = fmt.Errorf("rss_url value is not a string: %T", vc) + } + return predicate.CompanyOrErr(sql.FieldHasSuffix(FieldRssURL, vcs), err) +} + +// RssURLEqualFold applies the EqualFold predicate on the "rss_url" field. +func RssURLEqualFold(v *url.URL) predicate.Company { + vc, err := ValueScanner.RssURL.Value(v) + vcs, ok := vc.(string) + if err == nil && !ok { + err = fmt.Errorf("rss_url value is not a string: %T", vc) + } + return predicate.CompanyOrErr(sql.FieldEqualFold(FieldRssURL, vcs), err) +} + +// RssURLContainsFold applies the ContainsFold predicate on the "rss_url" field. +func RssURLContainsFold(v *url.URL) predicate.Company { + vc, err := ValueScanner.RssURL.Value(v) + vcs, ok := vc.(string) + if err == nil && !ok { + err = fmt.Errorf("rss_url value is not a string: %T", vc) + } + return predicate.CompanyOrErr(sql.FieldContainsFold(FieldRssURL, vcs), err) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Company) predicate.Company { + return predicate.Company(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Company) predicate.Company { + return predicate.Company(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Company) predicate.Company { + return predicate.Company(sql.NotPredicates(p)) +} diff --git a/ent/company_create.go b/ent/company_create.go new file mode 100644 index 0000000..6cc933b --- /dev/null +++ b/ent/company_create.go @@ -0,0 +1,325 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "net/url" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/techbloghub/server/ent/company" +) + +// CompanyCreate is the builder for creating a Company entity. +type CompanyCreate struct { + config + mutation *CompanyMutation + hooks []Hook +} + +// SetCreateTime sets the "create_time" field. +func (cc *CompanyCreate) SetCreateTime(t time.Time) *CompanyCreate { + cc.mutation.SetCreateTime(t) + return cc +} + +// SetNillableCreateTime sets the "create_time" field if the given value is not nil. +func (cc *CompanyCreate) SetNillableCreateTime(t *time.Time) *CompanyCreate { + if t != nil { + cc.SetCreateTime(*t) + } + return cc +} + +// SetUpdateTime sets the "update_time" field. +func (cc *CompanyCreate) SetUpdateTime(t time.Time) *CompanyCreate { + cc.mutation.SetUpdateTime(t) + return cc +} + +// SetNillableUpdateTime sets the "update_time" field if the given value is not nil. +func (cc *CompanyCreate) SetNillableUpdateTime(t *time.Time) *CompanyCreate { + if t != nil { + cc.SetUpdateTime(*t) + } + return cc +} + +// SetDeleteTime sets the "delete_time" field. +func (cc *CompanyCreate) SetDeleteTime(t time.Time) *CompanyCreate { + cc.mutation.SetDeleteTime(t) + return cc +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (cc *CompanyCreate) SetNillableDeleteTime(t *time.Time) *CompanyCreate { + if t != nil { + cc.SetDeleteTime(*t) + } + return cc +} + +// SetName sets the "name" field. +func (cc *CompanyCreate) SetName(s string) *CompanyCreate { + cc.mutation.SetName(s) + return cc +} + +// SetLogoURL sets the "logo_url" field. +func (cc *CompanyCreate) SetLogoURL(u *url.URL) *CompanyCreate { + cc.mutation.SetLogoURL(u) + return cc +} + +// SetBlogURL sets the "blog_url" field. +func (cc *CompanyCreate) SetBlogURL(u *url.URL) *CompanyCreate { + cc.mutation.SetBlogURL(u) + return cc +} + +// SetRssURL sets the "rss_url" field. +func (cc *CompanyCreate) SetRssURL(u *url.URL) *CompanyCreate { + cc.mutation.SetRssURL(u) + return cc +} + +// Mutation returns the CompanyMutation object of the builder. +func (cc *CompanyCreate) Mutation() *CompanyMutation { + return cc.mutation +} + +// Save creates the Company in the database. +func (cc *CompanyCreate) Save(ctx context.Context) (*Company, error) { + if err := cc.defaults(); err != nil { + return nil, err + } + return withHooks(ctx, cc.sqlSave, cc.mutation, cc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (cc *CompanyCreate) SaveX(ctx context.Context) *Company { + v, err := cc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (cc *CompanyCreate) Exec(ctx context.Context) error { + _, err := cc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (cc *CompanyCreate) ExecX(ctx context.Context) { + if err := cc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (cc *CompanyCreate) defaults() error { + if _, ok := cc.mutation.CreateTime(); !ok { + if company.DefaultCreateTime == nil { + return fmt.Errorf("ent: uninitialized company.DefaultCreateTime (forgotten import ent/runtime?)") + } + v := company.DefaultCreateTime() + cc.mutation.SetCreateTime(v) + } + if _, ok := cc.mutation.UpdateTime(); !ok { + if company.DefaultUpdateTime == nil { + return fmt.Errorf("ent: uninitialized company.DefaultUpdateTime (forgotten import ent/runtime?)") + } + v := company.DefaultUpdateTime() + cc.mutation.SetUpdateTime(v) + } + return nil +} + +// check runs all checks and user-defined validators on the builder. +func (cc *CompanyCreate) check() error { + if _, ok := cc.mutation.CreateTime(); !ok { + return &ValidationError{Name: "create_time", err: errors.New(`ent: missing required field "Company.create_time"`)} + } + if _, ok := cc.mutation.UpdateTime(); !ok { + return &ValidationError{Name: "update_time", err: errors.New(`ent: missing required field "Company.update_time"`)} + } + if _, ok := cc.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Company.name"`)} + } + if _, ok := cc.mutation.LogoURL(); !ok { + return &ValidationError{Name: "logo_url", err: errors.New(`ent: missing required field "Company.logo_url"`)} + } + if _, ok := cc.mutation.BlogURL(); !ok { + return &ValidationError{Name: "blog_url", err: errors.New(`ent: missing required field "Company.blog_url"`)} + } + if _, ok := cc.mutation.RssURL(); !ok { + return &ValidationError{Name: "rss_url", err: errors.New(`ent: missing required field "Company.rss_url"`)} + } + return nil +} + +func (cc *CompanyCreate) sqlSave(ctx context.Context) (*Company, error) { + if err := cc.check(); err != nil { + return nil, err + } + _node, _spec, err := cc.createSpec() + if err != nil { + return nil, err + } + if err := sqlgraph.CreateNode(ctx, cc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + cc.mutation.id = &_node.ID + cc.mutation.done = true + return _node, nil +} + +func (cc *CompanyCreate) createSpec() (*Company, *sqlgraph.CreateSpec, error) { + var ( + _node = &Company{config: cc.config} + _spec = sqlgraph.NewCreateSpec(company.Table, sqlgraph.NewFieldSpec(company.FieldID, field.TypeInt)) + ) + if value, ok := cc.mutation.CreateTime(); ok { + _spec.SetField(company.FieldCreateTime, field.TypeTime, value) + _node.CreateTime = value + } + if value, ok := cc.mutation.UpdateTime(); ok { + _spec.SetField(company.FieldUpdateTime, field.TypeTime, value) + _node.UpdateTime = value + } + if value, ok := cc.mutation.DeleteTime(); ok { + _spec.SetField(company.FieldDeleteTime, field.TypeTime, value) + _node.DeleteTime = value + } + if value, ok := cc.mutation.Name(); ok { + _spec.SetField(company.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := cc.mutation.LogoURL(); ok { + vv, err := company.ValueScanner.LogoURL.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(company.FieldLogoURL, field.TypeString, vv) + _node.LogoURL = value + } + if value, ok := cc.mutation.BlogURL(); ok { + vv, err := company.ValueScanner.BlogURL.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(company.FieldBlogURL, field.TypeString, vv) + _node.BlogURL = value + } + if value, ok := cc.mutation.RssURL(); ok { + vv, err := company.ValueScanner.RssURL.Value(value) + if err != nil { + return nil, nil, err + } + _spec.SetField(company.FieldRssURL, field.TypeString, vv) + _node.RssURL = value + } + return _node, _spec, nil +} + +// CompanyCreateBulk is the builder for creating many Company entities in bulk. +type CompanyCreateBulk struct { + config + err error + builders []*CompanyCreate +} + +// Save creates the Company entities in the database. +func (ccb *CompanyCreateBulk) Save(ctx context.Context) ([]*Company, error) { + if ccb.err != nil { + return nil, ccb.err + } + specs := make([]*sqlgraph.CreateSpec, len(ccb.builders)) + nodes := make([]*Company, len(ccb.builders)) + mutators := make([]Mutator, len(ccb.builders)) + for i := range ccb.builders { + func(i int, root context.Context) { + builder := ccb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*CompanyMutation) + 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], err = builder.createSpec() + if err != nil { + return nil, err + } + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, ccb.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, ccb.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 + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(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, ccb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (ccb *CompanyCreateBulk) SaveX(ctx context.Context) []*Company { + v, err := ccb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ccb *CompanyCreateBulk) Exec(ctx context.Context) error { + _, err := ccb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ccb *CompanyCreateBulk) ExecX(ctx context.Context) { + if err := ccb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/company_delete.go b/ent/company_delete.go new file mode 100644 index 0000000..db84d90 --- /dev/null +++ b/ent/company_delete.go @@ -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/techbloghub/server/ent/company" + "github.com/techbloghub/server/ent/predicate" +) + +// CompanyDelete is the builder for deleting a Company entity. +type CompanyDelete struct { + config + hooks []Hook + mutation *CompanyMutation +} + +// Where appends a list predicates to the CompanyDelete builder. +func (cd *CompanyDelete) Where(ps ...predicate.Company) *CompanyDelete { + cd.mutation.Where(ps...) + return cd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (cd *CompanyDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, cd.sqlExec, cd.mutation, cd.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (cd *CompanyDelete) ExecX(ctx context.Context) int { + n, err := cd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (cd *CompanyDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(company.Table, sqlgraph.NewFieldSpec(company.FieldID, field.TypeInt)) + if ps := cd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, cd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + cd.mutation.done = true + return affected, err +} + +// CompanyDeleteOne is the builder for deleting a single Company entity. +type CompanyDeleteOne struct { + cd *CompanyDelete +} + +// Where appends a list predicates to the CompanyDelete builder. +func (cdo *CompanyDeleteOne) Where(ps ...predicate.Company) *CompanyDeleteOne { + cdo.cd.mutation.Where(ps...) + return cdo +} + +// Exec executes the deletion query. +func (cdo *CompanyDeleteOne) Exec(ctx context.Context) error { + n, err := cdo.cd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{company.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (cdo *CompanyDeleteOne) ExecX(ctx context.Context) { + if err := cdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/company_query.go b/ent/company_query.go new file mode 100644 index 0000000..b5b3d74 --- /dev/null +++ b/ent/company_query.go @@ -0,0 +1,527 @@ +// 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/techbloghub/server/ent/company" + "github.com/techbloghub/server/ent/predicate" +) + +// CompanyQuery is the builder for querying Company entities. +type CompanyQuery struct { + config + ctx *QueryContext + order []company.OrderOption + inters []Interceptor + predicates []predicate.Company + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the CompanyQuery builder. +func (cq *CompanyQuery) Where(ps ...predicate.Company) *CompanyQuery { + cq.predicates = append(cq.predicates, ps...) + return cq +} + +// Limit the number of records to be returned by this query. +func (cq *CompanyQuery) Limit(limit int) *CompanyQuery { + cq.ctx.Limit = &limit + return cq +} + +// Offset to start from. +func (cq *CompanyQuery) Offset(offset int) *CompanyQuery { + cq.ctx.Offset = &offset + return cq +} + +// 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 (cq *CompanyQuery) Unique(unique bool) *CompanyQuery { + cq.ctx.Unique = &unique + return cq +} + +// Order specifies how the records should be ordered. +func (cq *CompanyQuery) Order(o ...company.OrderOption) *CompanyQuery { + cq.order = append(cq.order, o...) + return cq +} + +// First returns the first Company entity from the query. +// Returns a *NotFoundError when no Company was found. +func (cq *CompanyQuery) First(ctx context.Context) (*Company, error) { + nodes, err := cq.Limit(1).All(setContextOp(ctx, cq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{company.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (cq *CompanyQuery) FirstX(ctx context.Context) *Company { + node, err := cq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Company ID from the query. +// Returns a *NotFoundError when no Company ID was found. +func (cq *CompanyQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = cq.Limit(1).IDs(setContextOp(ctx, cq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{company.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (cq *CompanyQuery) FirstIDX(ctx context.Context) int { + id, err := cq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Company entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Company entity is found. +// Returns a *NotFoundError when no Company entities are found. +func (cq *CompanyQuery) Only(ctx context.Context) (*Company, error) { + nodes, err := cq.Limit(2).All(setContextOp(ctx, cq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{company.Label} + default: + return nil, &NotSingularError{company.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (cq *CompanyQuery) OnlyX(ctx context.Context) *Company { + node, err := cq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Company ID in the query. +// Returns a *NotSingularError when more than one Company ID is found. +// Returns a *NotFoundError when no entities are found. +func (cq *CompanyQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = cq.Limit(2).IDs(setContextOp(ctx, cq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{company.Label} + default: + err = &NotSingularError{company.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (cq *CompanyQuery) OnlyIDX(ctx context.Context) int { + id, err := cq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Companies. +func (cq *CompanyQuery) All(ctx context.Context) ([]*Company, error) { + ctx = setContextOp(ctx, cq.ctx, ent.OpQueryAll) + if err := cq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Company, *CompanyQuery]() + return withInterceptors[[]*Company](ctx, cq, qr, cq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (cq *CompanyQuery) AllX(ctx context.Context) []*Company { + nodes, err := cq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Company IDs. +func (cq *CompanyQuery) IDs(ctx context.Context) (ids []int, err error) { + if cq.ctx.Unique == nil && cq.path != nil { + cq.Unique(true) + } + ctx = setContextOp(ctx, cq.ctx, ent.OpQueryIDs) + if err = cq.Select(company.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (cq *CompanyQuery) IDsX(ctx context.Context) []int { + ids, err := cq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (cq *CompanyQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, cq.ctx, ent.OpQueryCount) + if err := cq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, cq, querierCount[*CompanyQuery](), cq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (cq *CompanyQuery) CountX(ctx context.Context) int { + count, err := cq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (cq *CompanyQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, cq.ctx, ent.OpQueryExist) + switch _, err := cq.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 (cq *CompanyQuery) ExistX(ctx context.Context) bool { + exist, err := cq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the CompanyQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (cq *CompanyQuery) Clone() *CompanyQuery { + if cq == nil { + return nil + } + return &CompanyQuery{ + config: cq.config, + ctx: cq.ctx.Clone(), + order: append([]company.OrderOption{}, cq.order...), + inters: append([]Interceptor{}, cq.inters...), + predicates: append([]predicate.Company{}, cq.predicates...), + // clone intermediate query. + sql: cq.sql.Clone(), + path: cq.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 { +// CreateTime time.Time `json:"create_time,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Company.Query(). +// GroupBy(company.FieldCreateTime). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (cq *CompanyQuery) GroupBy(field string, fields ...string) *CompanyGroupBy { + cq.ctx.Fields = append([]string{field}, fields...) + grbuild := &CompanyGroupBy{build: cq} + grbuild.flds = &cq.ctx.Fields + grbuild.label = company.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 { +// CreateTime time.Time `json:"create_time,omitempty"` +// } +// +// client.Company.Query(). +// Select(company.FieldCreateTime). +// Scan(ctx, &v) +func (cq *CompanyQuery) Select(fields ...string) *CompanySelect { + cq.ctx.Fields = append(cq.ctx.Fields, fields...) + sbuild := &CompanySelect{CompanyQuery: cq} + sbuild.label = company.Label + sbuild.flds, sbuild.scan = &cq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a CompanySelect configured with the given aggregations. +func (cq *CompanyQuery) Aggregate(fns ...AggregateFunc) *CompanySelect { + return cq.Select().Aggregate(fns...) +} + +func (cq *CompanyQuery) prepareQuery(ctx context.Context) error { + for _, inter := range cq.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, cq); err != nil { + return err + } + } + } + for _, f := range cq.ctx.Fields { + if !company.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if cq.path != nil { + prev, err := cq.path(ctx) + if err != nil { + return err + } + cq.sql = prev + } + return nil +} + +func (cq *CompanyQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Company, error) { + var ( + nodes = []*Company{} + _spec = cq.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Company).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Company{config: cq.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, cq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (cq *CompanyQuery) sqlCount(ctx context.Context) (int, error) { + _spec := cq.querySpec() + _spec.Node.Columns = cq.ctx.Fields + if len(cq.ctx.Fields) > 0 { + _spec.Unique = cq.ctx.Unique != nil && *cq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, cq.driver, _spec) +} + +func (cq *CompanyQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(company.Table, company.Columns, sqlgraph.NewFieldSpec(company.FieldID, field.TypeInt)) + _spec.From = cq.sql + if unique := cq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if cq.path != nil { + _spec.Unique = true + } + if fields := cq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, company.FieldID) + for i := range fields { + if fields[i] != company.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := cq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := cq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := cq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := cq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (cq *CompanyQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(cq.driver.Dialect()) + t1 := builder.Table(company.Table) + columns := cq.ctx.Fields + if len(columns) == 0 { + columns = company.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if cq.sql != nil { + selector = cq.sql + selector.Select(selector.Columns(columns...)...) + } + if cq.ctx.Unique != nil && *cq.ctx.Unique { + selector.Distinct() + } + for _, p := range cq.predicates { + p(selector) + } + for _, p := range cq.order { + p(selector) + } + if offset := cq.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 := cq.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// CompanyGroupBy is the group-by builder for Company entities. +type CompanyGroupBy struct { + selector + build *CompanyQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (cgb *CompanyGroupBy) Aggregate(fns ...AggregateFunc) *CompanyGroupBy { + cgb.fns = append(cgb.fns, fns...) + return cgb +} + +// Scan applies the selector query and scans the result into the given value. +func (cgb *CompanyGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, cgb.build.ctx, ent.OpQueryGroupBy) + if err := cgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*CompanyQuery, *CompanyGroupBy](ctx, cgb.build, cgb, cgb.build.inters, v) +} + +func (cgb *CompanyGroupBy) sqlScan(ctx context.Context, root *CompanyQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(cgb.fns)) + for _, fn := range cgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*cgb.flds)+len(cgb.fns)) + for _, f := range *cgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*cgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := cgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// CompanySelect is the builder for selecting fields of Company entities. +type CompanySelect struct { + *CompanyQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (cs *CompanySelect) Aggregate(fns ...AggregateFunc) *CompanySelect { + cs.fns = append(cs.fns, fns...) + return cs +} + +// Scan applies the selector query and scans the result into the given value. +func (cs *CompanySelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, cs.ctx, ent.OpQuerySelect) + if err := cs.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*CompanyQuery, *CompanySelect](ctx, cs.CompanyQuery, cs, cs.inters, v) +} + +func (cs *CompanySelect) sqlScan(ctx context.Context, root *CompanyQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(cs.fns)) + for _, fn := range cs.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*cs.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 := cs.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/ent/company_update.go b/ent/company_update.go new file mode 100644 index 0000000..3c7817a --- /dev/null +++ b/ent/company_update.go @@ -0,0 +1,389 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "net/url" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/techbloghub/server/ent/company" + "github.com/techbloghub/server/ent/predicate" +) + +// CompanyUpdate is the builder for updating Company entities. +type CompanyUpdate struct { + config + hooks []Hook + mutation *CompanyMutation +} + +// Where appends a list predicates to the CompanyUpdate builder. +func (cu *CompanyUpdate) Where(ps ...predicate.Company) *CompanyUpdate { + cu.mutation.Where(ps...) + return cu +} + +// SetUpdateTime sets the "update_time" field. +func (cu *CompanyUpdate) SetUpdateTime(t time.Time) *CompanyUpdate { + cu.mutation.SetUpdateTime(t) + return cu +} + +// SetDeleteTime sets the "delete_time" field. +func (cu *CompanyUpdate) SetDeleteTime(t time.Time) *CompanyUpdate { + cu.mutation.SetDeleteTime(t) + return cu +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (cu *CompanyUpdate) SetNillableDeleteTime(t *time.Time) *CompanyUpdate { + if t != nil { + cu.SetDeleteTime(*t) + } + return cu +} + +// ClearDeleteTime clears the value of the "delete_time" field. +func (cu *CompanyUpdate) ClearDeleteTime() *CompanyUpdate { + cu.mutation.ClearDeleteTime() + return cu +} + +// SetName sets the "name" field. +func (cu *CompanyUpdate) SetName(s string) *CompanyUpdate { + cu.mutation.SetName(s) + return cu +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (cu *CompanyUpdate) SetNillableName(s *string) *CompanyUpdate { + if s != nil { + cu.SetName(*s) + } + return cu +} + +// SetLogoURL sets the "logo_url" field. +func (cu *CompanyUpdate) SetLogoURL(u *url.URL) *CompanyUpdate { + cu.mutation.SetLogoURL(u) + return cu +} + +// SetBlogURL sets the "blog_url" field. +func (cu *CompanyUpdate) SetBlogURL(u *url.URL) *CompanyUpdate { + cu.mutation.SetBlogURL(u) + return cu +} + +// SetRssURL sets the "rss_url" field. +func (cu *CompanyUpdate) SetRssURL(u *url.URL) *CompanyUpdate { + cu.mutation.SetRssURL(u) + return cu +} + +// Mutation returns the CompanyMutation object of the builder. +func (cu *CompanyUpdate) Mutation() *CompanyMutation { + return cu.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (cu *CompanyUpdate) Save(ctx context.Context) (int, error) { + if err := cu.defaults(); err != nil { + return 0, err + } + return withHooks(ctx, cu.sqlSave, cu.mutation, cu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (cu *CompanyUpdate) SaveX(ctx context.Context) int { + affected, err := cu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (cu *CompanyUpdate) Exec(ctx context.Context) error { + _, err := cu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (cu *CompanyUpdate) ExecX(ctx context.Context) { + if err := cu.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (cu *CompanyUpdate) defaults() error { + if _, ok := cu.mutation.UpdateTime(); !ok { + if company.UpdateDefaultUpdateTime == nil { + return fmt.Errorf("ent: uninitialized company.UpdateDefaultUpdateTime (forgotten import ent/runtime?)") + } + v := company.UpdateDefaultUpdateTime() + cu.mutation.SetUpdateTime(v) + } + return nil +} + +func (cu *CompanyUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := sqlgraph.NewUpdateSpec(company.Table, company.Columns, sqlgraph.NewFieldSpec(company.FieldID, field.TypeInt)) + if ps := cu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := cu.mutation.UpdateTime(); ok { + _spec.SetField(company.FieldUpdateTime, field.TypeTime, value) + } + if value, ok := cu.mutation.DeleteTime(); ok { + _spec.SetField(company.FieldDeleteTime, field.TypeTime, value) + } + if cu.mutation.DeleteTimeCleared() { + _spec.ClearField(company.FieldDeleteTime, field.TypeTime) + } + if value, ok := cu.mutation.Name(); ok { + _spec.SetField(company.FieldName, field.TypeString, value) + } + if value, ok := cu.mutation.LogoURL(); ok { + vv, err := company.ValueScanner.LogoURL.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(company.FieldLogoURL, field.TypeString, vv) + } + if value, ok := cu.mutation.BlogURL(); ok { + vv, err := company.ValueScanner.BlogURL.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(company.FieldBlogURL, field.TypeString, vv) + } + if value, ok := cu.mutation.RssURL(); ok { + vv, err := company.ValueScanner.RssURL.Value(value) + if err != nil { + return 0, err + } + _spec.SetField(company.FieldRssURL, field.TypeString, vv) + } + if n, err = sqlgraph.UpdateNodes(ctx, cu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{company.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + cu.mutation.done = true + return n, nil +} + +// CompanyUpdateOne is the builder for updating a single Company entity. +type CompanyUpdateOne struct { + config + fields []string + hooks []Hook + mutation *CompanyMutation +} + +// SetUpdateTime sets the "update_time" field. +func (cuo *CompanyUpdateOne) SetUpdateTime(t time.Time) *CompanyUpdateOne { + cuo.mutation.SetUpdateTime(t) + return cuo +} + +// SetDeleteTime sets the "delete_time" field. +func (cuo *CompanyUpdateOne) SetDeleteTime(t time.Time) *CompanyUpdateOne { + cuo.mutation.SetDeleteTime(t) + return cuo +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (cuo *CompanyUpdateOne) SetNillableDeleteTime(t *time.Time) *CompanyUpdateOne { + if t != nil { + cuo.SetDeleteTime(*t) + } + return cuo +} + +// ClearDeleteTime clears the value of the "delete_time" field. +func (cuo *CompanyUpdateOne) ClearDeleteTime() *CompanyUpdateOne { + cuo.mutation.ClearDeleteTime() + return cuo +} + +// SetName sets the "name" field. +func (cuo *CompanyUpdateOne) SetName(s string) *CompanyUpdateOne { + cuo.mutation.SetName(s) + return cuo +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (cuo *CompanyUpdateOne) SetNillableName(s *string) *CompanyUpdateOne { + if s != nil { + cuo.SetName(*s) + } + return cuo +} + +// SetLogoURL sets the "logo_url" field. +func (cuo *CompanyUpdateOne) SetLogoURL(u *url.URL) *CompanyUpdateOne { + cuo.mutation.SetLogoURL(u) + return cuo +} + +// SetBlogURL sets the "blog_url" field. +func (cuo *CompanyUpdateOne) SetBlogURL(u *url.URL) *CompanyUpdateOne { + cuo.mutation.SetBlogURL(u) + return cuo +} + +// SetRssURL sets the "rss_url" field. +func (cuo *CompanyUpdateOne) SetRssURL(u *url.URL) *CompanyUpdateOne { + cuo.mutation.SetRssURL(u) + return cuo +} + +// Mutation returns the CompanyMutation object of the builder. +func (cuo *CompanyUpdateOne) Mutation() *CompanyMutation { + return cuo.mutation +} + +// Where appends a list predicates to the CompanyUpdate builder. +func (cuo *CompanyUpdateOne) Where(ps ...predicate.Company) *CompanyUpdateOne { + cuo.mutation.Where(ps...) + return cuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (cuo *CompanyUpdateOne) Select(field string, fields ...string) *CompanyUpdateOne { + cuo.fields = append([]string{field}, fields...) + return cuo +} + +// Save executes the query and returns the updated Company entity. +func (cuo *CompanyUpdateOne) Save(ctx context.Context) (*Company, error) { + if err := cuo.defaults(); err != nil { + return nil, err + } + return withHooks(ctx, cuo.sqlSave, cuo.mutation, cuo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (cuo *CompanyUpdateOne) SaveX(ctx context.Context) *Company { + node, err := cuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (cuo *CompanyUpdateOne) Exec(ctx context.Context) error { + _, err := cuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (cuo *CompanyUpdateOne) ExecX(ctx context.Context) { + if err := cuo.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (cuo *CompanyUpdateOne) defaults() error { + if _, ok := cuo.mutation.UpdateTime(); !ok { + if company.UpdateDefaultUpdateTime == nil { + return fmt.Errorf("ent: uninitialized company.UpdateDefaultUpdateTime (forgotten import ent/runtime?)") + } + v := company.UpdateDefaultUpdateTime() + cuo.mutation.SetUpdateTime(v) + } + return nil +} + +func (cuo *CompanyUpdateOne) sqlSave(ctx context.Context) (_node *Company, err error) { + _spec := sqlgraph.NewUpdateSpec(company.Table, company.Columns, sqlgraph.NewFieldSpec(company.FieldID, field.TypeInt)) + id, ok := cuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Company.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := cuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, company.FieldID) + for _, f := range fields { + if !company.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != company.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := cuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := cuo.mutation.UpdateTime(); ok { + _spec.SetField(company.FieldUpdateTime, field.TypeTime, value) + } + if value, ok := cuo.mutation.DeleteTime(); ok { + _spec.SetField(company.FieldDeleteTime, field.TypeTime, value) + } + if cuo.mutation.DeleteTimeCleared() { + _spec.ClearField(company.FieldDeleteTime, field.TypeTime) + } + if value, ok := cuo.mutation.Name(); ok { + _spec.SetField(company.FieldName, field.TypeString, value) + } + if value, ok := cuo.mutation.LogoURL(); ok { + vv, err := company.ValueScanner.LogoURL.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(company.FieldLogoURL, field.TypeString, vv) + } + if value, ok := cuo.mutation.BlogURL(); ok { + vv, err := company.ValueScanner.BlogURL.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(company.FieldBlogURL, field.TypeString, vv) + } + if value, ok := cuo.mutation.RssURL(); ok { + vv, err := company.ValueScanner.RssURL.Value(value) + if err != nil { + return nil, err + } + _spec.SetField(company.FieldRssURL, field.TypeString, vv) + } + _node = &Company{config: cuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, cuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{company.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + cuo.mutation.done = true + return _node, nil +} diff --git a/ent/ent.go b/ent/ent.go new file mode 100644 index 0000000..97a5bf2 --- /dev/null +++ b/ent/ent.go @@ -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/techbloghub/server/ent/company" +) + +// 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(table, column string) error { + initCheck.Do(func() { + columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ + company.Table: company.ValidColumn, + }) + }) + return columnCheck(table, column) +} + +// 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) diff --git a/ent/enttest/enttest.go b/ent/enttest/enttest.go new file mode 100644 index 0000000..9666320 --- /dev/null +++ b/ent/enttest/enttest.go @@ -0,0 +1,84 @@ +// Code generated by ent, DO NOT EDIT. + +package enttest + +import ( + "context" + + "github.com/techbloghub/server/ent" + // required by schema hooks. + _ "github.com/techbloghub/server/ent/runtime" + + "entgo.io/ent/dialect/sql/schema" + "github.com/techbloghub/server/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() + } +} diff --git a/ent/generate.go b/ent/generate.go new file mode 100644 index 0000000..95913ea --- /dev/null +++ b/ent/generate.go @@ -0,0 +1,3 @@ +package ent + +//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate --feature intercept,schema/snapshot ./schema diff --git a/ent/hook/hook.go b/ent/hook/hook.go new file mode 100644 index 0000000..0324e15 --- /dev/null +++ b/ent/hook/hook.go @@ -0,0 +1,199 @@ +// Code generated by ent, DO NOT EDIT. + +package hook + +import ( + "context" + "fmt" + + "github.com/techbloghub/server/ent" +) + +// The CompanyFunc type is an adapter to allow the use of ordinary +// function as Company mutator. +type CompanyFunc func(context.Context, *ent.CompanyMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f CompanyFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.CompanyMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.CompanyMutation", 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...) +} diff --git a/ent/intercept/intercept.go b/ent/intercept/intercept.go new file mode 100644 index 0000000..5da194c --- /dev/null +++ b/ent/intercept/intercept.go @@ -0,0 +1,149 @@ +// Code generated by ent, DO NOT EDIT. + +package intercept + +import ( + "context" + "fmt" + + "entgo.io/ent/dialect/sql" + "github.com/techbloghub/server/ent" + "github.com/techbloghub/server/ent/company" + "github.com/techbloghub/server/ent/predicate" +) + +// The Query interface represents an operation that queries a graph. +// By using this interface, users can write generic code that manipulates +// query builders of different types. +type Query interface { + // Type returns the string representation of the query type. + Type() string + // Limit the number of records to be returned by this query. + Limit(int) + // Offset to start from. + Offset(int) + // Unique configures the query builder to filter duplicate records. + Unique(bool) + // Order specifies how the records should be ordered. + Order(...func(*sql.Selector)) + // WhereP appends storage-level predicates to the query builder. Using this method, users + // can use type-assertion to append predicates that do not depend on any generated package. + WhereP(...func(*sql.Selector)) +} + +// The Func type is an adapter that allows ordinary functions to be used as interceptors. +// Unlike traversal functions, interceptors are skipped during graph traversals. Note that the +// implementation of Func is different from the one defined in entgo.io/ent.InterceptFunc. +type Func func(context.Context, Query) error + +// Intercept calls f(ctx, q) and then applied the next Querier. +func (f Func) Intercept(next ent.Querier) ent.Querier { + return ent.QuerierFunc(func(ctx context.Context, q ent.Query) (ent.Value, error) { + query, err := NewQuery(q) + if err != nil { + return nil, err + } + if err := f(ctx, query); err != nil { + return nil, err + } + return next.Query(ctx, q) + }) +} + +// The TraverseFunc type is an adapter to allow the use of ordinary function as Traverser. +// If f is a function with the appropriate signature, TraverseFunc(f) is a Traverser that calls f. +type TraverseFunc func(context.Context, Query) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseFunc) Intercept(next ent.Querier) ent.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseFunc) Traverse(ctx context.Context, q ent.Query) error { + query, err := NewQuery(q) + if err != nil { + return err + } + return f(ctx, query) +} + +// The CompanyFunc type is an adapter to allow the use of ordinary function as a Querier. +type CompanyFunc func(context.Context, *ent.CompanyQuery) (ent.Value, error) + +// Query calls f(ctx, q). +func (f CompanyFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) { + if q, ok := q.(*ent.CompanyQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *ent.CompanyQuery", q) +} + +// The TraverseCompany type is an adapter to allow the use of ordinary function as Traverser. +type TraverseCompany func(context.Context, *ent.CompanyQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseCompany) Intercept(next ent.Querier) ent.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseCompany) Traverse(ctx context.Context, q ent.Query) error { + if q, ok := q.(*ent.CompanyQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *ent.CompanyQuery", q) +} + +// NewQuery returns the generic Query interface for the given typed query. +func NewQuery(q ent.Query) (Query, error) { + switch q := q.(type) { + case *ent.CompanyQuery: + return &query[*ent.CompanyQuery, predicate.Company, company.OrderOption]{typ: ent.TypeCompany, tq: q}, nil + default: + return nil, fmt.Errorf("unknown query type %T", q) + } +} + +type query[T any, P ~func(*sql.Selector), R ~func(*sql.Selector)] struct { + typ string + tq interface { + Limit(int) T + Offset(int) T + Unique(bool) T + Order(...R) T + Where(...P) T + } +} + +func (q query[T, P, R]) Type() string { + return q.typ +} + +func (q query[T, P, R]) Limit(limit int) { + q.tq.Limit(limit) +} + +func (q query[T, P, R]) Offset(offset int) { + q.tq.Offset(offset) +} + +func (q query[T, P, R]) Unique(unique bool) { + q.tq.Unique(unique) +} + +func (q query[T, P, R]) Order(orders ...func(*sql.Selector)) { + rs := make([]R, len(orders)) + for i := range orders { + rs[i] = orders[i] + } + q.tq.Order(rs...) +} + +func (q query[T, P, R]) WhereP(ps ...func(*sql.Selector)) { + p := make([]P, len(ps)) + for i := range ps { + p[i] = ps[i] + } + q.tq.Where(p...) +} diff --git a/ent/internal/schema.go b/ent/internal/schema.go new file mode 100644 index 0000000..7e5fa82 --- /dev/null +++ b/ent/internal/schema.go @@ -0,0 +1,9 @@ +// Code generated by ent, DO NOT EDIT. + +//go:build tools +// +build tools + +// Package internal holds a loadable version of the latest schema. +package internal + +const Schema = "{\"Schema\":\"github.com/techbloghub/server/ent/schema\",\"Package\":\"github.com/techbloghub/server/ent\",\"Schemas\":[{\"name\":\"Company\",\"config\":{\"Table\":\"\"},\"fields\":[{\"name\":\"create_time\",\"type\":{\"Type\":2,\"Ident\":\"\",\"PkgPath\":\"time\",\"PkgName\":\"\",\"Nillable\":false,\"RType\":null},\"default\":true,\"default_kind\":19,\"immutable\":true,\"position\":{\"Index\":0,\"MixedIn\":true,\"MixinIndex\":0}},{\"name\":\"update_time\",\"type\":{\"Type\":2,\"Ident\":\"\",\"PkgPath\":\"time\",\"PkgName\":\"\",\"Nillable\":false,\"RType\":null},\"default\":true,\"default_kind\":19,\"update_default\":true,\"position\":{\"Index\":1,\"MixedIn\":true,\"MixinIndex\":0}},{\"name\":\"delete_time\",\"type\":{\"Type\":2,\"Ident\":\"\",\"PkgPath\":\"time\",\"PkgName\":\"\",\"Nillable\":false,\"RType\":null},\"optional\":true,\"position\":{\"Index\":0,\"MixedIn\":true,\"MixinIndex\":1}},{\"name\":\"name\",\"type\":{\"Type\":7,\"Ident\":\"\",\"PkgPath\":\"\",\"PkgName\":\"\",\"Nillable\":false,\"RType\":null},\"position\":{\"Index\":0,\"MixedIn\":false,\"MixinIndex\":0}},{\"name\":\"logo_url\",\"type\":{\"Type\":7,\"Ident\":\"*url.URL\",\"PkgPath\":\"net/url\",\"PkgName\":\"url\",\"Nillable\":true,\"RType\":{\"Name\":\"URL\",\"Ident\":\"url.URL\",\"Kind\":22,\"PkgPath\":\"net/url\",\"Methods\":{\"EscapedFragment\":{\"In\":[],\"Out\":[{\"Name\":\"string\",\"Ident\":\"string\",\"Kind\":24,\"PkgPath\":\"\",\"Methods\":null}]},\"EscapedPath\":{\"In\":[],\"Out\":[{\"Name\":\"string\",\"Ident\":\"string\",\"Kind\":24,\"PkgPath\":\"\",\"Methods\":null}]},\"Hostname\":{\"In\":[],\"Out\":[{\"Name\":\"string\",\"Ident\":\"string\",\"Kind\":24,\"PkgPath\":\"\",\"Methods\":null}]},\"IsAbs\":{\"In\":[],\"Out\":[{\"Name\":\"bool\",\"Ident\":\"bool\",\"Kind\":1,\"PkgPath\":\"\",\"Methods\":null}]},\"JoinPath\":{\"In\":[{\"Name\":\"\",\"Ident\":\"[]string\",\"Kind\":23,\"PkgPath\":\"\",\"Methods\":null}],\"Out\":[{\"Name\":\"\",\"Ident\":\"*url.URL\",\"Kind\":22,\"PkgPath\":\"\",\"Methods\":null}]},\"MarshalBinary\":{\"In\":[],\"Out\":[{\"Name\":\"\",\"Ident\":\"[]uint8\",\"Kind\":23,\"PkgPath\":\"\",\"Methods\":null},{\"Name\":\"error\",\"Ident\":\"error\",\"Kind\":20,\"PkgPath\":\"\",\"Methods\":null}]},\"Parse\":{\"In\":[{\"Name\":\"string\",\"Ident\":\"string\",\"Kind\":24,\"PkgPath\":\"\",\"Methods\":null}],\"Out\":[{\"Name\":\"\",\"Ident\":\"*url.URL\",\"Kind\":22,\"PkgPath\":\"\",\"Methods\":null},{\"Name\":\"error\",\"Ident\":\"error\",\"Kind\":20,\"PkgPath\":\"\",\"Methods\":null}]},\"Port\":{\"In\":[],\"Out\":[{\"Name\":\"string\",\"Ident\":\"string\",\"Kind\":24,\"PkgPath\":\"\",\"Methods\":null}]},\"Query\":{\"In\":[],\"Out\":[{\"Name\":\"Values\",\"Ident\":\"url.Values\",\"Kind\":21,\"PkgPath\":\"net/url\",\"Methods\":null}]},\"Redacted\":{\"In\":[],\"Out\":[{\"Name\":\"string\",\"Ident\":\"string\",\"Kind\":24,\"PkgPath\":\"\",\"Methods\":null}]},\"RequestURI\":{\"In\":[],\"Out\":[{\"Name\":\"string\",\"Ident\":\"string\",\"Kind\":24,\"PkgPath\":\"\",\"Methods\":null}]},\"ResolveReference\":{\"In\":[{\"Name\":\"\",\"Ident\":\"*url.URL\",\"Kind\":22,\"PkgPath\":\"\",\"Methods\":null}],\"Out\":[{\"Name\":\"\",\"Ident\":\"*url.URL\",\"Kind\":22,\"PkgPath\":\"\",\"Methods\":null}]},\"String\":{\"In\":[],\"Out\":[{\"Name\":\"string\",\"Ident\":\"string\",\"Kind\":24,\"PkgPath\":\"\",\"Methods\":null}]},\"UnmarshalBinary\":{\"In\":[{\"Name\":\"\",\"Ident\":\"[]uint8\",\"Kind\":23,\"PkgPath\":\"\",\"Methods\":null}],\"Out\":[{\"Name\":\"error\",\"Ident\":\"error\",\"Kind\":20,\"PkgPath\":\"\",\"Methods\":null}]}}}},\"value_scanner\":true,\"position\":{\"Index\":1,\"MixedIn\":false,\"MixinIndex\":0}},{\"name\":\"blog_url\",\"type\":{\"Type\":7,\"Ident\":\"*url.URL\",\"PkgPath\":\"net/url\",\"PkgName\":\"url\",\"Nillable\":true,\"RType\":{\"Name\":\"URL\",\"Ident\":\"url.URL\",\"Kind\":22,\"PkgPath\":\"net/url\",\"Methods\":{\"EscapedFragment\":{\"In\":[],\"Out\":[{\"Name\":\"string\",\"Ident\":\"string\",\"Kind\":24,\"PkgPath\":\"\",\"Methods\":null}]},\"EscapedPath\":{\"In\":[],\"Out\":[{\"Name\":\"string\",\"Ident\":\"string\",\"Kind\":24,\"PkgPath\":\"\",\"Methods\":null}]},\"Hostname\":{\"In\":[],\"Out\":[{\"Name\":\"string\",\"Ident\":\"string\",\"Kind\":24,\"PkgPath\":\"\",\"Methods\":null}]},\"IsAbs\":{\"In\":[],\"Out\":[{\"Name\":\"bool\",\"Ident\":\"bool\",\"Kind\":1,\"PkgPath\":\"\",\"Methods\":null}]},\"JoinPath\":{\"In\":[{\"Name\":\"\",\"Ident\":\"[]string\",\"Kind\":23,\"PkgPath\":\"\",\"Methods\":null}],\"Out\":[{\"Name\":\"\",\"Ident\":\"*url.URL\",\"Kind\":22,\"PkgPath\":\"\",\"Methods\":null}]},\"MarshalBinary\":{\"In\":[],\"Out\":[{\"Name\":\"\",\"Ident\":\"[]uint8\",\"Kind\":23,\"PkgPath\":\"\",\"Methods\":null},{\"Name\":\"error\",\"Ident\":\"error\",\"Kind\":20,\"PkgPath\":\"\",\"Methods\":null}]},\"Parse\":{\"In\":[{\"Name\":\"string\",\"Ident\":\"string\",\"Kind\":24,\"PkgPath\":\"\",\"Methods\":null}],\"Out\":[{\"Name\":\"\",\"Ident\":\"*url.URL\",\"Kind\":22,\"PkgPath\":\"\",\"Methods\":null},{\"Name\":\"error\",\"Ident\":\"error\",\"Kind\":20,\"PkgPath\":\"\",\"Methods\":null}]},\"Port\":{\"In\":[],\"Out\":[{\"Name\":\"string\",\"Ident\":\"string\",\"Kind\":24,\"PkgPath\":\"\",\"Methods\":null}]},\"Query\":{\"In\":[],\"Out\":[{\"Name\":\"Values\",\"Ident\":\"url.Values\",\"Kind\":21,\"PkgPath\":\"net/url\",\"Methods\":null}]},\"Redacted\":{\"In\":[],\"Out\":[{\"Name\":\"string\",\"Ident\":\"string\",\"Kind\":24,\"PkgPath\":\"\",\"Methods\":null}]},\"RequestURI\":{\"In\":[],\"Out\":[{\"Name\":\"string\",\"Ident\":\"string\",\"Kind\":24,\"PkgPath\":\"\",\"Methods\":null}]},\"ResolveReference\":{\"In\":[{\"Name\":\"\",\"Ident\":\"*url.URL\",\"Kind\":22,\"PkgPath\":\"\",\"Methods\":null}],\"Out\":[{\"Name\":\"\",\"Ident\":\"*url.URL\",\"Kind\":22,\"PkgPath\":\"\",\"Methods\":null}]},\"String\":{\"In\":[],\"Out\":[{\"Name\":\"string\",\"Ident\":\"string\",\"Kind\":24,\"PkgPath\":\"\",\"Methods\":null}]},\"UnmarshalBinary\":{\"In\":[{\"Name\":\"\",\"Ident\":\"[]uint8\",\"Kind\":23,\"PkgPath\":\"\",\"Methods\":null}],\"Out\":[{\"Name\":\"error\",\"Ident\":\"error\",\"Kind\":20,\"PkgPath\":\"\",\"Methods\":null}]}}}},\"value_scanner\":true,\"position\":{\"Index\":2,\"MixedIn\":false,\"MixinIndex\":0}},{\"name\":\"rss_url\",\"type\":{\"Type\":7,\"Ident\":\"*url.URL\",\"PkgPath\":\"net/url\",\"PkgName\":\"url\",\"Nillable\":true,\"RType\":{\"Name\":\"URL\",\"Ident\":\"url.URL\",\"Kind\":22,\"PkgPath\":\"net/url\",\"Methods\":{\"EscapedFragment\":{\"In\":[],\"Out\":[{\"Name\":\"string\",\"Ident\":\"string\",\"Kind\":24,\"PkgPath\":\"\",\"Methods\":null}]},\"EscapedPath\":{\"In\":[],\"Out\":[{\"Name\":\"string\",\"Ident\":\"string\",\"Kind\":24,\"PkgPath\":\"\",\"Methods\":null}]},\"Hostname\":{\"In\":[],\"Out\":[{\"Name\":\"string\",\"Ident\":\"string\",\"Kind\":24,\"PkgPath\":\"\",\"Methods\":null}]},\"IsAbs\":{\"In\":[],\"Out\":[{\"Name\":\"bool\",\"Ident\":\"bool\",\"Kind\":1,\"PkgPath\":\"\",\"Methods\":null}]},\"JoinPath\":{\"In\":[{\"Name\":\"\",\"Ident\":\"[]string\",\"Kind\":23,\"PkgPath\":\"\",\"Methods\":null}],\"Out\":[{\"Name\":\"\",\"Ident\":\"*url.URL\",\"Kind\":22,\"PkgPath\":\"\",\"Methods\":null}]},\"MarshalBinary\":{\"In\":[],\"Out\":[{\"Name\":\"\",\"Ident\":\"[]uint8\",\"Kind\":23,\"PkgPath\":\"\",\"Methods\":null},{\"Name\":\"error\",\"Ident\":\"error\",\"Kind\":20,\"PkgPath\":\"\",\"Methods\":null}]},\"Parse\":{\"In\":[{\"Name\":\"string\",\"Ident\":\"string\",\"Kind\":24,\"PkgPath\":\"\",\"Methods\":null}],\"Out\":[{\"Name\":\"\",\"Ident\":\"*url.URL\",\"Kind\":22,\"PkgPath\":\"\",\"Methods\":null},{\"Name\":\"error\",\"Ident\":\"error\",\"Kind\":20,\"PkgPath\":\"\",\"Methods\":null}]},\"Port\":{\"In\":[],\"Out\":[{\"Name\":\"string\",\"Ident\":\"string\",\"Kind\":24,\"PkgPath\":\"\",\"Methods\":null}]},\"Query\":{\"In\":[],\"Out\":[{\"Name\":\"Values\",\"Ident\":\"url.Values\",\"Kind\":21,\"PkgPath\":\"net/url\",\"Methods\":null}]},\"Redacted\":{\"In\":[],\"Out\":[{\"Name\":\"string\",\"Ident\":\"string\",\"Kind\":24,\"PkgPath\":\"\",\"Methods\":null}]},\"RequestURI\":{\"In\":[],\"Out\":[{\"Name\":\"string\",\"Ident\":\"string\",\"Kind\":24,\"PkgPath\":\"\",\"Methods\":null}]},\"ResolveReference\":{\"In\":[{\"Name\":\"\",\"Ident\":\"*url.URL\",\"Kind\":22,\"PkgPath\":\"\",\"Methods\":null}],\"Out\":[{\"Name\":\"\",\"Ident\":\"*url.URL\",\"Kind\":22,\"PkgPath\":\"\",\"Methods\":null}]},\"String\":{\"In\":[],\"Out\":[{\"Name\":\"string\",\"Ident\":\"string\",\"Kind\":24,\"PkgPath\":\"\",\"Methods\":null}]},\"UnmarshalBinary\":{\"In\":[{\"Name\":\"\",\"Ident\":\"[]uint8\",\"Kind\":23,\"PkgPath\":\"\",\"Methods\":null}],\"Out\":[{\"Name\":\"error\",\"Ident\":\"error\",\"Kind\":20,\"PkgPath\":\"\",\"Methods\":null}]}}}},\"value_scanner\":true,\"position\":{\"Index\":3,\"MixedIn\":false,\"MixinIndex\":0}}],\"hooks\":[{\"Index\":0,\"MixedIn\":true,\"MixinIndex\":1}],\"interceptors\":[{\"Index\":0,\"MixedIn\":true,\"MixinIndex\":1}]}],\"Features\":[\"intercept\",\"schema/snapshot\"]}" diff --git a/ent/migrate/migrate.go b/ent/migrate/migrate.go new file mode 100644 index 0000000..1956a6b --- /dev/null +++ b/ent/migrate/migrate.go @@ -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...) +} diff --git a/ent/migrate/migrations/20250118142329_create_company.sql b/ent/migrate/migrations/20250118142329_create_company.sql new file mode 100644 index 0000000..d27b1b0 --- /dev/null +++ b/ent/migrate/migrations/20250118142329_create_company.sql @@ -0,0 +1,12 @@ +-- Create "companies" table +CREATE TABLE "companies" ( + "id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY, + "create_time" timestamptz NOT NULL, + "update_time" timestamptz NOT NULL, + "delete_time" timestamptz NULL, + "name" character varying NOT NULL, + "logo_url" character varying NOT NULL, + "blog_url" character varying NOT NULL, + "rss_url" character varying NOT NULL, + PRIMARY KEY ("id") +); diff --git a/ent/migrate/migrations/atlas.sum b/ent/migrate/migrations/atlas.sum new file mode 100644 index 0000000..abc6e88 --- /dev/null +++ b/ent/migrate/migrations/atlas.sum @@ -0,0 +1,2 @@ +h1:kwIBmJcoRykLG8NBdp6FnP+xI+aBH01NJnwj+h4V7cQ= +20250118142329_create_company.sql h1:HDbigYfm6G4w1+Kzgwl+rMabQjLnctFRgIdyKGRxsKc= diff --git a/ent/migrate/schema.go b/ent/migrate/schema.go new file mode 100644 index 0000000..293e3d1 --- /dev/null +++ b/ent/migrate/schema.go @@ -0,0 +1,35 @@ +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/schema/field" +) + +var ( + // CompaniesColumns holds the columns for the "companies" table. + CompaniesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "create_time", Type: field.TypeTime}, + {Name: "update_time", Type: field.TypeTime}, + {Name: "delete_time", Type: field.TypeTime, Nullable: true}, + {Name: "name", Type: field.TypeString}, + {Name: "logo_url", Type: field.TypeString}, + {Name: "blog_url", Type: field.TypeString}, + {Name: "rss_url", Type: field.TypeString}, + } + // CompaniesTable holds the schema information for the "companies" table. + CompaniesTable = &schema.Table{ + Name: "companies", + Columns: CompaniesColumns, + PrimaryKey: []*schema.Column{CompaniesColumns[0]}, + } + // Tables holds all the tables in the schema. + Tables = []*schema.Table{ + CompaniesTable, + } +) + +func init() { +} diff --git a/ent/mutation.go b/ent/mutation.go new file mode 100644 index 0000000..71232c8 --- /dev/null +++ b/ent/mutation.go @@ -0,0 +1,701 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "net/url" + "sync" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/techbloghub/server/ent/company" + "github.com/techbloghub/server/ent/predicate" +) + +const ( + // Operation types. + OpCreate = ent.OpCreate + OpDelete = ent.OpDelete + OpDeleteOne = ent.OpDeleteOne + OpUpdate = ent.OpUpdate + OpUpdateOne = ent.OpUpdateOne + + // Node types. + TypeCompany = "Company" +) + +// CompanyMutation represents an operation that mutates the Company nodes in the graph. +type CompanyMutation struct { + config + op Op + typ string + id *int + create_time *time.Time + update_time *time.Time + delete_time *time.Time + name *string + logo_url **url.URL + blog_url **url.URL + rss_url **url.URL + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Company, error) + predicates []predicate.Company +} + +var _ ent.Mutation = (*CompanyMutation)(nil) + +// companyOption allows management of the mutation configuration using functional options. +type companyOption func(*CompanyMutation) + +// newCompanyMutation creates new mutation for the Company entity. +func newCompanyMutation(c config, op Op, opts ...companyOption) *CompanyMutation { + m := &CompanyMutation{ + config: c, + op: op, + typ: TypeCompany, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withCompanyID sets the ID field of the mutation. +func withCompanyID(id int) companyOption { + return func(m *CompanyMutation) { + var ( + err error + once sync.Once + value *Company + ) + m.oldValue = func(ctx context.Context) (*Company, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Company.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withCompany sets the old Company of the mutation. +func withCompany(node *Company) companyOption { + return func(m *CompanyMutation) { + m.oldValue = func(context.Context) (*Company, 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 CompanyMutation) 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 CompanyMutation) 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 +} + +// 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 *CompanyMutation) ID() (id int, 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 *CompanyMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Company.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetCreateTime sets the "create_time" field. +func (m *CompanyMutation) SetCreateTime(t time.Time) { + m.create_time = &t +} + +// CreateTime returns the value of the "create_time" field in the mutation. +func (m *CompanyMutation) CreateTime() (r time.Time, exists bool) { + v := m.create_time + if v == nil { + return + } + return *v, true +} + +// OldCreateTime returns the old "create_time" field's value of the Company entity. +// If the Company 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 *CompanyMutation) OldCreateTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreateTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreateTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreateTime: %w", err) + } + return oldValue.CreateTime, nil +} + +// ResetCreateTime resets all changes to the "create_time" field. +func (m *CompanyMutation) ResetCreateTime() { + m.create_time = nil +} + +// SetUpdateTime sets the "update_time" field. +func (m *CompanyMutation) SetUpdateTime(t time.Time) { + m.update_time = &t +} + +// UpdateTime returns the value of the "update_time" field in the mutation. +func (m *CompanyMutation) UpdateTime() (r time.Time, exists bool) { + v := m.update_time + if v == nil { + return + } + return *v, true +} + +// OldUpdateTime returns the old "update_time" field's value of the Company entity. +// If the Company 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 *CompanyMutation) OldUpdateTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUpdateTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdateTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdateTime: %w", err) + } + return oldValue.UpdateTime, nil +} + +// ResetUpdateTime resets all changes to the "update_time" field. +func (m *CompanyMutation) ResetUpdateTime() { + m.update_time = nil +} + +// SetDeleteTime sets the "delete_time" field. +func (m *CompanyMutation) SetDeleteTime(t time.Time) { + m.delete_time = &t +} + +// DeleteTime returns the value of the "delete_time" field in the mutation. +func (m *CompanyMutation) DeleteTime() (r time.Time, exists bool) { + v := m.delete_time + if v == nil { + return + } + return *v, true +} + +// OldDeleteTime returns the old "delete_time" field's value of the Company entity. +// If the Company 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 *CompanyMutation) OldDeleteTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDeleteTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDeleteTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeleteTime: %w", err) + } + return oldValue.DeleteTime, nil +} + +// ClearDeleteTime clears the value of the "delete_time" field. +func (m *CompanyMutation) ClearDeleteTime() { + m.delete_time = nil + m.clearedFields[company.FieldDeleteTime] = struct{}{} +} + +// DeleteTimeCleared returns if the "delete_time" field was cleared in this mutation. +func (m *CompanyMutation) DeleteTimeCleared() bool { + _, ok := m.clearedFields[company.FieldDeleteTime] + return ok +} + +// ResetDeleteTime resets all changes to the "delete_time" field. +func (m *CompanyMutation) ResetDeleteTime() { + m.delete_time = nil + delete(m.clearedFields, company.FieldDeleteTime) +} + +// SetName sets the "name" field. +func (m *CompanyMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *CompanyMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the Company entity. +// If the Company 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 *CompanyMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *CompanyMutation) ResetName() { + m.name = nil +} + +// SetLogoURL sets the "logo_url" field. +func (m *CompanyMutation) SetLogoURL(u *url.URL) { + m.logo_url = &u +} + +// LogoURL returns the value of the "logo_url" field in the mutation. +func (m *CompanyMutation) LogoURL() (r *url.URL, exists bool) { + v := m.logo_url + if v == nil { + return + } + return *v, true +} + +// OldLogoURL returns the old "logo_url" field's value of the Company entity. +// If the Company 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 *CompanyMutation) OldLogoURL(ctx context.Context) (v *url.URL, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLogoURL is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLogoURL requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLogoURL: %w", err) + } + return oldValue.LogoURL, nil +} + +// ResetLogoURL resets all changes to the "logo_url" field. +func (m *CompanyMutation) ResetLogoURL() { + m.logo_url = nil +} + +// SetBlogURL sets the "blog_url" field. +func (m *CompanyMutation) SetBlogURL(u *url.URL) { + m.blog_url = &u +} + +// BlogURL returns the value of the "blog_url" field in the mutation. +func (m *CompanyMutation) BlogURL() (r *url.URL, exists bool) { + v := m.blog_url + if v == nil { + return + } + return *v, true +} + +// OldBlogURL returns the old "blog_url" field's value of the Company entity. +// If the Company 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 *CompanyMutation) OldBlogURL(ctx context.Context) (v *url.URL, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBlogURL is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBlogURL requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBlogURL: %w", err) + } + return oldValue.BlogURL, nil +} + +// ResetBlogURL resets all changes to the "blog_url" field. +func (m *CompanyMutation) ResetBlogURL() { + m.blog_url = nil +} + +// SetRssURL sets the "rss_url" field. +func (m *CompanyMutation) SetRssURL(u *url.URL) { + m.rss_url = &u +} + +// RssURL returns the value of the "rss_url" field in the mutation. +func (m *CompanyMutation) RssURL() (r *url.URL, exists bool) { + v := m.rss_url + if v == nil { + return + } + return *v, true +} + +// OldRssURL returns the old "rss_url" field's value of the Company entity. +// If the Company 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 *CompanyMutation) OldRssURL(ctx context.Context) (v *url.URL, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRssURL is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRssURL requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRssURL: %w", err) + } + return oldValue.RssURL, nil +} + +// ResetRssURL resets all changes to the "rss_url" field. +func (m *CompanyMutation) ResetRssURL() { + m.rss_url = nil +} + +// Where appends a list predicates to the CompanyMutation builder. +func (m *CompanyMutation) Where(ps ...predicate.Company) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the CompanyMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *CompanyMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Company, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *CompanyMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *CompanyMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Company). +func (m *CompanyMutation) 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 *CompanyMutation) Fields() []string { + fields := make([]string, 0, 7) + if m.create_time != nil { + fields = append(fields, company.FieldCreateTime) + } + if m.update_time != nil { + fields = append(fields, company.FieldUpdateTime) + } + if m.delete_time != nil { + fields = append(fields, company.FieldDeleteTime) + } + if m.name != nil { + fields = append(fields, company.FieldName) + } + if m.logo_url != nil { + fields = append(fields, company.FieldLogoURL) + } + if m.blog_url != nil { + fields = append(fields, company.FieldBlogURL) + } + if m.rss_url != nil { + fields = append(fields, company.FieldRssURL) + } + 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 *CompanyMutation) Field(name string) (ent.Value, bool) { + switch name { + case company.FieldCreateTime: + return m.CreateTime() + case company.FieldUpdateTime: + return m.UpdateTime() + case company.FieldDeleteTime: + return m.DeleteTime() + case company.FieldName: + return m.Name() + case company.FieldLogoURL: + return m.LogoURL() + case company.FieldBlogURL: + return m.BlogURL() + case company.FieldRssURL: + return m.RssURL() + } + 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 *CompanyMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case company.FieldCreateTime: + return m.OldCreateTime(ctx) + case company.FieldUpdateTime: + return m.OldUpdateTime(ctx) + case company.FieldDeleteTime: + return m.OldDeleteTime(ctx) + case company.FieldName: + return m.OldName(ctx) + case company.FieldLogoURL: + return m.OldLogoURL(ctx) + case company.FieldBlogURL: + return m.OldBlogURL(ctx) + case company.FieldRssURL: + return m.OldRssURL(ctx) + } + return nil, fmt.Errorf("unknown Company 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 *CompanyMutation) SetField(name string, value ent.Value) error { + switch name { + case company.FieldCreateTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreateTime(v) + return nil + case company.FieldUpdateTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdateTime(v) + return nil + case company.FieldDeleteTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeleteTime(v) + return nil + case company.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case company.FieldLogoURL: + v, ok := value.(*url.URL) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLogoURL(v) + return nil + case company.FieldBlogURL: + v, ok := value.(*url.URL) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBlogURL(v) + return nil + case company.FieldRssURL: + v, ok := value.(*url.URL) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRssURL(v) + return nil + } + return fmt.Errorf("unknown Company field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *CompanyMutation) 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 *CompanyMutation) 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 *CompanyMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Company numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *CompanyMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(company.FieldDeleteTime) { + fields = append(fields, company.FieldDeleteTime) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *CompanyMutation) 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 *CompanyMutation) ClearField(name string) error { + switch name { + case company.FieldDeleteTime: + m.ClearDeleteTime() + return nil + } + return fmt.Errorf("unknown Company 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 *CompanyMutation) ResetField(name string) error { + switch name { + case company.FieldCreateTime: + m.ResetCreateTime() + return nil + case company.FieldUpdateTime: + m.ResetUpdateTime() + return nil + case company.FieldDeleteTime: + m.ResetDeleteTime() + return nil + case company.FieldName: + m.ResetName() + return nil + case company.FieldLogoURL: + m.ResetLogoURL() + return nil + case company.FieldBlogURL: + m.ResetBlogURL() + return nil + case company.FieldRssURL: + m.ResetRssURL() + return nil + } + return fmt.Errorf("unknown Company field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *CompanyMutation) 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 *CompanyMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *CompanyMutation) 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 *CompanyMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *CompanyMutation) 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 *CompanyMutation) 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 *CompanyMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Company 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 *CompanyMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Company edge %s", name) +} diff --git a/ent/predicate/predicate.go b/ent/predicate/predicate.go new file mode 100644 index 0000000..c30a342 --- /dev/null +++ b/ent/predicate/predicate.go @@ -0,0 +1,21 @@ +// Code generated by ent, DO NOT EDIT. + +package predicate + +import ( + "entgo.io/ent/dialect/sql" +) + +// Company is the predicate function for company builders. +type Company func(*sql.Selector) + +// CompanyOrErr calls the predicate only if the error is not nit. +func CompanyOrErr(p Company, err error) Company { + return func(s *sql.Selector) { + if err != nil { + s.AddError(err) + return + } + p(s) + } +} diff --git a/ent/runtime.go b/ent/runtime.go new file mode 100644 index 0000000..71b243e --- /dev/null +++ b/ent/runtime.go @@ -0,0 +1,5 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +// The schema-stitching logic is generated in github.com/techbloghub/server/ent/runtime/runtime.go diff --git a/ent/runtime/runtime.go b/ent/runtime/runtime.go new file mode 100644 index 0000000..f10a0f2 --- /dev/null +++ b/ent/runtime/runtime.go @@ -0,0 +1,52 @@ +// Code generated by ent, DO NOT EDIT. + +package runtime + +import ( + "net/url" + "time" + + "github.com/techbloghub/server/ent/company" + "github.com/techbloghub/server/ent/schema" + + "entgo.io/ent/schema/field" +) + +// 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() { + companyMixin := schema.Company{}.Mixin() + companyMixinHooks1 := companyMixin[1].Hooks() + company.Hooks[0] = companyMixinHooks1[0] + companyMixinInters1 := companyMixin[1].Interceptors() + company.Interceptors[0] = companyMixinInters1[0] + companyMixinFields0 := companyMixin[0].Fields() + _ = companyMixinFields0 + companyFields := schema.Company{}.Fields() + _ = companyFields + // companyDescCreateTime is the schema descriptor for create_time field. + companyDescCreateTime := companyMixinFields0[0].Descriptor() + // company.DefaultCreateTime holds the default value on creation for the create_time field. + company.DefaultCreateTime = companyDescCreateTime.Default.(func() time.Time) + // companyDescUpdateTime is the schema descriptor for update_time field. + companyDescUpdateTime := companyMixinFields0[1].Descriptor() + // company.DefaultUpdateTime holds the default value on creation for the update_time field. + company.DefaultUpdateTime = companyDescUpdateTime.Default.(func() time.Time) + // company.UpdateDefaultUpdateTime holds the default value on update for the update_time field. + company.UpdateDefaultUpdateTime = companyDescUpdateTime.UpdateDefault.(func() time.Time) + // companyDescLogoURL is the schema descriptor for logo_url field. + companyDescLogoURL := companyFields[1].Descriptor() + company.ValueScanner.LogoURL = companyDescLogoURL.ValueScanner.(field.TypeValueScanner[*url.URL]) + // companyDescBlogURL is the schema descriptor for blog_url field. + companyDescBlogURL := companyFields[2].Descriptor() + company.ValueScanner.BlogURL = companyDescBlogURL.ValueScanner.(field.TypeValueScanner[*url.URL]) + // companyDescRssURL is the schema descriptor for rss_url field. + companyDescRssURL := companyFields[3].Descriptor() + company.ValueScanner.RssURL = companyDescRssURL.ValueScanner.(field.TypeValueScanner[*url.URL]) +} + +const ( + Version = "v0.14.1" // Version of ent codegen. + Sum = "h1:fUERL506Pqr92EPHJqr8EYxbPioflJo6PudkrEA8a/s=" // Sum of ent codegen. +) diff --git a/ent/schema/company.go b/ent/schema/company.go new file mode 100644 index 0000000..f027af7 --- /dev/null +++ b/ent/schema/company.go @@ -0,0 +1,41 @@ +package schema + +import ( + "net/url" + + "entgo.io/ent" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/mixin" +) + +// Company holds the schema definition for the Company entity. +type Company struct { + ent.Schema +} + +func (Company) Mixin() []ent.Mixin { + return []ent.Mixin{ + mixin.Time{}, + SoftDeleteMixin{}, + } +} + +func (Company) Fields() []ent.Field { + urlField := func(name string) ent.Field { + return field.String(name). + GoType(&url.URL{}). + ValueScanner(field.BinaryValueScanner[*url.URL]{}) + } + + return []ent.Field{ + field.String("name"), + urlField("logo_url"), + urlField("blog_url"), + urlField("rss_url"), + } +} + +// Edges of the Company. +func (Company) Edges() []ent.Edge { + return nil +} diff --git a/ent/schema/softdeletemixin.go b/ent/schema/softdeletemixin.go new file mode 100644 index 0000000..dae899f --- /dev/null +++ b/ent/schema/softdeletemixin.go @@ -0,0 +1,87 @@ +package schema + +import ( + "context" + "fmt" + "time" + + gen "github.com/techbloghub/server/ent" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/mixin" + "github.com/techbloghub/server/ent/hook" + "github.com/techbloghub/server/ent/intercept" +) + +// SoftDeleteMixin implements the soft delete pattern for schemas. +type SoftDeleteMixin struct { + mixin.Schema +} + +// Fields of the SoftDeleteMixin. +func (SoftDeleteMixin) Fields() []ent.Field { + return []ent.Field{ + field.Time("delete_time"). + Optional(), + } +} + +type softDeleteKey struct{} + +// SkipSoftDelete returns a new context that skips the soft-delete interceptor/mutators. +func SkipSoftDelete(parent context.Context) context.Context { + return context.WithValue(parent, softDeleteKey{}, true) +} + +// Interceptors of the SoftDeleteMixin. +func (d SoftDeleteMixin) Interceptors() []ent.Interceptor { + return []ent.Interceptor{ + intercept.TraverseFunc(func(ctx context.Context, q intercept.Query) error { + // Skip soft-delete, means include soft-deleted entities. + if skip, _ := ctx.Value(softDeleteKey{}).(bool); skip { + return nil + } + d.P(q) + return nil + }), + } +} + +// Hooks of the SoftDeleteMixin. +func (d SoftDeleteMixin) Hooks() []ent.Hook { + return []ent.Hook{ + hook.On( + func(next ent.Mutator) ent.Mutator { + return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) { + // Skip soft-delete, means delete the entity permanently. + if skip, _ := ctx.Value(softDeleteKey{}).(bool); skip { + return next.Mutate(ctx, m) + } + mx, ok := m.(interface { + SetOp(ent.Op) + Client() *gen.Client + SetDeleteTime(time.Time) + WhereP(...func(*sql.Selector)) + }) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + d.P(mx) + mx.SetOp(ent.OpUpdate) + mx.SetDeleteTime(time.Now()) + return mx.Client().Mutate(ctx, m) + }) + }, + ent.OpDeleteOne|ent.OpDelete, + ), + } +} + +// P adds a storage-level predicate to the queries and mutations. +func (d SoftDeleteMixin) P(w interface{ WhereP(...func(*sql.Selector)) }) { + w.WhereP( + sql.FieldIsNull(d.Fields()[0].Descriptor().Name), + ) +} diff --git a/ent/tx.go b/ent/tx.go new file mode 100644 index 0000000..31a565c --- /dev/null +++ b/ent/tx.go @@ -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 + // Company is the client for interacting with the Company builders. + Company *CompanyClient + + // 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.Company = NewCompanyClient(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: Company.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) diff --git a/go.mod b/go.mod index 47ac749..2a51224 100644 --- a/go.mod +++ b/go.mod @@ -3,12 +3,17 @@ module github.com/techbloghub/server go 1.23.4 require ( + entgo.io/ent v0.14.1 github.com/gin-gonic/gin v1.10.0 github.com/joho/godotenv v1.5.1 + github.com/lib/pq v1.10.9 github.com/stretchr/testify v1.10.0 ) require ( + ariga.io/atlas v0.19.1-0.20240203083654-5948b60a8e43 // indirect + github.com/agext/levenshtein v1.2.1 // indirect + github.com/apparentlymart/go-textseg/v13 v13.0.0 // indirect github.com/bytedance/sonic v1.12.6 // indirect github.com/bytedance/sonic/loader v0.2.1 // indirect github.com/cloudwego/base64x v0.1.4 // indirect @@ -16,29 +21,32 @@ require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/gabriel-vasile/mimetype v1.4.7 // indirect github.com/gin-contrib/sse v0.1.0 // indirect + github.com/go-openapi/inflect v0.19.0 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/validator/v10 v10.23.0 // indirect github.com/goccy/go-json v0.10.4 // indirect github.com/google/go-cmp v0.6.0 // indirect + github.com/google/uuid v1.3.0 // indirect + github.com/hashicorp/hcl/v2 v2.13.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.2.9 // indirect - github.com/kr/pretty v0.1.0 // indirect - github.com/kr/text v0.2.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pelletier/go-toml/v2 v2.2.3 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.12 // indirect + github.com/zclconf/go-cty v1.8.0 // indirect golang.org/x/arch v0.12.0 // indirect golang.org/x/crypto v0.31.0 // indirect + golang.org/x/mod v0.20.0 // indirect golang.org/x/net v0.33.0 // indirect golang.org/x/sys v0.28.0 // indirect golang.org/x/text v0.21.0 // indirect google.golang.org/protobuf v1.36.1 // indirect - gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 26ec748..ab84d96 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,13 @@ +ariga.io/atlas v0.19.1-0.20240203083654-5948b60a8e43 h1:GwdJbXydHCYPedeeLt4x/lrlIISQ4JTH1mRWuE5ZZ14= +ariga.io/atlas v0.19.1-0.20240203083654-5948b60a8e43/go.mod h1:uj3pm+hUTVN/X5yfdBexHlZv+1Xu5u5ZbZx7+CDavNU= +entgo.io/ent v0.14.1 h1:fUERL506Pqr92EPHJqr8EYxbPioflJo6PudkrEA8a/s= +entgo.io/ent v0.14.1/go.mod h1:MH6XLG0KXpkcDQhKiHfANZSzR55TJyPL5IGNpI8wpco= +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.1 h1:QmvMAjj2aEICytGiWzmxoE0x2KZvE0fvmqMOfy2tjT8= +github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= +github.com/apparentlymart/go-textseg/v13 v13.0.0 h1:Y+KvPE1NYz0xl601PVImeQfFyEy6iT90AvPUL1NNfNw= +github.com/apparentlymart/go-textseg/v13 v13.0.0/go.mod h1:ZK2fH7c4NqDTLtiYLvIkEghdlcqw7yxLeM89kiTRPUo= github.com/bytedance/sonic v1.12.6 h1:/isNmCUF2x3Sh8RAp/4mh4ZGkcFAX/hLrzrK3AvpRzk= github.com/bytedance/sonic v1.12.6/go.mod h1:B8Gt/XvtZ3Fqj+iSKMypzymZxw/FVwgIGKzMzT9r/rk= github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= @@ -7,7 +17,6 @@ github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/ github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 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= @@ -17,6 +26,8 @@ github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU= github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y= +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-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= @@ -25,11 +36,20 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/validator/v10 v10.23.0 h1:/PwmTwZhS0dPkav3cdK9kV1FsAmrL8sThn8IHr/sO+o= github.com/go-playground/validator/v10 v10.23.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= +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/goccy/go-json v0.10.4 h1:JSwxQzIqKfmFX1swYPpUThQZp/Ka4wzJdK0LWVytLPM= github.com/goccy/go-json v0.10.4/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 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/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +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.13.0 h1:0Apadu1w6M11dyGFxWnmhhcMjkbAiKCv7G1r/2QgCNc= +github.com/hashicorp/hcl/v2 v2.13.0/go.mod h1:e4z5nxYlWNPdDSNYX+ph14EvWYMFm3eP0zIUqPc2jr0= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= @@ -44,19 +64,37 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 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/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +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-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0= +github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y= +github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg= +github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 h1:DpOJ2HYzCv8LZP15IdmG+YdwD2luVPHITV96TkirNBM= +github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= +github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M= github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc= 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/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ= +github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= +github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= +github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -71,17 +109,36 @@ github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +github.com/vmihailenco/msgpack/v4 v4.3.12/go.mod h1:gborTTJjAo/GWTqqRjrLCn9pgNN+NXzzngzBKDPIqw4= +github.com/vmihailenco/tagparser v0.1.1/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI= +github.com/zclconf/go-cty v1.8.0 h1:s4AvqaeQzJIu3ndv4gVIhplVD0krU+bgrcLSVUnaWuA= +github.com/zclconf/go-cty v1.8.0/go.mod h1:vVKLxnk3puL4qRAv72AO+W99LUD4da90g3uUAzyuvAk= golang.org/x/arch v0.12.0 h1:UsYJhbzPYGsT0HbEdmYcqtCv8UNGvnaL561NnIUvaKg= golang.org/x/arch v0.12.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U= golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= +golang.org/x/mod v0.20.0 h1:utOm6MM3R3dnawAiJgn0y+xvuYRsm1RKM/4giyfDgV0= +golang.org/x/mod v0.20.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I= golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= +golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= +golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.24.0 h1:J1shsA93PJUEVaUSaay7UXAyE8aimq3GW0pjlolpa24= +golang.org/x/tools v0.24.0/go.mod h1:YhNqVBIfWHdzvTLs0d8LCuMhkKUgSUKldakyV7W/WDQ= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/protobuf v1.36.1 h1:yBPeRvTftaleIgM3PZ/WBIZ7XM/eEYAaEyCwvyjq/gk= google.golang.org/protobuf v1.36.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/internal/database/database.go b/internal/database/database.go new file mode 100644 index 0000000..a7d5548 --- /dev/null +++ b/internal/database/database.go @@ -0,0 +1,27 @@ +package database + +import ( + "context" + "fmt" + + "github.com/techbloghub/server/config" + "github.com/techbloghub/server/ent" +) + +func ConnectDatabase(cfg *config.Config) (*ent.Client, error) { + pgCfg := cfg.PostgresConfig + client, errPg := ent.Open("postgres", fmt.Sprintf("host=%s port=%s user=%s dbname=%s password=%s sslmode=disable", + pgCfg.Host, pgCfg.Port, pgCfg.User, pgCfg.Db, pgCfg.Password)) + if errPg != nil { + return nil, errPg + } + + // 개발환경이면 스키마 자동 마이그래이션 + if cfg.ServerConfig.Env == "local" { + if err := client.Schema.Create(context.Background()); err != nil { + return nil, err + } + } + + return client, nil +} diff --git a/script/create_migration.sh b/script/create_migration.sh new file mode 100755 index 0000000..a483f42 --- /dev/null +++ b/script/create_migration.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +if [ -z "$1" ]; then + echo "Usage: $0 " + exit 1 +fi + +MIGRATION_NAME=$1 + +atlas migrate diff "$MIGRATION_NAME" \ + --dir "file://ent/migrate/migrations" \ + --to "ent://ent/schema" \ + --dev-url "docker://postgres/15/test?search_path=public" diff --git a/dev-db.sh b/script/dev-db.sh similarity index 100% rename from dev-db.sh rename to script/dev-db.sh diff --git a/test-db.sh b/script/test-db.sh similarity index 100% rename from test-db.sh rename to script/test-db.sh