forgot to add it

This commit is contained in:
maddalax 2024-09-19 18:13:04 -05:00
parent 1aab41bfa9
commit 43a5001d98
35 changed files with 4952 additions and 0 deletions

16
todo-list/Taskfile.yml Normal file
View file

@ -0,0 +1,16 @@
version: '3'
tasks:
run:
cmds:
- go run github.com/maddalax/htmgo/cli@latest run
silent: true
build:
cmds:
- go run github.com/maddalax/htmgo/cli@latest build
watch:
cmds:
- go run github.com/maddalax/htmgo/cli@latest watch
silent: true

View file

@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

View file

@ -0,0 +1,36 @@
const {join} = require("node:path");
/** @type {import('tailwindcss').Config} */
const root = join(__dirname, "../../");
const contentGo = join(root, "**/*.go");
const contentJs = join(root, "**/pages/**/*.js");
module.exports = {
content: [contentGo, contentJs],
theme: {
extend: {
colors: {
background: 'hsl(224, 71.4%, 4.1%)',
foreground: 'hsl(0, 0%, 89%)',
card: 'hsl(224, 71.4%, 4.1%)',
cardForeground: 'hsl(0, 0%, 89%)',
popover: 'hsl(224, 71.4%, 4.1%)',
popoverForeground: 'hsl(0, 0%, 89%)',
primary: 'hsl(0, 0%, 89%)',
primaryForeground: 'hsl(220.9, 39.3%, 11%)',
secondary: 'hsl(215, 27.9%, 16.9%)',
secondaryForeground: 'hsl(0, 0%, 89%)',
muted: 'hsl(215, 27.9%, 16.9%)',
mutedForeground: 'hsl(217.9, 10.6%, 64.9%)',
accent: 'hsl(215, 27.9%, 16.9%)',
accentForeground: 'hsl(0, 0%, 89%)',
destructive: 'hsl(0, 62.8%, 30.6%)',
destructiveForeground: 'hsl(0, 0%, 89%)',
border: 'hsl(215, 27.9%, 16.9%)',
input: 'hsl(215, 27.9%, 16.9%)',
ring: 'hsl(216, 12.2%, 83.9%)',
},
},
},
plugins: [],
};

342
todo-list/ent/client.go Normal file
View file

