github.com/iasthc/atlas/cmd/atlas@v0.0.0-20230523071841-73246df3f88d/internal/migrate/ent/client.go (about)

     1  // Copyright 2021-present The Atlas Authors. All rights reserved.
     2  // This source code is licensed under the Apache 2.0 license found
     3  // in the LICENSE file in the root directory of this source tree.
     4  
     5  // Code generated by entc, DO NOT EDIT.
     6  
     7  package ent
     8  
     9  import (
    10  	"context"
    11  	"errors"
    12  	"fmt"
    13  	"log"
    14  
    15  	"github.com/iasthc/atlas/cmd/atlas/internal/migrate/ent/migrate"
    16  
    17  	"github.com/iasthc/atlas/cmd/atlas/internal/migrate/ent/revision"
    18  	"entgo.io/ent"
    19  	"entgo.io/ent/dialect"
    20  	"entgo.io/ent/dialect/sql"
    21  
    22  	stdsql "database/sql"
    23  
    24  	"github.com/iasthc/atlas/cmd/atlas/internal/migrate/ent/internal"
    25  )
    26  
    27  // Client is the client that holds all ent builders.
    28  type Client struct {
    29  	config
    30  	// Schema is the client for creating, migrating and dropping schema.
    31  	Schema *migrate.Schema
    32  	// Revision is the client for interacting with the Revision builders.
    33  	Revision *RevisionClient
    34  }
    35  
    36  // NewClient creates a new client configured with the given options.
    37  func NewClient(opts ...Option) *Client {
    38  	cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}}
    39  	cfg.options(opts...)
    40  	client := &Client{config: cfg}
    41  	client.init()
    42  	return client
    43  }
    44  
    45  func (c *Client) init() {
    46  	c.Schema = migrate.NewSchema(c.driver)
    47  	c.Revision = NewRevisionClient(c.config)
    48  }
    49  
    50  type (
    51  	// config is the configuration for the client and its builder.
    52  	config struct {
    53  		// driver used for executing database requests.
    54  		driver dialect.Driver
    55  		// debug enable a debug logging.
    56  		debug bool
    57  		// log used for logging on debug mode.
    58  		log func(...any)
    59  		// hooks to execute on mutations.
    60  		hooks *hooks
    61  		// interceptors to execute on queries.
    62  		inters *inters
    63  		// schemaConfig contains alternative names for all tables.
    64  		schemaConfig SchemaConfig
    65  	}
    66  	// Option function to configure the client.
    67  	Option func(*config)
    68  )
    69  
    70  // options applies the options on the config object.
    71  func (c *config) options(opts ...Option) {
    72  	for _, opt := range opts {
    73  		opt(c)
    74  	}
    75  	if c.debug {
    76  		c.driver = dialect.Debug(c.driver, c.log)
    77  	}
    78  }
    79  
    80  // Debug enables debug logging on the ent.Driver.
    81  func Debug() Option {
    82  	return func(c *config) {
    83  		c.debug = true
    84  	}
    85  }
    86  
    87  // Log sets the logging function for debug mode.
    88  func Log(fn func(...any)) Option {
    89  	return func(c *config) {
    90  		c.log = fn
    91  	}
    92  }
    93  
    94  // Driver configures the client driver.
    95  func Driver(driver dialect.Driver) Option {
    96  	return func(c *config) {
    97  		c.driver = driver
    98  	}
    99  }
   100  
   101  // Open opens a database/sql.DB specified by the driver name and
   102  // the data source name, and returns a new client attached to it.
   103  // Optional parameters can be added for configuring the client.
   104  func Open(driverName, dataSourceName string, options ...Option) (*Client, error) {
   105  	switch driverName {
   106  	case dialect.MySQL, dialect.Postgres, dialect.SQLite:
   107  		drv, err := sql.Open(driverName, dataSourceName)
   108  		if err != nil {
   109  			return nil, err
   110  		}
   111  		return NewClient(append(options, Driver(drv))...), nil
   112  	default:
   113  		return nil, fmt.Errorf("unsupported driver: %q", driverName)
   114  	}
   115  }
   116  
   117  // Tx returns a new transactional client. The provided context
   118  // is used until the transaction is committed or rolled back.
   119  func (c *Client) Tx(ctx context.Context) (*Tx, error) {
   120  	if _, ok := c.driver.(*txDriver); ok {
   121  		return nil, errors.New("ent: cannot start a transaction within a transaction")
   122  	}
   123  	tx, err := newTx(ctx, c.driver)
   124  	if err != nil {
   125  		return nil, fmt.Errorf("ent: starting a transaction: %w", err)
   126  	}
   127  	cfg := c.config
   128  	cfg.driver = tx
   129  	return &Tx{
   130  		ctx:      ctx,
   131  		config:   cfg,
   132  		Revision: NewRevisionClient(cfg),
   133  	}, nil
   134  }
   135  
   136  // BeginTx returns a transactional client with specified options.
   137  func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
   138  	if _, ok := c.driver.(*txDriver); ok {
   139  		return nil, errors.New("ent: cannot start a transaction within a transaction")
   140  	}
   141  	tx, err := c.driver.(interface {
   142  		BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error)
   143  	}).BeginTx(ctx, opts)
   144  	if err != nil {
   145  		return nil, fmt.Errorf("ent: starting a transaction: %w", err)
   146  	}
   147  	cfg := c.config
   148  	cfg.driver = &txDriver{tx: tx, drv: c.driver}
   149  	return &Tx{
   150  		ctx:      ctx,
   151  		config:   cfg,
   152  		Revision: NewRevisionClient(cfg),
   153  	}, nil
   154  }
   155  
   156  // Debug returns a new debug-client. It's used to get verbose logging on specific operations.
   157  //
   158  //	client.Debug().
   159  //		Revision.
   160  //		Query().
   161  //		Count(ctx)
   162  func (c *Client) Debug() *Client {
   163  	if c.debug {
   164  		return c
   165  	}
   166  	cfg := c.config
   167  	cfg.driver = dialect.Debug(c.driver, c.log)
   168  	client := &Client{config: cfg}
   169  	client.init()
   170  	return client
   171  }
   172  
   173  // Close closes the database connection and prevents new queries from starting.
   174  func (c *Client) Close() error {
   175  	return c.driver.Close()
   176  }
   177  
   178  // Use adds the mutation hooks to all the entity clients.
   179  // In order to add hooks to a specific client, call: `client.Node.Use(...)`.
   180  func (c *Client) Use(hooks ...Hook) {
   181  	c.Revision.Use(hooks...)
   182  }
   183  
   184  // Intercept adds the query interceptors to all the entity clients.
   185  // In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`.
   186  func (c *Client) Intercept(interceptors ...Interceptor) {
   187  	c.Revision.Intercept(interceptors...)
   188  }
   189  
   190  // Mutate implements the ent.Mutator interface.
   191  func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
   192  	switch m := m.(type) {
   193  	case *RevisionMutation:
   194  		return c.Revision.mutate(ctx, m)
   195  	default:
   196  		return nil, fmt.Errorf("ent: unknown mutation type %T", m)
   197  	}
   198  }
   199  
   200  // RevisionClient is a client for the Revision schema.
   201  type RevisionClient struct {
   202  	config
   203  }
   204  
   205  // NewRevisionClient returns a client for the Revision from the given config.
   206  func NewRevisionClient(c config) *RevisionClient {
   207  	return &RevisionClient{config: c}
   208  }
   209  
   210  // Use adds a list of mutation hooks to the hooks stack.
   211  // A call to `Use(f, g, h)` equals to `revision.Hooks(f(g(h())))`.
   212  func (c *RevisionClient) Use(hooks ...Hook) {
   213  	c.hooks.Revision = append(c.hooks.Revision, hooks...)
   214  }
   215  
   216  // Intercept adds a list of query interceptors to the interceptors stack.
   217  // A call to `Intercept(f, g, h)` equals to `revision.Intercept(f(g(h())))`.
   218  func (c *RevisionClient) Intercept(interceptors ...Interceptor) {
   219  	c.inters.Revision = append(c.inters.Revision, interceptors...)
   220  }
   221  
   222  // Create returns a builder for creating a Revision entity.
   223  func (c *RevisionClient) Create() *RevisionCreate {
   224  	mutation := newRevisionMutation(c.config, OpCreate)
   225  	return &RevisionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
   226  }
   227  
   228  // CreateBulk returns a builder for creating a bulk of Revision entities.
   229  func (c *RevisionClient) CreateBulk(builders ...*RevisionCreate) *RevisionCreateBulk {
   230  	return &RevisionCreateBulk{config: c.config, builders: builders}
   231  }
   232  
   233  // Update returns an update builder for Revision.
   234  func (c *RevisionClient) Update() *RevisionUpdate {
   235  	mutation := newRevisionMutation(c.config, OpUpdate)
   236  	return &RevisionUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
   237  }
   238  
   239  // UpdateOne returns an update builder for the given entity.
   240  func (c *RevisionClient) UpdateOne(r *Revision) *RevisionUpdateOne {
   241  	mutation := newRevisionMutation(c.config, OpUpdateOne, withRevision(r))
   242  	return &RevisionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
   243  }
   244  
   245  // UpdateOneID returns an update builder for the given id.
   246  func (c *RevisionClient) UpdateOneID(id string) *RevisionUpdateOne {
   247  	mutation := newRevisionMutation(c.config, OpUpdateOne, withRevisionID(id))
   248  	return &RevisionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
   249  }
   250  
   251  // Delete returns a delete builder for Revision.
   252  func (c *RevisionClient) Delete() *RevisionDelete {
   253  	mutation := newRevisionMutation(c.config, OpDelete)
   254  	return &RevisionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
   255  }
   256  
   257  // DeleteOne returns a builder for deleting the given entity.
   258  func (c *RevisionClient) DeleteOne(r *Revision) *RevisionDeleteOne {
   259  	return c.DeleteOneID(r.ID)
   260  }
   261  
   262  // DeleteOneID returns a builder for deleting the given entity by its id.
   263  func (c *RevisionClient) DeleteOneID(id string) *RevisionDeleteOne {
   264  	builder := c.Delete().Where(revision.ID(id))
   265  	builder.mutation.id = &id
   266  	builder.mutation.op = OpDeleteOne
   267  	return &RevisionDeleteOne{builder}
   268  }
   269  
   270  // Query returns a query builder for Revision.
   271  func (c *RevisionClient) Query() *RevisionQuery {
   272  	return &RevisionQuery{
   273  		config: c.config,
   274  		ctx:    &QueryContext{Type: TypeRevision},
   275  		inters: c.Interceptors(),
   276  	}
   277  }
   278  
   279  // Get returns a Revision entity by its id.
   280  func (c *RevisionClient) Get(ctx context.Context, id string) (*Revision, error) {
   281  	return c.Query().Where(revision.ID(id)).Only(ctx)
   282  }
   283  
   284  // GetX is like Get, but panics if an error occurs.
   285  func (c *RevisionClient) GetX(ctx context.Context, id string) *Revision {
   286  	obj, err := c.Get(ctx, id)
   287  	if err != nil {
   288  		panic(err)
   289  	}
   290  	return obj
   291  }
   292  
   293  // Hooks returns the client hooks.
   294  func (c *RevisionClient) Hooks() []Hook {
   295  	return c.hooks.Revision
   296  }
   297  
   298  // Interceptors returns the client interceptors.
   299  func (c *RevisionClient) Interceptors() []Interceptor {
   300  	return c.inters.Revision
   301  }
   302  
   303  func (c *RevisionClient) mutate(ctx context.Context, m *RevisionMutation) (Value, error) {
   304  	switch m.Op() {
   305  	case OpCreate:
   306  		return (&RevisionCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
   307  	case OpUpdate:
   308  		return (&RevisionUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
   309  	case OpUpdateOne:
   310  		return (&RevisionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
   311  	case OpDelete, OpDeleteOne:
   312  		return (&RevisionDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
   313  	default:
   314  		return nil, fmt.Errorf("ent: unknown Revision mutation op: %q", m.Op())
   315  	}
   316  }
   317  
   318  // hooks and interceptors per client, for fast access.
   319  type (
   320  	hooks struct {
   321  		Revision []ent.Hook
   322  	}
   323  	inters struct {
   324  		Revision []ent.Interceptor
   325  	}
   326  )
   327  
   328  // SchemaConfig represents alternative schema names for all tables
   329  // that can be passed at runtime.
   330  type SchemaConfig = internal.SchemaConfig
   331  
   332  // AlternateSchemas allows alternate schema names to be
   333  // passed into ent operations.
   334  func AlternateSchema(schemaConfig SchemaConfig) Option {
   335  	return func(c *config) {
   336  		c.schemaConfig = schemaConfig
   337  	}
   338  }
   339  
   340  // ExecContext allows calling the underlying ExecContext method of the driver if it is supported by it.
   341  // See, database/sql#DB.ExecContext for more information.
   342  func (c *config) ExecContext(ctx context.Context, query string, args ...any) (stdsql.Result, error) {
   343  	ex, ok := c.driver.(interface {
   344  		ExecContext(context.Context, string, ...any) (stdsql.Result, error)
   345  	})
   346  	if !ok {
   347  		return nil, fmt.Errorf("Driver.ExecContext is not supported")
   348  	}
   349  	return ex.ExecContext(ctx, query, args...)
   350  }
   351  
   352  // QueryContext allows calling the underlying QueryContext method of the driver if it is supported by it.
   353  // See, database/sql#DB.QueryContext for more information.
   354  func (c *config) QueryContext(ctx context.Context, query string, args ...any) (*stdsql.Rows, error) {
   355  	q, ok := c.driver.(interface {
   356  		QueryContext(context.Context, string, ...any) (*stdsql.Rows, error)
   357  	})
   358  	if !ok {
   359  		return nil, fmt.Errorf("Driver.QueryContext is not supported")
   360  	}
   361  	return q.QueryContext(ctx, query, args...)
   362  }