From cf036565c4dc8a7c051ae22e2ceda1522393168e Mon Sep 17 00:00:00 2001 From: Alexander Vorobyov Date: Wed, 31 Jul 2024 07:58:22 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B2=D1=8B=D0=B9=20=D0=BF?= =?UTF-8?q?=D1=80=D0=BE=D1=82=D0=BE=D1=82=D0=B8=D0=BF=20=D1=81=20=D0=BE?= =?UTF-8?q?=D1=81=D0=BD=D0=BE=D0=B2=D0=BD=D1=8B=D0=BC=D0=B8=20=D0=B2=D0=BE?= =?UTF-8?q?=D0=B7=D0=BC=D0=BE=D0=B6=D0=BD=D0=BE=D1=81=D1=82=D1=8F=D0=BC?= =?UTF-8?q?=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .air.toml | 18 + .gitignore | 3 + Makefile | 22 + README.md | 3 +- config/env.go | 24 + db/ent.go | 41 ++ ent/client.go | 517 ++++++++++++++++++++ ent/ent.go | 610 +++++++++++++++++++++++ ent/enttest/enttest.go | 84 ++++ ent/generate.go | 3 + ent/hook/hook.go | 211 ++++++++ ent/link.go | 141 ++++++ ent/link/link.go | 98 ++++ ent/link/where.go | 233 +++++++++ ent/link_create.go | 266 ++++++++++ ent/link_delete.go | 88 ++++ ent/link_query.go | 638 ++++++++++++++++++++++++ ent/link_update.go | 433 +++++++++++++++++ ent/migrate/migrate.go | 64 +++ ent/migrate/schema.go | 77 +++ ent/mutation.go | 970 +++++++++++++++++++++++++++++++++++++ ent/predicate/predicate.go | 13 + ent/runtime.go | 32 ++ ent/runtime/runtime.go | 10 + ent/schema/link.go | 44 ++ ent/schema/user.go | 33 ++ ent/tx.go | 213 ++++++++ ent/user.go | 130 +++++ ent/user/user.go | 88 ++++ ent/user/where.go | 138 ++++++ ent/user_create.go | 245 ++++++++++ ent/user_delete.go | 88 ++++ ent/user_query.go | 638 ++++++++++++++++++++++++ ent/user_update.go | 339 +++++++++++++ go.mod | 43 ++ go.sum | 122 +++++ handlers.go | 45 ++ main.go | 84 ++++ services/key.go | 38 ++ services/link.go | 44 ++ services/user.go | 40 ++ 41 files changed, 6969 insertions(+), 2 deletions(-) create mode 100644 .air.toml create mode 100644 Makefile create mode 100644 config/env.go create mode 100644 db/ent.go create mode 100644 ent/client.go create mode 100644 ent/ent.go create mode 100644 ent/enttest/enttest.go create mode 100644 ent/generate.go create mode 100644 ent/hook/hook.go create mode 100644 ent/link.go create mode 100644 ent/link/link.go create mode 100644 ent/link/where.go create mode 100644 ent/link_create.go create mode 100644 ent/link_delete.go create mode 100644 ent/link_query.go create mode 100644 ent/link_update.go create mode 100644 ent/migrate/migrate.go create mode 100644 ent/migrate/schema.go create mode 100644 ent/mutation.go create mode 100644 ent/predicate/predicate.go create mode 100644 ent/runtime.go create mode 100644 ent/runtime/runtime.go create mode 100644 ent/schema/link.go create mode 100644 ent/schema/user.go create mode 100644 ent/tx.go create mode 100644 ent/user.go create mode 100644 ent/user/user.go create mode 100644 ent/user/where.go create mode 100644 ent/user_create.go create mode 100644 ent/user_delete.go create mode 100644 ent/user_query.go create mode 100644 ent/user_update.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 handlers.go create mode 100644 main.go create mode 100644 services/key.go create mode 100644 services/link.go create mode 100644 services/user.go diff --git a/.air.toml b/.air.toml new file mode 100644 index 0000000..a7a3166 --- /dev/null +++ b/.air.toml @@ -0,0 +1,18 @@ +root = "." +tmp_dir = ".air" + +[build] +pre_cmd = ["killall -9 muninn 2>/dev/null || true"] # kill off potential zombie processes from previous runs +cmd = "make --no-print-directory build" +bin = "muninn" +delay = 2000 +include_ext = ["go"] +include_file = ["main.go"] +include_dir = [] +exclude_dir = [ +] +exclude_regex = ["_test.go$", "_gen.go$"] +stop_on_error = true + +[log] +main_only = true \ No newline at end of file diff --git a/.gitignore b/.gitignore index adf8f72..496280b 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,6 @@ # Go workspace file go.work +.air/ +/muninn + diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..c28125a --- /dev/null +++ b/Makefile @@ -0,0 +1,22 @@ +AIR_PACKAGE ?= github.com/air-verse/air@v1 + +GO ?= go +HAS_GO := $(shell hash $(GO) > /dev/null 2>&1 && echo yes) + +GOFLAGS := -v +EXECUTABLE ?= muninn + +.PHONY: $(EXECUTABLE) +$(EXECUTABLE): + $(GO) build $(GOFLAGS) $(EXTRA_GOFLAGS) -tags '$(TAGS)' -ldflags '-s -w $(LDFLAGS)' -o $@ + +.PHONY: build +build: $(EXECUTABLE) + +.PHONY: deps-tools +deps-tools: + $(GO) install $(AIR_PACKAGE) + +.PHONY: watch +watch: + $(GO) run $(AIR_PACKAGE) -c .air.toml \ No newline at end of file diff --git a/README.md b/README.md index e27a8d8..6fb86b5 100644 --- a/README.md +++ b/README.md @@ -1,2 +1 @@ -# muninn-simple - +# Muninn All-In-One diff --git a/config/env.go b/config/env.go new file mode 100644 index 0000000..e8311b9 --- /dev/null +++ b/config/env.go @@ -0,0 +1,24 @@ +package config + +import ( + "github.com/kelseyhightower/envconfig" +) + +type Specification struct { + AppPort string `envconfig:"APP_PORT" default:":3000"` + AppUrl string `envconfig:"APP_URL" required:"true"` + DBType string `envconfig:"DATABASE_TYPE" default:"sqlite3"` + DBDSN string `envconfig:"DATABASE_DSN" default:"file:muninn.db?&cache=shared&_fk=1"` + TelegramToken string `envconfig:"TELEGRAM_TOKEN" required:"true"` + // DBSSLMode +} + +var Env Specification + +func Load() { + err := envconfig.Process("muninn", &Env) + + if err != nil { + panic(err) + } +} diff --git a/db/ent.go b/db/ent.go new file mode 100644 index 0000000..01bc230 --- /dev/null +++ b/db/ent.go @@ -0,0 +1,41 @@ +package db + +import ( + "context" + "log" + + "code.gurenya.net/carlsmei/muninn-aio/config" + "code.gurenya.net/carlsmei/muninn-aio/ent" +) + +var ( + entClient *ent.Client +) + +func GetEntClient() *ent.Client { + return entClient +} + +func SetEntClient(new *ent.Client) { + entClient = new +} + +func EntInit() { + driver := config.Env.DBType + dsn := config.Env.DBDSN + + if driver != "sqlite3" && driver != "pq" && driver != "mysql" { + panic("unsupported driver") + } + + client, err := ent.Open(driver, dsn) + if err != nil { + log.Fatalf("failed opening connection to sqlite: %v", err) + } + + if err := client.Schema.Create(context.Background()); err != nil { + log.Fatalf("failed creating schema resources: %v", err) + } + + entClient = client +} diff --git a/ent/client.go b/ent/client.go new file mode 100644 index 0000000..8c6daad --- /dev/null +++ b/ent/client.go @@ -0,0 +1,517 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "log" + "reflect" + + "code.gurenya.net/carlsmei/muninn-aio/ent/migrate" + "github.com/google/uuid" + + "code.gurenya.net/carlsmei/muninn-aio/ent/link" + "code.gurenya.net/carlsmei/muninn-aio/ent/user" + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// Client is the client that holds all ent builders. +type Client struct { + config + // Schema is the client for creating, migrating and dropping schema. + Schema *migrate.Schema + // Link is the client for interacting with the Link builders. + Link *LinkClient + // User is the client for interacting with the User builders. + User *UserClient +} + +// NewClient creates a new client configured with the given options. +func NewClient(opts ...Option) *Client { + client := &Client{config: newConfig(opts...)} + client.init() + return client +} + +func (c *Client) init() { + c.Schema = migrate.NewSchema(c.driver) + c.Link = NewLinkClient(c.config) + c.User = NewUserClient(c.config) +} + +type ( + // config is the configuration for the client and its builder. + config struct { + // driver used for executing database requests. + driver dialect.Driver + // debug enable a debug logging. + debug bool + // log used for logging on debug mode. + log func(...any) + // hooks to execute on mutations. + hooks *hooks + // interceptors to execute on queries. + inters *inters + } + // Option function to configure the client. + Option func(*config) +) + +// newConfig creates a new config for the client. +func newConfig(opts ...Option) config { + cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}} + cfg.options(opts...) + return cfg +} + +// options applies the options on the config object. +func (c *config) options(opts ...Option) { + for _, opt := range opts { + opt(c) + } + if c.debug { + c.driver = dialect.Debug(c.driver, c.log) + } +} + +// Debug enables debug logging on the ent.Driver. +func Debug() Option { + return func(c *config) { + c.debug = true + } +} + +// Log sets the logging function for debug mode. +func Log(fn func(...any)) Option { + return func(c *config) { + c.log = fn + } +} + +// Driver configures the client driver. +func Driver(driver dialect.Driver) Option { + return func(c *config) { + c.driver = driver + } +} + +// Open opens a database/sql.DB specified by the driver name and +// the data source name, and returns a new client attached to it. +// Optional parameters can be added for configuring the client. +func Open(driverName, dataSourceName string, options ...Option) (*Client, error) { + switch driverName { + case dialect.MySQL, dialect.Postgres, dialect.SQLite: + drv, err := sql.Open(driverName, dataSourceName) + if err != nil { + return nil, err + } + return NewClient(append(options, Driver(drv))...), nil + default: + return nil, fmt.Errorf("unsupported driver: %q", driverName) + } +} + +// ErrTxStarted is returned when trying to start a new transaction from a transactional client. +var ErrTxStarted = errors.New("ent: cannot start a transaction within a transaction") + +// Tx returns a new transactional client. The provided context +// is used until the transaction is committed or rolled back. +func (c *Client) Tx(ctx context.Context) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, ErrTxStarted + } + tx, err := newTx(ctx, c.driver) + if err != nil { + return nil, fmt.Errorf("ent: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = tx + return &Tx{ + ctx: ctx, + config: cfg, + Link: NewLinkClient(cfg), + User: NewUserClient(cfg), + }, nil +} + +// BeginTx returns a transactional client with specified options. +func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, errors.New("ent: cannot start a transaction within a transaction") + } + tx, err := c.driver.(interface { + BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error) + }).BeginTx(ctx, opts) + if err != nil { + return nil, fmt.Errorf("ent: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = &txDriver{tx: tx, drv: c.driver} + return &Tx{ + ctx: ctx, + config: cfg, + Link: NewLinkClient(cfg), + User: NewUserClient(cfg), + }, nil +} + +// Debug returns a new debug-client. It's used to get verbose logging on specific operations. +// +// client.Debug(). +// Link. +// Query(). +// Count(ctx) +func (c *Client) Debug() *Client { + if c.debug { + return c + } + cfg := c.config + cfg.driver = dialect.Debug(c.driver, c.log) + client := &Client{config: cfg} + client.init() + return client +} + +// Close closes the database connection and prevents new queries from starting. +func (c *Client) Close() error { + return c.driver.Close() +} + +// Use adds the mutation hooks to all the entity clients. +// In order to add hooks to a specific client, call: `client.Node.Use(...)`. +func (c *Client) Use(hooks ...Hook) { + c.Link.Use(hooks...) + c.User.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.Link.Intercept(interceptors...) + c.User.Intercept(interceptors...) +} + +// Mutate implements the ent.Mutator interface. +func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { + switch m := m.(type) { + case *LinkMutation: + return c.Link.mutate(ctx, m) + case *UserMutation: + return c.User.mutate(ctx, m) + default: + return nil, fmt.Errorf("ent: unknown mutation type %T", m) + } +} + +// LinkClient is a client for the Link schema. +type LinkClient struct { + config +} + +// NewLinkClient returns a client for the Link from the given config. +func NewLinkClient(c config) *LinkClient { + return &LinkClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `link.Hooks(f(g(h())))`. +func (c *LinkClient) Use(hooks ...Hook) { + c.hooks.Link = append(c.hooks.Link, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `link.Intercept(f(g(h())))`. +func (c *LinkClient) Intercept(interceptors ...Interceptor) { + c.inters.Link = append(c.inters.Link, interceptors...) +} + +// Create returns a builder for creating a Link entity. +func (c *LinkClient) Create() *LinkCreate { + mutation := newLinkMutation(c.config, OpCreate) + return &LinkCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Link entities. +func (c *LinkClient) CreateBulk(builders ...*LinkCreate) *LinkCreateBulk { + return &LinkCreateBulk{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 *LinkClient) MapCreateBulk(slice any, setFunc func(*LinkCreate, int)) *LinkCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &LinkCreateBulk{err: fmt.Errorf("calling to LinkClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*LinkCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &LinkCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Link. +func (c *LinkClient) Update() *LinkUpdate { + mutation := newLinkMutation(c.config, OpUpdate) + return &LinkUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LinkClient) UpdateOne(l *Link) *LinkUpdateOne { + mutation := newLinkMutation(c.config, OpUpdateOne, withLink(l)) + return &LinkUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LinkClient) UpdateOneID(id uuid.UUID) *LinkUpdateOne { + mutation := newLinkMutation(c.config, OpUpdateOne, withLinkID(id)) + return &LinkUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Link. +func (c *LinkClient) Delete() *LinkDelete { + mutation := newLinkMutation(c.config, OpDelete) + return &LinkDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *LinkClient) DeleteOne(l *Link) *LinkDeleteOne { + return c.DeleteOneID(l.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *LinkClient) DeleteOneID(id uuid.UUID) *LinkDeleteOne { + builder := c.Delete().Where(link.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LinkDeleteOne{builder} +} + +// Query returns a query builder for Link. +func (c *LinkClient) Query() *LinkQuery { + return &LinkQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeLink}, + inters: c.Interceptors(), + } +} + +// Get returns a Link entity by its id. +func (c *LinkClient) Get(ctx context.Context, id uuid.UUID) (*Link, error) { + return c.Query().Where(link.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LinkClient) GetX(ctx context.Context, id uuid.UUID) *Link { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryOwner queries the owner edge of a Link. +func (c *LinkClient) QueryOwner(l *Link) *UserQuery { + query := (&UserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := l.ID + step := sqlgraph.NewStep( + sqlgraph.From(link.Table, link.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, link.OwnerTable, link.OwnerPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(l.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *LinkClient) Hooks() []Hook { + return c.hooks.Link +} + +// Interceptors returns the client interceptors. +func (c *LinkClient) Interceptors() []Interceptor { + return c.inters.Link +} + +func (c *LinkClient) mutate(ctx context.Context, m *LinkMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&LinkCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&LinkUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&LinkUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&LinkDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Link mutation op: %q", m.Op()) + } +} + +// UserClient is a client for the User schema. +type UserClient struct { + config +} + +// NewUserClient returns a client for the User from the given config. +func NewUserClient(c config) *UserClient { + return &UserClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `user.Hooks(f(g(h())))`. +func (c *UserClient) Use(hooks ...Hook) { + c.hooks.User = append(c.hooks.User, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `user.Intercept(f(g(h())))`. +func (c *UserClient) Intercept(interceptors ...Interceptor) { + c.inters.User = append(c.inters.User, interceptors...) +} + +// Create returns a builder for creating a User entity. +func (c *UserClient) Create() *UserCreate { + mutation := newUserMutation(c.config, OpCreate) + return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of User entities. +func (c *UserClient) CreateBulk(builders ...*UserCreate) *UserCreateBulk { + return &UserCreateBulk{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 *UserClient) MapCreateBulk(slice any, setFunc func(*UserCreate, int)) *UserCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &UserCreateBulk{err: fmt.Errorf("calling to UserClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*UserCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &UserCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for User. +func (c *UserClient) Update() *UserUpdate { + mutation := newUserMutation(c.config, OpUpdate) + return &UserUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *UserClient) UpdateOne(u *User) *UserUpdateOne { + mutation := newUserMutation(c.config, OpUpdateOne, withUser(u)) + return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *UserClient) UpdateOneID(id uuid.UUID) *UserUpdateOne { + mutation := newUserMutation(c.config, OpUpdateOne, withUserID(id)) + return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for User. +func (c *UserClient) Delete() *UserDelete { + mutation := newUserMutation(c.config, OpDelete) + return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { + return c.DeleteOneID(u.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *UserClient) DeleteOneID(id uuid.UUID) *UserDeleteOne { + builder := c.Delete().Where(user.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &UserDeleteOne{builder} +} + +// Query returns a query builder for User. +func (c *UserClient) Query() *UserQuery { + return &UserQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeUser}, + inters: c.Interceptors(), + } +} + +// Get returns a User entity by its id. +func (c *UserClient) Get(ctx context.Context, id uuid.UUID) (*User, error) { + return c.Query().Where(user.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *UserClient) GetX(ctx context.Context, id uuid.UUID) *User { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryLinks queries the links edge of a User. +func (c *UserClient) QueryLinks(u *User) *LinkQuery { + query := (&LinkClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := u.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(link.Table, link.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, user.LinksTable, user.LinksPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *UserClient) Hooks() []Hook { + return c.hooks.User +} + +// Interceptors returns the client interceptors. +func (c *UserClient) Interceptors() []Interceptor { + return c.inters.User +} + +func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&UserCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&UserUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&UserDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown User mutation op: %q", m.Op()) + } +} + +// hooks and interceptors per client, for fast access. +type ( + hooks struct { + Link, User []ent.Hook + } + inters struct { + Link, User []ent.Interceptor + } +) diff --git a/ent/ent.go b/ent/ent.go new file mode 100644 index 0000000..64b6204 --- /dev/null +++ b/ent/ent.go @@ -0,0 +1,610 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "reflect" + "sync" + + "code.gurenya.net/carlsmei/muninn-aio/ent/link" + "code.gurenya.net/carlsmei/muninn-aio/ent/user" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// ent aliases to avoid import conflicts in user's code. +type ( + Op = ent.Op + Hook = ent.Hook + Value = ent.Value + Query = ent.Query + QueryContext = ent.QueryContext + Querier = ent.Querier + QuerierFunc = ent.QuerierFunc + Interceptor = ent.Interceptor + InterceptFunc = ent.InterceptFunc + Traverser = ent.Traverser + TraverseFunc = ent.TraverseFunc + Policy = ent.Policy + Mutator = ent.Mutator + Mutation = ent.Mutation + MutateFunc = ent.MutateFunc +) + +type clientCtxKey struct{} + +// FromContext returns a Client stored inside a context, or nil if there isn't one. +func FromContext(ctx context.Context) *Client { + c, _ := ctx.Value(clientCtxKey{}).(*Client) + return c +} + +// NewContext returns a new context with the given Client attached. +func NewContext(parent context.Context, c *Client) context.Context { + return context.WithValue(parent, clientCtxKey{}, c) +} + +type txCtxKey struct{} + +// TxFromContext returns a Tx stored inside a context, or nil if there isn't one. +func TxFromContext(ctx context.Context) *Tx { + tx, _ := ctx.Value(txCtxKey{}).(*Tx) + return tx +} + +// NewTxContext returns a new context with the given Tx attached. +func NewTxContext(parent context.Context, tx *Tx) context.Context { + return context.WithValue(parent, txCtxKey{}, tx) +} + +// OrderFunc applies an ordering on the sql selector. +// Deprecated: Use Asc/Desc functions or the package builders instead. +type OrderFunc func(*sql.Selector) + +var ( + initCheck sync.Once + columnCheck sql.ColumnCheck +) + +// checkColumn checks if the column exists in the given table. +func checkColumn(table, column string) error { + initCheck.Do(func() { + columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ + link.Table: link.ValidColumn, + user.Table: user.ValidColumn, + }) + }) + return columnCheck(table, column) +} + +// Asc applies the given fields in ASC order. +func Asc(fields ...string) func(*sql.Selector) { + return func(s *sql.Selector) { + for _, f := range fields { + if err := checkColumn(s.TableName(), f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)}) + } + s.OrderBy(sql.Asc(s.C(f))) + } + } +} + +// Desc applies the given fields in DESC order. +func Desc(fields ...string) func(*sql.Selector) { + return func(s *sql.Selector) { + for _, f := range fields { + if err := checkColumn(s.TableName(), f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)}) + } + s.OrderBy(sql.Desc(s.C(f))) + } + } +} + +// AggregateFunc applies an aggregation step on the group-by traversal/selector. +type AggregateFunc func(*sql.Selector) string + +// As is a pseudo aggregation function for renaming another other functions with custom names. For example: +// +// GroupBy(field1, field2). +// Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")). +// Scan(ctx, &v) +func As(fn AggregateFunc, end string) AggregateFunc { + return func(s *sql.Selector) string { + return sql.As(fn(s), end) + } +} + +// Count applies the "count" aggregation function on each group. +func Count() AggregateFunc { + return func(s *sql.Selector) string { + return sql.Count("*") + } +} + +// Max applies the "max" aggregation function on the given field of each group. +func Max(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) + return "" + } + return sql.Max(s.C(field)) + } +} + +// Mean applies the "mean" aggregation function on the given field of each group. +func Mean(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) + return "" + } + return sql.Avg(s.C(field)) + } +} + +// Min applies the "min" aggregation function on the given field of each group. +func Min(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) + return "" + } + return sql.Min(s.C(field)) + } +} + +// Sum applies the "sum" aggregation function on the given field of each group. +func Sum(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) + return "" + } + return sql.Sum(s.C(field)) + } +} + +// ValidationError returns when validating a field or edge fails. +type ValidationError struct { + Name string // Field or edge name. + err error +} + +// Error implements the error interface. +func (e *ValidationError) Error() string { + return e.err.Error() +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ValidationError) Unwrap() error { + return e.err +} + +// IsValidationError returns a boolean indicating whether the error is a validation error. +func IsValidationError(err error) bool { + if err == nil { + return false + } + var e *ValidationError + return errors.As(err, &e) +} + +// NotFoundError returns when trying to fetch a specific entity and it was not found in the database. +type NotFoundError struct { + label string +} + +// Error implements the error interface. +func (e *NotFoundError) Error() string { + return "ent: " + e.label + " not found" +} + +// IsNotFound returns a boolean indicating whether the error is a not found error. +func IsNotFound(err error) bool { + if err == nil { + return false + } + var e *NotFoundError + return errors.As(err, &e) +} + +// MaskNotFound masks not found error. +func MaskNotFound(err error) error { + if IsNotFound(err) { + return nil + } + return err +} + +// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database. +type NotSingularError struct { + label string +} + +// Error implements the error interface. +func (e *NotSingularError) Error() string { + return "ent: " + e.label + " not singular" +} + +// IsNotSingular returns a boolean indicating whether the error is a not singular error. +func IsNotSingular(err error) bool { + if err == nil { + return false + } + var e *NotSingularError + return errors.As(err, &e) +} + +// NotLoadedError returns when trying to get a node that was not loaded by the query. +type NotLoadedError struct { + edge string +} + +// Error implements the error interface. +func (e *NotLoadedError) Error() string { + return "ent: " + e.edge + " edge was not loaded" +} + +// IsNotLoaded returns a boolean indicating whether the error is a not loaded error. +func IsNotLoaded(err error) bool { + if err == nil { + return false + } + var e *NotLoadedError + return errors.As(err, &e) +} + +// ConstraintError returns when trying to create/update one or more entities and +// one or more of their constraints failed. For example, violation of edge or +// field uniqueness. +type ConstraintError struct { + msg string + wrap error +} + +// Error implements the error interface. +func (e ConstraintError) Error() string { + return "ent: constraint failed: " + e.msg +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ConstraintError) Unwrap() error { + return e.wrap +} + +// IsConstraintError returns a boolean indicating whether the error is a constraint failure. +func IsConstraintError(err error) bool { + if err == nil { + return false + } + var e *ConstraintError + return errors.As(err, &e) +} + +// selector embedded by the different Select/GroupBy builders. +type selector struct { + label string + flds *[]string + fns []AggregateFunc + scan func(context.Context, any) error +} + +// ScanX is like Scan, but panics if an error occurs. +func (s *selector) ScanX(ctx context.Context, v any) { + if err := s.scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (s *selector) Strings(ctx context.Context) ([]string, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (s *selector) StringsX(ctx context.Context) []string { + v, err := s.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (s *selector) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = s.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (s *selector) StringX(ctx context.Context) string { + v, err := s.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (s *selector) Ints(ctx context.Context) ([]int, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (s *selector) IntsX(ctx context.Context) []int { + v, err := s.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (s *selector) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = s.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (s *selector) IntX(ctx context.Context) int { + v, err := s.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (s *selector) Float64s(ctx context.Context) ([]float64, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (s *selector) Float64sX(ctx context.Context) []float64 { + v, err := s.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (s *selector) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = s.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (s *selector) Float64X(ctx context.Context) float64 { + v, err := s.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (s *selector) Bools(ctx context.Context) ([]bool, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (s *selector) BoolsX(ctx context.Context) []bool { + v, err := s.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (s *selector) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = s.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (s *selector) BoolX(ctx context.Context) bool { + v, err := s.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +// withHooks invokes the builder operation with the given hooks, if any. +func withHooks[V Value, M any, PM interface { + *M + Mutation +}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) { + if len(hooks) == 0 { + return exec(ctx) + } + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutationT, ok := any(m).(PM) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + // Set the mutation to the builder. + *mutation = *mutationT + return exec(ctx) + }) + for i := len(hooks) - 1; i >= 0; i-- { + if hooks[i] == nil { + return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = hooks[i](mut) + } + v, err := mut.Mutate(ctx, mutation) + if err != nil { + return value, err + } + nv, ok := v.(V) + if !ok { + return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation) + } + return nv, nil +} + +// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist. +func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context { + if ent.QueryFromContext(ctx) == nil { + qc.Op = op + ctx = ent.NewQueryContext(ctx, qc) + } + return ctx +} + +func querierAll[V Value, Q interface { + sqlAll(context.Context, ...queryHook) (V, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlAll(ctx) + }) +} + +func querierCount[Q interface { + sqlCount(context.Context) (int, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlCount(ctx) + }) +} + +func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) { + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + rv, err := qr.Query(ctx, q) + if err != nil { + return v, err + } + vt, ok := rv.(V) + if !ok { + return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v) + } + return vt, nil +} + +func scanWithInterceptors[Q1 ent.Query, Q2 interface { + sqlScan(context.Context, Q1, any) error +}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error { + rv := reflect.ValueOf(v) + var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q1) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + if err := selectOrGroup.sqlScan(ctx, query, v); err != nil { + return nil, err + } + if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() { + return rv.Elem().Interface(), nil + } + return v, nil + }) + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + vv, err := qr.Query(ctx, rootQuery) + if err != nil { + return err + } + switch rv2 := reflect.ValueOf(vv); { + case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer: + case rv.Type() == rv2.Type(): + rv.Elem().Set(rv2.Elem()) + case rv.Elem().Type() == rv2.Type(): + rv.Elem().Set(rv2) + } + return nil +} + +// queryHook describes an internal hook for the different sqlAll methods. +type queryHook func(context.Context, *sqlgraph.QuerySpec) diff --git a/ent/enttest/enttest.go b/ent/enttest/enttest.go new file mode 100644 index 0000000..5463735 --- /dev/null +++ b/ent/enttest/enttest.go @@ -0,0 +1,84 @@ +// Code generated by ent, DO NOT EDIT. + +package enttest + +import ( + "context" + + "code.gurenya.net/carlsmei/muninn-aio/ent" + // required by schema hooks. + _ "code.gurenya.net/carlsmei/muninn-aio/ent/runtime" + + "code.gurenya.net/carlsmei/muninn-aio/ent/migrate" + "entgo.io/ent/dialect/sql/schema" +) + +type ( + // TestingT is the interface that is shared between + // testing.T and testing.B and used by enttest. + TestingT interface { + FailNow() + Error(...any) + } + + // Option configures client creation. + Option func(*options) + + options struct { + opts []ent.Option + migrateOpts []schema.MigrateOption + } +) + +// WithOptions forwards options to client creation. +func WithOptions(opts ...ent.Option) Option { + return func(o *options) { + o.opts = append(o.opts, opts...) + } +} + +// WithMigrateOptions forwards options to auto migration. +func WithMigrateOptions(opts ...schema.MigrateOption) Option { + return func(o *options) { + o.migrateOpts = append(o.migrateOpts, opts...) + } +} + +func newOptions(opts []Option) *options { + o := &options{} + for _, opt := range opts { + opt(o) + } + return o +} + +// Open calls ent.Open and auto-run migration. +func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Client { + o := newOptions(opts) + c, err := ent.Open(driverName, dataSourceName, o.opts...) + if err != nil { + t.Error(err) + t.FailNow() + } + migrateSchema(t, c, o) + return c +} + +// NewClient calls ent.NewClient and auto-run migration. +func NewClient(t TestingT, opts ...Option) *ent.Client { + o := newOptions(opts) + c := ent.NewClient(o.opts...) + migrateSchema(t, c, o) + return c +} +func migrateSchema(t TestingT, c *ent.Client, o *options) { + tables, err := schema.CopyTables(migrate.Tables) + if err != nil { + t.Error(err) + t.FailNow() + } + if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil { + t.Error(err) + t.FailNow() + } +} diff --git a/ent/generate.go b/ent/generate.go new file mode 100644 index 0000000..8d3fdfd --- /dev/null +++ b/ent/generate.go @@ -0,0 +1,3 @@ +package ent + +//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate ./schema diff --git a/ent/hook/hook.go b/ent/hook/hook.go new file mode 100644 index 0000000..26df08c --- /dev/null +++ b/ent/hook/hook.go @@ -0,0 +1,211 @@ +// Code generated by ent, DO NOT EDIT. + +package hook + +import ( + "context" + "fmt" + + "code.gurenya.net/carlsmei/muninn-aio/ent" +) + +// The LinkFunc type is an adapter to allow the use of ordinary +// function as Link mutator. +type LinkFunc func(context.Context, *ent.LinkMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f LinkFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.LinkMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.LinkMutation", m) +} + +// The UserFunc type is an adapter to allow the use of ordinary +// function as User mutator. +type UserFunc func(context.Context, *ent.UserMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f UserFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.UserMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserMutation", m) +} + +// Condition is a hook condition function. +type Condition func(context.Context, ent.Mutation) bool + +// And groups conditions with the AND operator. +func And(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m ent.Mutation) bool { + if !first(ctx, m) || !second(ctx, m) { + return false + } + for _, cond := range rest { + if !cond(ctx, m) { + return false + } + } + return true + } +} + +// Or groups conditions with the OR operator. +func Or(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m ent.Mutation) bool { + if first(ctx, m) || second(ctx, m) { + return true + } + for _, cond := range rest { + if cond(ctx, m) { + return true + } + } + return false + } +} + +// Not negates a given condition. +func Not(cond Condition) Condition { + return func(ctx context.Context, m ent.Mutation) bool { + return !cond(ctx, m) + } +} + +// HasOp is a condition testing mutation operation. +func HasOp(op ent.Op) Condition { + return func(_ context.Context, m ent.Mutation) bool { + return m.Op().Is(op) + } +} + +// HasAddedFields is a condition validating `.AddedField` on fields. +func HasAddedFields(field string, fields ...string) Condition { + return func(_ context.Context, m ent.Mutation) bool { + if _, exists := m.AddedField(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.AddedField(field); !exists { + return false + } + } + return true + } +} + +// HasClearedFields is a condition validating `.FieldCleared` on fields. +func HasClearedFields(field string, fields ...string) Condition { + return func(_ context.Context, m ent.Mutation) bool { + if exists := m.FieldCleared(field); !exists { + return false + } + for _, field := range fields { + if exists := m.FieldCleared(field); !exists { + return false + } + } + return true + } +} + +// HasFields is a condition validating `.Field` on fields. +func HasFields(field string, fields ...string) Condition { + return func(_ context.Context, m ent.Mutation) bool { + if _, exists := m.Field(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.Field(field); !exists { + return false + } + } + return true + } +} + +// If executes the given hook under condition. +// +// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) +func If(hk ent.Hook, cond Condition) ent.Hook { + return func(next ent.Mutator) ent.Mutator { + return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if cond(ctx, m) { + return hk(next).Mutate(ctx, m) + } + return next.Mutate(ctx, m) + }) + } +} + +// On executes the given hook only for the given operation. +// +// hook.On(Log, ent.Delete|ent.Create) +func On(hk ent.Hook, op ent.Op) ent.Hook { + return If(hk, HasOp(op)) +} + +// Unless skips the given hook only for the given operation. +// +// hook.Unless(Log, ent.Update|ent.UpdateOne) +func Unless(hk ent.Hook, op ent.Op) ent.Hook { + return If(hk, Not(HasOp(op))) +} + +// FixedError is a hook returning a fixed error. +func FixedError(err error) ent.Hook { + return func(ent.Mutator) ent.Mutator { + return ent.MutateFunc(func(context.Context, ent.Mutation) (ent.Value, error) { + return nil, err + }) + } +} + +// Reject returns a hook that rejects all operations that match op. +// +// func (T) Hooks() []ent.Hook { +// return []ent.Hook{ +// Reject(ent.Delete|ent.Update), +// } +// } +func Reject(op ent.Op) ent.Hook { + hk := FixedError(fmt.Errorf("%s operation is not allowed", op)) + return On(hk, op) +} + +// Chain acts as a list of hooks and is effectively immutable. +// Once created, it will always hold the same set of hooks in the same order. +type Chain struct { + hooks []ent.Hook +} + +// NewChain creates a new chain of hooks. +func NewChain(hooks ...ent.Hook) Chain { + return Chain{append([]ent.Hook(nil), hooks...)} +} + +// Hook chains the list of hooks and returns the final hook. +func (c Chain) Hook() ent.Hook { + return func(mutator ent.Mutator) ent.Mutator { + for i := len(c.hooks) - 1; i >= 0; i-- { + mutator = c.hooks[i](mutator) + } + return mutator + } +} + +// Append extends a chain, adding the specified hook +// as the last ones in the mutation flow. +func (c Chain) Append(hooks ...ent.Hook) Chain { + newHooks := make([]ent.Hook, 0, len(c.hooks)+len(hooks)) + newHooks = append(newHooks, c.hooks...) + newHooks = append(newHooks, hooks...) + return Chain{newHooks} +} + +// Extend extends a chain, adding the specified chain +// as the last ones in the mutation flow. +func (c Chain) Extend(chain Chain) Chain { + return c.Append(chain.hooks...) +} diff --git a/ent/link.go b/ent/link.go new file mode 100644 index 0000000..721300b --- /dev/null +++ b/ent/link.go @@ -0,0 +1,141 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "code.gurenya.net/carlsmei/muninn-aio/ent/link" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/google/uuid" +) + +// Link is the model entity for the Link schema. +type Link struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // Key holds the value of the "key" field. + Key string `json:"key,omitempty"` + // OriginalURL holds the value of the "original_url" field. + OriginalURL string `json:"original_url,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the LinkQuery when eager-loading is set. + Edges LinkEdges `json:"edges"` + selectValues sql.SelectValues +} + +// LinkEdges holds the relations/edges for other nodes in the graph. +type LinkEdges struct { + // Owner holds the value of the owner edge. + Owner []*User `json:"owner,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// OwnerOrErr returns the Owner value or an error if the edge +// was not loaded in eager-loading. +func (e LinkEdges) OwnerOrErr() ([]*User, error) { + if e.loadedTypes[0] { + return e.Owner, nil + } + return nil, &NotLoadedError{edge: "owner"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Link) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case link.FieldKey, link.FieldOriginalURL: + values[i] = new(sql.NullString) + case link.FieldID: + values[i] = new(uuid.UUID) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Link fields. +func (l *Link) 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 link.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + l.ID = *value + } + case link.FieldKey: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field key", values[i]) + } else if value.Valid { + l.Key = value.String + } + case link.FieldOriginalURL: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field original_url", values[i]) + } else if value.Valid { + l.OriginalURL = value.String + } + default: + l.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Link. +// This includes values selected through modifiers, order, etc. +func (l *Link) Value(name string) (ent.Value, error) { + return l.selectValues.Get(name) +} + +// QueryOwner queries the "owner" edge of the Link entity. +func (l *Link) QueryOwner() *UserQuery { + return NewLinkClient(l.config).QueryOwner(l) +} + +// Update returns a builder for updating this Link. +// Note that you need to call Link.Unwrap() before calling this method if this Link +// was returned from a transaction, and the transaction was committed or rolled back. +func (l *Link) Update() *LinkUpdateOne { + return NewLinkClient(l.config).UpdateOne(l) +} + +// Unwrap unwraps the Link 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 (l *Link) Unwrap() *Link { + _tx, ok := l.config.driver.(*txDriver) + if !ok { + panic("ent: Link is not a transactional entity") + } + l.config.driver = _tx.drv + return l +} + +// String implements the fmt.Stringer. +func (l *Link) String() string { + var builder strings.Builder + builder.WriteString("Link(") + builder.WriteString(fmt.Sprintf("id=%v, ", l.ID)) + builder.WriteString("key=") + builder.WriteString(l.Key) + builder.WriteString(", ") + builder.WriteString("original_url=") + builder.WriteString(l.OriginalURL) + builder.WriteByte(')') + return builder.String() +} + +// Links is a parsable slice of Link. +type Links []*Link diff --git a/ent/link/link.go b/ent/link/link.go new file mode 100644 index 0000000..20e2ee8 --- /dev/null +++ b/ent/link/link.go @@ -0,0 +1,98 @@ +// Code generated by ent, DO NOT EDIT. + +package link + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/google/uuid" +) + +const ( + // Label holds the string label denoting the link type in the database. + Label = "link" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldKey holds the string denoting the key field in the database. + FieldKey = "key" + // FieldOriginalURL holds the string denoting the original_url field in the database. + FieldOriginalURL = "original_url" + // EdgeOwner holds the string denoting the owner edge name in mutations. + EdgeOwner = "owner" + // Table holds the table name of the link in the database. + Table = "links" + // OwnerTable is the table that holds the owner relation/edge. The primary key declared below. + OwnerTable = "user_links" + // OwnerInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + OwnerInverseTable = "users" +) + +// Columns holds all SQL columns for link fields. +var Columns = []string{ + FieldID, + FieldKey, + FieldOriginalURL, +} + +var ( + // OwnerPrimaryKey and OwnerColumn2 are the table columns denoting the + // primary key for the owner relation (M2M). + OwnerPrimaryKey = []string{"user_id", "link_id"} +) + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // OriginalURLValidator is a validator for the "original_url" field. It is called by the builders before save. + OriginalURLValidator func(string) error + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() uuid.UUID +) + +// OrderOption defines the ordering options for the Link 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() +} + +// ByKey orders the results by the key field. +func ByKey(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldKey, opts...).ToFunc() +} + +// ByOriginalURL orders the results by the original_url field. +func ByOriginalURL(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldOriginalURL, opts...).ToFunc() +} + +// ByOwnerCount orders the results by owner count. +func ByOwnerCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newOwnerStep(), opts...) + } +} + +// ByOwner orders the results by owner terms. +func ByOwner(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newOwnerStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newOwnerStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(OwnerInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, OwnerTable, OwnerPrimaryKey...), + ) +} diff --git a/ent/link/where.go b/ent/link/where.go new file mode 100644 index 0000000..9043548 --- /dev/null +++ b/ent/link/where.go @@ -0,0 +1,233 @@ +// Code generated by ent, DO NOT EDIT. + +package link + +import ( + "code.gurenya.net/carlsmei/muninn-aio/ent/predicate" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.Link { + return predicate.Link(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.Link { + return predicate.Link(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.Link { + return predicate.Link(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.Link { + return predicate.Link(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.Link { + return predicate.Link(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.Link { + return predicate.Link(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.Link { + return predicate.Link(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.Link { + return predicate.Link(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.Link { + return predicate.Link(sql.FieldLTE(FieldID, id)) +} + +// Key applies equality check predicate on the "key" field. It's identical to KeyEQ. +func Key(v string) predicate.Link { + return predicate.Link(sql.FieldEQ(FieldKey, v)) +} + +// OriginalURL applies equality check predicate on the "original_url" field. It's identical to OriginalURLEQ. +func OriginalURL(v string) predicate.Link { + return predicate.Link(sql.FieldEQ(FieldOriginalURL, v)) +} + +// KeyEQ applies the EQ predicate on the "key" field. +func KeyEQ(v string) predicate.Link { + return predicate.Link(sql.FieldEQ(FieldKey, v)) +} + +// KeyNEQ applies the NEQ predicate on the "key" field. +func KeyNEQ(v string) predicate.Link { + return predicate.Link(sql.FieldNEQ(FieldKey, v)) +} + +// KeyIn applies the In predicate on the "key" field. +func KeyIn(vs ...string) predicate.Link { + return predicate.Link(sql.FieldIn(FieldKey, vs...)) +} + +// KeyNotIn applies the NotIn predicate on the "key" field. +func KeyNotIn(vs ...string) predicate.Link { + return predicate.Link(sql.FieldNotIn(FieldKey, vs...)) +} + +// KeyGT applies the GT predicate on the "key" field. +func KeyGT(v string) predicate.Link { + return predicate.Link(sql.FieldGT(FieldKey, v)) +} + +// KeyGTE applies the GTE predicate on the "key" field. +func KeyGTE(v string) predicate.Link { + return predicate.Link(sql.FieldGTE(FieldKey, v)) +} + +// KeyLT applies the LT predicate on the "key" field. +func KeyLT(v string) predicate.Link { + return predicate.Link(sql.FieldLT(FieldKey, v)) +} + +// KeyLTE applies the LTE predicate on the "key" field. +func KeyLTE(v string) predicate.Link { + return predicate.Link(sql.FieldLTE(FieldKey, v)) +} + +// KeyContains applies the Contains predicate on the "key" field. +func KeyContains(v string) predicate.Link { + return predicate.Link(sql.FieldContains(FieldKey, v)) +} + +// KeyHasPrefix applies the HasPrefix predicate on the "key" field. +func KeyHasPrefix(v string) predicate.Link { + return predicate.Link(sql.FieldHasPrefix(FieldKey, v)) +} + +// KeyHasSuffix applies the HasSuffix predicate on the "key" field. +func KeyHasSuffix(v string) predicate.Link { + return predicate.Link(sql.FieldHasSuffix(FieldKey, v)) +} + +// KeyEqualFold applies the EqualFold predicate on the "key" field. +func KeyEqualFold(v string) predicate.Link { + return predicate.Link(sql.FieldEqualFold(FieldKey, v)) +} + +// KeyContainsFold applies the ContainsFold predicate on the "key" field. +func KeyContainsFold(v string) predicate.Link { + return predicate.Link(sql.FieldContainsFold(FieldKey, v)) +} + +// OriginalURLEQ applies the EQ predicate on the "original_url" field. +func OriginalURLEQ(v string) predicate.Link { + return predicate.Link(sql.FieldEQ(FieldOriginalURL, v)) +} + +// OriginalURLNEQ applies the NEQ predicate on the "original_url" field. +func OriginalURLNEQ(v string) predicate.Link { + return predicate.Link(sql.FieldNEQ(FieldOriginalURL, v)) +} + +// OriginalURLIn applies the In predicate on the "original_url" field. +func OriginalURLIn(vs ...string) predicate.Link { + return predicate.Link(sql.FieldIn(FieldOriginalURL, vs...)) +} + +// OriginalURLNotIn applies the NotIn predicate on the "original_url" field. +func OriginalURLNotIn(vs ...string) predicate.Link { + return predicate.Link(sql.FieldNotIn(FieldOriginalURL, vs...)) +} + +// OriginalURLGT applies the GT predicate on the "original_url" field. +func OriginalURLGT(v string) predicate.Link { + return predicate.Link(sql.FieldGT(FieldOriginalURL, v)) +} + +// OriginalURLGTE applies the GTE predicate on the "original_url" field. +func OriginalURLGTE(v string) predicate.Link { + return predicate.Link(sql.FieldGTE(FieldOriginalURL, v)) +} + +// OriginalURLLT applies the LT predicate on the "original_url" field. +func OriginalURLLT(v string) predicate.Link { + return predicate.Link(sql.FieldLT(FieldOriginalURL, v)) +} + +// OriginalURLLTE applies the LTE predicate on the "original_url" field. +func OriginalURLLTE(v string) predicate.Link { + return predicate.Link(sql.FieldLTE(FieldOriginalURL, v)) +} + +// OriginalURLContains applies the Contains predicate on the "original_url" field. +func OriginalURLContains(v string) predicate.Link { + return predicate.Link(sql.FieldContains(FieldOriginalURL, v)) +} + +// OriginalURLHasPrefix applies the HasPrefix predicate on the "original_url" field. +func OriginalURLHasPrefix(v string) predicate.Link { + return predicate.Link(sql.FieldHasPrefix(FieldOriginalURL, v)) +} + +// OriginalURLHasSuffix applies the HasSuffix predicate on the "original_url" field. +func OriginalURLHasSuffix(v string) predicate.Link { + return predicate.Link(sql.FieldHasSuffix(FieldOriginalURL, v)) +} + +// OriginalURLEqualFold applies the EqualFold predicate on the "original_url" field. +func OriginalURLEqualFold(v string) predicate.Link { + return predicate.Link(sql.FieldEqualFold(FieldOriginalURL, v)) +} + +// OriginalURLContainsFold applies the ContainsFold predicate on the "original_url" field. +func OriginalURLContainsFold(v string) predicate.Link { + return predicate.Link(sql.FieldContainsFold(FieldOriginalURL, v)) +} + +// HasOwner applies the HasEdge predicate on the "owner" edge. +func HasOwner() predicate.Link { + return predicate.Link(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, OwnerTable, OwnerPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasOwnerWith applies the HasEdge predicate on the "owner" edge with a given conditions (other predicates). +func HasOwnerWith(preds ...predicate.User) predicate.Link { + return predicate.Link(func(s *sql.Selector) { + step := newOwnerStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Link) predicate.Link { + return predicate.Link(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Link) predicate.Link { + return predicate.Link(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Link) predicate.Link { + return predicate.Link(sql.NotPredicates(p)) +} diff --git a/ent/link_create.go b/ent/link_create.go new file mode 100644 index 0000000..e26366d --- /dev/null +++ b/ent/link_create.go @@ -0,0 +1,266 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "code.gurenya.net/carlsmei/muninn-aio/ent/link" + "code.gurenya.net/carlsmei/muninn-aio/ent/user" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/google/uuid" +) + +// LinkCreate is the builder for creating a Link entity. +type LinkCreate struct { + config + mutation *LinkMutation + hooks []Hook +} + +// SetKey sets the "key" field. +func (lc *LinkCreate) SetKey(s string) *LinkCreate { + lc.mutation.SetKey(s) + return lc +} + +// SetOriginalURL sets the "original_url" field. +func (lc *LinkCreate) SetOriginalURL(s string) *LinkCreate { + lc.mutation.SetOriginalURL(s) + return lc +} + +// SetID sets the "id" field. +func (lc *LinkCreate) SetID(u uuid.UUID) *LinkCreate { + lc.mutation.SetID(u) + return lc +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (lc *LinkCreate) SetNillableID(u *uuid.UUID) *LinkCreate { + if u != nil { + lc.SetID(*u) + } + return lc +} + +// AddOwnerIDs adds the "owner" edge to the User entity by IDs. +func (lc *LinkCreate) AddOwnerIDs(ids ...uuid.UUID) *LinkCreate { + lc.mutation.AddOwnerIDs(ids...) + return lc +} + +// AddOwner adds the "owner" edges to the User entity. +func (lc *LinkCreate) AddOwner(u ...*User) *LinkCreate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return lc.AddOwnerIDs(ids...) +} + +// Mutation returns the LinkMutation object of the builder. +func (lc *LinkCreate) Mutation() *LinkMutation { + return lc.mutation +} + +// Save creates the Link in the database. +func (lc *LinkCreate) Save(ctx context.Context) (*Link, error) { + lc.defaults() + return withHooks(ctx, lc.sqlSave, lc.mutation, lc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (lc *LinkCreate) SaveX(ctx context.Context) *Link { + v, err := lc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (lc *LinkCreate) Exec(ctx context.Context) error { + _, err := lc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lc *LinkCreate) ExecX(ctx context.Context) { + if err := lc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (lc *LinkCreate) defaults() { + if _, ok := lc.mutation.ID(); !ok { + v := link.DefaultID() + lc.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (lc *LinkCreate) check() error { + if _, ok := lc.mutation.Key(); !ok { + return &ValidationError{Name: "key", err: errors.New(`ent: missing required field "Link.key"`)} + } + if _, ok := lc.mutation.OriginalURL(); !ok { + return &ValidationError{Name: "original_url", err: errors.New(`ent: missing required field "Link.original_url"`)} + } + if v, ok := lc.mutation.OriginalURL(); ok { + if err := link.OriginalURLValidator(v); err != nil { + return &ValidationError{Name: "original_url", err: fmt.Errorf(`ent: validator failed for field "Link.original_url": %w`, err)} + } + } + if len(lc.mutation.OwnerIDs()) == 0 { + return &ValidationError{Name: "owner", err: errors.New(`ent: missing required edge "Link.owner"`)} + } + return nil +} + +func (lc *LinkCreate) sqlSave(ctx context.Context) (*Link, error) { + if err := lc.check(); err != nil { + return nil, err + } + _node, _spec := lc.createSpec() + if err := sqlgraph.CreateNode(ctx, lc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != nil { + if id, ok := _spec.ID.Value.(*uuid.UUID); ok { + _node.ID = *id + } else if err := _node.ID.Scan(_spec.ID.Value); err != nil { + return nil, err + } + } + lc.mutation.id = &_node.ID + lc.mutation.done = true + return _node, nil +} + +func (lc *LinkCreate) createSpec() (*Link, *sqlgraph.CreateSpec) { + var ( + _node = &Link{config: lc.config} + _spec = sqlgraph.NewCreateSpec(link.Table, sqlgraph.NewFieldSpec(link.FieldID, field.TypeUUID)) + ) + if id, ok := lc.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := lc.mutation.Key(); ok { + _spec.SetField(link.FieldKey, field.TypeString, value) + _node.Key = value + } + if value, ok := lc.mutation.OriginalURL(); ok { + _spec.SetField(link.FieldOriginalURL, field.TypeString, value) + _node.OriginalURL = value + } + if nodes := lc.mutation.OwnerIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: link.OwnerTable, + Columns: link.OwnerPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// LinkCreateBulk is the builder for creating many Link entities in bulk. +type LinkCreateBulk struct { + config + err error + builders []*LinkCreate +} + +// Save creates the Link entities in the database. +func (lcb *LinkCreateBulk) Save(ctx context.Context) ([]*Link, error) { + if lcb.err != nil { + return nil, lcb.err + } + specs := make([]*sqlgraph.CreateSpec, len(lcb.builders)) + nodes := make([]*Link, len(lcb.builders)) + mutators := make([]Mutator, len(lcb.builders)) + for i := range lcb.builders { + func(i int, root context.Context) { + builder := lcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LinkMutation) + 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, lcb.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, lcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, lcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (lcb *LinkCreateBulk) SaveX(ctx context.Context) []*Link { + v, err := lcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (lcb *LinkCreateBulk) Exec(ctx context.Context) error { + _, err := lcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lcb *LinkCreateBulk) ExecX(ctx context.Context) { + if err := lcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/link_delete.go b/ent/link_delete.go new file mode 100644 index 0000000..bdb5a81 --- /dev/null +++ b/ent/link_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "code.gurenya.net/carlsmei/muninn-aio/ent/link" + "code.gurenya.net/carlsmei/muninn-aio/ent/predicate" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LinkDelete is the builder for deleting a Link entity. +type LinkDelete struct { + config + hooks []Hook + mutation *LinkMutation +} + +// Where appends a list predicates to the LinkDelete builder. +func (ld *LinkDelete) Where(ps ...predicate.Link) *LinkDelete { + ld.mutation.Where(ps...) + return ld +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (ld *LinkDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, ld.sqlExec, ld.mutation, ld.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (ld *LinkDelete) ExecX(ctx context.Context) int { + n, err := ld.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (ld *LinkDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(link.Table, sqlgraph.NewFieldSpec(link.FieldID, field.TypeUUID)) + if ps := ld.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, ld.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + ld.mutation.done = true + return affected, err +} + +// LinkDeleteOne is the builder for deleting a single Link entity. +type LinkDeleteOne struct { + ld *LinkDelete +} + +// Where appends a list predicates to the LinkDelete builder. +func (ldo *LinkDeleteOne) Where(ps ...predicate.Link) *LinkDeleteOne { + ldo.ld.mutation.Where(ps...) + return ldo +} + +// Exec executes the deletion query. +func (ldo *LinkDeleteOne) Exec(ctx context.Context) error { + n, err := ldo.ld.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{link.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (ldo *LinkDeleteOne) ExecX(ctx context.Context) { + if err := ldo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/link_query.go b/ent/link_query.go new file mode 100644 index 0000000..ecc832d --- /dev/null +++ b/ent/link_query.go @@ -0,0 +1,638 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + + "code.gurenya.net/carlsmei/muninn-aio/ent/link" + "code.gurenya.net/carlsmei/muninn-aio/ent/predicate" + "code.gurenya.net/carlsmei/muninn-aio/ent/user" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/google/uuid" +) + +// LinkQuery is the builder for querying Link entities. +type LinkQuery struct { + config + ctx *QueryContext + order []link.OrderOption + inters []Interceptor + predicates []predicate.Link + withOwner *UserQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the LinkQuery builder. +func (lq *LinkQuery) Where(ps ...predicate.Link) *LinkQuery { + lq.predicates = append(lq.predicates, ps...) + return lq +} + +// Limit the number of records to be returned by this query. +func (lq *LinkQuery) Limit(limit int) *LinkQuery { + lq.ctx.Limit = &limit + return lq +} + +// Offset to start from. +func (lq *LinkQuery) Offset(offset int) *LinkQuery { + lq.ctx.Offset = &offset + return lq +} + +// 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 (lq *LinkQuery) Unique(unique bool) *LinkQuery { + lq.ctx.Unique = &unique + return lq +} + +// Order specifies how the records should be ordered. +func (lq *LinkQuery) Order(o ...link.OrderOption) *LinkQuery { + lq.order = append(lq.order, o...) + return lq +} + +// QueryOwner chains the current query on the "owner" edge. +func (lq *LinkQuery) QueryOwner() *UserQuery { + query := (&UserClient{config: lq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := lq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := lq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(link.Table, link.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, link.OwnerTable, link.OwnerPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(lq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Link entity from the query. +// Returns a *NotFoundError when no Link was found. +func (lq *LinkQuery) First(ctx context.Context) (*Link, error) { + nodes, err := lq.Limit(1).All(setContextOp(ctx, lq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{link.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (lq *LinkQuery) FirstX(ctx context.Context) *Link { + node, err := lq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Link ID from the query. +// Returns a *NotFoundError when no Link ID was found. +func (lq *LinkQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = lq.Limit(1).IDs(setContextOp(ctx, lq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{link.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (lq *LinkQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := lq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Link entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Link entity is found. +// Returns a *NotFoundError when no Link entities are found. +func (lq *LinkQuery) Only(ctx context.Context) (*Link, error) { + nodes, err := lq.Limit(2).All(setContextOp(ctx, lq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{link.Label} + default: + return nil, &NotSingularError{link.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (lq *LinkQuery) OnlyX(ctx context.Context) *Link { + node, err := lq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Link ID in the query. +// Returns a *NotSingularError when more than one Link ID is found. +// Returns a *NotFoundError when no entities are found. +func (lq *LinkQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = lq.Limit(2).IDs(setContextOp(ctx, lq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{link.Label} + default: + err = &NotSingularError{link.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (lq *LinkQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := lq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Links. +func (lq *LinkQuery) All(ctx context.Context) ([]*Link, error) { + ctx = setContextOp(ctx, lq.ctx, ent.OpQueryAll) + if err := lq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Link, *LinkQuery]() + return withInterceptors[[]*Link](ctx, lq, qr, lq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (lq *LinkQuery) AllX(ctx context.Context) []*Link { + nodes, err := lq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Link IDs. +func (lq *LinkQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if lq.ctx.Unique == nil && lq.path != nil { + lq.Unique(true) + } + ctx = setContextOp(ctx, lq.ctx, ent.OpQueryIDs) + if err = lq.Select(link.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (lq *LinkQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := lq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (lq *LinkQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, lq.ctx, ent.OpQueryCount) + if err := lq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, lq, querierCount[*LinkQuery](), lq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (lq *LinkQuery) CountX(ctx context.Context) int { + count, err := lq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (lq *LinkQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, lq.ctx, ent.OpQueryExist) + switch _, err := lq.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 (lq *LinkQuery) ExistX(ctx context.Context) bool { + exist, err := lq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LinkQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (lq *LinkQuery) Clone() *LinkQuery { + if lq == nil { + return nil + } + return &LinkQuery{ + config: lq.config, + ctx: lq.ctx.Clone(), + order: append([]link.OrderOption{}, lq.order...), + inters: append([]Interceptor{}, lq.inters...), + predicates: append([]predicate.Link{}, lq.predicates...), + withOwner: lq.withOwner.Clone(), + // clone intermediate query. + sql: lq.sql.Clone(), + path: lq.path, + } +} + +// WithOwner tells the query-builder to eager-load the nodes that are connected to +// the "owner" edge. The optional arguments are used to configure the query builder of the edge. +func (lq *LinkQuery) WithOwner(opts ...func(*UserQuery)) *LinkQuery { + query := (&UserClient{config: lq.config}).Query() + for _, opt := range opts { + opt(query) + } + lq.withOwner = query + return lq +} + +// 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 { +// Key string `json:"key,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Link.Query(). +// GroupBy(link.FieldKey). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (lq *LinkQuery) GroupBy(field string, fields ...string) *LinkGroupBy { + lq.ctx.Fields = append([]string{field}, fields...) + grbuild := &LinkGroupBy{build: lq} + grbuild.flds = &lq.ctx.Fields + grbuild.label = link.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 { +// Key string `json:"key,omitempty"` +// } +// +// client.Link.Query(). +// Select(link.FieldKey). +// Scan(ctx, &v) +func (lq *LinkQuery) Select(fields ...string) *LinkSelect { + lq.ctx.Fields = append(lq.ctx.Fields, fields...) + sbuild := &LinkSelect{LinkQuery: lq} + sbuild.label = link.Label + sbuild.flds, sbuild.scan = &lq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a LinkSelect configured with the given aggregations. +func (lq *LinkQuery) Aggregate(fns ...AggregateFunc) *LinkSelect { + return lq.Select().Aggregate(fns...) +} + +func (lq *LinkQuery) prepareQuery(ctx context.Context) error { + for _, inter := range lq.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, lq); err != nil { + return err + } + } + } + for _, f := range lq.ctx.Fields { + if !link.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if lq.path != nil { + prev, err := lq.path(ctx) + if err != nil { + return err + } + lq.sql = prev + } + return nil +} + +func (lq *LinkQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Link, error) { + var ( + nodes = []*Link{} + _spec = lq.querySpec() + loadedTypes = [1]bool{ + lq.withOwner != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Link).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Link{config: lq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, lq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := lq.withOwner; query != nil { + if err := lq.loadOwner(ctx, query, nodes, + func(n *Link) { n.Edges.Owner = []*User{} }, + func(n *Link, e *User) { n.Edges.Owner = append(n.Edges.Owner, e) }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (lq *LinkQuery) loadOwner(ctx context.Context, query *UserQuery, nodes []*Link, init func(*Link), assign func(*Link, *User)) error { + edgeIDs := make([]driver.Value, len(nodes)) + byID := make(map[uuid.UUID]*Link) + nids := make(map[uuid.UUID]map[*Link]struct{}) + for i, node := range nodes { + edgeIDs[i] = node.ID + byID[node.ID] = node + if init != nil { + init(node) + } + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(link.OwnerTable) + s.Join(joinT).On(s.C(user.FieldID), joinT.C(link.OwnerPrimaryKey[0])) + s.Where(sql.InValues(joinT.C(link.OwnerPrimaryKey[1]), edgeIDs...)) + columns := s.SelectedColumns() + s.Select(joinT.C(link.OwnerPrimaryKey[1])) + s.AppendSelect(columns...) + s.SetDistinct(false) + }) + if err := query.prepareQuery(ctx); err != nil { + return err + } + qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) { + assign := spec.Assign + values := spec.ScanValues + spec.ScanValues = func(columns []string) ([]any, error) { + values, err := values(columns[1:]) + if err != nil { + return nil, err + } + return append([]any{new(uuid.UUID)}, values...), nil + } + spec.Assign = func(columns []string, values []any) error { + outValue := *values[0].(*uuid.UUID) + inValue := *values[1].(*uuid.UUID) + if nids[inValue] == nil { + nids[inValue] = map[*Link]struct{}{byID[outValue]: {}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byID[outValue]] = struct{}{} + return nil + } + }) + }) + neighbors, err := withInterceptors[[]*User](ctx, query, qr, query.inters) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nids[n.ID] + if !ok { + return fmt.Errorf(`unexpected "owner" node returned %v`, n.ID) + } + for kn := range nodes { + assign(kn, n) + } + } + return nil +} + +func (lq *LinkQuery) sqlCount(ctx context.Context) (int, error) { + _spec := lq.querySpec() + _spec.Node.Columns = lq.ctx.Fields + if len(lq.ctx.Fields) > 0 { + _spec.Unique = lq.ctx.Unique != nil && *lq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, lq.driver, _spec) +} + +func (lq *LinkQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(link.Table, link.Columns, sqlgraph.NewFieldSpec(link.FieldID, field.TypeUUID)) + _spec.From = lq.sql + if unique := lq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if lq.path != nil { + _spec.Unique = true + } + if fields := lq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, link.FieldID) + for i := range fields { + if fields[i] != link.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := lq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := lq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := lq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := lq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (lq *LinkQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(lq.driver.Dialect()) + t1 := builder.Table(link.Table) + columns := lq.ctx.Fields + if len(columns) == 0 { + columns = link.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if lq.sql != nil { + selector = lq.sql + selector.Select(selector.Columns(columns...)...) + } + if lq.ctx.Unique != nil && *lq.ctx.Unique { + selector.Distinct() + } + for _, p := range lq.predicates { + p(selector) + } + for _, p := range lq.order { + p(selector) + } + if offset := lq.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 := lq.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// LinkGroupBy is the group-by builder for Link entities. +type LinkGroupBy struct { + selector + build *LinkQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (lgb *LinkGroupBy) Aggregate(fns ...AggregateFunc) *LinkGroupBy { + lgb.fns = append(lgb.fns, fns...) + return lgb +} + +// Scan applies the selector query and scans the result into the given value. +func (lgb *LinkGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, lgb.build.ctx, ent.OpQueryGroupBy) + if err := lgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*LinkQuery, *LinkGroupBy](ctx, lgb.build, lgb, lgb.build.inters, v) +} + +func (lgb *LinkGroupBy) sqlScan(ctx context.Context, root *LinkQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(lgb.fns)) + for _, fn := range lgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*lgb.flds)+len(lgb.fns)) + for _, f := range *lgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*lgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := lgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// LinkSelect is the builder for selecting fields of Link entities. +type LinkSelect struct { + *LinkQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (ls *LinkSelect) Aggregate(fns ...AggregateFunc) *LinkSelect { + ls.fns = append(ls.fns, fns...) + return ls +} + +// Scan applies the selector query and scans the result into the given value. +func (ls *LinkSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ls.ctx, ent.OpQuerySelect) + if err := ls.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*LinkQuery, *LinkSelect](ctx, ls.LinkQuery, ls, ls.inters, v) +} + +func (ls *LinkSelect) sqlScan(ctx context.Context, root *LinkQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(ls.fns)) + for _, fn := range ls.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*ls.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 := ls.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/ent/link_update.go b/ent/link_update.go new file mode 100644 index 0000000..de7ec11 --- /dev/null +++ b/ent/link_update.go @@ -0,0 +1,433 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "code.gurenya.net/carlsmei/muninn-aio/ent/link" + "code.gurenya.net/carlsmei/muninn-aio/ent/predicate" + "code.gurenya.net/carlsmei/muninn-aio/ent/user" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/google/uuid" +) + +// LinkUpdate is the builder for updating Link entities. +type LinkUpdate struct { + config + hooks []Hook + mutation *LinkMutation +} + +// Where appends a list predicates to the LinkUpdate builder. +func (lu *LinkUpdate) Where(ps ...predicate.Link) *LinkUpdate { + lu.mutation.Where(ps...) + return lu +} + +// SetKey sets the "key" field. +func (lu *LinkUpdate) SetKey(s string) *LinkUpdate { + lu.mutation.SetKey(s) + return lu +} + +// SetNillableKey sets the "key" field if the given value is not nil. +func (lu *LinkUpdate) SetNillableKey(s *string) *LinkUpdate { + if s != nil { + lu.SetKey(*s) + } + return lu +} + +// SetOriginalURL sets the "original_url" field. +func (lu *LinkUpdate) SetOriginalURL(s string) *LinkUpdate { + lu.mutation.SetOriginalURL(s) + return lu +} + +// SetNillableOriginalURL sets the "original_url" field if the given value is not nil. +func (lu *LinkUpdate) SetNillableOriginalURL(s *string) *LinkUpdate { + if s != nil { + lu.SetOriginalURL(*s) + } + return lu +} + +// AddOwnerIDs adds the "owner" edge to the User entity by IDs. +func (lu *LinkUpdate) AddOwnerIDs(ids ...uuid.UUID) *LinkUpdate { + lu.mutation.AddOwnerIDs(ids...) + return lu +} + +// AddOwner adds the "owner" edges to the User entity. +func (lu *LinkUpdate) AddOwner(u ...*User) *LinkUpdate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return lu.AddOwnerIDs(ids...) +} + +// Mutation returns the LinkMutation object of the builder. +func (lu *LinkUpdate) Mutation() *LinkMutation { + return lu.mutation +} + +// ClearOwner clears all "owner" edges to the User entity. +func (lu *LinkUpdate) ClearOwner() *LinkUpdate { + lu.mutation.ClearOwner() + return lu +} + +// RemoveOwnerIDs removes the "owner" edge to User entities by IDs. +func (lu *LinkUpdate) RemoveOwnerIDs(ids ...uuid.UUID) *LinkUpdate { + lu.mutation.RemoveOwnerIDs(ids...) + return lu +} + +// RemoveOwner removes "owner" edges to User entities. +func (lu *LinkUpdate) RemoveOwner(u ...*User) *LinkUpdate { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return lu.RemoveOwnerIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (lu *LinkUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, lu.sqlSave, lu.mutation, lu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (lu *LinkUpdate) SaveX(ctx context.Context) int { + affected, err := lu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (lu *LinkUpdate) Exec(ctx context.Context) error { + _, err := lu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (lu *LinkUpdate) ExecX(ctx context.Context) { + if err := lu.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (lu *LinkUpdate) check() error { + if v, ok := lu.mutation.OriginalURL(); ok { + if err := link.OriginalURLValidator(v); err != nil { + return &ValidationError{Name: "original_url", err: fmt.Errorf(`ent: validator failed for field "Link.original_url": %w`, err)} + } + } + return nil +} + +func (lu *LinkUpdate) sqlSave(ctx context.Context) (n int, err error) { + if err := lu.check(); err != nil { + return n, err + } + _spec := sqlgraph.NewUpdateSpec(link.Table, link.Columns, sqlgraph.NewFieldSpec(link.FieldID, field.TypeUUID)) + if ps := lu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := lu.mutation.Key(); ok { + _spec.SetField(link.FieldKey, field.TypeString, value) + } + if value, ok := lu.mutation.OriginalURL(); ok { + _spec.SetField(link.FieldOriginalURL, field.TypeString, value) + } + if lu.mutation.OwnerCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: link.OwnerTable, + Columns: link.OwnerPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lu.mutation.RemovedOwnerIDs(); len(nodes) > 0 && !lu.mutation.OwnerCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: link.OwnerTable, + Columns: link.OwnerPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := lu.mutation.OwnerIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: link.OwnerTable, + Columns: link.OwnerPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if n, err = sqlgraph.UpdateNodes(ctx, lu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{link.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + lu.mutation.done = true + return n, nil +} + +// LinkUpdateOne is the builder for updating a single Link entity. +type LinkUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LinkMutation +} + +// SetKey sets the "key" field. +func (luo *LinkUpdateOne) SetKey(s string) *LinkUpdateOne { + luo.mutation.SetKey(s) + return luo +} + +// SetNillableKey sets the "key" field if the given value is not nil. +func (luo *LinkUpdateOne) SetNillableKey(s *string) *LinkUpdateOne { + if s != nil { + luo.SetKey(*s) + } + return luo +} + +// SetOriginalURL sets the "original_url" field. +func (luo *LinkUpdateOne) SetOriginalURL(s string) *LinkUpdateOne { + luo.mutation.SetOriginalURL(s) + return luo +} + +// SetNillableOriginalURL sets the "original_url" field if the given value is not nil. +func (luo *LinkUpdateOne) SetNillableOriginalURL(s *string) *LinkUpdateOne { + if s != nil { + luo.SetOriginalURL(*s) + } + return luo +} + +// AddOwnerIDs adds the "owner" edge to the User entity by IDs. +func (luo *LinkUpdateOne) AddOwnerIDs(ids ...uuid.UUID) *LinkUpdateOne { + luo.mutation.AddOwnerIDs(ids...) + return luo +} + +// AddOwner adds the "owner" edges to the User entity. +func (luo *LinkUpdateOne) AddOwner(u ...*User) *LinkUpdateOne { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return luo.AddOwnerIDs(ids...) +} + +// Mutation returns the LinkMutation object of the builder. +func (luo *LinkUpdateOne) Mutation() *LinkMutation { + return luo.mutation +} + +// ClearOwner clears all "owner" edges to the User entity. +func (luo *LinkUpdateOne) ClearOwner() *LinkUpdateOne { + luo.mutation.ClearOwner() + return luo +} + +// RemoveOwnerIDs removes the "owner" edge to User entities by IDs. +func (luo *LinkUpdateOne) RemoveOwnerIDs(ids ...uuid.UUID) *LinkUpdateOne { + luo.mutation.RemoveOwnerIDs(ids...) + return luo +} + +// RemoveOwner removes "owner" edges to User entities. +func (luo *LinkUpdateOne) RemoveOwner(u ...*User) *LinkUpdateOne { + ids := make([]uuid.UUID, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return luo.RemoveOwnerIDs(ids...) +} + +// Where appends a list predicates to the LinkUpdate builder. +func (luo *LinkUpdateOne) Where(ps ...predicate.Link) *LinkUpdateOne { + luo.mutation.Where(ps...) + return luo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (luo *LinkUpdateOne) Select(field string, fields ...string) *LinkUpdateOne { + luo.fields = append([]string{field}, fields...) + return luo +} + +// Save executes the query and returns the updated Link entity. +func (luo *LinkUpdateOne) Save(ctx context.Context) (*Link, error) { + return withHooks(ctx, luo.sqlSave, luo.mutation, luo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (luo *LinkUpdateOne) SaveX(ctx context.Context) *Link { + node, err := luo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (luo *LinkUpdateOne) Exec(ctx context.Context) error { + _, err := luo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (luo *LinkUpdateOne) ExecX(ctx context.Context) { + if err := luo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (luo *LinkUpdateOne) check() error { + if v, ok := luo.mutation.OriginalURL(); ok { + if err := link.OriginalURLValidator(v); err != nil { + return &ValidationError{Name: "original_url", err: fmt.Errorf(`ent: validator failed for field "Link.original_url": %w`, err)} + } + } + return nil +} + +func (luo *LinkUpdateOne) sqlSave(ctx context.Context) (_node *Link, err error) { + if err := luo.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(link.Table, link.Columns, sqlgraph.NewFieldSpec(link.FieldID, field.TypeUUID)) + id, ok := luo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Link.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := luo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, link.FieldID) + for _, f := range fields { + if !link.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != link.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := luo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := luo.mutation.Key(); ok { + _spec.SetField(link.FieldKey, field.TypeString, value) + } + if value, ok := luo.mutation.OriginalURL(); ok { + _spec.SetField(link.FieldOriginalURL, field.TypeString, value) + } + if luo.mutation.OwnerCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: link.OwnerTable, + Columns: link.OwnerPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := luo.mutation.RemovedOwnerIDs(); len(nodes) > 0 && !luo.mutation.OwnerCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: link.OwnerTable, + Columns: link.OwnerPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := luo.mutation.OwnerIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: link.OwnerTable, + Columns: link.OwnerPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &Link{config: luo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, luo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{link.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + luo.mutation.done = true + return _node, nil +} diff --git a/ent/migrate/migrate.go b/ent/migrate/migrate.go new file mode 100644 index 0000000..1956a6b --- /dev/null +++ b/ent/migrate/migrate.go @@ -0,0 +1,64 @@ +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "context" + "fmt" + "io" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql/schema" +) + +var ( + // WithGlobalUniqueID sets the universal ids options to the migration. + // If this option is enabled, ent migration will allocate a 1<<32 range + // for the ids of each entity (table). + // Note that this option cannot be applied on tables that already exist. + WithGlobalUniqueID = schema.WithGlobalUniqueID + // WithDropColumn sets the drop column option to the migration. + // If this option is enabled, ent migration will drop old columns + // that were used for both fields and edges. This defaults to false. + WithDropColumn = schema.WithDropColumn + // WithDropIndex sets the drop index option to the migration. + // If this option is enabled, ent migration will drop old indexes + // that were defined in the schema. This defaults to false. + // Note that unique constraints are defined using `UNIQUE INDEX`, + // and therefore, it's recommended to enable this option to get more + // flexibility in the schema changes. + WithDropIndex = schema.WithDropIndex + // WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true. + WithForeignKeys = schema.WithForeignKeys +) + +// Schema is the API for creating, migrating and dropping a schema. +type Schema struct { + drv dialect.Driver +} + +// NewSchema creates a new schema client. +func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} } + +// Create creates all schema resources. +func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error { + return Create(ctx, s, Tables, opts...) +} + +// Create creates all table resources using the given schema driver. +func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error { + migrate, err := schema.NewMigrate(s.drv, opts...) + if err != nil { + return fmt.Errorf("ent/migrate: %w", err) + } + return migrate.Create(ctx, tables...) +} + +// WriteTo writes the schema changes to w instead of running them against the database. +// +// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { +// log.Fatal(err) +// } +func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error { + return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...) +} diff --git a/ent/migrate/schema.go b/ent/migrate/schema.go new file mode 100644 index 0000000..c7b004e --- /dev/null +++ b/ent/migrate/schema.go @@ -0,0 +1,77 @@ +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/schema/field" +) + +var ( + // LinksColumns holds the columns for the "links" table. + LinksColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID, Unique: true}, + {Name: "key", Type: field.TypeString, Unique: true}, + {Name: "original_url", Type: field.TypeString}, + } + // LinksTable holds the schema information for the "links" table. + LinksTable = &schema.Table{ + Name: "links", + Columns: LinksColumns, + PrimaryKey: []*schema.Column{LinksColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "link_key", + Unique: true, + Columns: []*schema.Column{LinksColumns[1]}, + }, + }, + } + // UsersColumns holds the columns for the "users" table. + UsersColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID, Unique: true}, + {Name: "telegram_id", Type: field.TypeInt64, Unique: true}, + } + // UsersTable holds the schema information for the "users" table. + UsersTable = &schema.Table{ + Name: "users", + Columns: UsersColumns, + PrimaryKey: []*schema.Column{UsersColumns[0]}, + } + // UserLinksColumns holds the columns for the "user_links" table. + UserLinksColumns = []*schema.Column{ + {Name: "user_id", Type: field.TypeUUID}, + {Name: "link_id", Type: field.TypeUUID}, + } + // UserLinksTable holds the schema information for the "user_links" table. + UserLinksTable = &schema.Table{ + Name: "user_links", + Columns: UserLinksColumns, + PrimaryKey: []*schema.Column{UserLinksColumns[0], UserLinksColumns[1]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "user_links_user_id", + Columns: []*schema.Column{UserLinksColumns[0]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "user_links_link_id", + Columns: []*schema.Column{UserLinksColumns[1]}, + RefColumns: []*schema.Column{LinksColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + } + // Tables holds all the tables in the schema. + Tables = []*schema.Table{ + LinksTable, + UsersTable, + UserLinksTable, + } +) + +func init() { + UserLinksTable.ForeignKeys[0].RefTable = UsersTable + UserLinksTable.ForeignKeys[1].RefTable = LinksTable +} diff --git a/ent/mutation.go b/ent/mutation.go new file mode 100644 index 0000000..f8b347e --- /dev/null +++ b/ent/mutation.go @@ -0,0 +1,970 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "sync" + + "code.gurenya.net/carlsmei/muninn-aio/ent/link" + "code.gurenya.net/carlsmei/muninn-aio/ent/predicate" + "code.gurenya.net/carlsmei/muninn-aio/ent/user" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/google/uuid" +) + +const ( + // Operation types. + OpCreate = ent.OpCreate + OpDelete = ent.OpDelete + OpDeleteOne = ent.OpDeleteOne + OpUpdate = ent.OpUpdate + OpUpdateOne = ent.OpUpdateOne + + // Node types. + TypeLink = "Link" + TypeUser = "User" +) + +// LinkMutation represents an operation that mutates the Link nodes in the graph. +type LinkMutation struct { + config + op Op + typ string + id *uuid.UUID + key *string + original_url *string + clearedFields map[string]struct{} + owner map[uuid.UUID]struct{} + removedowner map[uuid.UUID]struct{} + clearedowner bool + done bool + oldValue func(context.Context) (*Link, error) + predicates []predicate.Link +} + +var _ ent.Mutation = (*LinkMutation)(nil) + +// linkOption allows management of the mutation configuration using functional options. +type linkOption func(*LinkMutation) + +// newLinkMutation creates new mutation for the Link entity. +func newLinkMutation(c config, op Op, opts ...linkOption) *LinkMutation { + m := &LinkMutation{ + config: c, + op: op, + typ: TypeLink, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLinkID sets the ID field of the mutation. +func withLinkID(id uuid.UUID) linkOption { + return func(m *LinkMutation) { + var ( + err error + once sync.Once + value *Link + ) + m.oldValue = func(ctx context.Context) (*Link, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Link.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLink sets the old Link of the mutation. +func withLink(node *Link) linkOption { + return func(m *LinkMutation) { + m.oldValue = func(context.Context) (*Link, 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 LinkMutation) 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 LinkMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of Link entities. +func (m *LinkMutation) SetID(id uuid.UUID) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *LinkMutation) ID() (id uuid.UUID, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *LinkMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []uuid.UUID{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Link.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetKey sets the "key" field. +func (m *LinkMutation) SetKey(s string) { + m.key = &s +} + +// Key returns the value of the "key" field in the mutation. +func (m *LinkMutation) Key() (r string, exists bool) { + v := m.key + if v == nil { + return + } + return *v, true +} + +// OldKey returns the old "key" field's value of the Link entity. +// If the Link 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 *LinkMutation) OldKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldKey: %w", err) + } + return oldValue.Key, nil +} + +// ResetKey resets all changes to the "key" field. +func (m *LinkMutation) ResetKey() { + m.key = nil +} + +// SetOriginalURL sets the "original_url" field. +func (m *LinkMutation) SetOriginalURL(s string) { + m.original_url = &s +} + +// OriginalURL returns the value of the "original_url" field in the mutation. +func (m *LinkMutation) OriginalURL() (r string, exists bool) { + v := m.original_url + if v == nil { + return + } + return *v, true +} + +// OldOriginalURL returns the old "original_url" field's value of the Link entity. +// If the Link 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 *LinkMutation) OldOriginalURL(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOriginalURL is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOriginalURL requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOriginalURL: %w", err) + } + return oldValue.OriginalURL, nil +} + +// ResetOriginalURL resets all changes to the "original_url" field. +func (m *LinkMutation) ResetOriginalURL() { + m.original_url = nil +} + +// AddOwnerIDs adds the "owner" edge to the User entity by ids. +func (m *LinkMutation) AddOwnerIDs(ids ...uuid.UUID) { + if m.owner == nil { + m.owner = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.owner[ids[i]] = struct{}{} + } +} + +// ClearOwner clears the "owner" edge to the User entity. +func (m *LinkMutation) ClearOwner() { + m.clearedowner = true +} + +// OwnerCleared reports if the "owner" edge to the User entity was cleared. +func (m *LinkMutation) OwnerCleared() bool { + return m.clearedowner +} + +// RemoveOwnerIDs removes the "owner" edge to the User entity by IDs. +func (m *LinkMutation) RemoveOwnerIDs(ids ...uuid.UUID) { + if m.removedowner == nil { + m.removedowner = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.owner, ids[i]) + m.removedowner[ids[i]] = struct{}{} + } +} + +// RemovedOwner returns the removed IDs of the "owner" edge to the User entity. +func (m *LinkMutation) RemovedOwnerIDs() (ids []uuid.UUID) { + for id := range m.removedowner { + ids = append(ids, id) + } + return +} + +// OwnerIDs returns the "owner" edge IDs in the mutation. +func (m *LinkMutation) OwnerIDs() (ids []uuid.UUID) { + for id := range m.owner { + ids = append(ids, id) + } + return +} + +// ResetOwner resets all changes to the "owner" edge. +func (m *LinkMutation) ResetOwner() { + m.owner = nil + m.clearedowner = false + m.removedowner = nil +} + +// Where appends a list predicates to the LinkMutation builder. +func (m *LinkMutation) Where(ps ...predicate.Link) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the LinkMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *LinkMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Link, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *LinkMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *LinkMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Link). +func (m *LinkMutation) 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 *LinkMutation) Fields() []string { + fields := make([]string, 0, 2) + if m.key != nil { + fields = append(fields, link.FieldKey) + } + if m.original_url != nil { + fields = append(fields, link.FieldOriginalURL) + } + 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 *LinkMutation) Field(name string) (ent.Value, bool) { + switch name { + case link.FieldKey: + return m.Key() + case link.FieldOriginalURL: + return m.OriginalURL() + } + 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 *LinkMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case link.FieldKey: + return m.OldKey(ctx) + case link.FieldOriginalURL: + return m.OldOriginalURL(ctx) + } + return nil, fmt.Errorf("unknown Link 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 *LinkMutation) SetField(name string, value ent.Value) error { + switch name { + case link.FieldKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetKey(v) + return nil + case link.FieldOriginalURL: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOriginalURL(v) + return nil + } + return fmt.Errorf("unknown Link field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LinkMutation) 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 *LinkMutation) 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 *LinkMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Link numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LinkMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LinkMutation) 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 *LinkMutation) ClearField(name string) error { + return fmt.Errorf("unknown Link 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 *LinkMutation) ResetField(name string) error { + switch name { + case link.FieldKey: + m.ResetKey() + return nil + case link.FieldOriginalURL: + m.ResetOriginalURL() + return nil + } + return fmt.Errorf("unknown Link field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LinkMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.owner != nil { + edges = append(edges, link.EdgeOwner) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LinkMutation) AddedIDs(name string) []ent.Value { + switch name { + case link.EdgeOwner: + ids := make([]ent.Value, 0, len(m.owner)) + for id := range m.owner { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LinkMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + if m.removedowner != nil { + edges = append(edges, link.EdgeOwner) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LinkMutation) RemovedIDs(name string) []ent.Value { + switch name { + case link.EdgeOwner: + ids := make([]ent.Value, 0, len(m.removedowner)) + for id := range m.removedowner { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LinkMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedowner { + edges = append(edges, link.EdgeOwner) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LinkMutation) EdgeCleared(name string) bool { + switch name { + case link.EdgeOwner: + return m.clearedowner + } + 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 *LinkMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown Link 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 *LinkMutation) ResetEdge(name string) error { + switch name { + case link.EdgeOwner: + m.ResetOwner() + return nil + } + return fmt.Errorf("unknown Link edge %s", name) +} + +// UserMutation represents an operation that mutates the User nodes in the graph. +type UserMutation struct { + config + op Op + typ string + id *uuid.UUID + telegram_id *int64 + addtelegram_id *int64 + clearedFields map[string]struct{} + links map[uuid.UUID]struct{} + removedlinks map[uuid.UUID]struct{} + clearedlinks bool + done bool + oldValue func(context.Context) (*User, error) + predicates []predicate.User +} + +var _ ent.Mutation = (*UserMutation)(nil) + +// userOption allows management of the mutation configuration using functional options. +type userOption func(*UserMutation) + +// newUserMutation creates new mutation for the User entity. +func newUserMutation(c config, op Op, opts ...userOption) *UserMutation { + m := &UserMutation{ + config: c, + op: op, + typ: TypeUser, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withUserID sets the ID field of the mutation. +func withUserID(id uuid.UUID) userOption { + return func(m *UserMutation) { + var ( + err error + once sync.Once + value *User + ) + m.oldValue = func(ctx context.Context) (*User, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().User.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withUser sets the old User of the mutation. +func withUser(node *User) userOption { + return func(m *UserMutation) { + m.oldValue = func(context.Context) (*User, 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 UserMutation) 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 UserMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of User entities. +func (m *UserMutation) SetID(id uuid.UUID) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *UserMutation) ID() (id uuid.UUID, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *UserMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []uuid.UUID{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().User.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetTelegramID sets the "telegram_id" field. +func (m *UserMutation) SetTelegramID(i int64) { + m.telegram_id = &i + m.addtelegram_id = nil +} + +// TelegramID returns the value of the "telegram_id" field in the mutation. +func (m *UserMutation) TelegramID() (r int64, exists bool) { + v := m.telegram_id + if v == nil { + return + } + return *v, true +} + +// OldTelegramID returns the old "telegram_id" field's value of the User entity. +// If the User 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 *UserMutation) OldTelegramID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTelegramID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTelegramID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTelegramID: %w", err) + } + return oldValue.TelegramID, nil +} + +// AddTelegramID adds i to the "telegram_id" field. +func (m *UserMutation) AddTelegramID(i int64) { + if m.addtelegram_id != nil { + *m.addtelegram_id += i + } else { + m.addtelegram_id = &i + } +} + +// AddedTelegramID returns the value that was added to the "telegram_id" field in this mutation. +func (m *UserMutation) AddedTelegramID() (r int64, exists bool) { + v := m.addtelegram_id + if v == nil { + return + } + return *v, true +} + +// ResetTelegramID resets all changes to the "telegram_id" field. +func (m *UserMutation) ResetTelegramID() { + m.telegram_id = nil + m.addtelegram_id = nil +} + +// AddLinkIDs adds the "links" edge to the Link entity by ids. +func (m *UserMutation) AddLinkIDs(ids ...uuid.UUID) { + if m.links == nil { + m.links = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.links[ids[i]] = struct{}{} + } +} + +// ClearLinks clears the "links" edge to the Link entity. +func (m *UserMutation) ClearLinks() { + m.clearedlinks = true +} + +// LinksCleared reports if the "links" edge to the Link entity was cleared. +func (m *UserMutation) LinksCleared() bool { + return m.clearedlinks +} + +// RemoveLinkIDs removes the "links" edge to the Link entity by IDs. +func (m *UserMutation) RemoveLinkIDs(ids ...uuid.UUID) { + if m.removedlinks == nil { + m.removedlinks = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.links, ids[i]) + m.removedlinks[ids[i]] = struct{}{} + } +} + +// RemovedLinks returns the removed IDs of the "links" edge to the Link entity. +func (m *UserMutation) RemovedLinksIDs() (ids []uuid.UUID) { + for id := range m.removedlinks { + ids = append(ids, id) + } + return +} + +// LinksIDs returns the "links" edge IDs in the mutation. +func (m *UserMutation) LinksIDs() (ids []uuid.UUID) { + for id := range m.links { + ids = append(ids, id) + } + return +} + +// ResetLinks resets all changes to the "links" edge. +func (m *UserMutation) ResetLinks() { + m.links = nil + m.clearedlinks = false + m.removedlinks = nil +} + +// Where appends a list predicates to the UserMutation builder. +func (m *UserMutation) Where(ps ...predicate.User) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the UserMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *UserMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.User, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *UserMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *UserMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (User). +func (m *UserMutation) 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 *UserMutation) Fields() []string { + fields := make([]string, 0, 1) + if m.telegram_id != nil { + fields = append(fields, user.FieldTelegramID) + } + 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 *UserMutation) Field(name string) (ent.Value, bool) { + switch name { + case user.FieldTelegramID: + return m.TelegramID() + } + 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 *UserMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case user.FieldTelegramID: + return m.OldTelegramID(ctx) + } + return nil, fmt.Errorf("unknown User 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 *UserMutation) SetField(name string, value ent.Value) error { + switch name { + case user.FieldTelegramID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTelegramID(v) + return nil + } + return fmt.Errorf("unknown User field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *UserMutation) AddedFields() []string { + var fields []string + if m.addtelegram_id != nil { + fields = append(fields, user.FieldTelegramID) + } + return fields +} + +// 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 *UserMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case user.FieldTelegramID: + return m.AddedTelegramID() + } + 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 *UserMutation) AddField(name string, value ent.Value) error { + switch name { + case user.FieldTelegramID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddTelegramID(v) + return nil + } + return fmt.Errorf("unknown User numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *UserMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *UserMutation) 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 *UserMutation) ClearField(name string) error { + return fmt.Errorf("unknown User 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 *UserMutation) ResetField(name string) error { + switch name { + case user.FieldTelegramID: + m.ResetTelegramID() + return nil + } + return fmt.Errorf("unknown User field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *UserMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.links != nil { + edges = append(edges, user.EdgeLinks) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *UserMutation) AddedIDs(name string) []ent.Value { + switch name { + case user.EdgeLinks: + ids := make([]ent.Value, 0, len(m.links)) + for id := range m.links { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *UserMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + if m.removedlinks != nil { + edges = append(edges, user.EdgeLinks) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *UserMutation) RemovedIDs(name string) []ent.Value { + switch name { + case user.EdgeLinks: + ids := make([]ent.Value, 0, len(m.removedlinks)) + for id := range m.removedlinks { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *UserMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedlinks { + edges = append(edges, user.EdgeLinks) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *UserMutation) EdgeCleared(name string) bool { + switch name { + case user.EdgeLinks: + return m.clearedlinks + } + 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 *UserMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown User 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 *UserMutation) ResetEdge(name string) error { + switch name { + case user.EdgeLinks: + m.ResetLinks() + return nil + } + return fmt.Errorf("unknown User edge %s", name) +} diff --git a/ent/predicate/predicate.go b/ent/predicate/predicate.go new file mode 100644 index 0000000..3251f27 --- /dev/null +++ b/ent/predicate/predicate.go @@ -0,0 +1,13 @@ +// Code generated by ent, DO NOT EDIT. + +package predicate + +import ( + "entgo.io/ent/dialect/sql" +) + +// Link is the predicate function for link builders. +type Link func(*sql.Selector) + +// User is the predicate function for user builders. +type User func(*sql.Selector) diff --git a/ent/runtime.go b/ent/runtime.go new file mode 100644 index 0000000..5a76867 --- /dev/null +++ b/ent/runtime.go @@ -0,0 +1,32 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "code.gurenya.net/carlsmei/muninn-aio/ent/link" + "code.gurenya.net/carlsmei/muninn-aio/ent/schema" + "code.gurenya.net/carlsmei/muninn-aio/ent/user" + "github.com/google/uuid" +) + +// The init function reads all schema descriptors with runtime code +// (default values, validators, hooks and policies) and stitches it +// to their package variables. +func init() { + linkFields := schema.Link{}.Fields() + _ = linkFields + // linkDescOriginalURL is the schema descriptor for original_url field. + linkDescOriginalURL := linkFields[2].Descriptor() + // link.OriginalURLValidator is a validator for the "original_url" field. It is called by the builders before save. + link.OriginalURLValidator = linkDescOriginalURL.Validators[0].(func(string) error) + // linkDescID is the schema descriptor for id field. + linkDescID := linkFields[0].Descriptor() + // link.DefaultID holds the default value on creation for the id field. + link.DefaultID = linkDescID.Default.(func() uuid.UUID) + userFields := schema.User{}.Fields() + _ = userFields + // userDescID is the schema descriptor for id field. + userDescID := userFields[0].Descriptor() + // user.DefaultID holds the default value on creation for the id field. + user.DefaultID = userDescID.Default.(func() uuid.UUID) +} diff --git a/ent/runtime/runtime.go b/ent/runtime/runtime.go new file mode 100644 index 0000000..495783a --- /dev/null +++ b/ent/runtime/runtime.go @@ -0,0 +1,10 @@ +// Code generated by ent, DO NOT EDIT. + +package runtime + +// The schema-stitching logic is generated in code.gurenya.net/carlsmei/muninn-aio/ent/runtime.go + +const ( + Version = "v0.14.0" // Version of ent codegen. + Sum = "h1:EO3Z9aZ5bXJatJeGqu/EVdnNr6K4mRq3rWe5owt0MC4=" // Sum of ent codegen. +) diff --git a/ent/schema/link.go b/ent/schema/link.go new file mode 100644 index 0000000..e0f2cef --- /dev/null +++ b/ent/schema/link.go @@ -0,0 +1,44 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" + "github.com/google/uuid" +) + +// URL holds the schema definition for the URL entity. +type Link struct { + ent.Schema +} + +// Fields of the URL. +func (Link) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}). + Default(uuid.New). + Unique(). + Immutable(), + field.String("key"). + Unique(), + field.String("original_url"). + NotEmpty(), + } +} + +func (Link) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("key"). + Unique(), + } +} + +// Edges of the URL. +func (Link) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("owner", User.Type). + Required(). + Ref("links"), + } +} diff --git a/ent/schema/user.go b/ent/schema/user.go new file mode 100644 index 0000000..ddd176e --- /dev/null +++ b/ent/schema/user.go @@ -0,0 +1,33 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "github.com/google/uuid" +) + +// User holds the schema definition for the User entity. +type User struct { + ent.Schema +} + +// Fields of the User. +func (User) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}). + Default(uuid.New). + Unique(). + Immutable(), + field.Int64("telegram_id"). + Immutable(). + Unique(), + } +} + +// Edges of the User. +func (User) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("links", Link.Type), + } +} diff --git a/ent/tx.go b/ent/tx.go new file mode 100644 index 0000000..eec0a22 --- /dev/null +++ b/ent/tx.go @@ -0,0 +1,213 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "sync" + + "entgo.io/ent/dialect" +) + +// Tx is a transactional client that is created by calling Client.Tx(). +type Tx struct { + config + // Link is the client for interacting with the Link builders. + Link *LinkClient + // User is the client for interacting with the User builders. + User *UserClient + + // lazily loaded. + client *Client + clientOnce sync.Once + // ctx lives for the life of the transaction. It is + // the same context used by the underlying connection. + ctx context.Context +} + +type ( + // Committer is the interface that wraps the Commit method. + Committer interface { + Commit(context.Context, *Tx) error + } + + // The CommitFunc type is an adapter to allow the use of ordinary + // function as a Committer. If f is a function with the appropriate + // signature, CommitFunc(f) is a Committer that calls f. + CommitFunc func(context.Context, *Tx) error + + // CommitHook defines the "commit middleware". A function that gets a Committer + // and returns a Committer. For example: + // + // hook := func(next ent.Committer) ent.Committer { + // return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Commit(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + CommitHook func(Committer) Committer +) + +// Commit calls f(ctx, m). +func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Commit commits the transaction. +func (tx *Tx) Commit() error { + txDriver := tx.config.driver.(*txDriver) + var fn Committer = CommitFunc(func(context.Context, *Tx) error { + return txDriver.tx.Commit() + }) + txDriver.mu.Lock() + hooks := append([]CommitHook(nil), txDriver.onCommit...) + txDriver.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Commit(tx.ctx, tx) +} + +// OnCommit adds a hook to call on commit. +func (tx *Tx) OnCommit(f CommitHook) { + txDriver := tx.config.driver.(*txDriver) + txDriver.mu.Lock() + txDriver.onCommit = append(txDriver.onCommit, f) + txDriver.mu.Unlock() +} + +type ( + // Rollbacker is the interface that wraps the Rollback method. + Rollbacker interface { + Rollback(context.Context, *Tx) error + } + + // The RollbackFunc type is an adapter to allow the use of ordinary + // function as a Rollbacker. If f is a function with the appropriate + // signature, RollbackFunc(f) is a Rollbacker that calls f. + RollbackFunc func(context.Context, *Tx) error + + // RollbackHook defines the "rollback middleware". A function that gets a Rollbacker + // and returns a Rollbacker. For example: + // + // hook := func(next ent.Rollbacker) ent.Rollbacker { + // return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Rollback(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + RollbackHook func(Rollbacker) Rollbacker +) + +// Rollback calls f(ctx, m). +func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Rollback rollbacks the transaction. +func (tx *Tx) Rollback() error { + txDriver := tx.config.driver.(*txDriver) + var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error { + return txDriver.tx.Rollback() + }) + txDriver.mu.Lock() + hooks := append([]RollbackHook(nil), txDriver.onRollback...) + txDriver.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Rollback(tx.ctx, tx) +} + +// OnRollback adds a hook to call on rollback. +func (tx *Tx) OnRollback(f RollbackHook) { + txDriver := tx.config.driver.(*txDriver) + txDriver.mu.Lock() + txDriver.onRollback = append(txDriver.onRollback, f) + txDriver.mu.Unlock() +} + +// Client returns a Client that binds to current transaction. +func (tx *Tx) Client() *Client { + tx.clientOnce.Do(func() { + tx.client = &Client{config: tx.config} + tx.client.init() + }) + return tx.client +} + +func (tx *Tx) init() { + tx.Link = NewLinkClient(tx.config) + tx.User = NewUserClient(tx.config) +} + +// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation. +// The idea is to support transactions without adding any extra code to the builders. +// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance. +// Commit and Rollback are nop for the internal builders and the user must call one +// of them in order to commit or rollback the transaction. +// +// If a closed transaction is embedded in one of the generated entities, and the entity +// applies a query, for example: Link.QueryXXX(), the query will be executed +// through the driver which created this transaction. +// +// Note that txDriver is not goroutine safe. +type txDriver struct { + // the driver we started the transaction from. + drv dialect.Driver + // tx is the underlying transaction. + tx dialect.Tx + // completion hooks. + mu sync.Mutex + onCommit []CommitHook + onRollback []RollbackHook +} + +// newTx creates a new transactional driver. +func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) { + tx, err := drv.Tx(ctx) + if err != nil { + return nil, err + } + return &txDriver{tx: tx, drv: drv}, nil +} + +// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls +// from the internal builders. Should be called only by the internal builders. +func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil } + +// Dialect returns the dialect of the driver we started the transaction from. +func (tx *txDriver) Dialect() string { return tx.drv.Dialect() } + +// Close is a nop close. +func (*txDriver) Close() error { return nil } + +// Commit is a nop commit for the internal builders. +// User must call `Tx.Commit` in order to commit the transaction. +func (*txDriver) Commit() error { return nil } + +// Rollback is a nop rollback for the internal builders. +// User must call `Tx.Rollback` in order to rollback the transaction. +func (*txDriver) Rollback() error { return nil } + +// Exec calls tx.Exec. +func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error { + return tx.tx.Exec(ctx, query, args, v) +} + +// Query calls tx.Query. +func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error { + return tx.tx.Query(ctx, query, args, v) +} + +var _ dialect.Driver = (*txDriver)(nil) diff --git a/ent/user.go b/ent/user.go new file mode 100644 index 0000000..3dfdfaa --- /dev/null +++ b/ent/user.go @@ -0,0 +1,130 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "code.gurenya.net/carlsmei/muninn-aio/ent/user" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/google/uuid" +) + +// User is the model entity for the User schema. +type User struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // TelegramID holds the value of the "telegram_id" field. + TelegramID int64 `json:"telegram_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the UserQuery when eager-loading is set. + Edges UserEdges `json:"edges"` + selectValues sql.SelectValues +} + +// UserEdges holds the relations/edges for other nodes in the graph. +type UserEdges struct { + // Links holds the value of the links edge. + Links []*Link `json:"links,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// LinksOrErr returns the Links value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) LinksOrErr() ([]*Link, error) { + if e.loadedTypes[0] { + return e.Links, nil + } + return nil, &NotLoadedError{edge: "links"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*User) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case user.FieldTelegramID: + values[i] = new(sql.NullInt64) + case user.FieldID: + values[i] = new(uuid.UUID) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the User fields. +func (u *User) 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 user.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + u.ID = *value + } + case user.FieldTelegramID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field telegram_id", values[i]) + } else if value.Valid { + u.TelegramID = value.Int64 + } + default: + u.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the User. +// This includes values selected through modifiers, order, etc. +func (u *User) Value(name string) (ent.Value, error) { + return u.selectValues.Get(name) +} + +// QueryLinks queries the "links" edge of the User entity. +func (u *User) QueryLinks() *LinkQuery { + return NewUserClient(u.config).QueryLinks(u) +} + +// Update returns a builder for updating this User. +// Note that you need to call User.Unwrap() before calling this method if this User +// was returned from a transaction, and the transaction was committed or rolled back. +func (u *User) Update() *UserUpdateOne { + return NewUserClient(u.config).UpdateOne(u) +} + +// Unwrap unwraps the User 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 (u *User) Unwrap() *User { + _tx, ok := u.config.driver.(*txDriver) + if !ok { + panic("ent: User is not a transactional entity") + } + u.config.driver = _tx.drv + return u +} + +// String implements the fmt.Stringer. +func (u *User) String() string { + var builder strings.Builder + builder.WriteString("User(") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("telegram_id=") + builder.WriteString(fmt.Sprintf("%v", u.TelegramID)) + builder.WriteByte(')') + return builder.String() +} + +// Users is a parsable slice of User. +type Users []*User diff --git a/ent/user/user.go b/ent/user/user.go new file mode 100644 index 0000000..0b92216 --- /dev/null +++ b/ent/user/user.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package user + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/google/uuid" +) + +const ( + // Label holds the string label denoting the user type in the database. + Label = "user" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldTelegramID holds the string denoting the telegram_id field in the database. + FieldTelegramID = "telegram_id" + // EdgeLinks holds the string denoting the links edge name in mutations. + EdgeLinks = "links" + // Table holds the table name of the user in the database. + Table = "users" + // LinksTable is the table that holds the links relation/edge. The primary key declared below. + LinksTable = "user_links" + // LinksInverseTable is the table name for the Link entity. + // It exists in this package in order to avoid circular dependency with the "link" package. + LinksInverseTable = "links" +) + +// Columns holds all SQL columns for user fields. +var Columns = []string{ + FieldID, + FieldTelegramID, +} + +var ( + // LinksPrimaryKey and LinksColumn2 are the table columns denoting the + // primary key for the links relation (M2M). + LinksPrimaryKey = []string{"user_id", "link_id"} +) + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() uuid.UUID +) + +// OrderOption defines the ordering options for the User 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() +} + +// ByTelegramID orders the results by the telegram_id field. +func ByTelegramID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTelegramID, opts...).ToFunc() +} + +// ByLinksCount orders the results by links count. +func ByLinksCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newLinksStep(), opts...) + } +} + +// ByLinks orders the results by links terms. +func ByLinks(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newLinksStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newLinksStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(LinksInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, LinksTable, LinksPrimaryKey...), + ) +} diff --git a/ent/user/where.go b/ent/user/where.go new file mode 100644 index 0000000..33c86fb --- /dev/null +++ b/ent/user/where.go @@ -0,0 +1,138 @@ +// Code generated by ent, DO NOT EDIT. + +package user + +import ( + "code.gurenya.net/carlsmei/muninn-aio/ent/predicate" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.User { + return predicate.User(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.User { + return predicate.User(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.User { + return predicate.User(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.User { + return predicate.User(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.User { + return predicate.User(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.User { + return predicate.User(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.User { + return predicate.User(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.User { + return predicate.User(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.User { + return predicate.User(sql.FieldLTE(FieldID, id)) +} + +// TelegramID applies equality check predicate on the "telegram_id" field. It's identical to TelegramIDEQ. +func TelegramID(v int64) predicate.User { + return predicate.User(sql.FieldEQ(FieldTelegramID, v)) +} + +// TelegramIDEQ applies the EQ predicate on the "telegram_id" field. +func TelegramIDEQ(v int64) predicate.User { + return predicate.User(sql.FieldEQ(FieldTelegramID, v)) +} + +// TelegramIDNEQ applies the NEQ predicate on the "telegram_id" field. +func TelegramIDNEQ(v int64) predicate.User { + return predicate.User(sql.FieldNEQ(FieldTelegramID, v)) +} + +// TelegramIDIn applies the In predicate on the "telegram_id" field. +func TelegramIDIn(vs ...int64) predicate.User { + return predicate.User(sql.FieldIn(FieldTelegramID, vs...)) +} + +// TelegramIDNotIn applies the NotIn predicate on the "telegram_id" field. +func TelegramIDNotIn(vs ...int64) predicate.User { + return predicate.User(sql.FieldNotIn(FieldTelegramID, vs...)) +} + +// TelegramIDGT applies the GT predicate on the "telegram_id" field. +func TelegramIDGT(v int64) predicate.User { + return predicate.User(sql.FieldGT(FieldTelegramID, v)) +} + +// TelegramIDGTE applies the GTE predicate on the "telegram_id" field. +func TelegramIDGTE(v int64) predicate.User { + return predicate.User(sql.FieldGTE(FieldTelegramID, v)) +} + +// TelegramIDLT applies the LT predicate on the "telegram_id" field. +func TelegramIDLT(v int64) predicate.User { + return predicate.User(sql.FieldLT(FieldTelegramID, v)) +} + +// TelegramIDLTE applies the LTE predicate on the "telegram_id" field. +func TelegramIDLTE(v int64) predicate.User { + return predicate.User(sql.FieldLTE(FieldTelegramID, v)) +} + +// HasLinks applies the HasEdge predicate on the "links" edge. +func HasLinks() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, LinksTable, LinksPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasLinksWith applies the HasEdge predicate on the "links" edge with a given conditions (other predicates). +func HasLinksWith(preds ...predicate.Link) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := newLinksStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.User) predicate.User { + return predicate.User(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.User) predicate.User { + return predicate.User(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.User) predicate.User { + return predicate.User(sql.NotPredicates(p)) +} diff --git a/ent/user_create.go b/ent/user_create.go new file mode 100644 index 0000000..34d601b --- /dev/null +++ b/ent/user_create.go @@ -0,0 +1,245 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "code.gurenya.net/carlsmei/muninn-aio/ent/link" + "code.gurenya.net/carlsmei/muninn-aio/ent/user" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/google/uuid" +) + +// UserCreate is the builder for creating a User entity. +type UserCreate struct { + config + mutation *UserMutation + hooks []Hook +} + +// SetTelegramID sets the "telegram_id" field. +func (uc *UserCreate) SetTelegramID(i int64) *UserCreate { + uc.mutation.SetTelegramID(i) + return uc +} + +// SetID sets the "id" field. +func (uc *UserCreate) SetID(u uuid.UUID) *UserCreate { + uc.mutation.SetID(u) + return uc +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (uc *UserCreate) SetNillableID(u *uuid.UUID) *UserCreate { + if u != nil { + uc.SetID(*u) + } + return uc +} + +// AddLinkIDs adds the "links" edge to the Link entity by IDs. +func (uc *UserCreate) AddLinkIDs(ids ...uuid.UUID) *UserCreate { + uc.mutation.AddLinkIDs(ids...) + return uc +} + +// AddLinks adds the "links" edges to the Link entity. +func (uc *UserCreate) AddLinks(l ...*Link) *UserCreate { + ids := make([]uuid.UUID, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return uc.AddLinkIDs(ids...) +} + +// Mutation returns the UserMutation object of the builder. +func (uc *UserCreate) Mutation() *UserMutation { + return uc.mutation +} + +// Save creates the User in the database. +func (uc *UserCreate) Save(ctx context.Context) (*User, error) { + uc.defaults() + return withHooks(ctx, uc.sqlSave, uc.mutation, uc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (uc *UserCreate) SaveX(ctx context.Context) *User { + v, err := uc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (uc *UserCreate) Exec(ctx context.Context) error { + _, err := uc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (uc *UserCreate) ExecX(ctx context.Context) { + if err := uc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (uc *UserCreate) defaults() { + if _, ok := uc.mutation.ID(); !ok { + v := user.DefaultID() + uc.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (uc *UserCreate) check() error { + if _, ok := uc.mutation.TelegramID(); !ok { + return &ValidationError{Name: "telegram_id", err: errors.New(`ent: missing required field "User.telegram_id"`)} + } + return nil +} + +func (uc *UserCreate) sqlSave(ctx context.Context) (*User, error) { + if err := uc.check(); err != nil { + return nil, err + } + _node, _spec := uc.createSpec() + if err := sqlgraph.CreateNode(ctx, uc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != nil { + if id, ok := _spec.ID.Value.(*uuid.UUID); ok { + _node.ID = *id + } else if err := _node.ID.Scan(_spec.ID.Value); err != nil { + return nil, err + } + } + uc.mutation.id = &_node.ID + uc.mutation.done = true + return _node, nil +} + +func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { + var ( + _node = &User{config: uc.config} + _spec = sqlgraph.NewCreateSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID)) + ) + if id, ok := uc.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := uc.mutation.TelegramID(); ok { + _spec.SetField(user.FieldTelegramID, field.TypeInt64, value) + _node.TelegramID = value + } + if nodes := uc.mutation.LinksIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.LinksTable, + Columns: user.LinksPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(link.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// UserCreateBulk is the builder for creating many User entities in bulk. +type UserCreateBulk struct { + config + err error + builders []*UserCreate +} + +// Save creates the User entities in the database. +func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { + if ucb.err != nil { + return nil, ucb.err + } + specs := make([]*sqlgraph.CreateSpec, len(ucb.builders)) + nodes := make([]*User, len(ucb.builders)) + mutators := make([]Mutator, len(ucb.builders)) + for i := range ucb.builders { + func(i int, root context.Context) { + builder := ucb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserMutation) + 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, ucb.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, ucb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, ucb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (ucb *UserCreateBulk) SaveX(ctx context.Context) []*User { + v, err := ucb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ucb *UserCreateBulk) Exec(ctx context.Context) error { + _, err := ucb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ucb *UserCreateBulk) ExecX(ctx context.Context) { + if err := ucb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/user_delete.go b/ent/user_delete.go new file mode 100644 index 0000000..729c3cf --- /dev/null +++ b/ent/user_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "code.gurenya.net/carlsmei/muninn-aio/ent/predicate" + "code.gurenya.net/carlsmei/muninn-aio/ent/user" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// UserDelete is the builder for deleting a User entity. +type UserDelete struct { + config + hooks []Hook + mutation *UserMutation +} + +// Where appends a list predicates to the UserDelete builder. +func (ud *UserDelete) Where(ps ...predicate.User) *UserDelete { + ud.mutation.Where(ps...) + return ud +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (ud *UserDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, ud.sqlExec, ud.mutation, ud.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (ud *UserDelete) ExecX(ctx context.Context) int { + n, err := ud.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (ud *UserDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID)) + if ps := ud.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, ud.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + ud.mutation.done = true + return affected, err +} + +// UserDeleteOne is the builder for deleting a single User entity. +type UserDeleteOne struct { + ud *UserDelete +} + +// Where appends a list predicates to the UserDelete builder. +func (udo *UserDeleteOne) Where(ps ...predicate.User) *UserDeleteOne { + udo.ud.mutation.Where(ps...) + return udo +} + +// Exec executes the deletion query. +func (udo *UserDeleteOne) Exec(ctx context.Context) error { + n, err := udo.ud.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{user.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (udo *UserDeleteOne) ExecX(ctx context.Context) { + if err := udo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/user_query.go b/ent/user_query.go new file mode 100644 index 0000000..e2ec748 --- /dev/null +++ b/ent/user_query.go @@ -0,0 +1,638 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + + "code.gurenya.net/carlsmei/muninn-aio/ent/link" + "code.gurenya.net/carlsmei/muninn-aio/ent/predicate" + "code.gurenya.net/carlsmei/muninn-aio/ent/user" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/google/uuid" +) + +// UserQuery is the builder for querying User entities. +type UserQuery struct { + config + ctx *QueryContext + order []user.OrderOption + inters []Interceptor + predicates []predicate.User + withLinks *LinkQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the UserQuery builder. +func (uq *UserQuery) Where(ps ...predicate.User) *UserQuery { + uq.predicates = append(uq.predicates, ps...) + return uq +} + +// Limit the number of records to be returned by this query. +func (uq *UserQuery) Limit(limit int) *UserQuery { + uq.ctx.Limit = &limit + return uq +} + +// Offset to start from. +func (uq *UserQuery) Offset(offset int) *UserQuery { + uq.ctx.Offset = &offset + return uq +} + +// 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 (uq *UserQuery) Unique(unique bool) *UserQuery { + uq.ctx.Unique = &unique + return uq +} + +// Order specifies how the records should be ordered. +func (uq *UserQuery) Order(o ...user.OrderOption) *UserQuery { + uq.order = append(uq.order, o...) + return uq +} + +// QueryLinks chains the current query on the "links" edge. +func (uq *UserQuery) QueryLinks() *LinkQuery { + query := (&LinkClient{config: uq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := uq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(link.Table, link.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, user.LinksTable, user.LinksPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first User entity from the query. +// Returns a *NotFoundError when no User was found. +func (uq *UserQuery) First(ctx context.Context) (*User, error) { + nodes, err := uq.Limit(1).All(setContextOp(ctx, uq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{user.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (uq *UserQuery) FirstX(ctx context.Context) *User { + node, err := uq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first User ID from the query. +// Returns a *NotFoundError when no User ID was found. +func (uq *UserQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = uq.Limit(1).IDs(setContextOp(ctx, uq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{user.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (uq *UserQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := uq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single User entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one User entity is found. +// Returns a *NotFoundError when no User entities are found. +func (uq *UserQuery) Only(ctx context.Context) (*User, error) { + nodes, err := uq.Limit(2).All(setContextOp(ctx, uq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{user.Label} + default: + return nil, &NotSingularError{user.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (uq *UserQuery) OnlyX(ctx context.Context) *User { + node, err := uq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only User ID in the query. +// Returns a *NotSingularError when more than one User ID is found. +// Returns a *NotFoundError when no entities are found. +func (uq *UserQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = uq.Limit(2).IDs(setContextOp(ctx, uq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{user.Label} + default: + err = &NotSingularError{user.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (uq *UserQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := uq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Users. +func (uq *UserQuery) All(ctx context.Context) ([]*User, error) { + ctx = setContextOp(ctx, uq.ctx, ent.OpQueryAll) + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*User, *UserQuery]() + return withInterceptors[[]*User](ctx, uq, qr, uq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (uq *UserQuery) AllX(ctx context.Context) []*User { + nodes, err := uq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of User IDs. +func (uq *UserQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if uq.ctx.Unique == nil && uq.path != nil { + uq.Unique(true) + } + ctx = setContextOp(ctx, uq.ctx, ent.OpQueryIDs) + if err = uq.Select(user.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (uq *UserQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := uq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (uq *UserQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, uq.ctx, ent.OpQueryCount) + if err := uq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, uq, querierCount[*UserQuery](), uq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (uq *UserQuery) CountX(ctx context.Context) int { + count, err := uq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (uq *UserQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, uq.ctx, ent.OpQueryExist) + switch _, err := uq.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 (uq *UserQuery) ExistX(ctx context.Context) bool { + exist, err := uq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the UserQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (uq *UserQuery) Clone() *UserQuery { + if uq == nil { + return nil + } + return &UserQuery{ + config: uq.config, + ctx: uq.ctx.Clone(), + order: append([]user.OrderOption{}, uq.order...), + inters: append([]Interceptor{}, uq.inters...), + predicates: append([]predicate.User{}, uq.predicates...), + withLinks: uq.withLinks.Clone(), + // clone intermediate query. + sql: uq.sql.Clone(), + path: uq.path, + } +} + +// WithLinks tells the query-builder to eager-load the nodes that are connected to +// the "links" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithLinks(opts ...func(*LinkQuery)) *UserQuery { + query := (&LinkClient{config: uq.config}).Query() + for _, opt := range opts { + opt(query) + } + uq.withLinks = query + return uq +} + +// 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 { +// TelegramID int64 `json:"telegram_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.User.Query(). +// GroupBy(user.FieldTelegramID). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (uq *UserQuery) GroupBy(field string, fields ...string) *UserGroupBy { + uq.ctx.Fields = append([]string{field}, fields...) + grbuild := &UserGroupBy{build: uq} + grbuild.flds = &uq.ctx.Fields + grbuild.label = user.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 { +// TelegramID int64 `json:"telegram_id,omitempty"` +// } +// +// client.User.Query(). +// Select(user.FieldTelegramID). +// Scan(ctx, &v) +func (uq *UserQuery) Select(fields ...string) *UserSelect { + uq.ctx.Fields = append(uq.ctx.Fields, fields...) + sbuild := &UserSelect{UserQuery: uq} + sbuild.label = user.Label + sbuild.flds, sbuild.scan = &uq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a UserSelect configured with the given aggregations. +func (uq *UserQuery) Aggregate(fns ...AggregateFunc) *UserSelect { + return uq.Select().Aggregate(fns...) +} + +func (uq *UserQuery) prepareQuery(ctx context.Context) error { + for _, inter := range uq.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, uq); err != nil { + return err + } + } + } + for _, f := range uq.ctx.Fields { + if !user.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if uq.path != nil { + prev, err := uq.path(ctx) + if err != nil { + return err + } + uq.sql = prev + } + return nil +} + +func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, error) { + var ( + nodes = []*User{} + _spec = uq.querySpec() + loadedTypes = [1]bool{ + uq.withLinks != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*User).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &User{config: uq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, uq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := uq.withLinks; query != nil { + if err := uq.loadLinks(ctx, query, nodes, + func(n *User) { n.Edges.Links = []*Link{} }, + func(n *User, e *Link) { n.Edges.Links = append(n.Edges.Links, e) }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (uq *UserQuery) loadLinks(ctx context.Context, query *LinkQuery, nodes []*User, init func(*User), assign func(*User, *Link)) error { + edgeIDs := make([]driver.Value, len(nodes)) + byID := make(map[uuid.UUID]*User) + nids := make(map[uuid.UUID]map[*User]struct{}) + for i, node := range nodes { + edgeIDs[i] = node.ID + byID[node.ID] = node + if init != nil { + init(node) + } + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(user.LinksTable) + s.Join(joinT).On(s.C(link.FieldID), joinT.C(user.LinksPrimaryKey[1])) + s.Where(sql.InValues(joinT.C(user.LinksPrimaryKey[0]), edgeIDs...)) + columns := s.SelectedColumns() + s.Select(joinT.C(user.LinksPrimaryKey[0])) + s.AppendSelect(columns...) + s.SetDistinct(false) + }) + if err := query.prepareQuery(ctx); err != nil { + return err + } + qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) { + assign := spec.Assign + values := spec.ScanValues + spec.ScanValues = func(columns []string) ([]any, error) { + values, err := values(columns[1:]) + if err != nil { + return nil, err + } + return append([]any{new(uuid.UUID)}, values...), nil + } + spec.Assign = func(columns []string, values []any) error { + outValue := *values[0].(*uuid.UUID) + inValue := *values[1].(*uuid.UUID) + if nids[inValue] == nil { + nids[inValue] = map[*User]struct{}{byID[outValue]: {}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byID[outValue]] = struct{}{} + return nil + } + }) + }) + neighbors, err := withInterceptors[[]*Link](ctx, query, qr, query.inters) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nids[n.ID] + if !ok { + return fmt.Errorf(`unexpected "links" node returned %v`, n.ID) + } + for kn := range nodes { + assign(kn, n) + } + } + return nil +} + +func (uq *UserQuery) sqlCount(ctx context.Context) (int, error) { + _spec := uq.querySpec() + _spec.Node.Columns = uq.ctx.Fields + if len(uq.ctx.Fields) > 0 { + _spec.Unique = uq.ctx.Unique != nil && *uq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, uq.driver, _spec) +} + +func (uq *UserQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID)) + _spec.From = uq.sql + if unique := uq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if uq.path != nil { + _spec.Unique = true + } + if fields := uq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, user.FieldID) + for i := range fields { + if fields[i] != user.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := uq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := uq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := uq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := uq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (uq *UserQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(uq.driver.Dialect()) + t1 := builder.Table(user.Table) + columns := uq.ctx.Fields + if len(columns) == 0 { + columns = user.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if uq.sql != nil { + selector = uq.sql + selector.Select(selector.Columns(columns...)...) + } + if uq.ctx.Unique != nil && *uq.ctx.Unique { + selector.Distinct() + } + for _, p := range uq.predicates { + p(selector) + } + for _, p := range uq.order { + p(selector) + } + if offset := uq.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 := uq.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// UserGroupBy is the group-by builder for User entities. +type UserGroupBy struct { + selector + build *UserQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (ugb *UserGroupBy) Aggregate(fns ...AggregateFunc) *UserGroupBy { + ugb.fns = append(ugb.fns, fns...) + return ugb +} + +// Scan applies the selector query and scans the result into the given value. +func (ugb *UserGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ugb.build.ctx, ent.OpQueryGroupBy) + if err := ugb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*UserQuery, *UserGroupBy](ctx, ugb.build, ugb, ugb.build.inters, v) +} + +func (ugb *UserGroupBy) sqlScan(ctx context.Context, root *UserQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(ugb.fns)) + for _, fn := range ugb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*ugb.flds)+len(ugb.fns)) + for _, f := range *ugb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*ugb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := ugb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// UserSelect is the builder for selecting fields of User entities. +type UserSelect struct { + *UserQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (us *UserSelect) Aggregate(fns ...AggregateFunc) *UserSelect { + us.fns = append(us.fns, fns...) + return us +} + +// Scan applies the selector query and scans the result into the given value. +func (us *UserSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, us.ctx, ent.OpQuerySelect) + if err := us.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*UserQuery, *UserSelect](ctx, us.UserQuery, us, us.inters, v) +} + +func (us *UserSelect) sqlScan(ctx context.Context, root *UserQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(us.fns)) + for _, fn := range us.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*us.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 := us.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/ent/user_update.go b/ent/user_update.go new file mode 100644 index 0000000..63e37c6 --- /dev/null +++ b/ent/user_update.go @@ -0,0 +1,339 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "code.gurenya.net/carlsmei/muninn-aio/ent/link" + "code.gurenya.net/carlsmei/muninn-aio/ent/predicate" + "code.gurenya.net/carlsmei/muninn-aio/ent/user" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/google/uuid" +) + +// UserUpdate is the builder for updating User entities. +type UserUpdate struct { + config + hooks []Hook + mutation *UserMutation +} + +// Where appends a list predicates to the UserUpdate builder. +func (uu *UserUpdate) Where(ps ...predicate.User) *UserUpdate { + uu.mutation.Where(ps...) + return uu +} + +// AddLinkIDs adds the "links" edge to the Link entity by IDs. +func (uu *UserUpdate) AddLinkIDs(ids ...uuid.UUID) *UserUpdate { + uu.mutation.AddLinkIDs(ids...) + return uu +} + +// AddLinks adds the "links" edges to the Link entity. +func (uu *UserUpdate) AddLinks(l ...*Link) *UserUpdate { + ids := make([]uuid.UUID, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return uu.AddLinkIDs(ids...) +} + +// Mutation returns the UserMutation object of the builder. +func (uu *UserUpdate) Mutation() *UserMutation { + return uu.mutation +} + +// ClearLinks clears all "links" edges to the Link entity. +func (uu *UserUpdate) ClearLinks() *UserUpdate { + uu.mutation.ClearLinks() + return uu +} + +// RemoveLinkIDs removes the "links" edge to Link entities by IDs. +func (uu *UserUpdate) RemoveLinkIDs(ids ...uuid.UUID) *UserUpdate { + uu.mutation.RemoveLinkIDs(ids...) + return uu +} + +// RemoveLinks removes "links" edges to Link entities. +func (uu *UserUpdate) RemoveLinks(l ...*Link) *UserUpdate { + ids := make([]uuid.UUID, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return uu.RemoveLinkIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (uu *UserUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, uu.sqlSave, uu.mutation, uu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (uu *UserUpdate) SaveX(ctx context.Context) int { + affected, err := uu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (uu *UserUpdate) Exec(ctx context.Context) error { + _, err := uu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (uu *UserUpdate) ExecX(ctx context.Context) { + if err := uu.Exec(ctx); err != nil { + panic(err) + } +} + +func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID)) + if ps := uu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if uu.mutation.LinksCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.LinksTable, + Columns: user.LinksPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(link.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.RemovedLinksIDs(); len(nodes) > 0 && !uu.mutation.LinksCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.LinksTable, + Columns: user.LinksPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(link.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.LinksIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.LinksTable, + Columns: user.LinksPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(link.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if n, err = sqlgraph.UpdateNodes(ctx, uu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{user.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + uu.mutation.done = true + return n, nil +} + +// UserUpdateOne is the builder for updating a single User entity. +type UserUpdateOne struct { + config + fields []string + hooks []Hook + mutation *UserMutation +} + +// AddLinkIDs adds the "links" edge to the Link entity by IDs. +func (uuo *UserUpdateOne) AddLinkIDs(ids ...uuid.UUID) *UserUpdateOne { + uuo.mutation.AddLinkIDs(ids...) + return uuo +} + +// AddLinks adds the "links" edges to the Link entity. +func (uuo *UserUpdateOne) AddLinks(l ...*Link) *UserUpdateOne { + ids := make([]uuid.UUID, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return uuo.AddLinkIDs(ids...) +} + +// Mutation returns the UserMutation object of the builder. +func (uuo *UserUpdateOne) Mutation() *UserMutation { + return uuo.mutation +} + +// ClearLinks clears all "links" edges to the Link entity. +func (uuo *UserUpdateOne) ClearLinks() *UserUpdateOne { + uuo.mutation.ClearLinks() + return uuo +} + +// RemoveLinkIDs removes the "links" edge to Link entities by IDs. +func (uuo *UserUpdateOne) RemoveLinkIDs(ids ...uuid.UUID) *UserUpdateOne { + uuo.mutation.RemoveLinkIDs(ids...) + return uuo +} + +// RemoveLinks removes "links" edges to Link entities. +func (uuo *UserUpdateOne) RemoveLinks(l ...*Link) *UserUpdateOne { + ids := make([]uuid.UUID, len(l)) + for i := range l { + ids[i] = l[i].ID + } + return uuo.RemoveLinkIDs(ids...) +} + +// Where appends a list predicates to the UserUpdate builder. +func (uuo *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne { + uuo.mutation.Where(ps...) + return uuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (uuo *UserUpdateOne) Select(field string, fields ...string) *UserUpdateOne { + uuo.fields = append([]string{field}, fields...) + return uuo +} + +// Save executes the query and returns the updated User entity. +func (uuo *UserUpdateOne) Save(ctx context.Context) (*User, error) { + return withHooks(ctx, uuo.sqlSave, uuo.mutation, uuo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (uuo *UserUpdateOne) SaveX(ctx context.Context) *User { + node, err := uuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (uuo *UserUpdateOne) Exec(ctx context.Context) error { + _, err := uuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (uuo *UserUpdateOne) ExecX(ctx context.Context) { + if err := uuo.Exec(ctx); err != nil { + panic(err) + } +} + +func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) { + _spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID)) + id, ok := uuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "User.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := uuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, user.FieldID) + for _, f := range fields { + if !user.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != user.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := uuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if uuo.mutation.LinksCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.LinksTable, + Columns: user.LinksPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(link.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.RemovedLinksIDs(); len(nodes) > 0 && !uuo.mutation.LinksCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.LinksTable, + Columns: user.LinksPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(link.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.LinksIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.LinksTable, + Columns: user.LinksPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(link.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &User{config: uuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, uuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{user.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + uuo.mutation.done = true + return _node, nil +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..dd61ce9 --- /dev/null +++ b/go.mod @@ -0,0 +1,43 @@ +module code.gurenya.net/carlsmei/muninn-aio + +go 1.22.2 + +require ( + entgo.io/ent v0.14.0 + github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 + github.com/go-sql-driver/mysql v1.8.1 + github.com/go-telegram/bot v1.6.1 + github.com/google/uuid v1.6.0 + github.com/kelseyhightower/envconfig v1.4.0 + github.com/lib/pq v1.10.9 + github.com/mattn/go-sqlite3 v1.14.22 +) + +require ( + ariga.io/atlas v0.19.1-0.20240203083654-5948b60a8e43 // indirect + filippo.io/edwards25519 v1.1.0 // indirect + github.com/agext/levenshtein v1.2.1 // indirect + github.com/andybalholm/brotli v1.1.0 // indirect + github.com/apparentlymart/go-textseg/v13 v13.0.0 // indirect + github.com/go-openapi/inflect v0.19.0 // indirect + github.com/gofiber/fiber/v2 v2.52.5 // indirect + github.com/gofiber/utils v0.0.10 // indirect + github.com/google/go-cmp v0.6.0 // indirect + github.com/gorilla/schema v1.1.0 // indirect + github.com/hashicorp/hcl/v2 v2.13.0 // indirect + github.com/klauspost/compress v1.17.9 // indirect + github.com/kr/pretty v0.3.1 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-runewidth v0.0.15 // indirect + github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 // indirect + github.com/rivo/uniseg v0.2.0 // indirect + github.com/stretchr/testify v1.9.0 // indirect + github.com/valyala/bytebufferpool v1.0.0 // indirect + github.com/valyala/fasthttp v1.55.0 // indirect + github.com/valyala/tcplisten v1.0.0 // indirect + github.com/zclconf/go-cty v1.8.0 // indirect + golang.org/x/mod v0.17.0 // indirect + golang.org/x/sys v0.22.0 // indirect + golang.org/x/text v0.16.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..282a811 --- /dev/null +++ b/go.sum @@ -0,0 +1,122 @@ +ariga.io/atlas v0.19.1-0.20240203083654-5948b60a8e43 h1:GwdJbXydHCYPedeeLt4x/lrlIISQ4JTH1mRWuE5ZZ14= +ariga.io/atlas v0.19.1-0.20240203083654-5948b60a8e43/go.mod h1:uj3pm+hUTVN/X5yfdBexHlZv+1Xu5u5ZbZx7+CDavNU= +entgo.io/ent v0.14.0 h1:EO3Z9aZ5bXJatJeGqu/EVdnNr6K4mRq3rWe5owt0MC4= +entgo.io/ent v0.14.0/go.mod h1:qCEmo+biw3ccBn9OyL4ZK5dfpwg++l1Gxwac5B1206A= +filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= +filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= +github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60= +github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= +github.com/agext/levenshtein v1.2.1 h1:QmvMAjj2aEICytGiWzmxoE0x2KZvE0fvmqMOfy2tjT8= +github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= +github.com/andybalholm/brotli v1.0.0/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y= +github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M= +github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY= +github.com/apparentlymart/go-textseg/v13 v13.0.0 h1:Y+KvPE1NYz0xl601PVImeQfFyEy6iT90AvPUL1NNfNw= +github.com/apparentlymart/go-textseg/v13 v13.0.0/go.mod h1:ZK2fH7c4NqDTLtiYLvIkEghdlcqw7yxLeM89kiTRPUo= +github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= +github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-openapi/inflect v0.19.0 h1:9jCH9scKIbHeV9m12SmPilScz6krDxKRasNNSNPXu/4= +github.com/go-openapi/inflect v0.19.0/go.mod h1:lHpZVlpIQqLyKwJ4N+YSc9hchQy/i12fJykb83CRBH4= +github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= +github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= +github.com/go-telegram/bot v1.6.1 h1:jiIYq8Z7HfL4nZ+rPpCBMPWLvll04LLxaGs/DleWnbU= +github.com/go-telegram/bot v1.6.1/go.mod h1:i2TRs7fXWIeaceF3z7KzsMt/he0TwkVC680mvdTFYeM= +github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68= +github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA= +github.com/gofiber/fiber v1.14.6 h1:QRUPvPmr8ijQuGo1MgupHBn8E+wW0IKqiOvIZPtV70o= +github.com/gofiber/fiber v1.14.6/go.mod h1:Yw2ekF1YDPreO9V6TMYjynu94xRxZBdaa8X5HhHsjCM= +github.com/gofiber/fiber/v2 v2.52.5 h1:tWoP1MJQjGEe4GB5TUGOi7P2E0ZMMRx5ZTG4rT+yGMo= +github.com/gofiber/fiber/v2 v2.52.5/go.mod h1:KEOE+cXMhXG0zHc9d8+E38hoX+ZN7bhOtgeF2oT6jrQ= +github.com/gofiber/utils v0.0.10 h1:3Mr7X7JdCUo7CWf/i5sajSaDmArEDtti8bM1JUVso2U= +github.com/gofiber/utils v0.0.10/go.mod h1:9J5aHFUIjq0XfknT4+hdSMG6/jzfaAgCu4HEbWDeBlo= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gorilla/schema v1.1.0 h1:CamqUDOFUBqzrvxuz2vEwo8+SUdwsluFh7IlzJh30LY= +github.com/gorilla/schema v1.1.0/go.mod h1:kgLaKoK1FELgZqMAVxx/5cbj0kT+57qxUrAlIO2eleU= +github.com/hashicorp/hcl/v2 v2.13.0 h1:0Apadu1w6M11dyGFxWnmhhcMjkbAiKCv7G1r/2QgCNc= +github.com/hashicorp/hcl/v2 v2.13.0/go.mod h1:e4z5nxYlWNPdDSNYX+ph14EvWYMFm3eP0zIUqPc2jr0= +github.com/kelseyhightower/envconfig v1.4.0 h1:Im6hONhd3pLkfDFsbRgu68RDNkGF1r3dvMUtDTo2cv8= +github.com/kelseyhightower/envconfig v1.4.0/go.mod h1:cccZRl6mQpaq41TPp5QxidR+Sa3axMbJDNb//FQX6Gg= +github.com/klauspost/compress v1.10.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= +github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA= +github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= +github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= +github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= +github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= +github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 h1:DpOJ2HYzCv8LZP15IdmG+YdwD2luVPHITV96TkirNBM= +github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= +github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ= +github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +github.com/valyala/fasthttp v1.16.0/go.mod h1:YOKImeEosDdBPnxc0gy7INqi3m1zK6A+xl6TwOBhHCA= +github.com/valyala/fasthttp v1.55.0 h1:Zkefzgt6a7+bVKHnu/YaYSOPfNYNisSVBo/unVCf8k8= +github.com/valyala/fasthttp v1.55.0/go.mod h1:NkY9JtkrpPKmgwV3HTaS2HWaJss9RSIsRVfcxxoHiOM= +github.com/valyala/tcplisten v0.0.0-20161114210144-ceec8f93295a/go.mod h1:v3UYOV9WzVtRmSR+PDvWpU/qWl4Wa5LApYYX4ZtKbio= +github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8= +github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc= +github.com/vmihailenco/msgpack/v4 v4.3.12/go.mod h1:gborTTJjAo/GWTqqRjrLCn9pgNN+NXzzngzBKDPIqw4= +github.com/vmihailenco/tagparser v0.1.1/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI= +github.com/zclconf/go-cty v1.8.0 h1:s4AvqaeQzJIu3ndv4gVIhplVD0krU+bgrcLSVUnaWuA= +github.com/zclconf/go-cty v1.8.0/go.mod h1:vVKLxnk3puL4qRAv72AO+W99LUD4da90g3uUAzyuvAk= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA= +golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200602114024-627f9648deb9/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI= +golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4= +golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/handlers.go b/handlers.go new file mode 100644 index 0000000..454f22e --- /dev/null +++ b/handlers.go @@ -0,0 +1,45 @@ +package main + +import ( + "context" + "fmt" + "net/url" + + "code.gurenya.net/carlsmei/muninn-aio/services" + "github.com/go-telegram/bot" + "github.com/go-telegram/bot/models" +) + +func generateLinkHandler(ctx context.Context, b *bot.Bot, update *models.Update) { + user, err := services.GetOrCreateUser(ctx, update.Message.From.ID) + + if err != nil { + panic(err) + } + + link, err := services.CreateLink(ctx, user, update.Message.Text, "") + + if err != nil { + panic(err) + } + + url, err := url.Parse("http://localhost:3000") + url.Path = link.Key + + if err != nil { + panic(err) + } + + b.SendMessage(ctx, &bot.SendMessageParams{ + ChatID: update.Message.Chat.ID, + Text: fmt.Sprintf("Ваша короткая ссылка готова - %s", url.String()), + ParseMode: models.ParseModeHTML, + }) +} + +func startHandler(ctx context.Context, b *bot.Bot, update *models.Update) { + b.SendMessage(ctx, &bot.SendMessageParams{ + ChatID: update.Message.Chat.ID, + Text: fmt.Sprintf("Привет! Я Muninn, бот для укорачивания ссылок.\n\nВ данный момент у меня нет особых возможностей, но в скором времени что-нибудь да появится.\n\nЭто быстренький прототип написанный за ночь, в оригинальной версии сервис делится на части и состоит из разных приложений взаимодействующих между собой :/\n\nVersion: %s\nRepository: https://code.gurenya.net/carlsmei/muninn-aio", Version), + }) +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..1cd8ecf --- /dev/null +++ b/main.go @@ -0,0 +1,84 @@ +package main + +import ( + "context" + "fmt" + "strings" + + "code.gurenya.net/carlsmei/muninn-aio/config" + "code.gurenya.net/carlsmei/muninn-aio/db" + "code.gurenya.net/carlsmei/muninn-aio/ent" + "code.gurenya.net/carlsmei/muninn-aio/services" + "github.com/asaskevich/govalidator" + "github.com/go-telegram/bot" + "github.com/go-telegram/bot/models" + "github.com/gofiber/fiber/v2" + + _ "github.com/go-sql-driver/mysql" + _ "github.com/lib/pq" + _ "github.com/mattn/go-sqlite3" +) + +var ( + Version = "dev" +) + +func main() { + config.Load() + db.EntInit() + + // TELEGRAM + opts := []bot.Option{ + // bot.WithDefaultHandler(handler), + } + + b, err := bot.New(config.Env.TelegramToken, opts...) + if err != nil { + panic(err) + } + + b.RegisterHandler(bot.HandlerTypeMessageText, "/start", bot.MatchTypeExact, startHandler) + b.RegisterHandlerMatchFunc(func(update *models.Update) bool { + return update.Message != nil && govalidator.IsURL(update.Message.Text) + }, generateLinkHandler) + + go b.Start(context.Background()) + + // FIBER + app := fiber.New() + + app.Use(func(c *fiber.Ctx) error { + c.Set("Server", fmt.Sprintf("muninn-aio (%s)", Version)) + + return c.Next() + }) + + app.Get("/:key", func(c *fiber.Ctx) error { + key := c.Params("key") + + link, err := services.GetLinkByKey(c.Context(), key) + if err != nil { + if ent.IsNotFound(err) { + return c.Status(404).SendString("not found") + } + } + + c.SendString(fmt.Sprintf("Found. Redirecting to %s", link.OriginalURL)) + return c.Redirect(link.OriginalURL, 302) + }) + + var addr string + if strings.Contains(config.Env.AppPort, ":") { + addr = config.Env.AppPort + } else { + addr = ":" + config.Env.AppPort + } + + app.Listen(addr) + + // quit := make(chan os.Signal, 1) + // signal.Notify(quit, os.Interrupt, syscall.SIGTERM) + // sig := <-quit + + // fmt.Printf("Shutting down server... Reason: %s\n", sig) +} diff --git a/services/key.go b/services/key.go new file mode 100644 index 0000000..c7aaa0a --- /dev/null +++ b/services/key.go @@ -0,0 +1,38 @@ +package services + +import ( + "context" + "math/rand" + "time" + + "code.gurenya.net/carlsmei/muninn-aio/db" + "code.gurenya.net/carlsmei/muninn-aio/ent/link" +) + +// Key Generation Algorithm 6:51 MSK 29.07.24 + +var numChars = 8 +var keyAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" +var seededRand *rand.Rand = rand.New( + rand.NewSource(time.Now().UnixNano())) + +func GenerateKey(ctx context.Context) string { + client := db.GetEntClient() + cond := false + key := make([]byte, numChars) + + for !cond { + for i := range key { + key[i] = keyAlphabet[seededRand.Intn(len(keyAlphabet))] + } + + exists, _ := client.Link. + Query(). + Where(link.Key(string(key))). + Exist(ctx) + + cond = !exists + } + + return string(key) +} diff --git a/services/link.go b/services/link.go new file mode 100644 index 0000000..3dff9bf --- /dev/null +++ b/services/link.go @@ -0,0 +1,44 @@ +package services + +import ( + "context" + + "code.gurenya.net/carlsmei/muninn-aio/db" + "code.gurenya.net/carlsmei/muninn-aio/ent" + "code.gurenya.net/carlsmei/muninn-aio/ent/link" +) + +func CreateLink(ctx context.Context, user *ent.User, original_url string, key string) (*ent.Link, error) { + client := db.GetEntClient() + + if key == "" { + key = GenerateKey(ctx) + } + + link, err := client.Link.Create(). + AddOwner(user). + SetKey(key). + SetOriginalURL(original_url). + Save(ctx) + + if err != nil { + return nil, err + } + + return link, nil +} + +func GetLinkByKey(ctx context.Context, key string) (*ent.Link, error) { + client := db.GetEntClient() + + link, err := client.Link. + Query(). + Where(link.Key(key)). + Only(ctx) + + if err != nil { + return nil, err + } + + return link, nil +} diff --git a/services/user.go b/services/user.go new file mode 100644 index 0000000..7b0f49d --- /dev/null +++ b/services/user.go @@ -0,0 +1,40 @@ +package services + +import ( + "context" + + "code.gurenya.net/carlsmei/muninn-aio/db" + "code.gurenya.net/carlsmei/muninn-aio/ent" + "code.gurenya.net/carlsmei/muninn-aio/ent/user" +) + +func GetOrCreateUser(ctx context.Context, telegram_id int64) (*ent.User, error) { + client := db.GetEntClient() + + // fmt.Printf("GetOrCreateUser(context, %d)\n", telegram_id) + + user, err := client.User.Query(). + Where(user.TelegramID(telegram_id)). + Only(ctx) + if err != nil { + if ent.IsNotFound(err) { + // fmt.Printf("user not found - creating user with telegram id %d\n", telegram_id) + } else { + return nil, err + } + } else { + return user, nil + } + + user, err = client.User.Create(). + SetTelegramID(telegram_id). + Save(ctx) + + if err != nil { + return nil, err + } + + // fmt.Printf("user created with telegram id %d\n", telegram_id) + + return user, nil +}