@ -0,0 +1,342 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"log"
"reflect"
"todolist/ent/migrate"
"todolist/ent/task"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"github.com/google/uuid"
)
// 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
// Task is the client for interacting with the Task builders.
Task *TaskClient
}
// 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.Task = NewTaskClient(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,
Task: NewTaskClient(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,
Task: NewTaskClient(cfg),
}, nil
}
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
//
// client.Debug().
// Task.
// 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.Task.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.Task.Intercept(interceptors...)
}
// Mutate implements the ent.Mutator interface.
func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
switch m := m.(type) {
case *TaskMutation:
return c.Task.mutate(ctx, m)
default:
return nil, fmt.Errorf("ent: unknown mutation type %T", m)
}
}
// TaskClient is a client for the Task schema.
type TaskClient struct {
config
}
// NewTaskClient returns a client for the Task from the given config.
func NewTaskClient(c config) *TaskClient {
return &TaskClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `task.Hooks(f(g(h())))`.
func (c *TaskClient) Use(hooks ...Hook) {
c.hooks.Task = append(c.hooks.Task, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `task.Intercept(f(g(h())))`.
func (c *TaskClient) Intercept(interceptors ...Interceptor) {
c.inters.Task = append(c.inters.Task, interceptors...)
}
// Create returns a builder for creating a Task entity.
func (c *TaskClient) Create() *TaskCreate {
mutation := newTaskMutation(c.config, OpCreate)
return &TaskCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Task entities.
func (c *TaskClient) CreateBulk(builders ...*TaskCreate) *TaskCreateBulk {
return &TaskCreateBulk{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 *TaskClient) MapCreateBulk(slice any, setFunc func(*TaskCreate, int)) *TaskCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &TaskCreateBulk{err: fmt.Errorf("calling to TaskClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*TaskCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &TaskCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Task.
func (c *TaskClient) Update() *TaskUpdate {
mutation := newTaskMutation(c.config, OpUpdate)
return &TaskUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *TaskClient) UpdateOne(t *Task) *TaskUpdateOne {
mutation := newTaskMutation(c.config, OpUpdateOne, withTask(t))
return &TaskUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *TaskClient) UpdateOneID(id uuid.UUID) *TaskUpdateOne {
mutation := newTaskMutation(c.config, OpUpdateOne, withTaskID(id))
return &TaskUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Task.
func (c *TaskClient) Delete() *TaskDelete {
mutation := newTaskMutation(c.config, OpDelete)
return &TaskDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *TaskClient) DeleteOne(t *Task) *TaskDeleteOne {
return c.DeleteOneID(t.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *TaskClient) DeleteOneID(id uuid.UUID) *TaskDeleteOne {
builder := c.Delete().Where(task.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &TaskDeleteOne{builder}
}
// Query returns a query builder for Task.
func (c *TaskClient) Query() *TaskQuery {
return &TaskQuery{
config: c.config,
ctx: &QueryContext{Type: TypeTask},
inters: c.Interceptors(),
}
}
// Get returns a Task entity by its id.
func (c *TaskClient) Get(ctx context.Context, id uuid.UUID) (*Task, error) {
return c.Query().Where(task.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *TaskClient) GetX(ctx context.Context, id uuid.UUID) *Task {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// Hooks returns the client hooks.
func (c *TaskClient) Hooks() []Hook {
return c.hooks.Task
}
// Interceptors returns the client interceptors.
func (c *TaskClient) Interceptors() []Interceptor {
return c.inters.Task
}
func (c *TaskClient) mutate(ctx context.Context, m *TaskMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&TaskCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&TaskUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&TaskUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&TaskDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Task mutation op: %q", m.Op())
}
}
// hooks and interceptors per client, for fast access.
type (
hooks struct {
Task []ent.Hook
}
inters struct {
Task []ent.Interceptor
}
)

608
todo-list/ent/ent.go Normal file
View file

@ -0,0 +1,608 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"reflect"
"sync"
"todolist/ent/task"
"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{
task.Table: task.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)

View file

@ -0,0 +1,85 @@
// Code generated by ent, DO NOT EDIT.
package enttest
import (
"context"
"todolist/ent"
// required by schema hooks.
_ "todolist/ent/runtime"
"todolist/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()
}
}

View file

@ -0,0 +1,3 @@
package ent
//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate ./schema

198
todo-list/ent/hook/hook.go Normal file
View file

@ -0,0 +1,198 @@
// Code generated by ent, DO NOT EDIT.
package hook
import (
"context"
"fmt"
"todolist/ent"
)
// The TaskFunc type is an adapter to allow the use of ordinary
// function as Task mutator.
type TaskFunc func(context.Context, *ent.TaskMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f TaskFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.TaskMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.TaskMutation", 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...)
}

View file

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

View file

@ -0,0 +1,33 @@
// Code generated by ent, DO NOT EDIT.
package migrate
import (
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/schema/field"
)
var (
// TasksColumns holds the columns for the "tasks" table.
TasksColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID},
{Name: "name", Type: field.TypeString, Default: "unknown"},
{Name: "created_at", Type: field.TypeTime, Default: "CURRENT_TIMESTAMP"},
{Name: "updated_at", Type: field.TypeTime, Default: "CURRENT_TIMESTAMP"},
{Name: "completed_at", Type: field.TypeTime, Nullable: true},
{Name: "tags", Type: field.TypeJSON, Nullable: true},
}
// TasksTable holds the schema information for the "tasks" table.
TasksTable = &schema.Table{
Name: "tasks",
Columns: TasksColumns,
PrimaryKey: []*schema.Column{TasksColumns[0]},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
TasksTable,
}
)
func init() {
}

635
todo-list/ent/mutation.go Normal file
View file

@ -0,0 +1,635 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"sync"
"time"
"todolist/ent/predicate"
"todolist/ent/task"
"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.
TypeTask = "Task"
)
// TaskMutation represents an operation that mutates the Task nodes in the graph.
type TaskMutation struct {
config
op Op
typ string
id *uuid.UUID
name *string
created_at *time.Time
updated_at *time.Time
completed_at *time.Time
tags *[]string
appendtags []string
clearedFields map[string]struct{}
done bool
oldValue func(context.Context) (*Task, error)
predicates []predicate.Task
}
var _ ent.Mutation = (*TaskMutation)(nil)
// taskOption allows management of the mutation configuration using functional options.
type taskOption func(*TaskMutation)
// newTaskMutation creates new mutation for the Task entity.
func newTaskMutation(c config, op Op, opts ...taskOption) *TaskMutation {
m := &TaskMutation{
config: c,
op: op,
typ: TypeTask,
clearedFields: make(map[string]struct{}),
}
for _, opt := range opts {
opt(m)
}
return m
}
// withTaskID sets the ID field of the mutation.
func withTaskID(id uuid.UUID) taskOption {
return func(m *TaskMutation) {
var (
err error
once sync.Once
value *Task
)
m.oldValue = func(ctx context.Context) (*Task, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().Task.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withTask sets the old Task of the mutation.
func withTask(node *Task) taskOption {
return func(m *TaskMutation) {
m.oldValue = func(context.Context) (*Task, 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 TaskMutation) 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 TaskMutation) 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 Task entities.
func (m *TaskMutation) 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 *TaskMutation) 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 *TaskMutation) 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().Task.Query().Where(m.predicates...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
}
}
// SetName sets the "name" field.
func (m *TaskMutation) SetName(s string) {
m.name = &s
}
// Name returns the value of the "name" field in the mutation.
func (m *TaskMutation) Name() (r string, exists bool) {
v := m.name
if v == nil {
return
}
return *v, true
}
// OldName returns the old "name" field's value of the Task entity.
// If the Task 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 *TaskMutation) OldName(ctx context.Context) (v string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldName is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldName requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldName: %w", err)
}
return oldValue.Name, nil
}
// ResetName resets all changes to the "name" field.
func (m *TaskMutation) ResetName() {
m.name = nil
}
// SetCreatedAt sets the "created_at" field.
func (m *TaskMutation) SetCreatedAt(t time.Time) {
m.created_at = &t
}
// CreatedAt returns the value of the "created_at" field in the mutation.
func (m *TaskMutation) CreatedAt() (r time.Time, exists bool) {
v := m.created_at
if v == nil {
return
}
return *v, true
}
// OldCreatedAt returns the old "created_at" field's value of the Task entity.
// If the Task 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 *TaskMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldCreatedAt requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err)
}
return oldValue.CreatedAt, nil
}
// ResetCreatedAt resets all changes to the "created_at" field.
func (m *TaskMutation) ResetCreatedAt() {
m.created_at = nil
}
// SetUpdatedAt sets the "updated_at" field.
func (m *TaskMutation) SetUpdatedAt(t time.Time) {
m.updated_at = &t
}
// UpdatedAt returns the value of the "updated_at" field in the mutation.
func (m *TaskMutation) UpdatedAt() (r time.Time, exists bool) {
v := m.updated_at
if v == nil {
return
}
return *v, true
}
// OldUpdatedAt returns the old "updated_at" field's value of the Task entity.
// If the Task 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 *TaskMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldUpdatedAt requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err)
}
return oldValue.UpdatedAt, nil
}
// ResetUpdatedAt resets all changes to the "updated_at" field.
func (m *TaskMutation) ResetUpdatedAt() {
m.updated_at = nil
}
// SetCompletedAt sets the "completed_at" field.
func (m *TaskMutation) SetCompletedAt(t time.Time) {
m.completed_at = &t
}
// CompletedAt returns the value of the "completed_at" field in the mutation.
func (m *TaskMutation) CompletedAt() (r time.Time, exists bool) {
v := m.completed_at
if v == nil {
return
}
return *v, true
}
// OldCompletedAt returns the old "completed_at" field's value of the Task entity.
// If the Task 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 *TaskMutation) OldCompletedAt(ctx context.Context) (v *time.Time, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldCompletedAt is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldCompletedAt requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldCompletedAt: %w", err)
}
return oldValue.CompletedAt, nil
}
// ClearCompletedAt clears the value of the "completed_at" field.
func (m *TaskMutation) ClearCompletedAt() {
m.completed_at = nil
m.clearedFields[task.FieldCompletedAt] = struct{}{}
}
// CompletedAtCleared returns if the "completed_at" field was cleared in this mutation.
func (m *TaskMutation) CompletedAtCleared() bool {
_, ok := m.clearedFields[task.FieldCompletedAt]
return ok
}
// ResetCompletedAt resets all changes to the "completed_at" field.
func (m *TaskMutation) ResetCompletedAt() {
m.completed_at = nil
delete(m.clearedFields, task.FieldCompletedAt)
}
// SetTags sets the "tags" field.
func (m *TaskMutation) SetTags(s []string) {
m.tags = &s
m.appendtags = nil
}
// Tags returns the value of the "tags" field in the mutation.
func (m *TaskMutation) Tags() (r []string, exists bool) {
v := m.tags
if v == nil {
return
}
return *v, true
}
// OldTags returns the old "tags" field's value of the Task entity.
// If the Task 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 *TaskMutation) OldTags(ctx context.Context) (v []string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldTags is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldTags requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldTags: %w", err)
}
return oldValue.Tags, nil
}
// AppendTags adds s to the "tags" field.
func (m *TaskMutation) AppendTags(s []string) {
m.appendtags = append(m.appendtags, s...)
}
// AppendedTags returns the list of values that were appended to the "tags" field in this mutation.
func (m *TaskMutation) AppendedTags() ([]string, bool) {
if len(m.appendtags) == 0 {
return nil, false
}
return m.appendtags, true
}
// ClearTags clears the value of the "tags" field.
func (m *TaskMutation) ClearTags() {
m.tags = nil
m.appendtags = nil
m.clearedFields[task.FieldTags] = struct{}{}
}
// TagsCleared returns if the "tags" field was cleared in this mutation.
func (m *TaskMutation) TagsCleared() bool {
_, ok := m.clearedFields[task.FieldTags]
return ok
}
// ResetTags resets all changes to the "tags" field.
func (m *TaskMutation) ResetTags() {
m.tags = nil
m.appendtags = nil
delete(m.clearedFields, task.FieldTags)
}
// Where appends a list predicates to the TaskMutation builder.
func (m *TaskMutation) Where(ps ...predicate.Task) {
m.predicates = append(m.predicates, ps...)
}
// WhereP appends storage-level predicates to the TaskMutation builder. Using this method,
// users can use type-assertion to append predicates that do not depend on any generated package.
func (m *TaskMutation) WhereP(ps ...func(*sql.Selector)) {
p := make([]predicate.Task, len(ps))
for i := range ps {
p[i] = ps[i]
}
m.Where(p...)
}
// Op returns the operation name.
func (m *TaskMutation) Op() Op {
return m.op
}
// SetOp allows setting the mutation operation.
func (m *TaskMutation) SetOp(op Op) {
m.op = op
}
// Type returns the node type of this mutation (Task).
func (m *TaskMutation) 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 *TaskMutation) Fields() []string {
fields := make([]string, 0, 5)
if m.name != nil {
fields = append(fields, task.FieldName)
}
if m.created_at != nil {
fields = append(fields, task.FieldCreatedAt)
}
if m.updated_at != nil {
fields = append(fields, task.FieldUpdatedAt)
}
if m.completed_at != nil {
fields = append(fields, task.FieldCompletedAt)
}
if m.tags != nil {
fields = append(fields, task.FieldTags)
}
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 *TaskMutation) Field(name string) (ent.Value, bool) {
switch name {
case task.FieldName:
return m.Name()
case task.FieldCreatedAt:
return m.CreatedAt()
case task.FieldUpdatedAt:
return m.UpdatedAt()
case task.FieldCompletedAt:
return m.CompletedAt()
case task.FieldTags:
return m.Tags()
}
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 *TaskMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case task.FieldName:
return m.OldName(ctx)
case task.FieldCreatedAt:
return m.OldCreatedAt(ctx)
case task.FieldUpdatedAt:
return m.OldUpdatedAt(ctx)
case task.FieldCompletedAt:
return m.OldCompletedAt(ctx)
case task.FieldTags:
return m.OldTags(ctx)
}
return nil, fmt.Errorf("unknown Task 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 *TaskMutation) SetField(name string, value ent.Value) error {
switch name {
case task.FieldName:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetName(v)
return nil
case task.FieldCreatedAt:
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetCreatedAt(v)
return nil
case task.FieldUpdatedAt:
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetUpdatedAt(v)
return nil
case task.FieldCompletedAt:
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetCompletedAt(v)
return nil
case task.FieldTags:
v, ok := value.([]string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetTags(v)
return nil
}
return fmt.Errorf("unknown Task field %s", name)
}
// AddedFields returns all numeric fields that were incremented/decremented during
// this mutation.
func (m *TaskMutation) 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 *TaskMutation) 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 *TaskMutation) AddField(name string, value ent.Value) error {
switch name {
}
return fmt.Errorf("unknown Task numeric field %s", name)
}
// ClearedFields returns all nullable fields that were cleared during this
// mutation.
func (m *TaskMutation) ClearedFields() []string {
var fields []string
if m.FieldCleared(task.FieldCompletedAt) {
fields = append(fields, task.FieldCompletedAt)
}
if m.FieldCleared(task.FieldTags) {
fields = append(fields, task.FieldTags)
}
return fields
}
// FieldCleared returns a boolean indicating if a field with the given name was
// cleared in this mutation.
func (m *TaskMutation) 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 *TaskMutation) ClearField(name string) error {
switch name {
case task.FieldCompletedAt:
m.ClearCompletedAt()
return nil
case task.FieldTags:
m.ClearTags()
return nil
}
return fmt.Errorf("unknown Task 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 *TaskMutation) ResetField(name string) error {
switch name {
case task.FieldName:
m.ResetName()
return nil
case task.FieldCreatedAt:
m.ResetCreatedAt()
return nil
case task.FieldUpdatedAt:
m.ResetUpdatedAt()
return nil
case task.FieldCompletedAt:
m.ResetCompletedAt()
return nil
case task.FieldTags:
m.ResetTags()
return nil
}
return fmt.Errorf("unknown Task field %s", name)
}
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *TaskMutation) AddedEdges() []string {
edges := make([]string, 0, 0)
return edges
}
// AddedIDs returns all IDs (to other nodes) that were added for the given edge
// name in this mutation.
func (m *TaskMutation) AddedIDs(name string) []ent.Value {
return nil
}
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *TaskMutation) RemovedEdges() []string {
edges := make([]string, 0, 0)
return edges
}
// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
// the given name in this mutation.
func (m *TaskMutation) RemovedIDs(name string) []ent.Value {
return nil
}
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *TaskMutation) ClearedEdges() []string {
edges := make([]string, 0, 0)
return edges
}
// EdgeCleared returns a boolean which indicates if the edge with the given name
// was cleared in this mutation.
func (m *TaskMutation) EdgeCleared(name string) bool {
return false
}
// ClearEdge clears the value of the edge with the given name. It returns an error
// if that edge is not defined in the schema.
func (m *TaskMutation) ClearEdge(name string) error {
return fmt.Errorf("unknown Task 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 *TaskMutation) ResetEdge(name string) error {
return fmt.Errorf("unknown Task edge %s", name)
}

View file

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

35
todo-list/ent/runtime.go Normal file
View file

@ -0,0 +1,35 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"time"
"todolist/ent/schema"
"todolist/ent/task"
"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() {
taskFields := schema.Task{}.Fields()
_ = taskFields
// taskDescName is the schema descriptor for name field.
taskDescName := taskFields[1].Descriptor()
// task.DefaultName holds the default value on creation for the name field.
task.DefaultName = taskDescName.Default.(string)
// taskDescCreatedAt is the schema descriptor for created_at field.
taskDescCreatedAt := taskFields[2].Descriptor()
// task.DefaultCreatedAt holds the default value on creation for the created_at field.
task.DefaultCreatedAt = taskDescCreatedAt.Default.(func() time.Time)
// taskDescUpdatedAt is the schema descriptor for updated_at field.
taskDescUpdatedAt := taskFields[3].Descriptor()
// task.DefaultUpdatedAt holds the default value on creation for the updated_at field.
task.DefaultUpdatedAt = taskDescUpdatedAt.Default.(func() time.Time)
// taskDescID is the schema descriptor for id field.
taskDescID := taskFields[0].Descriptor()
// task.DefaultID holds the default value on creation for the id field.
task.DefaultID = taskDescID.Default.(func() uuid.UUID)
}

