diff --git a/ent/client.go b/ent/client.go index 68b4126..f1b2464 100644 --- a/ent/client.go +++ b/ent/client.go @@ -15,6 +15,7 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "github.com/techbloghub/server/ent/company" + "github.com/techbloghub/server/ent/tag" ) // Client is the client that holds all ent builders. @@ -24,6 +25,8 @@ type Client struct { Schema *migrate.Schema // Company is the client for interacting with the Company builders. Company *CompanyClient + // Tag is the client for interacting with the Tag builders. + Tag *TagClient } // NewClient creates a new client configured with the given options. @@ -36,6 +39,7 @@ func NewClient(opts ...Option) *Client { func (c *Client) init() { c.Schema = migrate.NewSchema(c.driver) c.Company = NewCompanyClient(c.config) + c.Tag = NewTagClient(c.config) } type ( @@ -129,6 +133,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { ctx: ctx, config: cfg, Company: NewCompanyClient(cfg), + Tag: NewTagClient(cfg), }, nil } @@ -149,6 +154,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) ctx: ctx, config: cfg, Company: NewCompanyClient(cfg), + Tag: NewTagClient(cfg), }, nil } @@ -178,12 +184,14 @@ func (c *Client) Close() error { // In order to add hooks to a specific client, call: `client.Node.Use(...)`. func (c *Client) Use(hooks ...Hook) { c.Company.Use(hooks...) + c.Tag.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...) + c.Tag.Intercept(interceptors...) } // Mutate implements the ent.Mutator interface. @@ -191,6 +199,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { switch m := m.(type) { case *CompanyMutation: return c.Company.mutate(ctx, m) + case *TagMutation: + return c.Tag.mutate(ctx, m) default: return nil, fmt.Errorf("ent: unknown mutation type %T", m) } @@ -331,12 +341,147 @@ func (c *CompanyClient) mutate(ctx context.Context, m *CompanyMutation) (Value, } } +// TagClient is a client for the Tag schema. +type TagClient struct { + config +} + +// NewTagClient returns a client for the Tag from the given config. +func NewTagClient(c config) *TagClient { + return &TagClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `tag.Hooks(f(g(h())))`. +func (c *TagClient) Use(hooks ...Hook) { + c.hooks.Tag = append(c.hooks.Tag, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `tag.Intercept(f(g(h())))`. +func (c *TagClient) Intercept(interceptors ...Interceptor) { + c.inters.Tag = append(c.inters.Tag, interceptors...) +} + +// Create returns a builder for creating a Tag entity. +func (c *TagClient) Create() *TagCreate { + mutation := newTagMutation(c.config, OpCreate) + return &TagCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Tag entities. +func (c *TagClient) CreateBulk(builders ...*TagCreate) *TagCreateBulk { + return &TagCreateBulk{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 *TagClient) MapCreateBulk(slice any, setFunc func(*TagCreate, int)) *TagCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &TagCreateBulk{err: fmt.Errorf("calling to TagClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*TagCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &TagCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Tag. +func (c *TagClient) Update() *TagUpdate { + mutation := newTagMutation(c.config, OpUpdate) + return &TagUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *TagClient) UpdateOne(t *Tag) *TagUpdateOne { + mutation := newTagMutation(c.config, OpUpdateOne, withTag(t)) + return &TagUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *TagClient) UpdateOneID(id int) *TagUpdateOne { + mutation := newTagMutation(c.config, OpUpdateOne, withTagID(id)) + return &TagUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Tag. +func (c *TagClient) Delete() *TagDelete { + mutation := newTagMutation(c.config, OpDelete) + return &TagDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *TagClient) DeleteOne(t *Tag) *TagDeleteOne { + return c.DeleteOneID(t.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *TagClient) DeleteOneID(id int) *TagDeleteOne { + builder := c.Delete().Where(tag.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &TagDeleteOne{builder} +} + +// Query returns a query builder for Tag. +func (c *TagClient) Query() *TagQuery { + return &TagQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeTag}, + inters: c.Interceptors(), + } +} + +// Get returns a Tag entity by its id. +func (c *TagClient) Get(ctx context.Context, id int) (*Tag, error) { + return c.Query().Where(tag.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *TagClient) GetX(ctx context.Context, id int) *Tag { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *TagClient) Hooks() []Hook { + hooks := c.hooks.Tag + return append(hooks[:len(hooks):len(hooks)], tag.Hooks[:]...) +} + +// Interceptors returns the client interceptors. +func (c *TagClient) Interceptors() []Interceptor { + inters := c.inters.Tag + return append(inters[:len(inters):len(inters)], tag.Interceptors[:]...) +} + +func (c *TagClient) mutate(ctx context.Context, m *TagMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&TagCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&TagUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&TagUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&TagDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Tag mutation op: %q", m.Op()) + } +} + // hooks and interceptors per client, for fast access. type ( hooks struct { - Company []ent.Hook + Company, Tag []ent.Hook } inters struct { - Company []ent.Interceptor + Company, Tag []ent.Interceptor } ) diff --git a/ent/ent.go b/ent/ent.go index 97a5bf2..0ae6918 100644 --- a/ent/ent.go +++ b/ent/ent.go @@ -13,6 +13,7 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "github.com/techbloghub/server/ent/company" + "github.com/techbloghub/server/ent/tag" ) // ent aliases to avoid import conflicts in user's code. @@ -74,6 +75,7 @@ func checkColumn(table, column string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ company.Table: company.ValidColumn, + tag.Table: tag.ValidColumn, }) }) return columnCheck(table, column) diff --git a/ent/hook/hook.go b/ent/hook/hook.go index 0324e15..0923266 100644 --- a/ent/hook/hook.go +++ b/ent/hook/hook.go @@ -21,6 +21,18 @@ func (f CompanyFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, err return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.CompanyMutation", m) } +// The TagFunc type is an adapter to allow the use of ordinary +// function as Tag mutator. +type TagFunc func(context.Context, *ent.TagMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f TagFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.TagMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.TagMutation", m) +} + // Condition is a hook condition function. type Condition func(context.Context, ent.Mutation) bool diff --git a/ent/intercept/intercept.go b/ent/intercept/intercept.go index 5da194c..edfb063 100644 --- a/ent/intercept/intercept.go +++ b/ent/intercept/intercept.go @@ -10,6 +10,7 @@ import ( "github.com/techbloghub/server/ent" "github.com/techbloghub/server/ent/company" "github.com/techbloghub/server/ent/predicate" + "github.com/techbloghub/server/ent/tag" ) // The Query interface represents an operation that queries a graph. @@ -95,11 +96,40 @@ func (f TraverseCompany) Traverse(ctx context.Context, q ent.Query) error { return fmt.Errorf("unexpected query type %T. expect *ent.CompanyQuery", q) } +// The TagFunc type is an adapter to allow the use of ordinary function as a Querier. +type TagFunc func(context.Context, *ent.TagQuery) (ent.Value, error) + +// Query calls f(ctx, q). +func (f TagFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) { + if q, ok := q.(*ent.TagQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *ent.TagQuery", q) +} + +// The TraverseTag type is an adapter to allow the use of ordinary function as Traverser. +type TraverseTag func(context.Context, *ent.TagQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseTag) Intercept(next ent.Querier) ent.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseTag) Traverse(ctx context.Context, q ent.Query) error { + if q, ok := q.(*ent.TagQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *ent.TagQuery", 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 + case *ent.TagQuery: + return &query[*ent.TagQuery, predicate.Tag, tag.OrderOption]{typ: ent.TypeTag, tq: q}, nil default: return nil, fmt.Errorf("unknown query type %T", q) } diff --git a/ent/internal/schema.go b/ent/internal/schema.go index 7e5fa82..0a3deaf 100644 --- a/ent/internal/schema.go +++ b/ent/internal/schema.go @@ -6,4 +6,4 @@ // 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\"]}" +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}]},{\"name\":\"Tag\",\"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},\"unique\":true,\"validators\":1,\"position\":{\"Index\":0,\"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/migrations/20250202031149_create-tag.sql b/ent/migrate/migrations/20250202031149_create-tag.sql new file mode 100644 index 0000000..2a28a32 --- /dev/null +++ b/ent/migrate/migrations/20250202031149_create-tag.sql @@ -0,0 +1,4 @@ +-- Create "tags" table +CREATE TABLE "tags" ("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, PRIMARY KEY ("id")); +-- Create index "tags_name_key" to table: "tags" +CREATE UNIQUE INDEX "tags_name_key" ON "tags" ("name"); diff --git a/ent/migrate/migrations/atlas.sum b/ent/migrate/migrations/atlas.sum index abc6e88..41562da 100644 --- a/ent/migrate/migrations/atlas.sum +++ b/ent/migrate/migrations/atlas.sum @@ -1,2 +1,3 @@ -h1:kwIBmJcoRykLG8NBdp6FnP+xI+aBH01NJnwj+h4V7cQ= +h1:alOmJfaGEBI+WU4MkAO/eJouQLYqLbPL+RxYOjF4eCc= 20250118142329_create_company.sql h1:HDbigYfm6G4w1+Kzgwl+rMabQjLnctFRgIdyKGRxsKc= +20250202031149_create-tag.sql h1:0hc8Co99P4bEvB9KZT3OUZflUCnjScW+UdrTR/WC0vA= diff --git a/ent/migrate/schema.go b/ent/migrate/schema.go index 293e3d1..c9c698b 100644 --- a/ent/migrate/schema.go +++ b/ent/migrate/schema.go @@ -25,9 +25,24 @@ var ( Columns: CompaniesColumns, PrimaryKey: []*schema.Column{CompaniesColumns[0]}, } + // TagsColumns holds the columns for the "tags" table. + TagsColumns = []*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, Unique: true}, + } + // TagsTable holds the schema information for the "tags" table. + TagsTable = &schema.Table{ + Name: "tags", + Columns: TagsColumns, + PrimaryKey: []*schema.Column{TagsColumns[0]}, + } // Tables holds all the tables in the schema. Tables = []*schema.Table{ CompaniesTable, + TagsTable, } ) diff --git a/ent/mutation.go b/ent/mutation.go index 71232c8..9523c82 100644 --- a/ent/mutation.go +++ b/ent/mutation.go @@ -14,6 +14,7 @@ import ( "entgo.io/ent/dialect/sql" "github.com/techbloghub/server/ent/company" "github.com/techbloghub/server/ent/predicate" + "github.com/techbloghub/server/ent/tag" ) const ( @@ -26,6 +27,7 @@ const ( // Node types. TypeCompany = "Company" + TypeTag = "Tag" ) // CompanyMutation represents an operation that mutates the Company nodes in the graph. @@ -699,3 +701,513 @@ func (m *CompanyMutation) ClearEdge(name string) error { func (m *CompanyMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Company edge %s", name) } + +// TagMutation represents an operation that mutates the Tag nodes in the graph. +type TagMutation struct { + config + op Op + typ string + id *int + create_time *time.Time + update_time *time.Time + delete_time *time.Time + name *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Tag, error) + predicates []predicate.Tag +} + +var _ ent.Mutation = (*TagMutation)(nil) + +// tagOption allows management of the mutation configuration using functional options. +type tagOption func(*TagMutation) + +// newTagMutation creates new mutation for the Tag entity. +func newTagMutation(c config, op Op, opts ...tagOption) *TagMutation { + m := &TagMutation{ + config: c, + op: op, + typ: TypeTag, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withTagID sets the ID field of the mutation. +func withTagID(id int) tagOption { + return func(m *TagMutation) { + var ( + err error + once sync.Once + value *Tag + ) + m.oldValue = func(ctx context.Context) (*Tag, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Tag.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withTag sets the old Tag of the mutation. +func withTag(node *Tag) tagOption { + return func(m *TagMutation) { + m.oldValue = func(context.Context) (*Tag, 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 TagMutation) 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 TagMutation) 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 *TagMutation) 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 *TagMutation) 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().Tag.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 *TagMutation) SetCreateTime(t time.Time) { + m.create_time = &t +} + +// CreateTime returns the value of the "create_time" field in the mutation. +func (m *TagMutation) 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 Tag entity. +// If the Tag 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 *TagMutation) 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 *TagMutation) ResetCreateTime() { + m.create_time = nil +} + +// SetUpdateTime sets the "update_time" field. +func (m *TagMutation) SetUpdateTime(t time.Time) { + m.update_time = &t +} + +// UpdateTime returns the value of the "update_time" field in the mutation. +func (m *TagMutation) 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 Tag entity. +// If the Tag 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 *TagMutation) 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 *TagMutation) ResetUpdateTime() { + m.update_time = nil +} + +// SetDeleteTime sets the "delete_time" field. +func (m *TagMutation) SetDeleteTime(t time.Time) { + m.delete_time = &t +} + +// DeleteTime returns the value of the "delete_time" field in the mutation. +func (m *TagMutation) 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 Tag entity. +// If the Tag 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 *TagMutation) 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 *TagMutation) ClearDeleteTime() { + m.delete_time = nil + m.clearedFields[tag.FieldDeleteTime] = struct{}{} +} + +// DeleteTimeCleared returns if the "delete_time" field was cleared in this mutation. +func (m *TagMutation) DeleteTimeCleared() bool { + _, ok := m.clearedFields[tag.FieldDeleteTime] + return ok +} + +// ResetDeleteTime resets all changes to the "delete_time" field. +func (m *TagMutation) ResetDeleteTime() { + m.delete_time = nil + delete(m.clearedFields, tag.FieldDeleteTime) +} + +// SetName sets the "name" field. +func (m *TagMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *TagMutation) 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 Tag entity. +// If the Tag 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 *TagMutation) 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 *TagMutation) ResetName() { + m.name = nil +} + +// Where appends a list predicates to the TagMutation builder. +func (m *TagMutation) Where(ps ...predicate.Tag) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the TagMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *TagMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Tag, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *TagMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *TagMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Tag). +func (m *TagMutation) 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 *TagMutation) Fields() []string { + fields := make([]string, 0, 4) + if m.create_time != nil { + fields = append(fields, tag.FieldCreateTime) + } + if m.update_time != nil { + fields = append(fields, tag.FieldUpdateTime) + } + if m.delete_time != nil { + fields = append(fields, tag.FieldDeleteTime) + } + if m.name != nil { + fields = append(fields, tag.FieldName) + } + 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 *TagMutation) Field(name string) (ent.Value, bool) { + switch name { + case tag.FieldCreateTime: + return m.CreateTime() + case tag.FieldUpdateTime: + return m.UpdateTime() + case tag.FieldDeleteTime: + return m.DeleteTime() + case tag.FieldName: + return m.Name() + } + 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 *TagMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case tag.FieldCreateTime: + return m.OldCreateTime(ctx) + case tag.FieldUpdateTime: + return m.OldUpdateTime(ctx) + case tag.FieldDeleteTime: + return m.OldDeleteTime(ctx) + case tag.FieldName: + return m.OldName(ctx) + } + return nil, fmt.Errorf("unknown Tag 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 *TagMutation) SetField(name string, value ent.Value) error { + switch name { + case tag.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 tag.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 tag.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 tag.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + } + return fmt.Errorf("unknown Tag field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *TagMutation) 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 *TagMutation) 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 *TagMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Tag numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *TagMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(tag.FieldDeleteTime) { + fields = append(fields, tag.FieldDeleteTime) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *TagMutation) 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 *TagMutation) ClearField(name string) error { + switch name { + case tag.FieldDeleteTime: + m.ClearDeleteTime() + return nil + } + return fmt.Errorf("unknown Tag 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 *TagMutation) ResetField(name string) error { + switch name { + case tag.FieldCreateTime: + m.ResetCreateTime() + return nil + case tag.FieldUpdateTime: + m.ResetUpdateTime() + return nil + case tag.FieldDeleteTime: + m.ResetDeleteTime() + return nil + case tag.FieldName: + m.ResetName() + return nil + } + return fmt.Errorf("unknown Tag field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *TagMutation) 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 *TagMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *TagMutation) 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 *TagMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *TagMutation) 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 *TagMutation) 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 *TagMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Tag 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 *TagMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Tag edge %s", name) +} diff --git a/ent/predicate/predicate.go b/ent/predicate/predicate.go index c30a342..cb80009 100644 --- a/ent/predicate/predicate.go +++ b/ent/predicate/predicate.go @@ -19,3 +19,6 @@ func CompanyOrErr(p Company, err error) Company { p(s) } } + +// Tag is the predicate function for tag builders. +type Tag func(*sql.Selector) diff --git a/ent/runtime/runtime.go b/ent/runtime/runtime.go index f10a0f2..85cc2c2 100644 --- a/ent/runtime/runtime.go +++ b/ent/runtime/runtime.go @@ -8,6 +8,7 @@ import ( "github.com/techbloghub/server/ent/company" "github.com/techbloghub/server/ent/schema" + "github.com/techbloghub/server/ent/tag" "entgo.io/ent/schema/field" ) @@ -44,6 +45,29 @@ func init() { // companyDescRssURL is the schema descriptor for rss_url field. companyDescRssURL := companyFields[3].Descriptor() company.ValueScanner.RssURL = companyDescRssURL.ValueScanner.(field.TypeValueScanner[*url.URL]) + tagMixin := schema.Tag{}.Mixin() + tagMixinHooks1 := tagMixin[1].Hooks() + tag.Hooks[0] = tagMixinHooks1[0] + tagMixinInters1 := tagMixin[1].Interceptors() + tag.Interceptors[0] = tagMixinInters1[0] + tagMixinFields0 := tagMixin[0].Fields() + _ = tagMixinFields0 + tagFields := schema.Tag{}.Fields() + _ = tagFields + // tagDescCreateTime is the schema descriptor for create_time field. + tagDescCreateTime := tagMixinFields0[0].Descriptor() + // tag.DefaultCreateTime holds the default value on creation for the create_time field. + tag.DefaultCreateTime = tagDescCreateTime.Default.(func() time.Time) + // tagDescUpdateTime is the schema descriptor for update_time field. + tagDescUpdateTime := tagMixinFields0[1].Descriptor() + // tag.DefaultUpdateTime holds the default value on creation for the update_time field. + tag.DefaultUpdateTime = tagDescUpdateTime.Default.(func() time.Time) + // tag.UpdateDefaultUpdateTime holds the default value on update for the update_time field. + tag.UpdateDefaultUpdateTime = tagDescUpdateTime.UpdateDefault.(func() time.Time) + // tagDescName is the schema descriptor for name field. + tagDescName := tagFields[0].Descriptor() + // tag.NameValidator is a validator for the "name" field. It is called by the builders before save. + tag.NameValidator = tagDescName.Validators[0].(func(string) error) } const ( diff --git a/ent/schema/tag.go b/ent/schema/tag.go new file mode 100644 index 0000000..c38e6e9 --- /dev/null +++ b/ent/schema/tag.go @@ -0,0 +1,42 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/mixin" +) + +// Tag holds the schema definition for the Tag entity. +type Tag struct { + ent.Schema +} + +func (Tag) Mixin() []ent.Mixin { + return []ent.Mixin{ + mixin.Time{}, + SoftDeleteMixin{}, + } +} + +func (Tag) Fields() []ent.Field { + return []ent.Field{ + field.String("name").NotEmpty().Unique(), + } +} + +//func (Tag) Indexes() []ent.Index { +// return []ent.Index{ +// index.Fields("name").Unique(). +// Annotations( +// entsql.IndexTypes(map[string]string{ +// "postgres": "GIN", +// }), +// entsql.OpClass("gin_trgm_ops"), +// ), +// } +//} + +// Edges of the Tag. +func (Tag) Edges() []ent.Edge { + return nil +} diff --git a/ent/tag.go b/ent/tag.go new file mode 100644 index 0000000..1136354 --- /dev/null +++ b/ent/tag.go @@ -0,0 +1,139 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/techbloghub/server/ent/tag" +) + +// Tag is the model entity for the Tag schema. +type Tag 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"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Tag) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case tag.FieldID: + values[i] = new(sql.NullInt64) + case tag.FieldName: + values[i] = new(sql.NullString) + case tag.FieldCreateTime, tag.FieldUpdateTime, tag.FieldDeleteTime: + values[i] = new(sql.NullTime) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Tag fields. +func (t *Tag) 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 tag.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + t.ID = int(value.Int64) + case tag.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 { + t.CreateTime = value.Time + } + case tag.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 { + t.UpdateTime = value.Time + } + case tag.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 { + t.DeleteTime = value.Time + } + case tag.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + t.Name = value.String + } + default: + t.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Tag. +// This includes values selected through modifiers, order, etc. +func (t *Tag) Value(name string) (ent.Value, error) { + return t.selectValues.Get(name) +} + +// Update returns a builder for updating this Tag. +// Note that you need to call Tag.Unwrap() before calling this method if this Tag +// was returned from a transaction, and the transaction was committed or rolled back. +func (t *Tag) Update() *TagUpdateOne { + return NewTagClient(t.config).UpdateOne(t) +} + +// Unwrap unwraps the Tag 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 (t *Tag) Unwrap() *Tag { + _tx, ok := t.config.driver.(*txDriver) + if !ok { + panic("ent: Tag is not a transactional entity") + } + t.config.driver = _tx.drv + return t +} + +// String implements the fmt.Stringer. +func (t *Tag) String() string { + var builder strings.Builder + builder.WriteString("Tag(") + builder.WriteString(fmt.Sprintf("id=%v, ", t.ID)) + builder.WriteString("create_time=") + builder.WriteString(t.CreateTime.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("update_time=") + builder.WriteString(t.UpdateTime.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("delete_time=") + builder.WriteString(t.DeleteTime.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("name=") + builder.WriteString(t.Name) + builder.WriteByte(')') + return builder.String() +} + +// Tags is a parsable slice of Tag. +type Tags []*Tag diff --git a/ent/tag/tag.go b/ent/tag/tag.go new file mode 100644 index 0000000..59db80a --- /dev/null +++ b/ent/tag/tag.go @@ -0,0 +1,92 @@ +// Code generated by ent, DO NOT EDIT. + +package tag + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the tag type in the database. + Label = "tag" + // 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" + // Table holds the table name of the tag in the database. + Table = "tags" +) + +// Columns holds all SQL columns for tag fields. +var Columns = []string{ + FieldID, + FieldCreateTime, + FieldUpdateTime, + FieldDeleteTime, + FieldName, +} + +// 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 + // NameValidator is a validator for the "name" field. It is called by the builders before save. + NameValidator func(string) error +) + +// OrderOption defines the ordering options for the Tag 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() +} diff --git a/ent/tag/where.go b/ent/tag/where.go new file mode 100644 index 0000000..563ac63 --- /dev/null +++ b/ent/tag/where.go @@ -0,0 +1,285 @@ +// Code generated by ent, DO NOT EDIT. + +package tag + +import ( + "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.Tag { + return predicate.Tag(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.Tag { + return predicate.Tag(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.Tag { + return predicate.Tag(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.Tag { + return predicate.Tag(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.Tag { + return predicate.Tag(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.Tag { + return predicate.Tag(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.Tag { + return predicate.Tag(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.Tag { + return predicate.Tag(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.Tag { + return predicate.Tag(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.Tag { + return predicate.Tag(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.Tag { + return predicate.Tag(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.Tag { + return predicate.Tag(sql.FieldEQ(FieldDeleteTime, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.Tag { + return predicate.Tag(sql.FieldEQ(FieldName, v)) +} + +// CreateTimeEQ applies the EQ predicate on the "create_time" field. +func CreateTimeEQ(v time.Time) predicate.Tag { + return predicate.Tag(sql.FieldEQ(FieldCreateTime, v)) +} + +// CreateTimeNEQ applies the NEQ predicate on the "create_time" field. +func CreateTimeNEQ(v time.Time) predicate.Tag { + return predicate.Tag(sql.FieldNEQ(FieldCreateTime, v)) +} + +// CreateTimeIn applies the In predicate on the "create_time" field. +func CreateTimeIn(vs ...time.Time) predicate.Tag { + return predicate.Tag(sql.FieldIn(FieldCreateTime, vs...)) +} + +// CreateTimeNotIn applies the NotIn predicate on the "create_time" field. +func CreateTimeNotIn(vs ...time.Time) predicate.Tag { + return predicate.Tag(sql.FieldNotIn(FieldCreateTime, vs...)) +} + +// CreateTimeGT applies the GT predicate on the "create_time" field. +func CreateTimeGT(v time.Time) predicate.Tag { + return predicate.Tag(sql.FieldGT(FieldCreateTime, v)) +} + +// CreateTimeGTE applies the GTE predicate on the "create_time" field. +func CreateTimeGTE(v time.Time) predicate.Tag { + return predicate.Tag(sql.FieldGTE(FieldCreateTime, v)) +} + +// CreateTimeLT applies the LT predicate on the "create_time" field. +func CreateTimeLT(v time.Time) predicate.Tag { + return predicate.Tag(sql.FieldLT(FieldCreateTime, v)) +} + +// CreateTimeLTE applies the LTE predicate on the "create_time" field. +func CreateTimeLTE(v time.Time) predicate.Tag { + return predicate.Tag(sql.FieldLTE(FieldCreateTime, v)) +} + +// UpdateTimeEQ applies the EQ predicate on the "update_time" field. +func UpdateTimeEQ(v time.Time) predicate.Tag { + return predicate.Tag(sql.FieldEQ(FieldUpdateTime, v)) +} + +// UpdateTimeNEQ applies the NEQ predicate on the "update_time" field. +func UpdateTimeNEQ(v time.Time) predicate.Tag { + return predicate.Tag(sql.FieldNEQ(FieldUpdateTime, v)) +} + +// UpdateTimeIn applies the In predicate on the "update_time" field. +func UpdateTimeIn(vs ...time.Time) predicate.Tag { + return predicate.Tag(sql.FieldIn(FieldUpdateTime, vs...)) +} + +// UpdateTimeNotIn applies the NotIn predicate on the "update_time" field. +func UpdateTimeNotIn(vs ...time.Time) predicate.Tag { + return predicate.Tag(sql.FieldNotIn(FieldUpdateTime, vs...)) +} + +// UpdateTimeGT applies the GT predicate on the "update_time" field. +func UpdateTimeGT(v time.Time) predicate.Tag { + return predicate.Tag(sql.FieldGT(FieldUpdateTime, v)) +} + +// UpdateTimeGTE applies the GTE predicate on the "update_time" field. +func UpdateTimeGTE(v time.Time) predicate.Tag { + return predicate.Tag(sql.FieldGTE(FieldUpdateTime, v)) +} + +// UpdateTimeLT applies the LT predicate on the "update_time" field. +func UpdateTimeLT(v time.Time) predicate.Tag { + return predicate.Tag(sql.FieldLT(FieldUpdateTime, v)) +} + +// UpdateTimeLTE applies the LTE predicate on the "update_time" field. +func UpdateTimeLTE(v time.Time) predicate.Tag { + return predicate.Tag(sql.FieldLTE(FieldUpdateTime, v)) +} + +// DeleteTimeEQ applies the EQ predicate on the "delete_time" field. +func DeleteTimeEQ(v time.Time) predicate.Tag { + return predicate.Tag(sql.FieldEQ(FieldDeleteTime, v)) +} + +// DeleteTimeNEQ applies the NEQ predicate on the "delete_time" field. +func DeleteTimeNEQ(v time.Time) predicate.Tag { + return predicate.Tag(sql.FieldNEQ(FieldDeleteTime, v)) +} + +// DeleteTimeIn applies the In predicate on the "delete_time" field. +func DeleteTimeIn(vs ...time.Time) predicate.Tag { + return predicate.Tag(sql.FieldIn(FieldDeleteTime, vs...)) +} + +// DeleteTimeNotIn applies the NotIn predicate on the "delete_time" field. +func DeleteTimeNotIn(vs ...time.Time) predicate.Tag { + return predicate.Tag(sql.FieldNotIn(FieldDeleteTime, vs...)) +} + +// DeleteTimeGT applies the GT predicate on the "delete_time" field. +func DeleteTimeGT(v time.Time) predicate.Tag { + return predicate.Tag(sql.FieldGT(FieldDeleteTime, v)) +} + +// DeleteTimeGTE applies the GTE predicate on the "delete_time" field. +func DeleteTimeGTE(v time.Time) predicate.Tag { + return predicate.Tag(sql.FieldGTE(FieldDeleteTime, v)) +} + +// DeleteTimeLT applies the LT predicate on the "delete_time" field. +func DeleteTimeLT(v time.Time) predicate.Tag { + return predicate.Tag(sql.FieldLT(FieldDeleteTime, v)) +} + +// DeleteTimeLTE applies the LTE predicate on the "delete_time" field. +func DeleteTimeLTE(v time.Time) predicate.Tag { + return predicate.Tag(sql.FieldLTE(FieldDeleteTime, v)) +} + +// DeleteTimeIsNil applies the IsNil predicate on the "delete_time" field. +func DeleteTimeIsNil() predicate.Tag { + return predicate.Tag(sql.FieldIsNull(FieldDeleteTime)) +} + +// DeleteTimeNotNil applies the NotNil predicate on the "delete_time" field. +func DeleteTimeNotNil() predicate.Tag { + return predicate.Tag(sql.FieldNotNull(FieldDeleteTime)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.Tag { + return predicate.Tag(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.Tag { + return predicate.Tag(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.Tag { + return predicate.Tag(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.Tag { + return predicate.Tag(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.Tag { + return predicate.Tag(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.Tag { + return predicate.Tag(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.Tag { + return predicate.Tag(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.Tag { + return predicate.Tag(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.Tag { + return predicate.Tag(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.Tag { + return predicate.Tag(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.Tag { + return predicate.Tag(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.Tag { + return predicate.Tag(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.Tag { + return predicate.Tag(sql.FieldContainsFold(FieldName, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Tag) predicate.Tag { + return predicate.Tag(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Tag) predicate.Tag { + return predicate.Tag(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Tag) predicate.Tag { + return predicate.Tag(sql.NotPredicates(p)) +} diff --git a/ent/tag_create.go b/ent/tag_create.go new file mode 100644 index 0000000..b30a0f5 --- /dev/null +++ b/ent/tag_create.go @@ -0,0 +1,272 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/techbloghub/server/ent/tag" +) + +// TagCreate is the builder for creating a Tag entity. +type TagCreate struct { + config + mutation *TagMutation + hooks []Hook +} + +// SetCreateTime sets the "create_time" field. +func (tc *TagCreate) SetCreateTime(t time.Time) *TagCreate { + tc.mutation.SetCreateTime(t) + return tc +} + +// SetNillableCreateTime sets the "create_time" field if the given value is not nil. +func (tc *TagCreate) SetNillableCreateTime(t *time.Time) *TagCreate { + if t != nil { + tc.SetCreateTime(*t) + } + return tc +} + +// SetUpdateTime sets the "update_time" field. +func (tc *TagCreate) SetUpdateTime(t time.Time) *TagCreate { + tc.mutation.SetUpdateTime(t) + return tc +} + +// SetNillableUpdateTime sets the "update_time" field if the given value is not nil. +func (tc *TagCreate) SetNillableUpdateTime(t *time.Time) *TagCreate { + if t != nil { + tc.SetUpdateTime(*t) + } + return tc +} + +// SetDeleteTime sets the "delete_time" field. +func (tc *TagCreate) SetDeleteTime(t time.Time) *TagCreate { + tc.mutation.SetDeleteTime(t) + return tc +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (tc *TagCreate) SetNillableDeleteTime(t *time.Time) *TagCreate { + if t != nil { + tc.SetDeleteTime(*t) + } + return tc +} + +// SetName sets the "name" field. +func (tc *TagCreate) SetName(s string) *TagCreate { + tc.mutation.SetName(s) + return tc +} + +// Mutation returns the TagMutation object of the builder. +func (tc *TagCreate) Mutation() *TagMutation { + return tc.mutation +} + +// Save creates the Tag in the database. +func (tc *TagCreate) Save(ctx context.Context) (*Tag, error) { + if err := tc.defaults(); err != nil { + return nil, err + } + return withHooks(ctx, tc.sqlSave, tc.mutation, tc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (tc *TagCreate) SaveX(ctx context.Context) *Tag { + v, err := tc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (tc *TagCreate) Exec(ctx context.Context) error { + _, err := tc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tc *TagCreate) ExecX(ctx context.Context) { + if err := tc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (tc *TagCreate) defaults() error { + if _, ok := tc.mutation.CreateTime(); !ok { + if tag.DefaultCreateTime == nil { + return fmt.Errorf("ent: uninitialized tag.DefaultCreateTime (forgotten import ent/runtime?)") + } + v := tag.DefaultCreateTime() + tc.mutation.SetCreateTime(v) + } + if _, ok := tc.mutation.UpdateTime(); !ok { + if tag.DefaultUpdateTime == nil { + return fmt.Errorf("ent: uninitialized tag.DefaultUpdateTime (forgotten import ent/runtime?)") + } + v := tag.DefaultUpdateTime() + tc.mutation.SetUpdateTime(v) + } + return nil +} + +// check runs all checks and user-defined validators on the builder. +func (tc *TagCreate) check() error { + if _, ok := tc.mutation.CreateTime(); !ok { + return &ValidationError{Name: "create_time", err: errors.New(`ent: missing required field "Tag.create_time"`)} + } + if _, ok := tc.mutation.UpdateTime(); !ok { + return &ValidationError{Name: "update_time", err: errors.New(`ent: missing required field "Tag.update_time"`)} + } + if _, ok := tc.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Tag.name"`)} + } + if v, ok := tc.mutation.Name(); ok { + if err := tag.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Tag.name": %w`, err)} + } + } + return nil +} + +func (tc *TagCreate) sqlSave(ctx context.Context) (*Tag, error) { + if err := tc.check(); err != nil { + return nil, err + } + _node, _spec := tc.createSpec() + if err := sqlgraph.CreateNode(ctx, tc.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) + tc.mutation.id = &_node.ID + tc.mutation.done = true + return _node, nil +} + +func (tc *TagCreate) createSpec() (*Tag, *sqlgraph.CreateSpec) { + var ( + _node = &Tag{config: tc.config} + _spec = sqlgraph.NewCreateSpec(tag.Table, sqlgraph.NewFieldSpec(tag.FieldID, field.TypeInt)) + ) + if value, ok := tc.mutation.CreateTime(); ok { + _spec.SetField(tag.FieldCreateTime, field.TypeTime, value) + _node.CreateTime = value + } + if value, ok := tc.mutation.UpdateTime(); ok { + _spec.SetField(tag.FieldUpdateTime, field.TypeTime, value) + _node.UpdateTime = value + } + if value, ok := tc.mutation.DeleteTime(); ok { + _spec.SetField(tag.FieldDeleteTime, field.TypeTime, value) + _node.DeleteTime = value + } + if value, ok := tc.mutation.Name(); ok { + _spec.SetField(tag.FieldName, field.TypeString, value) + _node.Name = value + } + return _node, _spec +} + +// TagCreateBulk is the builder for creating many Tag entities in bulk. +type TagCreateBulk struct { + config + err error + builders []*TagCreate +} + +// Save creates the Tag entities in the database. +func (tcb *TagCreateBulk) Save(ctx context.Context) ([]*Tag, error) { + if tcb.err != nil { + return nil, tcb.err + } + specs := make([]*sqlgraph.CreateSpec, len(tcb.builders)) + nodes := make([]*Tag, len(tcb.builders)) + mutators := make([]Mutator, len(tcb.builders)) + for i := range tcb.builders { + func(i int, root context.Context) { + builder := tcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TagMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, tcb.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, tcb.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, tcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (tcb *TagCreateBulk) SaveX(ctx context.Context) []*Tag { + v, err := tcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (tcb *TagCreateBulk) Exec(ctx context.Context) error { + _, err := tcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tcb *TagCreateBulk) ExecX(ctx context.Context) { + if err := tcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/tag_delete.go b/ent/tag_delete.go new file mode 100644 index 0000000..375d6d4 --- /dev/null +++ b/ent/tag_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/predicate" + "github.com/techbloghub/server/ent/tag" +) + +// TagDelete is the builder for deleting a Tag entity. +type TagDelete struct { + config + hooks []Hook + mutation *TagMutation +} + +// Where appends a list predicates to the TagDelete builder. +func (td *TagDelete) Where(ps ...predicate.Tag) *TagDelete { + td.mutation.Where(ps...) + return td +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (td *TagDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, td.sqlExec, td.mutation, td.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (td *TagDelete) ExecX(ctx context.Context) int { + n, err := td.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (td *TagDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(tag.Table, sqlgraph.NewFieldSpec(tag.FieldID, field.TypeInt)) + if ps := td.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, td.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + td.mutation.done = true + return affected, err +} + +// TagDeleteOne is the builder for deleting a single Tag entity. +type TagDeleteOne struct { + td *TagDelete +} + +// Where appends a list predicates to the TagDelete builder. +func (tdo *TagDeleteOne) Where(ps ...predicate.Tag) *TagDeleteOne { + tdo.td.mutation.Where(ps...) + return tdo +} + +// Exec executes the deletion query. +func (tdo *TagDeleteOne) Exec(ctx context.Context) error { + n, err := tdo.td.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{tag.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (tdo *TagDeleteOne) ExecX(ctx context.Context) { + if err := tdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/tag_query.go b/ent/tag_query.go new file mode 100644 index 0000000..ec8c556 --- /dev/null +++ b/ent/tag_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/predicate" + "github.com/techbloghub/server/ent/tag" +) + +// TagQuery is the builder for querying Tag entities. +type TagQuery struct { + config + ctx *QueryContext + order []tag.OrderOption + inters []Interceptor + predicates []predicate.Tag + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the TagQuery builder. +func (tq *TagQuery) Where(ps ...predicate.Tag) *TagQuery { + tq.predicates = append(tq.predicates, ps...) + return tq +} + +// Limit the number of records to be returned by this query. +func (tq *TagQuery) Limit(limit int) *TagQuery { + tq.ctx.Limit = &limit + return tq +} + +// Offset to start from. +func (tq *TagQuery) Offset(offset int) *TagQuery { + tq.ctx.Offset = &offset + return tq +} + +// 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 (tq *TagQuery) Unique(unique bool) *TagQuery { + tq.ctx.Unique = &unique + return tq +} + +// Order specifies how the records should be ordered. +func (tq *TagQuery) Order(o ...tag.OrderOption) *TagQuery { + tq.order = append(tq.order, o...) + return tq +} + +// First returns the first Tag entity from the query. +// Returns a *NotFoundError when no Tag was found. +func (tq *TagQuery) First(ctx context.Context) (*Tag, error) { + nodes, err := tq.Limit(1).All(setContextOp(ctx, tq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{tag.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (tq *TagQuery) FirstX(ctx context.Context) *Tag { + node, err := tq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Tag ID from the query. +// Returns a *NotFoundError when no Tag ID was found. +func (tq *TagQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = tq.Limit(1).IDs(setContextOp(ctx, tq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{tag.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (tq *TagQuery) FirstIDX(ctx context.Context) int { + id, err := tq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Tag entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Tag entity is found. +// Returns a *NotFoundError when no Tag entities are found. +func (tq *TagQuery) Only(ctx context.Context) (*Tag, error) { + nodes, err := tq.Limit(2).All(setContextOp(ctx, tq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{tag.Label} + default: + return nil, &NotSingularError{tag.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (tq *TagQuery) OnlyX(ctx context.Context) *Tag { + node, err := tq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Tag ID in the query. +// Returns a *NotSingularError when more than one Tag ID is found. +// Returns a *NotFoundError when no entities are found. +func (tq *TagQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = tq.Limit(2).IDs(setContextOp(ctx, tq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{tag.Label} + default: + err = &NotSingularError{tag.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (tq *TagQuery) OnlyIDX(ctx context.Context) int { + id, err := tq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Tags. +func (tq *TagQuery) All(ctx context.Context) ([]*Tag, error) { + ctx = setContextOp(ctx, tq.ctx, ent.OpQueryAll) + if err := tq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Tag, *TagQuery]() + return withInterceptors[[]*Tag](ctx, tq, qr, tq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (tq *TagQuery) AllX(ctx context.Context) []*Tag { + nodes, err := tq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Tag IDs. +func (tq *TagQuery) IDs(ctx context.Context) (ids []int, err error) { + if tq.ctx.Unique == nil && tq.path != nil { + tq.Unique(true) + } + ctx = setContextOp(ctx, tq.ctx, ent.OpQueryIDs) + if err = tq.Select(tag.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (tq *TagQuery) IDsX(ctx context.Context) []int { + ids, err := tq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (tq *TagQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, tq.ctx, ent.OpQueryCount) + if err := tq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, tq, querierCount[*TagQuery](), tq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (tq *TagQuery) CountX(ctx context.Context) int { + count, err := tq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (tq *TagQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, tq.ctx, ent.OpQueryExist) + switch _, err := tq.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 (tq *TagQuery) ExistX(ctx context.Context) bool { + exist, err := tq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the TagQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (tq *TagQuery) Clone() *TagQuery { + if tq == nil { + return nil + } + return &TagQuery{ + config: tq.config, + ctx: tq.ctx.Clone(), + order: append([]tag.OrderOption{}, tq.order...), + inters: append([]Interceptor{}, tq.inters...), + predicates: append([]predicate.Tag{}, tq.predicates...), + // clone intermediate query. + sql: tq.sql.Clone(), + path: tq.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.Tag.Query(). +// GroupBy(tag.FieldCreateTime). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (tq *TagQuery) GroupBy(field string, fields ...string) *TagGroupBy { + tq.ctx.Fields = append([]string{field}, fields...) + grbuild := &TagGroupBy{build: tq} + grbuild.flds = &tq.ctx.Fields + grbuild.label = tag.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.Tag.Query(). +// Select(tag.FieldCreateTime). +// Scan(ctx, &v) +func (tq *TagQuery) Select(fields ...string) *TagSelect { + tq.ctx.Fields = append(tq.ctx.Fields, fields...) + sbuild := &TagSelect{TagQuery: tq} + sbuild.label = tag.Label + sbuild.flds, sbuild.scan = &tq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a TagSelect configured with the given aggregations. +func (tq *TagQuery) Aggregate(fns ...AggregateFunc) *TagSelect { + return tq.Select().Aggregate(fns...) +} + +func (tq *TagQuery) prepareQuery(ctx context.Context) error { + for _, inter := range tq.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, tq); err != nil { + return err + } + } + } + for _, f := range tq.ctx.Fields { + if !tag.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if tq.path != nil { + prev, err := tq.path(ctx) + if err != nil { + return err + } + tq.sql = prev + } + return nil +} + +func (tq *TagQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Tag, error) { + var ( + nodes = []*Tag{} + _spec = tq.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Tag).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Tag{config: tq.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, tq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (tq *TagQuery) sqlCount(ctx context.Context) (int, error) { + _spec := tq.querySpec() + _spec.Node.Columns = tq.ctx.Fields + if len(tq.ctx.Fields) > 0 { + _spec.Unique = tq.ctx.Unique != nil && *tq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, tq.driver, _spec) +} + +func (tq *TagQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(tag.Table, tag.Columns, sqlgraph.NewFieldSpec(tag.FieldID, field.TypeInt)) + _spec.From = tq.sql + if unique := tq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if tq.path != nil { + _spec.Unique = true + } + if fields := tq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, tag.FieldID) + for i := range fields { + if fields[i] != tag.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := tq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := tq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := tq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := tq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (tq *TagQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(tq.driver.Dialect()) + t1 := builder.Table(tag.Table) + columns := tq.ctx.Fields + if len(columns) == 0 { + columns = tag.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if tq.sql != nil { + selector = tq.sql + selector.Select(selector.Columns(columns...)...) + } + if tq.ctx.Unique != nil && *tq.ctx.Unique { + selector.Distinct() + } + for _, p := range tq.predicates { + p(selector) + } + for _, p := range tq.order { + p(selector) + } + if offset := tq.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 := tq.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// TagGroupBy is the group-by builder for Tag entities. +type TagGroupBy struct { + selector + build *TagQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (tgb *TagGroupBy) Aggregate(fns ...AggregateFunc) *TagGroupBy { + tgb.fns = append(tgb.fns, fns...) + return tgb +} + +// Scan applies the selector query and scans the result into the given value. +func (tgb *TagGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, tgb.build.ctx, ent.OpQueryGroupBy) + if err := tgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*TagQuery, *TagGroupBy](ctx, tgb.build, tgb, tgb.build.inters, v) +} + +func (tgb *TagGroupBy) sqlScan(ctx context.Context, root *TagQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(tgb.fns)) + for _, fn := range tgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*tgb.flds)+len(tgb.fns)) + for _, f := range *tgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*tgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := tgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// TagSelect is the builder for selecting fields of Tag entities. +type TagSelect struct { + *TagQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (ts *TagSelect) Aggregate(fns ...AggregateFunc) *TagSelect { + ts.fns = append(ts.fns, fns...) + return ts +} + +// Scan applies the selector query and scans the result into the given value. +func (ts *TagSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ts.ctx, ent.OpQuerySelect) + if err := ts.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*TagQuery, *TagSelect](ctx, ts.TagQuery, ts, ts.inters, v) +} + +func (ts *TagSelect) sqlScan(ctx context.Context, root *TagQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(ts.fns)) + for _, fn := range ts.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*ts.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 := ts.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/ent/tag_update.go b/ent/tag_update.go new file mode 100644 index 0000000..43d34c0 --- /dev/null +++ b/ent/tag_update.go @@ -0,0 +1,336 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/techbloghub/server/ent/predicate" + "github.com/techbloghub/server/ent/tag" +) + +// TagUpdate is the builder for updating Tag entities. +type TagUpdate struct { + config + hooks []Hook + mutation *TagMutation +} + +// Where appends a list predicates to the TagUpdate builder. +func (tu *TagUpdate) Where(ps ...predicate.Tag) *TagUpdate { + tu.mutation.Where(ps...) + return tu +} + +// SetUpdateTime sets the "update_time" field. +func (tu *TagUpdate) SetUpdateTime(t time.Time) *TagUpdate { + tu.mutation.SetUpdateTime(t) + return tu +} + +// SetDeleteTime sets the "delete_time" field. +func (tu *TagUpdate) SetDeleteTime(t time.Time) *TagUpdate { + tu.mutation.SetDeleteTime(t) + return tu +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (tu *TagUpdate) SetNillableDeleteTime(t *time.Time) *TagUpdate { + if t != nil { + tu.SetDeleteTime(*t) + } + return tu +} + +// ClearDeleteTime clears the value of the "delete_time" field. +func (tu *TagUpdate) ClearDeleteTime() *TagUpdate { + tu.mutation.ClearDeleteTime() + return tu +} + +// SetName sets the "name" field. +func (tu *TagUpdate) SetName(s string) *TagUpdate { + tu.mutation.SetName(s) + return tu +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (tu *TagUpdate) SetNillableName(s *string) *TagUpdate { + if s != nil { + tu.SetName(*s) + } + return tu +} + +// Mutation returns the TagMutation object of the builder. +func (tu *TagUpdate) Mutation() *TagMutation { + return tu.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (tu *TagUpdate) Save(ctx context.Context) (int, error) { + if err := tu.defaults(); err != nil { + return 0, err + } + return withHooks(ctx, tu.sqlSave, tu.mutation, tu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (tu *TagUpdate) SaveX(ctx context.Context) int { + affected, err := tu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (tu *TagUpdate) Exec(ctx context.Context) error { + _, err := tu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tu *TagUpdate) ExecX(ctx context.Context) { + if err := tu.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (tu *TagUpdate) defaults() error { + if _, ok := tu.mutation.UpdateTime(); !ok { + if tag.UpdateDefaultUpdateTime == nil { + return fmt.Errorf("ent: uninitialized tag.UpdateDefaultUpdateTime (forgotten import ent/runtime?)") + } + v := tag.UpdateDefaultUpdateTime() + tu.mutation.SetUpdateTime(v) + } + return nil +} + +// check runs all checks and user-defined validators on the builder. +func (tu *TagUpdate) check() error { + if v, ok := tu.mutation.Name(); ok { + if err := tag.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Tag.name": %w`, err)} + } + } + return nil +} + +func (tu *TagUpdate) sqlSave(ctx context.Context) (n int, err error) { + if err := tu.check(); err != nil { + return n, err + } + _spec := sqlgraph.NewUpdateSpec(tag.Table, tag.Columns, sqlgraph.NewFieldSpec(tag.FieldID, field.TypeInt)) + if ps := tu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := tu.mutation.UpdateTime(); ok { + _spec.SetField(tag.FieldUpdateTime, field.TypeTime, value) + } + if value, ok := tu.mutation.DeleteTime(); ok { + _spec.SetField(tag.FieldDeleteTime, field.TypeTime, value) + } + if tu.mutation.DeleteTimeCleared() { + _spec.ClearField(tag.FieldDeleteTime, field.TypeTime) + } + if value, ok := tu.mutation.Name(); ok { + _spec.SetField(tag.FieldName, field.TypeString, value) + } + if n, err = sqlgraph.UpdateNodes(ctx, tu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{tag.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + tu.mutation.done = true + return n, nil +} + +// TagUpdateOne is the builder for updating a single Tag entity. +type TagUpdateOne struct { + config + fields []string + hooks []Hook + mutation *TagMutation +} + +// SetUpdateTime sets the "update_time" field. +func (tuo *TagUpdateOne) SetUpdateTime(t time.Time) *TagUpdateOne { + tuo.mutation.SetUpdateTime(t) + return tuo +} + +// SetDeleteTime sets the "delete_time" field. +func (tuo *TagUpdateOne) SetDeleteTime(t time.Time) *TagUpdateOne { + tuo.mutation.SetDeleteTime(t) + return tuo +} + +// SetNillableDeleteTime sets the "delete_time" field if the given value is not nil. +func (tuo *TagUpdateOne) SetNillableDeleteTime(t *time.Time) *TagUpdateOne { + if t != nil { + tuo.SetDeleteTime(*t) + } + return tuo +} + +// ClearDeleteTime clears the value of the "delete_time" field. +func (tuo *TagUpdateOne) ClearDeleteTime() *TagUpdateOne { + tuo.mutation.ClearDeleteTime() + return tuo +} + +// SetName sets the "name" field. +func (tuo *TagUpdateOne) SetName(s string) *TagUpdateOne { + tuo.mutation.SetName(s) + return tuo +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (tuo *TagUpdateOne) SetNillableName(s *string) *TagUpdateOne { + if s != nil { + tuo.SetName(*s) + } + return tuo +} + +// Mutation returns the TagMutation object of the builder. +func (tuo *TagUpdateOne) Mutation() *TagMutation { + return tuo.mutation +} + +// Where appends a list predicates to the TagUpdate builder. +func (tuo *TagUpdateOne) Where(ps ...predicate.Tag) *TagUpdateOne { + tuo.mutation.Where(ps...) + return tuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (tuo *TagUpdateOne) Select(field string, fields ...string) *TagUpdateOne { + tuo.fields = append([]string{field}, fields...) + return tuo +} + +// Save executes the query and returns the updated Tag entity. +func (tuo *TagUpdateOne) Save(ctx context.Context) (*Tag, error) { + if err := tuo.defaults(); err != nil { + return nil, err + } + return withHooks(ctx, tuo.sqlSave, tuo.mutation, tuo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (tuo *TagUpdateOne) SaveX(ctx context.Context) *Tag { + node, err := tuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (tuo *TagUpdateOne) Exec(ctx context.Context) error { + _, err := tuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tuo *TagUpdateOne) ExecX(ctx context.Context) { + if err := tuo.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (tuo *TagUpdateOne) defaults() error { + if _, ok := tuo.mutation.UpdateTime(); !ok { + if tag.UpdateDefaultUpdateTime == nil { + return fmt.Errorf("ent: uninitialized tag.UpdateDefaultUpdateTime (forgotten import ent/runtime?)") + } + v := tag.UpdateDefaultUpdateTime() + tuo.mutation.SetUpdateTime(v) + } + return nil +} + +// check runs all checks and user-defined validators on the builder. +func (tuo *TagUpdateOne) check() error { + if v, ok := tuo.mutation.Name(); ok { + if err := tag.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Tag.name": %w`, err)} + } + } + return nil +} + +func (tuo *TagUpdateOne) sqlSave(ctx context.Context) (_node *Tag, err error) { + if err := tuo.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(tag.Table, tag.Columns, sqlgraph.NewFieldSpec(tag.FieldID, field.TypeInt)) + id, ok := tuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Tag.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := tuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, tag.FieldID) + for _, f := range fields { + if !tag.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != tag.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := tuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := tuo.mutation.UpdateTime(); ok { + _spec.SetField(tag.FieldUpdateTime, field.TypeTime, value) + } + if value, ok := tuo.mutation.DeleteTime(); ok { + _spec.SetField(tag.FieldDeleteTime, field.TypeTime, value) + } + if tuo.mutation.DeleteTimeCleared() { + _spec.ClearField(tag.FieldDeleteTime, field.TypeTime) + } + if value, ok := tuo.mutation.Name(); ok { + _spec.SetField(tag.FieldName, field.TypeString, value) + } + _node = &Tag{config: tuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, tuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{tag.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + tuo.mutation.done = true + return _node, nil +} diff --git a/ent/tx.go b/ent/tx.go index 31a565c..eb5d870 100644 --- a/ent/tx.go +++ b/ent/tx.go @@ -14,6 +14,8 @@ type Tx struct { config // Company is the client for interacting with the Company builders. Company *CompanyClient + // Tag is the client for interacting with the Tag builders. + Tag *TagClient // lazily loaded. client *Client @@ -146,6 +148,7 @@ func (tx *Tx) Client() *Client { func (tx *Tx) init() { tx.Company = NewCompanyClient(tx.config) + tx.Tag = NewTagClient(tx.config) } // txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation. diff --git a/internal/.gitkeep b/internal/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/internal/database/database.go b/internal/database/database.go index a7d5548..9fe55d9 100644 --- a/internal/database/database.go +++ b/internal/database/database.go @@ -12,12 +12,14 @@ 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" { + client = client.Debug() if err := client.Schema.Create(context.Background()); err != nil { return nil, err } diff --git a/internal/http/handler/taghandler.go b/internal/http/handler/taghandler.go new file mode 100644 index 0000000..9b6ce19 --- /dev/null +++ b/internal/http/handler/taghandler.go @@ -0,0 +1,59 @@ +package handler + +import ( + "github.com/gin-gonic/gin" + "github.com/techbloghub/server/ent" + "github.com/techbloghub/server/ent/tag" +) + +type TagResponse struct { + ID int `json:"id"` + Name string `json:"name"` +} + +type TagResponses struct { + Count int `json:"count"` + Tags []TagResponse `json:"tags"` +} + +func GetTags(client *ent.Client) gin.HandlerFunc { + return func(c *gin.Context) { + searchParam := c.DefaultQuery("search", "") + + tags, err := fetchTags(c, searchParam, client) + if err != nil { + c.JSON(500, gin.H{"error": err.Error()}) + return + } + + tagResponses := makeTagResponses(tags) + c.JSON(200, TagResponses{ + Count: len(tagResponses), + Tags: tagResponses, + }) + } +} + +func fetchTags(c *gin.Context, searchParam string, client *ent.Client) ([]*ent.Tag, error) { + if searchParam != "" { + return searchTagsByName(c, client, searchParam) + } + return client.Tag.Query().All(c) +} + +func searchTagsByName(c *gin.Context, client *ent.Client, searchParam string) ([]*ent.Tag, error) { + return client.Tag.Query(). + Where(tag.NameContainsFold(searchParam)). + All(c) +} + +func makeTagResponses(tags []*ent.Tag) []TagResponse { + tagResponses := make([]TagResponse, len(tags)) + for i, tag := range tags { + tagResponses[i] = TagResponse{ + ID: tag.ID, + Name: tag.Name, + } + } + return tagResponses +} diff --git a/internal/http/router/router.go b/internal/http/router/router.go index 0e009e8..2cfb6c6 100644 --- a/internal/http/router/router.go +++ b/internal/http/router/router.go @@ -13,4 +13,7 @@ func InitRouter(r *gin.Engine, client *ent.Client) { // 회사 리스트 조회 // curl -X GET http://localhost:8080/companies r.GET("/companies", handler.ListCompanies(client)) + + // 태그 전체 목록 조회 + r.GET("/tags", handler.GetTags(client)) }