View file

@ -0,0 +1,10 @@
// Code generated by ent, DO NOT EDIT.
package runtime
// The schema-stitching logic is generated in todolist/ent/runtime.go
const (
Version = "v0.14.1" // Version of ent codegen.
Sum = "h1:fUERL506Pqr92EPHJqr8EYxbPioflJo6PudkrEA8a/s=" // Sum of ent codegen.
)

View file

@ -0,0 +1,36 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
"time"
)
type Task struct {
ent.Schema
}
// Fields of the User.
func (Task) Fields() []ent.Field {
return []ent.Field{
field.UUID("id", uuid.UUID{}).
Default(uuid.New),
field.String("name").
Default("unknown"),
field.Time("created_at").Default(time.Now).Annotations(
entsql.Default("CURRENT_TIMESTAMP"),
),
field.Time("updated_at").Default(time.Now).Annotations(
entsql.Default("CURRENT_TIMESTAMP"),
),
field.Time("completed_at").Optional().Nillable(),
field.Strings("tags").Optional(),
}
}
// Edges of the User.
func (Task) Edges() []ent.Edge {
return nil
}

159
todo-list/ent/task.go Normal file
View file

@ -0,0 +1,159 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"encoding/json"
"fmt"
"strings"
"time"
"todolist/ent/task"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"github.com/google/uuid"
)
// Task is the model entity for the Task schema.
type Task struct {
config `json:"-"`
// ID of the ent.
ID uuid.UUID `json:"id,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt time.Time `json:"updated_at,omitempty"`
// CompletedAt holds the value of the "completed_at" field.
CompletedAt *time.Time `json:"completed_at,omitempty"`
// Tags holds the value of the "tags" field.
Tags []string `json:"tags,omitempty"`
selectValues sql.SelectValues
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Task) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case task.FieldTags:
values[i] = new([]byte)
case task.FieldName:
values[i] = new(sql.NullString)
case task.FieldCreatedAt, task.FieldUpdatedAt, task.FieldCompletedAt:
values[i] = new(sql.NullTime)
case task.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 Task fields.
func (t *Task) 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 task.FieldID:
if value, ok := values[i].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field id", values[i])
} else if value != nil {
t.ID = *value
}
case task.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
t.Name = value.String
}
case task.FieldCreatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
t.CreatedAt = value.Time
}
case task.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
t.UpdatedAt = value.Time
}
case task.FieldCompletedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field completed_at", values[i])
} else if value.Valid {
t.CompletedAt = new(time.Time)
*t.CompletedAt = value.Time
}
case task.FieldTags:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field tags", values[i])
} else if value != nil && len(*value) > 0 {
if err := json.Unmarshal(*value, &t.Tags); err != nil {
return fmt.Errorf("unmarshal field tags: %w", err)
}
}
default:
t.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Task.
// This includes values selected through modifiers, order, etc.
func (t *Task) Value(name string) (ent.Value, error) {
return t.selectValues.Get(name)
}
// Update returns a builder for updating this Task.
// Note that you need to call Task.Unwrap() before calling this method if this Task
// was returned from a transaction, and the transaction was committed or rolled back.
func (t *Task) Update() *TaskUpdateOne {
return NewTaskClient(t.config).UpdateOne(t)
}
// Unwrap unwraps the Task entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (t *Task) Unwrap() *Task {
_tx, ok := t.config.driver.(*txDriver)
if !ok {
panic("ent: Task is not a transactional entity")
}
t.config.driver = _tx.drv
return t
}
// String implements the fmt.Stringer.
func (t *Task) String() string {
var builder strings.Builder
builder.WriteString("Task(")
builder.WriteString(fmt.Sprintf("id=%v, ", t.ID))
builder.WriteString("name=")
builder.WriteString(t.Name)
builder.WriteString(", ")
builder.WriteString("created_at=")
builder.WriteString(t.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(t.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
if v := t.CompletedAt; v != nil {
builder.WriteString("completed_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString(", ")
builder.WriteString("tags=")
builder.WriteString(fmt.Sprintf("%v", t.Tags))
builder.WriteByte(')')
return builder.String()
}
// Tasks is a parsable slice of Task.
type Tasks []*Task

View file

@ -0,0 +1,88 @@
// Code generated by ent, DO NOT EDIT.
package task
import (
"time"
"entgo.io/ent/dialect/sql"
"github.com/google/uuid"
)
const (
// Label holds the string label denoting the task type in the database.
Label = "task"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
FieldUpdatedAt = "updated_at"
// FieldCompletedAt holds the string denoting the completed_at field in the database.
FieldCompletedAt = "completed_at"
// FieldTags holds the string denoting the tags field in the database.
FieldTags = "tags"
// Table holds the table name of the task in the database.
Table = "tasks"
)
// Columns holds all SQL columns for task fields.
var Columns = []string{
FieldID,
FieldName,
FieldCreatedAt,
FieldUpdatedAt,
FieldCompletedAt,
FieldTags,
}
// 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 (
// DefaultName holds the default value on creation for the "name" field.
DefaultName string
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// DefaultID holds the default value on creation for the "id" field.
DefaultID func() uuid.UUID
)
// OrderOption defines the ordering options for the Task 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()
}
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, opts...).ToFunc()
}
// ByCreatedAt orders the results by the created_at field.
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
}
// ByUpdatedAt orders the results by the updated_at field.
func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
}
// ByCompletedAt orders the results by the completed_at field.
func ByCompletedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCompletedAt, opts...).ToFunc()
}

296
todo-list/ent/task/where.go Normal file
View file

@ -0,0 +1,296 @@
// Code generated by ent, DO NOT EDIT.
package task
import (
"time"
"todolist/ent/predicate"
"entgo.io/ent/dialect/sql"
"github.com/google/uuid"
)
// ID filters vertices based on their ID field.
func ID(id uuid.UUID) predicate.Task {
return predicate.Task(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id uuid.UUID) predicate.Task {
return predicate.Task(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id uuid.UUID) predicate.Task {
return predicate.Task(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...uuid.UUID) predicate.Task {
return predicate.Task(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...uuid.UUID) predicate.Task {
return predicate.Task(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id uuid.UUID) predicate.Task {
return predicate.Task(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id uuid.UUID) predicate.Task {
return predicate.Task(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id uuid.UUID) predicate.Task {
return predicate.Task(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id uuid.UUID) predicate.Task {
return predicate.Task(sql.FieldLTE(FieldID, id))
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Task {
return predicate.Task(sql.FieldEQ(FieldName, v))
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.Task {
return predicate.Task(sql.FieldEQ(FieldCreatedAt, v))
}
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
func UpdatedAt(v time.Time) predicate.Task {
return predicate.Task(sql.FieldEQ(FieldUpdatedAt, v))
}
// CompletedAt applies equality check predicate on the "completed_at" field. It's identical to CompletedAtEQ.
func CompletedAt(v time.Time) predicate.Task {
return predicate.Task(sql.FieldEQ(FieldCompletedAt, v))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Task {
return predicate.Task(sql.FieldEQ(FieldName, v))
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.Task {
return predicate.Task(sql.FieldNEQ(FieldName, v))
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.Task {
return predicate.Task(sql.FieldIn(FieldName, vs...))
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.Task {
return predicate.Task(sql.FieldNotIn(FieldName, vs...))
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.Task {
return predicate.Task(sql.FieldGT(FieldName, v))
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.Task {
return predicate.Task(sql.FieldGTE(FieldName, v))
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.Task {
return predicate.Task(sql.FieldLT(FieldName, v))
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.Task {
return predicate.Task(sql.FieldLTE(FieldName, v))
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.Task {
return predicate.Task(sql.FieldContains(FieldName, v))
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.Task {
return predicate.Task(sql.FieldHasPrefix(FieldName, v))
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.Task {
return predicate.Task(sql.FieldHasSuffix(FieldName, v))
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.Task {
return predicate.Task(sql.FieldEqualFold(FieldName, v))
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.Task {
return predicate.Task(sql.FieldContainsFold(FieldName, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Task {
return predicate.Task(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.Task {
return predicate.Task(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.Task {
return predicate.Task(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.Task {
return predicate.Task(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.Task {
return predicate.Task(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.Task {
return predicate.Task(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.Task {
return predicate.Task(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.Task {
return predicate.Task(sql.FieldLTE(FieldCreatedAt, v))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.Task {
return predicate.Task(sql.FieldEQ(FieldUpdatedAt, v))
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v time.Time) predicate.Task {
return predicate.Task(sql.FieldNEQ(FieldUpdatedAt, v))
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...time.Time) predicate.Task {
return predicate.Task(sql.FieldIn(FieldUpdatedAt, vs...))
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...time.Time) predicate.Task {
return predicate.Task(sql.FieldNotIn(FieldUpdatedAt, vs...))
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v time.Time) predicate.Task {
return predicate.Task(sql.FieldGT(FieldUpdatedAt, v))
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v time.Time) predicate.Task {
return predicate.Task(sql.FieldGTE(FieldUpdatedAt, v))
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v time.Time) predicate.Task {
return predicate.Task(sql.FieldLT(FieldUpdatedAt, v))
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v time.Time) predicate.Task {
return predicate.Task(sql.FieldLTE(FieldUpdatedAt, v))
}
// CompletedAtEQ applies the EQ predicate on the "completed_at" field.
func CompletedAtEQ(v time.Time) predicate.Task {
return predicate.Task(sql.FieldEQ(FieldCompletedAt, v))
}
// CompletedAtNEQ applies the NEQ predicate on the "completed_at" field.
func CompletedAtNEQ(v time.Time) predicate.Task {
return predicate.Task(sql.FieldNEQ(FieldCompletedAt, v))
}
// CompletedAtIn applies the In predicate on the "completed_at" field.
func CompletedAtIn(vs ...time.Time) predicate.Task {
return predicate.Task(sql.FieldIn(FieldCompletedAt, vs...))
}
// CompletedAtNotIn applies the NotIn predicate on the "completed_at" field.
func CompletedAtNotIn(vs ...time.Time) predicate.Task {
return predicate.Task(sql.FieldNotIn(FieldCompletedAt, vs...))
}
// CompletedAtGT applies the GT predicate on the "completed_at" field.
func CompletedAtGT(v time.Time) predicate.Task {
return predicate.Task(sql.FieldGT(FieldCompletedAt, v))
}
// CompletedAtGTE applies the GTE predicate on the "completed_at" field.
func CompletedAtGTE(v time.Time) predicate.Task {
return predicate.Task(sql.FieldGTE(FieldCompletedAt, v))
}
// CompletedAtLT applies the LT predicate on the "completed_at" field.
func CompletedAtLT(v time.Time) predicate.Task {
return predicate.Task(sql.FieldLT(FieldCompletedAt, v))
}
// CompletedAtLTE applies the LTE predicate on the "completed_at" field.
func CompletedAtLTE(v time.Time) predicate.Task {
return predicate.Task(sql.FieldLTE(FieldCompletedAt, v))
}
// CompletedAtIsNil applies the IsNil predicate on the "completed_at" field.
func CompletedAtIsNil() predicate.Task {
return predicate.Task(sql.FieldIsNull(FieldCompletedAt))
}
// CompletedAtNotNil applies the NotNil predicate on the "completed_at" field.
func CompletedAtNotNil() predicate.Task {
return predicate.Task(sql.FieldNotNull(FieldCompletedAt))
}
// TagsIsNil applies the IsNil predicate on the "tags" field.
func TagsIsNil() predicate.Task {
return predicate.Task(sql.FieldIsNull(FieldTags))
}
// TagsNotNil applies the NotNil predicate on the "tags" field.
func TagsNotNil() predicate.Task {
return predicate.Task(sql.FieldNotNull(FieldTags))
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Task) predicate.Task {
return predicate.Task(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Task) predicate.Task {
return predicate.Task(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Task) predicate.Task {
return predicate.Task(sql.NotPredicates(p))
}

View file

@ -0,0 +1,304 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"todolist/ent/task"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
)
// TaskCreate is the builder for creating a Task entity.
type TaskCreate struct {
config
mutation *TaskMutation
hooks []Hook
}
// SetName sets the "name" field.
func (tc *TaskCreate) SetName(s string) *TaskCreate {
tc.mutation.SetName(s)
return tc
}
// SetNillableName sets the "name" field if the given value is not nil.
func (tc *TaskCreate) SetNillableName(s *string) *TaskCreate {
if s != nil {
tc.SetName(*s)
}
return tc
}
// SetCreatedAt sets the "created_at" field.
func (tc *TaskCreate) SetCreatedAt(t time.Time) *TaskCreate {
tc.mutation.SetCreatedAt(t)
return tc
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (tc *TaskCreate) SetNillableCreatedAt(t *time.Time) *TaskCreate {
if t != nil {
tc.SetCreatedAt(*t)
}
return tc
}
// SetUpdatedAt sets the "updated_at" field.
func (tc *TaskCreate) SetUpdatedAt(t time.Time) *TaskCreate {
tc.mutation.SetUpdatedAt(t)
return tc
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (tc *TaskCreate) SetNillableUpdatedAt(t *time.Time) *TaskCreate {
if t != nil {
tc.SetUpdatedAt(*t)
}
return tc
}
// SetCompletedAt sets the "completed_at" field.
func (tc *TaskCreate) SetCompletedAt(t time.Time) *TaskCreate {
tc.mutation.SetCompletedAt(t)
return tc
}
// SetNillableCompletedAt sets the "completed_at" field if the given value is not nil.
func (tc *TaskCreate) SetNillableCompletedAt(t *time.Time) *TaskCreate {
if t != nil {
tc.SetCompletedAt(*t)
}
return tc
}
// SetTags sets the "tags" field.
func (tc *TaskCreate) SetTags(s []string) *TaskCreate {
tc.mutation.SetTags(s)
return tc
}
// SetID sets the "id" field.
func (tc *TaskCreate) SetID(u uuid.UUID) *TaskCreate {
tc.mutation.SetID(u)
return tc
}
// SetNillableID sets the "id" field if the given value is not nil.
func (tc *TaskCreate) SetNillableID(u *uuid.UUID) *TaskCreate {
if u != nil {
tc.SetID(*u)
}
return tc
}
// Mutation returns the TaskMutation object of the builder.
func (tc *TaskCreate) Mutation() *TaskMutation {
return tc.mutation
}
// Save creates the Task in the database.
func (tc *TaskCreate) Save(ctx context.Context) (*Task, error) {
tc.defaults()
return withHooks(ctx, tc.sqlSave, tc.mutation, tc.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (tc *TaskCreate) SaveX(ctx context.Context) *Task {
v, err := tc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (tc *TaskCreate) Exec(ctx context.Context) error {
_, err := tc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (tc *TaskCreate) ExecX(ctx context.Context) {
if err := tc.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (tc *TaskCreate) defaults() {
if _, ok := tc.mutation.Name(); !ok {
v := task.DefaultName
tc.mutation.SetName(v)
}
if _, ok := tc.mutation.CreatedAt(); !ok {
v := task.DefaultCreatedAt()
tc.mutation.SetCreatedAt(v)
}
if _, ok := tc.mutation.UpdatedAt(); !ok {
v := task.DefaultUpdatedAt()
tc.mutation.SetUpdatedAt(v)
}
if _, ok := tc.mutation.ID(); !ok {
v := task.DefaultID()
tc.mutation.SetID(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (tc *TaskCreate) check() error {
if _, ok := tc.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Task.name"`)}
}
if _, ok := tc.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Task.created_at"`)}
}
if _, ok := tc.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Task.updated_at"`)}
}
return nil
}
func (tc *TaskCreate) sqlSave(ctx context.Context) (*Task, error) {
if err := tc.check(); err != nil {
return nil, err
}
_node, _spec := tc.createSpec()
if err := sqlgraph.CreateNode(ctx, tc.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
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
}
}
tc.mutation.id = &_node.ID
tc.mutation.done = true
return _node, nil
}
func (tc *TaskCreate) createSpec() (*Task, *sqlgraph.CreateSpec) {
var (
_node = &Task{config: tc.config}
_spec = sqlgraph.NewCreateSpec(task.Table, sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID))
)
if id, ok := tc.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = &id
}
if value, ok := tc.mutation.Name(); ok {
_spec.SetField(task.FieldName, field.TypeString, value)
_node.Name = value
}
if value, ok := tc.mutation.CreatedAt(); ok {
_spec.SetField(task.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = value
}
if value, ok := tc.mutation.UpdatedAt(); ok {
_spec.SetField(task.FieldUpdatedAt, field.TypeTime, value)
_node.UpdatedAt = value
}
if value, ok := tc.mutation.CompletedAt(); ok {
_spec.SetField(task.FieldCompletedAt, field.TypeTime, value)
_node.CompletedAt = &value
}
if value, ok := tc.mutation.Tags(); ok {
_spec.SetField(task.FieldTags, field.TypeJSON, value)
_node.Tags = value
}
return _node, _spec
}
// TaskCreateBulk is the builder for creating many Task entities in bulk.
type TaskCreateBulk struct {
config
err error
builders []*TaskCreate
}
// Save creates the Task entities in the database.
func (tcb *TaskCreateBulk) Save(ctx context.Context) ([]*Task, error) {
if tcb.err != nil {
return nil, tcb.err
}
specs := make([]*sqlgraph.CreateSpec, len(tcb.builders))
nodes := make([]*Task, len(tcb.builders))
mutators := make([]Mutator, len(tcb.builders))
for i := range tcb.builders {
func(i int, root context.Context) {
builder := tcb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*TaskMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, tcb.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, tcb.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, tcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (tcb *TaskCreateBulk) SaveX(ctx context.Context) []*Task {
v, err := tcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (tcb *TaskCreateBulk) Exec(ctx context.Context) error {
_, err := tcb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (tcb *TaskCreateBulk) ExecX(ctx context.Context) {
if err := tcb.Exec(ctx); err != nil {
panic(err)
}
}

View file

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

528
todo-list/ent/task_query.go Normal file
View file

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

View file

@ -0,0 +1,389 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"todolist/ent/predicate"
"todolist/ent/task"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/dialect/sql/sqljson"
"entgo.io/ent/schema/field"
)
// TaskUpdate is the builder for updating Task entities.
type TaskUpdate struct {
config
hooks []Hook
mutation *TaskMutation
}
// Where appends a list predicates to the TaskUpdate builder.
func (tu *TaskUpdate) Where(ps ...predicate.Task) *TaskUpdate {
tu.mutation.Where(ps...)
return tu
}
// SetName sets the "name" field.
func (tu *TaskUpdate) SetName(s string) *TaskUpdate {
tu.mutation.SetName(s)
return tu
}
// SetNillableName sets the "name" field if the given value is not nil.
func (tu *TaskUpdate) SetNillableName(s *string) *TaskUpdate {
if s != nil {
tu.SetName(*s)
}
return tu
}
// SetCreatedAt sets the "created_at" field.
func (tu *TaskUpdate) SetCreatedAt(t time.Time) *TaskUpdate {
tu.mutation.SetCreatedAt(t)
return tu
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (tu *TaskUpdate) SetNillableCreatedAt(t *time.Time) *TaskUpdate {
if t != nil {
tu.SetCreatedAt(*t)
}
return tu
}
// SetUpdatedAt sets the "updated_at" field.
func (tu *TaskUpdate) SetUpdatedAt(t time.Time) *TaskUpdate {
tu.mutation.SetUpdatedAt(t)
return tu
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (tu *TaskUpdate) SetNillableUpdatedAt(t *time.Time) *TaskUpdate {
if t != nil {
tu.SetUpdatedAt(*t)
}
return tu
}
// SetCompletedAt sets the "completed_at" field.
func (tu *TaskUpdate) SetCompletedAt(t time.Time) *TaskUpdate {
tu.mutation.SetCompletedAt(t)
return tu
}
// SetNillableCompletedAt sets the "completed_at" field if the given value is not nil.
func (tu *TaskUpdate) SetNillableCompletedAt(t *time.Time) *TaskUpdate {
if t != nil {
tu.SetCompletedAt(*t)
}
return tu
}
// ClearCompletedAt clears the value of the "completed_at" field.
func (tu *TaskUpdate) ClearCompletedAt() *TaskUpdate {
tu.mutation.ClearCompletedAt()
return tu
}
// SetTags sets the "tags" field.
func (tu *TaskUpdate) SetTags(s []string) *TaskUpdate {
tu.mutation.SetTags(s)
return tu
}
// AppendTags appends s to the "tags" field.
func (tu *TaskUpdate) AppendTags(s []string) *TaskUpdate {
tu.mutation.AppendTags(s)
return tu
}
// ClearTags clears the value of the "tags" field.
func (tu *TaskUpdate) ClearTags() *TaskUpdate {
tu.mutation.ClearTags()
return tu
}
// Mutation returns the TaskMutation object of the builder.
func (tu *TaskUpdate) Mutation() *TaskMutation {
return tu.mutation
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (tu *TaskUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, tu.sqlSave, tu.mutation, tu.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (tu *TaskUpdate) SaveX(ctx context.Context) int {
affected, err := tu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (tu *TaskUpdate) Exec(ctx context.Context) error {
_, err := tu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (tu *TaskUpdate) ExecX(ctx context.Context) {
if err := tu.Exec(ctx); err != nil {
panic(err)
}
}
func (tu *TaskUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := sqlgraph.NewUpdateSpec(task.Table, task.Columns, sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID))
if ps := tu.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := tu.mutation.Name(); ok {
_spec.SetField(task.FieldName, field.TypeString, value)
}
if value, ok := tu.mutation.CreatedAt(); ok {
_spec.SetField(task.FieldCreatedAt, field.TypeTime, value)
}
if value, ok := tu.mutation.UpdatedAt(); ok {
_spec.SetField(task.FieldUpdatedAt, field.TypeTime, value)
}
if value, ok := tu.mutation.CompletedAt(); ok {
_spec.SetField(task.FieldCompletedAt, field.TypeTime, value)
}
if tu.mutation.CompletedAtCleared() {
_spec.ClearField(task.FieldCompletedAt, field.TypeTime)
}
if value, ok := tu.mutation.Tags(); ok {
_spec.SetField(task.FieldTags, field.TypeJSON, value)
}
if value, ok := tu.mutation.AppendedTags(); ok {
_spec.AddModifier(func(u *sql.UpdateBuilder) {
sqljson.Append(u, task.FieldTags, value)
})
}
if tu.mutation.TagsCleared() {
_spec.ClearField(task.FieldTags, field.TypeJSON)
}
if n, err = sqlgraph.UpdateNodes(ctx, tu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{task.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
tu.mutation.done = true
return n, nil
}
// TaskUpdateOne is the builder for updating a single Task entity.
type TaskUpdateOne struct {
config
fields []string
hooks []Hook
mutation *TaskMutation
}
// SetName sets the "name" field.
func (tuo *TaskUpdateOne) SetName(s string) *TaskUpdateOne {
tuo.mutation.SetName(s)
return tuo
}
// SetNillableName sets the "name" field if the given value is not nil.
func (tuo *TaskUpdateOne) SetNillableName(s *string) *TaskUpdateOne {
if s != nil {
tuo.SetName(*s)
}
return tuo
}
// SetCreatedAt sets the "created_at" field.
func (tuo *TaskUpdateOne) SetCreatedAt(t time.Time) *TaskUpdateOne {
tuo.mutation.SetCreatedAt(t)
return tuo
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (tuo *TaskUpdateOne) SetNillableCreatedAt(t *time.Time) *TaskUpdateOne {
if t != nil {
tuo.SetCreatedAt(*t)
}
return tuo
}
// SetUpdatedAt sets the "updated_at" field.
func (tuo *TaskUpdateOne) SetUpdatedAt(t time.Time) *TaskUpdateOne {
tuo.mutation.SetUpdatedAt(t)
return tuo
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (tuo *TaskUpdateOne) SetNillableUpdatedAt(t *time.Time) *TaskUpdateOne {
if t != nil {
tuo.SetUpdatedAt(*t)
}
return tuo
}
// SetCompletedAt sets the "completed_at" field.
func (tuo *TaskUpdateOne) SetCompletedAt(t time.Time) *TaskUpdateOne {
tuo.mutation.SetCompletedAt(t)
return tuo
}
// SetNillableCompletedAt sets the "completed_at" field if the given value is not nil.
func (tuo *TaskUpdateOne) SetNillableCompletedAt(t *time.Time) *TaskUpdateOne {
if t != nil {
tuo.SetCompletedAt(*t)
}
return tuo
}
// ClearCompletedAt clears the value of the "completed_at" field.
func (tuo *TaskUpdateOne) ClearCompletedAt() *TaskUpdateOne {
tuo.mutation.ClearCompletedAt()
return tuo
}
// SetTags sets the "tags" field.
func (tuo *TaskUpdateOne) SetTags(s []string) *TaskUpdateOne {
tuo.mutation.SetTags(s)
return tuo
}
// AppendTags appends s to the "tags" field.
func (tuo *TaskUpdateOne) AppendTags(s []string) *TaskUpdateOne {
tuo.mutation.AppendTags(s)
return tuo
}
// ClearTags clears the value of the "tags" field.
func (tuo *TaskUpdateOne) ClearTags() *TaskUpdateOne {
tuo.mutation.ClearTags()
return tuo
}
// Mutation returns the TaskMutation object of the builder.
func (tuo *TaskUpdateOne) Mutation() *TaskMutation {
return tuo.mutation
}
// Where appends a list predicates to the TaskUpdate builder.
func (tuo *TaskUpdateOne) Where(ps ...predicate.Task) *TaskUpdateOne {
tuo.mutation.Where(ps...)
return tuo
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (tuo *TaskUpdateOne) Select(field string, fields ...string) *TaskUpdateOne {
tuo.fields = append([]string{field}, fields...)
return tuo
}
// Save executes the query and returns the updated Task entity.
func (tuo *TaskUpdateOne) Save(ctx context.Context) (*Task, error) {
return withHooks(ctx, tuo.sqlSave, tuo.mutation, tuo.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (tuo *TaskUpdateOne) SaveX(ctx context.Context) *Task {
node, err := tuo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (tuo *TaskUpdateOne) Exec(ctx context.Context) error {
_, err := tuo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (tuo *TaskUpdateOne) ExecX(ctx context.Context) {
if err := tuo.Exec(ctx); err != nil {
panic(err)
}
}
func (tuo *TaskUpdateOne) sqlSave(ctx context.Context) (_node *Task, err error) {
_spec := sqlgraph.NewUpdateSpec(task.Table, task.Columns, sqlgraph.NewFieldSpec(task.FieldID, field.TypeUUID))
id, ok := tuo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Task.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := tuo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, task.FieldID)
for _, f := range fields {
if !task.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != task.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := tuo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := tuo.mutation.Name(); ok {
_spec.SetField(task.FieldName, field.TypeString, value)
}
if value, ok := tuo.mutation.CreatedAt(); ok {
_spec.SetField(task.FieldCreatedAt, field.TypeTime, value)
}
if value, ok := tuo.mutation.UpdatedAt(); ok {
_spec.SetField(task.FieldUpdatedAt, field.TypeTime, value)
}
if value, ok := tuo.mutation.CompletedAt(); ok {
_spec.SetField(task.FieldCompletedAt, field.TypeTime, value)
}
if tuo.mutation.CompletedAtCleared() {
_spec.ClearField(task.FieldCompletedAt, field.TypeTime)
}
if value, ok := tuo.mutation.Tags(); ok {
_spec.SetField(task.FieldTags, field.TypeJSON, value)
}
if value, ok := tuo.mutation.AppendedTags(); ok {
_spec.AddModifier(func(u *sql.UpdateBuilder) {
sqljson.Append(u, task.FieldTags, value)
})
}
if tuo.mutation.TagsCleared() {
_spec.ClearField(task.FieldTags, field.TypeJSON)
}
_node = &Task{config: tuo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, tuo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{task.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
tuo.mutation.done = true
return _node, nil
}

210
todo-list/ent/tx.go Normal file
View file

@ -0,0 +1,210 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"sync"
"entgo.io/ent/dialect"
)
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
// Task is the client for interacting with the Task builders.
Task *TaskClient
// 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.Task = NewTaskClient(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: Task.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)

32
todo-list/go.mod Normal file
View file

@ -0,0 +1,32 @@
module todolist
go 1.23.0
require (
entgo.io/ent v0.14.1
github.com/labstack/echo/v4 v4.12.0
github.com/maddalax/htmgo/framework v0.0.0-20240918150417-f0f979e3a293
github.com/mattn/go-sqlite3 v1.14.16
)
require (
ariga.io/atlas v0.19.1-0.20240203083654-5948b60a8e43 // indirect
github.com/agext/levenshtein v1.2.1 // indirect
github.com/apparentlymart/go-textseg/v13 v13.0.0 // indirect
github.com/go-openapi/inflect v0.19.0 // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hashicorp/hcl/v2 v2.13.0 // indirect
github.com/labstack/gommon v0.4.2 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
github.com/zclconf/go-cty v1.8.0 // indirect
golang.org/x/crypto v0.27.0 // indirect
golang.org/x/mod v0.20.0 // indirect
golang.org/x/net v0.29.0 // indirect
golang.org/x/sys v0.25.0 // indirect
golang.org/x/text v0.18.0 // indirect
)

100
todo-list/go.sum Normal file
View file

@ -0,0 +1,100 @@
ariga.io/atlas v0.19.1-0.20240203083654-5948b60a8e43 h1:GwdJbXydHCYPedeeLt4x/lrlIISQ4JTH1mRWuE5ZZ14=
ariga.io/atlas v0.19.1-0.20240203083654-5948b60a8e43/go.mod h1:uj3pm+hUTVN/X5yfdBexHlZv+1Xu5u5ZbZx7+CDavNU=
entgo.io/ent v0.14.1 h1:fUERL506Pqr92EPHJqr8EYxbPioflJo6PudkrEA8a/s=
entgo.io/ent v0.14.1/go.mod h1:MH6XLG0KXpkcDQhKiHfANZSzR55TJyPL5IGNpI8wpco=
github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60=
github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM=
github.com/agext/levenshtein v1.2.1 h1:QmvMAjj2aEICytGiWzmxoE0x2KZvE0fvmqMOfy2tjT8=
github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558=
github.com/apparentlymart/go-textseg/v13 v13.0.0 h1:Y+KvPE1NYz0xl601PVImeQfFyEy6iT90AvPUL1NNfNw=
github.com/apparentlymart/go-textseg/v13 v13.0.0/go.mod h1:ZK2fH7c4NqDTLtiYLvIkEghdlcqw7yxLeM89kiTRPUo=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-openapi/inflect v0.19.0 h1:9jCH9scKIbHeV9m12SmPilScz6krDxKRasNNSNPXu/4=
github.com/go-openapi/inflect v0.19.0/go.mod h1:lHpZVlpIQqLyKwJ4N+YSc9hchQy/i12fJykb83CRBH4=
github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68=
github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA=
github.com/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/hashicorp/hcl/v2 v2.13.0 h1:0Apadu1w6M11dyGFxWnmhhcMjkbAiKCv7G1r/2QgCNc=
github.com/hashicorp/hcl/v2 v2.13.0/go.mod h1:e4z5nxYlWNPdDSNYX+ph14EvWYMFm3eP0zIUqPc2jr0=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
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/labstack/echo/v4 v4.12.0 h1:IKpw49IMryVB2p1a4dzwlhP1O2Tf2E0Ir/450lH+kI0=
github.com/labstack/echo/v4 v4.12.0/go.mod h1:UP9Cr2DJXbOK3Kr9ONYzNowSh7HP0aG0ShAyycHSJvM=
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
github.com/maddalax/htmgo/framework v0.0.0-20240918150417-f0f979e3a293 h1:/VisQ3836jcJkZQDiZUXk9CdOUCu3AY9476/924OSTQ=
github.com/maddalax/htmgo/framework v0.0.0-20240918150417-f0f979e3a293/go.mod h1:hH6EgyyjquAj9BWFRPcTnAB+dOVfLuO125/L8C3iilA=
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.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.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y=
github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 h1:DpOJ2HYzCv8LZP15IdmG+YdwD2luVPHITV96TkirNBM=
github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo=
github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
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.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ=
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I=
github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
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/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
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/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A=
golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70=
golang.org/x/mod v0.20.0 h1:utOm6MM3R3dnawAiJgn0y+xvuYRsm1RKM/4giyfDgV0=
golang.org/x/mod v0.20.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo=
golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0=
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.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.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=
golang.org/x/sys v0.25.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.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224=
golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.24.0 h1:J1shsA93PJUEVaUSaay7UXAyE8aimq3GW0pjlolpa24=
golang.org/x/tools v0.24.0/go.mod h1:YhNqVBIfWHdzvTLs0d8LCuMhkKUgSUKldakyV7W/WDQ=
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
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=

View file

@ -0,0 +1,21 @@
package db
import (
"context"
"fmt"
"log"
"todolist/ent"
)
func Provide() *ent.Client {
fmt.Printf("providing db client\n")
client, err := ent.Open("sqlite3", "file:ent.db?cache=shared&_fk=1")
if err != nil {
log.Fatalf("failed opening connection to sqlite: %v", err)
}
// Run the auto migration tool.
if err := client.Schema.Create(context.Background()); err != nil {
log.Fatalf("failed schema resources: %v", err)
}
return client
}

View file

@ -0,0 +1,83 @@
package tasks
import (
"context"
"github.com/google/uuid"
"github.com/maddalax/htmgo/framework/htmgo/service"
"time"
"todolist/ent"
"todolist/ent/predicate"
"todolist/ent/task"
)
type Service struct {
db *ent.Client
}
type CreateRequest struct {
Name string
Tags []string
}
func NewService(locator *service.Locator) Service {
return Service{
db: service.Get[ent.Client](locator),
}
}
func (s *Service) Create(request CreateRequest) (*ent.Task, error) {
return s.db.Task.Create().
SetName(request.Name).
SetTags(request.Tags).
Save(context.Background())
}
func (s *Service) Get(id uuid.UUID) (*ent.Task, error) {
return s.db.Task.Get(context.Background(), id)
}
func (s *Service) SetName(id uuid.UUID, name string) (*ent.Task, error) {
return s.db.Task.UpdateOneID(id).SetName(name).Save(context.Background())
}
func (s *Service) SetAllCompleted(value bool) error {
ctx := context.Background()
updater := s.db.Task.Update()
if value {
updater = updater.SetCompletedAt(time.Now())
} else {
updater = updater.ClearCompletedAt()
}
_, err := updater.
SetUpdatedAt(time.Now()).
Save(ctx)
return err
}
func (s *Service) ClearCompleted() error {
ctx := context.Background()
_, err := s.db.Task.Delete().Where(task.CompletedAtNotNil()).Exec(ctx)
return err
}
func (s *Service) SetCompleted(id uuid.UUID, value bool) (*ent.Task, error) {
ctx := context.Background()
updater := s.db.Task.UpdateOneID(id)
if value {
updater = updater.SetCompletedAt(time.Now())
} else {
updater = updater.ClearCompletedAt()
}
return updater.
SetUpdatedAt(time.Now()).
Save(ctx)
}
func (s *Service) List(ps ...predicate.Task) ([]*ent.Task, error) {
return s.db.Task.Query().Where(ps...).All(context.Background())
}

39
todo-list/main.go Normal file
View file

@ -0,0 +1,39 @@
package main
import (
"github.com/labstack/echo/v4"
"github.com/maddalax/htmgo/framework/h"
"github.com/maddalax/htmgo/framework/htmgo/service"
_ "github.com/mattn/go-sqlite3"
"todolist/ent"
"todolist/infrastructure/db"
"todolist/pages"
"todolist/partials/load"
)
type CustomContext struct {
echo.Context
locator *service.Locator
}
func (c *CustomContext) ServiceLocator() *service.Locator {
return c.locator
}
func main() {
locator := service.NewLocator()
service.Set[ent.Client](locator, service.Singleton, func() *ent.Client {
return db.Provide()
})
h.Start(h.AppOpts{
ServiceLocator: locator,
LiveReload: true,
Register: func(e *echo.Echo) {
e.Static("/public", "./assets/dist")
load.RegisterPartials(e)
pages.RegisterPages(e)
},
})
}

View file

@ -0,0 +1,25 @@
package base
import (
"github.com/maddalax/htmgo/framework/h"
"strings"
)
func Extensions() string {
extensions := []string{"path-deps", "response-targets", "mutation-error"}
if h.IsDevelopment() {
extensions = append(extensions, "livereload")
}
return strings.Join(extensions, ", ")
}
func RootPage(children ...h.Renderable) h.Renderable {
return h.Html(
h.HxExtension(Extensions()),
h.Head(
h.Link("/public/main.css", "stylesheet"),
h.Script("/public/htmgo.js"),
),
h.Fragment(children...),
)
}

View file

@ -0,0 +1,16 @@
// Package pages THIS FILE IS GENERATED. DO NOT EDIT.
package pages
import "github.com/labstack/echo/v4"
import "github.com/maddalax/htmgo/framework/h"
func RegisterPages(f *echo.Echo) {
f.GET("/", func(ctx echo.Context) error {
cc := ctx.(*h.RequestContext)
return h.HtmlView(ctx, IndexPage(cc))
})
f.GET("/tasks", func(ctx echo.Context) error {
cc := ctx.(*h.RequestContext)
return h.HtmlView(ctx, TaskListPage(cc))
})
}

40
todo-list/pages/index.go Normal file
View file

@ -0,0 +1,40 @@
package pages
import (
"github.com/labstack/echo/v4"
"github.com/maddalax/htmgo/framework/h"
"todolist/pages/base"
"todolist/partials"
)
func IndexPage(c echo.Context) *h.Page {
return h.NewPage(h.Html(
h.HxExtension(base.Extensions()),
h.Class("bg-red-200 flex flex-col items-center h-full w-full"),
h.Head(
h.Link("/public/main.css", "stylesheet"),
h.Script("/public/htmgo.js"),
),
h.Body(
h.Class("flex flex-col gap-4"),
h.Div(h.Class("flex gap-2 mt-6"),
Button(),
Button(),
Button(),
Button(),
),
),
))
}
func Button() h.Renderable {
return h.Button(h.Class("btn bg-green-500 p-4 rounded text-white"),
h.Text("my button"),
h.AfterRequest(
h.SetDisabled(true),
h.RemoveClass("bg-red-600"),
h.AddClass("bg-gray-500"),
),
h.GetPartial(partials.SamplePartial),
)
}

26
todo-list/pages/tasks.go Normal file
View file

@ -0,0 +1,26 @@
package pages
import (
"todolist/pages/base"
"todolist/partials/task"
"github.com/maddalax/htmgo/framework/h"
)
func TaskListPage(ctx *h.RequestContext) *h.Page {
title := h.Div(
h.H1(h.Class("text-7xl font-extralight text-rose-500 tracking-wide"), h.Text("todos")),
)
return h.NewPage(base.RootPage(
h.Div(
h.Class("bg-neutral-100 min-h-screen"),
h.Div(
h.Class("flex flex-col gap-6 p-4 items-center max-w-xl mx-auto pb-12"),
title,
task.Card(ctx),
),
),
))
}

View file

@ -0,0 +1,17 @@
package partials
import (
"github.com/maddalax/htmgo/framework/h"
)
func SamplePartial(ctx *h.RequestContext) *h.Partial {
return h.NewPartial(h.Div(h.P(h.Text(" asdasasds"))))
}
func NewPartial(ctx *h.RequestContext) *h.Partial {
return h.NewPartial(h.Div(h.P(h.Text("This sadsl."))))
}
func NewPartial2(ctx *h.RequestContext) *h.Partial {
return h.NewPartial(h.Div(h.P(h.Text("This sasdsadasdwl."))))
}

View file

@ -0,0 +1,62 @@
// Package partials THIS FILE IS GENERATED. DO NOT EDIT.
package load
import "github.com/maddalax/htmgo/framework/h"
import "github.com/labstack/echo/v4"
import "todolist/partials"
import "todolist/partials/task"
func GetPartialFromContext(ctx echo.Context) *h.Partial {
path := ctx.Request().URL.Path
if path == "SamplePartial" || path == "/todolist/partials.SamplePartial" {
cc := ctx.(*h.RequestContext)
return partials.SamplePartial(cc)
}
if path == "NewPartial" || path == "/todolist/partials.NewPartial" {
cc := ctx.(*h.RequestContext)
return partials.NewPartial(cc)
}
if path == "NewPartial2" || path == "/todolist/partials.NewPartial2" {
cc := ctx.(*h.RequestContext)
return partials.NewPartial2(cc)
}
if path == "UpdateName" || path == "/todolist/partials/task.UpdateName" {
cc := ctx.(*h.RequestContext)
return task.UpdateName(cc)
}
if path == "EditNameForm" || path == "/todolist/partials/task.EditNameForm" {
cc := ctx.(*h.RequestContext)
return task.EditNameForm(cc)
}
if path == "ToggleCompleted" || path == "/todolist/partials/task.ToggleCompleted" {
cc := ctx.(*h.RequestContext)
return task.ToggleCompleted(cc)
}
if path == "CompleteAll" || path == "/todolist/partials/task.CompleteAll" {
cc := ctx.(*h.RequestContext)
return task.CompleteAll(cc)
}
if path == "ClearCompleted" || path == "/todolist/partials/task.ClearCompleted" {
cc := ctx.(*h.RequestContext)
return task.ClearCompleted(cc)
}
if path == "Create" || path == "/todolist/partials/task.Create" {
cc := ctx.(*h.RequestContext)
return task.Create(cc)
}
if path == "ChangeTab" || path == "/todolist/partials/task.ChangeTab" {
cc := ctx.(*h.RequestContext)
return task.ChangeTab(cc)
}
return nil
}
func RegisterPartials(f *echo.Echo) {
f.Any("todolist/partials*", func(ctx echo.Context) error {
partial := GetPartialFromContext(ctx)
if partial == nil {
return ctx.NoContent(404)
}
return h.PartialView(ctx, partial)
})
}

View file

@ -0,0 +1,315 @@
package task
import (
"fmt"
"github.com/google/uuid"
"github.com/maddalax/htmgo/framework/h"
"todolist/ent"
"todolist/internal/tasks"
)
type Tab = string
const (
TabAll Tab = "All"
TabActive Tab = "Active"
TabComplete Tab = "Complete"
)
func getActiveTab(ctx *h.RequestContext) Tab {
if tab := h.GetQueryParam(ctx, "tab"); tab != "" {
return tab
}
return TabAll
}
func Card(ctx *h.RequestContext) h.Renderable {
service := tasks.NewService(ctx.ServiceLocator())
list, _ := service.List()
return h.Div(
h.Id("task-card"),
h.Class("bg-white w-full rounded shadow-md"),
CardBody(list, getActiveTab(ctx)),
)
}
func CardBody(list []*ent.Task, tab Tab) h.Renderable {
return h.Div(
h.Id("tasks-card-body"),
Input(list),
List(list, tab),
Footer(list, tab),
)
}
func Input(list []*ent.Task) h.Renderable {
return h.Div(
h.Id("task-card-input"),
h.Class("border border-b-slate-100 relative"),
h.Input(
"text",
h.Attribute("autocomplete", "off"),
h.Attribute("autofocus", "true"),
h.Attribute("name", "name"),
h.Class("pl-12 text-xl p-4 w-full outline-none focus:outline-2 focus:outline-rose-400"),
h.Placeholder("What needs to be done?"),
h.Post(h.GetPartialPath(Create)),
h.Trigger("keyup[keyCode==13]"),
),
CompleteAllIcon(list),
)
}
func CompleteAllIcon(list []*ent.Task) h.Renderable {
notCompletedCount := len(h.Filter(list, func(item *ent.Task) bool {
return item.CompletedAt == nil
}))
return h.Div(
h.ClassX("absolute top-0 left-0 p-4 rotate-90 text-2xl cursor-pointer", map[string]bool{
"text-slate-400": notCompletedCount > 0,
}), h.Text(""),
h.PostPartialOnClickQs(CompleteAll, h.Ternary(notCompletedCount > 0, "complete=true", "complete=false")),
)
}
func Footer(list []*ent.Task, activeTab Tab) h.Renderable {
notCompletedCount := len(h.Filter(list, func(item *ent.Task) bool {
return item.CompletedAt == nil
}))
tabs := []Tab{TabAll, TabActive, TabComplete}
return h.Div(
h.Id("task-card-footer"),
h.Class("flex items-center justify-between p-4 border-t border-b-slate-100"),
h.Div(
h.TextF("%d items left", notCompletedCount),
),
h.Div(
h.Class("flex items-center gap-4"),
h.List(tabs, func(tab Tab, index int) h.Renderable {
return h.P(
h.PostOnClick(h.GetPartialPathWithQs(ChangeTab, "tab="+tab)),
h.ClassX("cursor-pointer px-2 py-1 rounded", map[string]bool{
"border border-rose-600": activeTab == tab,
}),
h.Text(tab),
)
}),
),
h.Div(
h.PostPartialOnClick(ClearCompleted),
h.ClassX("flex gap-2 cursor-pointer", map[string]bool{
"opacity-0": notCompletedCount == len(list),
}),
h.Text("Clear completed"),
),
)
}
func List(list []*ent.Task, tab Tab) h.Renderable {
return h.Div(
h.Id("task-card-list"),
h.Class("bg-white w-full"),
h.Div(
h.List(list, func(item *ent.Task, index int) h.Renderable {
if tab == TabActive && item.CompletedAt != nil {
return h.Empty()
}
if tab == TabComplete && item.CompletedAt == nil {
return h.Empty()
}
return Task(item, false)
}),
),
)
}
func Task(task *ent.Task, editing bool) h.Renderable {
return h.Div(
h.Id(fmt.Sprintf("task-%s", task.ID.String())),
h.ClassX("h-[80px] max-h-[80px] max-w-2xl flex items-center p-4 gap-4 cursor-pointer", map[string]bool{
"border border-b-slate-100": !editing,
}),
CompleteIcon(task),
h.IfElse(editing,
h.Div(
h.Class("flex-1 h-full"),
h.Form(
h.Class("h-full"),
h.Input("text",
h.Attribute("name", "task"),
h.Attribute("value", task.ID.String()),
h.Class("hidden"),
),
h.Input(
"text",
h.Post(h.GetPartialPath(UpdateName)),
h.Trigger("blur, keyup[keyCode==13]"),
h.Attribute("autocomplete", "off"),
h.Attribute("autofocus", "true"),
h.Attribute("name", "name"),
h.Class("pl-1 h-full w-full text-xl outline-none outline-2 outline-rose-300"),
h.Attribute("value", task.Name),
),
),
),
h.P(
h.Trigger("dblclick"),
h.GetPartialWithQs(EditNameForm, "id="+task.ID.String()),
h.ClassX("text-xl break-all text-wrap truncate", map[string]bool{
"line-through text-slate-400": task.CompletedAt != nil,
}),
h.Text(task.Name),
)),
)
}
func CompleteIcon(task *ent.Task) h.Renderable {
return h.Div(
h.Trigger("click"),
h.Post(h.GetPartialPathWithQs(ToggleCompleted, "id="+task.ID.String())),
h.Class("flex items-center justify-center cursor-pointer"),
h.Div(
h.ClassX("w-10 h-10 border rounded-full flex items-center justify-center", map[string]bool{
"border-green-500": task.CompletedAt != nil,
"border-slate-400": task.CompletedAt == nil,
}),
h.If(task.CompletedAt != nil, h.Raw(`
<svg class="w-6 h-6 text-green-500" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"></path>
</svg>
`)),
),
)
}
func UpdateName(ctx *h.RequestContext) *h.Partial {
id, err := uuid.Parse(ctx.FormValue("task"))
if err != nil {
return h.NewPartial(h.Div(h.Text("invalid id")))
}
name := ctx.FormValue("name")
if name == "" {
return h.NewPartial(h.Div(h.Text("name is required")))
}
service := tasks.NewService(ctx.ServiceLocator())
task, err := service.Get(id)
if task == nil {
return h.NewPartial(h.Div(h.Text("task not found")))
}
task, err = service.SetName(task.ID, name)
if err != nil {
return h.NewPartial(h.Div(h.Text("failed to update")))
}
return h.NewPartial(h.OobSwap(ctx, Task(task, false)))
}
func EditNameForm(ctx *h.RequestContext) *h.Partial {
id, err := uuid.Parse(ctx.QueryParam("id"))
if err != nil {
return h.NewPartial(h.Div(h.Text("invalid id")))
}
service := tasks.NewService(ctx.ServiceLocator())
task, err := service.Get(id)
if task == nil {
return h.NewPartial(h.Div(h.Text("task not found")))
}
return h.NewPartial(
h.OobSwap(ctx, Task(task, true)),
)
}
func ToggleCompleted(ctx *h.RequestContext) *h.Partial {
id, err := uuid.Parse(ctx.QueryParam("id"))
if err != nil {
return h.NewPartial(h.Div(h.Text("invalid id")))
}
service := tasks.NewService(ctx.ServiceLocator())
task, err := service.Get(id)
if task == nil {
return h.NewPartial(h.Div(h.Text("task not found")))
}
task, err = service.SetCompleted(task.ID, h.
Ternary(task.CompletedAt == nil, true, false))
if err != nil {
return h.NewPartial(h.Div(h.Text("failed to update")))
}
list, _ := service.List()
return h.NewPartial(h.Fragment(
h.OobSwap(ctx, List(list, getActiveTab(ctx))),
h.OobSwap(ctx, Footer(list, getActiveTab(ctx))),
h.OobSwap(ctx, CompleteAllIcon(list)),
))
}
func CompleteAll(ctx *h.RequestContext) *h.Partial {
service := tasks.NewService(ctx.ServiceLocator())
service.SetAllCompleted(ctx.QueryParam("complete") == "true")
list, _ := service.List()
return h.NewPartial(h.OobSwap(ctx, CardBody(list, getActiveTab(ctx))))
}
func ClearCompleted(ctx *h.RequestContext) *h.Partial {
service := tasks.NewService(ctx.ServiceLocator())
_ = service.ClearCompleted()
list, _ := service.List()
return h.NewPartial(h.OobSwap(ctx, CardBody(list, getActiveTab(ctx))))
}
func Create(ctx *h.RequestContext) *h.Partial {
name := ctx.FormValue("name")
if name == "" {
return h.NewPartial(h.Div(h.Text("name is required")))
}
service := tasks.NewService(ctx.ServiceLocator())
_, err := service.Create(tasks.CreateRequest{
Name: name,
})
if err != nil {
return h.NewPartial(h.Div(h.Text("failed to create")))
}
list, _ := service.List()
return h.NewPartial(h.Fragment(h.OobSwap(ctx, CardBody(list, getActiveTab(ctx)))))
}
func ChangeTab(ctx *h.RequestContext) *h.Partial {
service := tasks.NewService(ctx.ServiceLocator())
list, _ := service.List()
tab := ctx.QueryParam("tab")
return h.NewPartialWithHeaders(&h.Headers{"hx-push-url": fmt.Sprintf("/tasks?tab=%s", tab)},
h.Fragment(
h.OobSwap(ctx, List(list, tab)),
h.OobSwap(ctx, Footer(list, tab)),
),
)
}