diff --git a/README.md b/README.md index 044db26..27f0299 100644 --- a/README.md +++ b/README.md @@ -30,8 +30,16 @@ Create a new migration: atlas migrate diff \ --dir "file://internal/database/migrations" \ --to "ent://internal/database/schema" \ - --dev-url "postgres://mensatt:mensatt@localhost:5432/mensatt?search_path=public&sslmode=disable" \ + --dev-url "docker://postgres/15/dev?search_path=public" \ --format '{{ sql . " " }}' ``` The `--format` flag uses a tab as indentation. If you want to manually edit this command you can use `ctrl + v + tab` to insert a tab character in your shell. +The `--dev-url` flag is used to connect to an ephemeral local Docker container containing a PostgreSQL instance required for creating the migration. + +Apply the migration: +```bash +atlas migrate apply \ + --dir "file://internal/database/migrations" \ + --url "postgres://mensatt:mensatt@localhost:5432/mensatt?search_path=public&sslmode=disable" +``` diff --git a/internal/database/ent/image.go b/internal/database/ent/image.go index ae2d964..57c0dc4 100644 --- a/internal/database/ent/image.go +++ b/internal/database/ent/image.go @@ -15,9 +15,13 @@ import ( // Image is the model entity for the Image schema. type Image struct { - config + config `json:"-"` // ID of the ent. ID uuid.UUID `json:"id,omitempty"` + // Width holds the value of the "width" field. + Width int `json:"width,omitempty"` + // Height holds the value of the "height" field. + Height int `json:"height,omitempty"` // Edges holds the relations/edges for other nodes in the graph. // The values are being populated by the ImageQuery when eager-loading is set. Edges ImageEdges `json:"edges"` @@ -50,6 +54,8 @@ func (*Image) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) for i := range columns { switch columns[i] { + case image.FieldWidth, image.FieldHeight: + values[i] = new(sql.NullInt64) case image.FieldID: values[i] = new(uuid.UUID) case image.ForeignKeys[0]: // review @@ -75,6 +81,18 @@ func (i *Image) assignValues(columns []string, values []any) error { } else if value != nil { i.ID = *value } + case image.FieldWidth: + if value, ok := values[j].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field width", values[j]) + } else if value.Valid { + i.Width = int(value.Int64) + } + case image.FieldHeight: + if value, ok := values[j].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field height", values[j]) + } else if value.Valid { + i.Height = int(value.Int64) + } case image.ForeignKeys[0]: if value, ok := values[j].(*sql.NullScanner); !ok { return fmt.Errorf("unexpected type %T for field review", values[j]) @@ -122,7 +140,12 @@ func (i *Image) Unwrap() *Image { func (i *Image) String() string { var builder strings.Builder builder.WriteString("Image(") - builder.WriteString(fmt.Sprintf("id=%v", i.ID)) + builder.WriteString(fmt.Sprintf("id=%v, ", i.ID)) + builder.WriteString("width=") + builder.WriteString(fmt.Sprintf("%v", i.Width)) + builder.WriteString(", ") + builder.WriteString("height=") + builder.WriteString(fmt.Sprintf("%v", i.Height)) builder.WriteByte(')') return builder.String() } diff --git a/internal/database/ent/image/image.go b/internal/database/ent/image/image.go index df3d91f..4543f5e 100644 --- a/internal/database/ent/image/image.go +++ b/internal/database/ent/image/image.go @@ -13,6 +13,10 @@ const ( Label = "image" // FieldID holds the string denoting the id field in the database. FieldID = "id" + // FieldWidth holds the string denoting the width field in the database. + FieldWidth = "width" + // FieldHeight holds the string denoting the height field in the database. + FieldHeight = "height" // EdgeReview holds the string denoting the review edge name in mutations. EdgeReview = "review" // Table holds the table name of the image in the database. @@ -29,6 +33,8 @@ const ( // Columns holds all SQL columns for image fields. var Columns = []string{ FieldID, + FieldWidth, + FieldHeight, } // ForeignKeys holds the SQL foreign-keys that are owned by the "image" @@ -53,6 +59,10 @@ func ValidColumn(column string) bool { } var ( + // WidthValidator is a validator for the "width" field. It is called by the builders before save. + WidthValidator func(int) error + // HeightValidator is a validator for the "height" field. It is called by the builders before save. + HeightValidator func(int) error // DefaultID holds the default value on creation for the "id" field. DefaultID func() uuid.UUID ) @@ -65,6 +75,16 @@ func ByID(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldID, opts...).ToFunc() } +// ByWidth orders the results by the width field. +func ByWidth(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldWidth, opts...).ToFunc() +} + +// ByHeight orders the results by the height field. +func ByHeight(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldHeight, opts...).ToFunc() +} + // ByReviewField orders the results by review field. func ByReviewField(field string, opts ...sql.OrderTermOption) OrderOption { return func(s *sql.Selector) { diff --git a/internal/database/ent/image/where.go b/internal/database/ent/image/where.go index 240b8a5..b4e8865 100644 --- a/internal/database/ent/image/where.go +++ b/internal/database/ent/image/where.go @@ -54,6 +54,96 @@ func IDLTE(id uuid.UUID) predicate.Image { return predicate.Image(sql.FieldLTE(FieldID, id)) } +// Width applies equality check predicate on the "width" field. It's identical to WidthEQ. +func Width(v int) predicate.Image { + return predicate.Image(sql.FieldEQ(FieldWidth, v)) +} + +// Height applies equality check predicate on the "height" field. It's identical to HeightEQ. +func Height(v int) predicate.Image { + return predicate.Image(sql.FieldEQ(FieldHeight, v)) +} + +// WidthEQ applies the EQ predicate on the "width" field. +func WidthEQ(v int) predicate.Image { + return predicate.Image(sql.FieldEQ(FieldWidth, v)) +} + +// WidthNEQ applies the NEQ predicate on the "width" field. +func WidthNEQ(v int) predicate.Image { + return predicate.Image(sql.FieldNEQ(FieldWidth, v)) +} + +// WidthIn applies the In predicate on the "width" field. +func WidthIn(vs ...int) predicate.Image { + return predicate.Image(sql.FieldIn(FieldWidth, vs...)) +} + +// WidthNotIn applies the NotIn predicate on the "width" field. +func WidthNotIn(vs ...int) predicate.Image { + return predicate.Image(sql.FieldNotIn(FieldWidth, vs...)) +} + +// WidthGT applies the GT predicate on the "width" field. +func WidthGT(v int) predicate.Image { + return predicate.Image(sql.FieldGT(FieldWidth, v)) +} + +// WidthGTE applies the GTE predicate on the "width" field. +func WidthGTE(v int) predicate.Image { + return predicate.Image(sql.FieldGTE(FieldWidth, v)) +} + +// WidthLT applies the LT predicate on the "width" field. +func WidthLT(v int) predicate.Image { + return predicate.Image(sql.FieldLT(FieldWidth, v)) +} + +// WidthLTE applies the LTE predicate on the "width" field. +func WidthLTE(v int) predicate.Image { + return predicate.Image(sql.FieldLTE(FieldWidth, v)) +} + +// HeightEQ applies the EQ predicate on the "height" field. +func HeightEQ(v int) predicate.Image { + return predicate.Image(sql.FieldEQ(FieldHeight, v)) +} + +// HeightNEQ applies the NEQ predicate on the "height" field. +func HeightNEQ(v int) predicate.Image { + return predicate.Image(sql.FieldNEQ(FieldHeight, v)) +} + +// HeightIn applies the In predicate on the "height" field. +func HeightIn(vs ...int) predicate.Image { + return predicate.Image(sql.FieldIn(FieldHeight, vs...)) +} + +// HeightNotIn applies the NotIn predicate on the "height" field. +func HeightNotIn(vs ...int) predicate.Image { + return predicate.Image(sql.FieldNotIn(FieldHeight, vs...)) +} + +// HeightGT applies the GT predicate on the "height" field. +func HeightGT(v int) predicate.Image { + return predicate.Image(sql.FieldGT(FieldHeight, v)) +} + +// HeightGTE applies the GTE predicate on the "height" field. +func HeightGTE(v int) predicate.Image { + return predicate.Image(sql.FieldGTE(FieldHeight, v)) +} + +// HeightLT applies the LT predicate on the "height" field. +func HeightLT(v int) predicate.Image { + return predicate.Image(sql.FieldLT(FieldHeight, v)) +} + +// HeightLTE applies the LTE predicate on the "height" field. +func HeightLTE(v int) predicate.Image { + return predicate.Image(sql.FieldLTE(FieldHeight, v)) +} + // HasReview applies the HasEdge predicate on the "review" edge. func HasReview() predicate.Image { return predicate.Image(func(s *sql.Selector) { diff --git a/internal/database/ent/image_create.go b/internal/database/ent/image_create.go index 24d7f97..0acc7c3 100644 --- a/internal/database/ent/image_create.go +++ b/internal/database/ent/image_create.go @@ -24,6 +24,18 @@ type ImageCreate struct { conflict []sql.ConflictOption } +// SetWidth sets the "width" field. +func (ic *ImageCreate) SetWidth(i int) *ImageCreate { + ic.mutation.SetWidth(i) + return ic +} + +// SetHeight sets the "height" field. +func (ic *ImageCreate) SetHeight(i int) *ImageCreate { + ic.mutation.SetHeight(i) + return ic +} + // SetID sets the "id" field. func (ic *ImageCreate) SetID(u uuid.UUID) *ImageCreate { ic.mutation.SetID(u) @@ -92,6 +104,22 @@ func (ic *ImageCreate) defaults() { // check runs all checks and user-defined validators on the builder. func (ic *ImageCreate) check() error { + if _, ok := ic.mutation.Width(); !ok { + return &ValidationError{Name: "width", err: errors.New(`ent: missing required field "Image.width"`)} + } + if v, ok := ic.mutation.Width(); ok { + if err := image.WidthValidator(v); err != nil { + return &ValidationError{Name: "width", err: fmt.Errorf(`ent: validator failed for field "Image.width": %w`, err)} + } + } + if _, ok := ic.mutation.Height(); !ok { + return &ValidationError{Name: "height", err: errors.New(`ent: missing required field "Image.height"`)} + } + if v, ok := ic.mutation.Height(); ok { + if err := image.HeightValidator(v); err != nil { + return &ValidationError{Name: "height", err: fmt.Errorf(`ent: validator failed for field "Image.height": %w`, err)} + } + } if _, ok := ic.mutation.ReviewID(); !ok { return &ValidationError{Name: "review", err: errors.New(`ent: missing required edge "Image.review"`)} } @@ -131,6 +159,14 @@ func (ic *ImageCreate) createSpec() (*Image, *sqlgraph.CreateSpec) { _node.ID = id _spec.ID.Value = &id } + if value, ok := ic.mutation.Width(); ok { + _spec.SetField(image.FieldWidth, field.TypeInt, value) + _node.Width = value + } + if value, ok := ic.mutation.Height(); ok { + _spec.SetField(image.FieldHeight, field.TypeInt, value) + _node.Height = value + } if nodes := ic.mutation.ReviewIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, @@ -155,11 +191,17 @@ func (ic *ImageCreate) createSpec() (*Image, *sqlgraph.CreateSpec) { // of the `INSERT` statement. For example: // // client.Image.Create(). +// SetWidth(v). // OnConflict( // // Update the row with the new values // // the was proposed for insertion. // sql.ResolveWithNewValues(), // ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.ImageUpsert) { +// SetWidth(v+v). +// }). // Exec(ctx) func (ic *ImageCreate) OnConflict(opts ...sql.ConflictOption) *ImageUpsertOne { ic.conflict = opts @@ -194,6 +236,42 @@ type ( } ) +// SetWidth sets the "width" field. +func (u *ImageUpsert) SetWidth(v int) *ImageUpsert { + u.Set(image.FieldWidth, v) + return u +} + +// UpdateWidth sets the "width" field to the value that was provided on create. +func (u *ImageUpsert) UpdateWidth() *ImageUpsert { + u.SetExcluded(image.FieldWidth) + return u +} + +// AddWidth adds v to the "width" field. +func (u *ImageUpsert) AddWidth(v int) *ImageUpsert { + u.Add(image.FieldWidth, v) + return u +} + +// SetHeight sets the "height" field. +func (u *ImageUpsert) SetHeight(v int) *ImageUpsert { + u.Set(image.FieldHeight, v) + return u +} + +// UpdateHeight sets the "height" field to the value that was provided on create. +func (u *ImageUpsert) UpdateHeight() *ImageUpsert { + u.SetExcluded(image.FieldHeight) + return u +} + +// AddHeight adds v to the "height" field. +func (u *ImageUpsert) AddHeight(v int) *ImageUpsert { + u.Add(image.FieldHeight, v) + return u +} + // UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. // Using this option is equivalent to using: // @@ -242,6 +320,48 @@ func (u *ImageUpsertOne) Update(set func(*ImageUpsert)) *ImageUpsertOne { return u } +// SetWidth sets the "width" field. +func (u *ImageUpsertOne) SetWidth(v int) *ImageUpsertOne { + return u.Update(func(s *ImageUpsert) { + s.SetWidth(v) + }) +} + +// AddWidth adds v to the "width" field. +func (u *ImageUpsertOne) AddWidth(v int) *ImageUpsertOne { + return u.Update(func(s *ImageUpsert) { + s.AddWidth(v) + }) +} + +// UpdateWidth sets the "width" field to the value that was provided on create. +func (u *ImageUpsertOne) UpdateWidth() *ImageUpsertOne { + return u.Update(func(s *ImageUpsert) { + s.UpdateWidth() + }) +} + +// SetHeight sets the "height" field. +func (u *ImageUpsertOne) SetHeight(v int) *ImageUpsertOne { + return u.Update(func(s *ImageUpsert) { + s.SetHeight(v) + }) +} + +// AddHeight adds v to the "height" field. +func (u *ImageUpsertOne) AddHeight(v int) *ImageUpsertOne { + return u.Update(func(s *ImageUpsert) { + s.AddHeight(v) + }) +} + +// UpdateHeight sets the "height" field to the value that was provided on create. +func (u *ImageUpsertOne) UpdateHeight() *ImageUpsertOne { + return u.Update(func(s *ImageUpsert) { + s.UpdateHeight() + }) +} + // Exec executes the query. func (u *ImageUpsertOne) Exec(ctx context.Context) error { if len(u.create.conflict) == 0 { @@ -375,6 +495,11 @@ func (icb *ImageCreateBulk) ExecX(ctx context.Context) { // // the was proposed for insertion. // sql.ResolveWithNewValues(), // ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.ImageUpsert) { +// SetWidth(v+v). +// }). // Exec(ctx) func (icb *ImageCreateBulk) OnConflict(opts ...sql.ConflictOption) *ImageUpsertBulk { icb.conflict = opts @@ -452,6 +577,48 @@ func (u *ImageUpsertBulk) Update(set func(*ImageUpsert)) *ImageUpsertBulk { return u } +// SetWidth sets the "width" field. +func (u *ImageUpsertBulk) SetWidth(v int) *ImageUpsertBulk { + return u.Update(func(s *ImageUpsert) { + s.SetWidth(v) + }) +} + +// AddWidth adds v to the "width" field. +func (u *ImageUpsertBulk) AddWidth(v int) *ImageUpsertBulk { + return u.Update(func(s *ImageUpsert) { + s.AddWidth(v) + }) +} + +// UpdateWidth sets the "width" field to the value that was provided on create. +func (u *ImageUpsertBulk) UpdateWidth() *ImageUpsertBulk { + return u.Update(func(s *ImageUpsert) { + s.UpdateWidth() + }) +} + +// SetHeight sets the "height" field. +func (u *ImageUpsertBulk) SetHeight(v int) *ImageUpsertBulk { + return u.Update(func(s *ImageUpsert) { + s.SetHeight(v) + }) +} + +// AddHeight adds v to the "height" field. +func (u *ImageUpsertBulk) AddHeight(v int) *ImageUpsertBulk { + return u.Update(func(s *ImageUpsert) { + s.AddHeight(v) + }) +} + +// UpdateHeight sets the "height" field to the value that was provided on create. +func (u *ImageUpsertBulk) UpdateHeight() *ImageUpsertBulk { + return u.Update(func(s *ImageUpsert) { + s.UpdateHeight() + }) +} + // Exec executes the query. func (u *ImageUpsertBulk) Exec(ctx context.Context) error { if u.create.err != nil { diff --git a/internal/database/ent/image_query.go b/internal/database/ent/image_query.go index c602e36..3c8faa8 100644 --- a/internal/database/ent/image_query.go +++ b/internal/database/ent/image_query.go @@ -295,6 +295,18 @@ func (iq *ImageQuery) WithReview(opts ...func(*ReviewQuery)) *ImageQuery { // 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 { +// Width int `json:"width,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Image.Query(). +// GroupBy(image.FieldWidth). +// Aggregate(ent.Count()). +// Scan(ctx, &v) func (iq *ImageQuery) GroupBy(field string, fields ...string) *ImageGroupBy { iq.ctx.Fields = append([]string{field}, fields...) grbuild := &ImageGroupBy{build: iq} @@ -306,6 +318,16 @@ func (iq *ImageQuery) GroupBy(field string, fields ...string) *ImageGroupBy { // 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 { +// Width int `json:"width,omitempty"` +// } +// +// client.Image.Query(). +// Select(image.FieldWidth). +// Scan(ctx, &v) func (iq *ImageQuery) Select(fields ...string) *ImageSelect { iq.ctx.Fields = append(iq.ctx.Fields, fields...) sbuild := &ImageSelect{ImageQuery: iq} diff --git a/internal/database/ent/image_update.go b/internal/database/ent/image_update.go index 4fb9859..4e33db1 100644 --- a/internal/database/ent/image_update.go +++ b/internal/database/ent/image_update.go @@ -29,6 +29,48 @@ func (iu *ImageUpdate) Where(ps ...predicate.Image) *ImageUpdate { return iu } +// SetWidth sets the "width" field. +func (iu *ImageUpdate) SetWidth(i int) *ImageUpdate { + iu.mutation.ResetWidth() + iu.mutation.SetWidth(i) + return iu +} + +// SetNillableWidth sets the "width" field if the given value is not nil. +func (iu *ImageUpdate) SetNillableWidth(i *int) *ImageUpdate { + if i != nil { + iu.SetWidth(*i) + } + return iu +} + +// AddWidth adds i to the "width" field. +func (iu *ImageUpdate) AddWidth(i int) *ImageUpdate { + iu.mutation.AddWidth(i) + return iu +} + +// SetHeight sets the "height" field. +func (iu *ImageUpdate) SetHeight(i int) *ImageUpdate { + iu.mutation.ResetHeight() + iu.mutation.SetHeight(i) + return iu +} + +// SetNillableHeight sets the "height" field if the given value is not nil. +func (iu *ImageUpdate) SetNillableHeight(i *int) *ImageUpdate { + if i != nil { + iu.SetHeight(*i) + } + return iu +} + +// AddHeight adds i to the "height" field. +func (iu *ImageUpdate) AddHeight(i int) *ImageUpdate { + iu.mutation.AddHeight(i) + return iu +} + // SetReviewID sets the "review" edge to the Review entity by ID. func (iu *ImageUpdate) SetReviewID(id uuid.UUID) *ImageUpdate { iu.mutation.SetReviewID(id) @@ -80,6 +122,16 @@ func (iu *ImageUpdate) ExecX(ctx context.Context) { // check runs all checks and user-defined validators on the builder. func (iu *ImageUpdate) check() error { + if v, ok := iu.mutation.Width(); ok { + if err := image.WidthValidator(v); err != nil { + return &ValidationError{Name: "width", err: fmt.Errorf(`ent: validator failed for field "Image.width": %w`, err)} + } + } + if v, ok := iu.mutation.Height(); ok { + if err := image.HeightValidator(v); err != nil { + return &ValidationError{Name: "height", err: fmt.Errorf(`ent: validator failed for field "Image.height": %w`, err)} + } + } if _, ok := iu.mutation.ReviewID(); iu.mutation.ReviewCleared() && !ok { return errors.New(`ent: clearing a required unique edge "Image.review"`) } @@ -98,6 +150,18 @@ func (iu *ImageUpdate) sqlSave(ctx context.Context) (n int, err error) { } } } + if value, ok := iu.mutation.Width(); ok { + _spec.SetField(image.FieldWidth, field.TypeInt, value) + } + if value, ok := iu.mutation.AddedWidth(); ok { + _spec.AddField(image.FieldWidth, field.TypeInt, value) + } + if value, ok := iu.mutation.Height(); ok { + _spec.SetField(image.FieldHeight, field.TypeInt, value) + } + if value, ok := iu.mutation.AddedHeight(); ok { + _spec.AddField(image.FieldHeight, field.TypeInt, value) + } if iu.mutation.ReviewCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, @@ -147,6 +211,48 @@ type ImageUpdateOne struct { mutation *ImageMutation } +// SetWidth sets the "width" field. +func (iuo *ImageUpdateOne) SetWidth(i int) *ImageUpdateOne { + iuo.mutation.ResetWidth() + iuo.mutation.SetWidth(i) + return iuo +} + +// SetNillableWidth sets the "width" field if the given value is not nil. +func (iuo *ImageUpdateOne) SetNillableWidth(i *int) *ImageUpdateOne { + if i != nil { + iuo.SetWidth(*i) + } + return iuo +} + +// AddWidth adds i to the "width" field. +func (iuo *ImageUpdateOne) AddWidth(i int) *ImageUpdateOne { + iuo.mutation.AddWidth(i) + return iuo +} + +// SetHeight sets the "height" field. +func (iuo *ImageUpdateOne) SetHeight(i int) *ImageUpdateOne { + iuo.mutation.ResetHeight() + iuo.mutation.SetHeight(i) + return iuo +} + +// SetNillableHeight sets the "height" field if the given value is not nil. +func (iuo *ImageUpdateOne) SetNillableHeight(i *int) *ImageUpdateOne { + if i != nil { + iuo.SetHeight(*i) + } + return iuo +} + +// AddHeight adds i to the "height" field. +func (iuo *ImageUpdateOne) AddHeight(i int) *ImageUpdateOne { + iuo.mutation.AddHeight(i) + return iuo +} + // SetReviewID sets the "review" edge to the Review entity by ID. func (iuo *ImageUpdateOne) SetReviewID(id uuid.UUID) *ImageUpdateOne { iuo.mutation.SetReviewID(id) @@ -211,6 +317,16 @@ func (iuo *ImageUpdateOne) ExecX(ctx context.Context) { // check runs all checks and user-defined validators on the builder. func (iuo *ImageUpdateOne) check() error { + if v, ok := iuo.mutation.Width(); ok { + if err := image.WidthValidator(v); err != nil { + return &ValidationError{Name: "width", err: fmt.Errorf(`ent: validator failed for field "Image.width": %w`, err)} + } + } + if v, ok := iuo.mutation.Height(); ok { + if err := image.HeightValidator(v); err != nil { + return &ValidationError{Name: "height", err: fmt.Errorf(`ent: validator failed for field "Image.height": %w`, err)} + } + } if _, ok := iuo.mutation.ReviewID(); iuo.mutation.ReviewCleared() && !ok { return errors.New(`ent: clearing a required unique edge "Image.review"`) } @@ -246,6 +362,18 @@ func (iuo *ImageUpdateOne) sqlSave(ctx context.Context) (_node *Image, err error } } } + if value, ok := iuo.mutation.Width(); ok { + _spec.SetField(image.FieldWidth, field.TypeInt, value) + } + if value, ok := iuo.mutation.AddedWidth(); ok { + _spec.AddField(image.FieldWidth, field.TypeInt, value) + } + if value, ok := iuo.mutation.Height(); ok { + _spec.SetField(image.FieldHeight, field.TypeInt, value) + } + if value, ok := iuo.mutation.AddedHeight(); ok { + _spec.AddField(image.FieldHeight, field.TypeInt, value) + } if iuo.mutation.ReviewCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, diff --git a/internal/database/ent/migrate/schema.go b/internal/database/ent/migrate/schema.go index 2f18fc5..488282a 100644 --- a/internal/database/ent/migrate/schema.go +++ b/internal/database/ent/migrate/schema.go @@ -44,6 +44,8 @@ var ( // ImageColumns holds the columns for the "image" table. ImageColumns = []*schema.Column{ {Name: "id", Type: field.TypeUUID}, + {Name: "width", Type: field.TypeInt}, + {Name: "height", Type: field.TypeInt}, {Name: "review", Type: field.TypeUUID}, } // ImageTable holds the schema information for the "image" table. @@ -54,7 +56,7 @@ var ( ForeignKeys: []*schema.ForeignKey{ { Symbol: "image_review_images", - Columns: []*schema.Column{ImageColumns[1]}, + Columns: []*schema.Column{ImageColumns[3]}, RefColumns: []*schema.Column{ReviewColumns[0]}, OnDelete: schema.Cascade, }, diff --git a/internal/database/ent/mutation.go b/internal/database/ent/mutation.go index 5c9cd71..bfe0652 100644 --- a/internal/database/ent/mutation.go +++ b/internal/database/ent/mutation.go @@ -1115,6 +1115,10 @@ type ImageMutation struct { op Op typ string id *uuid.UUID + width *int + addwidth *int + height *int + addheight *int clearedFields map[string]struct{} review *uuid.UUID clearedreview bool @@ -1227,6 +1231,118 @@ func (m *ImageMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { } } +// SetWidth sets the "width" field. +func (m *ImageMutation) SetWidth(i int) { + m.width = &i + m.addwidth = nil +} + +// Width returns the value of the "width" field in the mutation. +func (m *ImageMutation) Width() (r int, exists bool) { + v := m.width + if v == nil { + return + } + return *v, true +} + +// OldWidth returns the old "width" field's value of the Image entity. +// If the Image 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 *ImageMutation) OldWidth(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldWidth is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldWidth requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldWidth: %w", err) + } + return oldValue.Width, nil +} + +// AddWidth adds i to the "width" field. +func (m *ImageMutation) AddWidth(i int) { + if m.addwidth != nil { + *m.addwidth += i + } else { + m.addwidth = &i + } +} + +// AddedWidth returns the value that was added to the "width" field in this mutation. +func (m *ImageMutation) AddedWidth() (r int, exists bool) { + v := m.addwidth + if v == nil { + return + } + return *v, true +} + +// ResetWidth resets all changes to the "width" field. +func (m *ImageMutation) ResetWidth() { + m.width = nil + m.addwidth = nil +} + +// SetHeight sets the "height" field. +func (m *ImageMutation) SetHeight(i int) { + m.height = &i + m.addheight = nil +} + +// Height returns the value of the "height" field in the mutation. +func (m *ImageMutation) Height() (r int, exists bool) { + v := m.height + if v == nil { + return + } + return *v, true +} + +// OldHeight returns the old "height" field's value of the Image entity. +// If the Image 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 *ImageMutation) OldHeight(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldHeight is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldHeight requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldHeight: %w", err) + } + return oldValue.Height, nil +} + +// AddHeight adds i to the "height" field. +func (m *ImageMutation) AddHeight(i int) { + if m.addheight != nil { + *m.addheight += i + } else { + m.addheight = &i + } +} + +// AddedHeight returns the value that was added to the "height" field in this mutation. +func (m *ImageMutation) AddedHeight() (r int, exists bool) { + v := m.addheight + if v == nil { + return + } + return *v, true +} + +// ResetHeight resets all changes to the "height" field. +func (m *ImageMutation) ResetHeight() { + m.height = nil + m.addheight = nil +} + // SetReviewID sets the "review" edge to the Review entity by id. func (m *ImageMutation) SetReviewID(id uuid.UUID) { m.review = &id @@ -1300,7 +1416,13 @@ func (m *ImageMutation) Type() string { // order to get all numeric fields that were incremented/decremented, call // AddedFields(). func (m *ImageMutation) Fields() []string { - fields := make([]string, 0, 0) + fields := make([]string, 0, 2) + if m.width != nil { + fields = append(fields, image.FieldWidth) + } + if m.height != nil { + fields = append(fields, image.FieldHeight) + } return fields } @@ -1308,6 +1430,12 @@ func (m *ImageMutation) Fields() []string { // return value indicates that this field was not set, or was not defined in the // schema. func (m *ImageMutation) Field(name string) (ent.Value, bool) { + switch name { + case image.FieldWidth: + return m.Width() + case image.FieldHeight: + return m.Height() + } return nil, false } @@ -1315,6 +1443,12 @@ func (m *ImageMutation) Field(name string) (ent.Value, bool) { // returned if the mutation operation is not UpdateOne, or the query to the // database failed. func (m *ImageMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case image.FieldWidth: + return m.OldWidth(ctx) + case image.FieldHeight: + return m.OldHeight(ctx) + } return nil, fmt.Errorf("unknown Image field %s", name) } @@ -1323,6 +1457,20 @@ func (m *ImageMutation) OldField(ctx context.Context, name string) (ent.Value, e // type. func (m *ImageMutation) SetField(name string, value ent.Value) error { switch name { + case image.FieldWidth: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetWidth(v) + return nil + case image.FieldHeight: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetHeight(v) + return nil } return fmt.Errorf("unknown Image field %s", name) } @@ -1330,13 +1478,26 @@ func (m *ImageMutation) SetField(name string, value ent.Value) error { // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. func (m *ImageMutation) AddedFields() []string { - return nil + var fields []string + if m.addwidth != nil { + fields = append(fields, image.FieldWidth) + } + if m.addheight != nil { + fields = append(fields, image.FieldHeight) + } + return fields } // AddedField returns the numeric value that was incremented/decremented on a field // with the given name. The second boolean return value indicates that this field // was not set, or was not defined in the schema. func (m *ImageMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case image.FieldWidth: + return m.AddedWidth() + case image.FieldHeight: + return m.AddedHeight() + } return nil, false } @@ -1344,6 +1505,22 @@ func (m *ImageMutation) AddedField(name string) (ent.Value, bool) { // the field is not defined in the schema, or if the type mismatched the field // type. func (m *ImageMutation) AddField(name string, value ent.Value) error { + switch name { + case image.FieldWidth: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddWidth(v) + return nil + case image.FieldHeight: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddHeight(v) + return nil + } return fmt.Errorf("unknown Image numeric field %s", name) } @@ -1369,6 +1546,14 @@ func (m *ImageMutation) ClearField(name string) error { // 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 *ImageMutation) ResetField(name string) error { + switch name { + case image.FieldWidth: + m.ResetWidth() + return nil + case image.FieldHeight: + m.ResetHeight() + return nil + } return fmt.Errorf("unknown Image field %s", name) } diff --git a/internal/database/ent/runtime.go b/internal/database/ent/runtime.go index d24f119..0ac9117 100644 --- a/internal/database/ent/runtime.go +++ b/internal/database/ent/runtime.go @@ -43,6 +43,14 @@ func init() { dishalias.NormalizedAliasNameValidator = dishaliasDescNormalizedAliasName.Validators[0].(func(string) error) imageFields := schema.Image{}.Fields() _ = imageFields + // imageDescWidth is the schema descriptor for width field. + imageDescWidth := imageFields[1].Descriptor() + // image.WidthValidator is a validator for the "width" field. It is called by the builders before save. + image.WidthValidator = imageDescWidth.Validators[0].(func(int) error) + // imageDescHeight is the schema descriptor for height field. + imageDescHeight := imageFields[2].Descriptor() + // image.HeightValidator is a validator for the "height" field. It is called by the builders before save. + image.HeightValidator = imageDescHeight.Validators[0].(func(int) error) // imageDescID is the schema descriptor for id field. imageDescID := imageFields[0].Descriptor() // image.DefaultID holds the default value on creation for the id field. diff --git a/internal/database/migrations/20240614195816_add_image_dimensions.sql b/internal/database/migrations/20240614195816_add_image_dimensions.sql new file mode 100644 index 0000000..f44fa82 --- /dev/null +++ b/internal/database/migrations/20240614195816_add_image_dimensions.sql @@ -0,0 +1,2 @@ +-- Modify "image" table +ALTER TABLE "image" ADD COLUMN "width" bigint NOT NULL, ADD COLUMN "height" bigint NOT NULL; diff --git a/internal/database/migrations/atlas.sum b/internal/database/migrations/atlas.sum index aed62ca..2a999d2 100644 --- a/internal/database/migrations/atlas.sum +++ b/internal/database/migrations/atlas.sum @@ -1,3 +1,4 @@ -h1:ypzyeji9KQBdETJjweuCcw374RzxgkfE5YiJcDNKG3I= +h1:P9gL4/8NzeCC8A9H8HGlZuvWEzhqZou8KrMgxwtjukQ= 20231103235442_initial_database.sql h1:rXmCB2eMDP8LJVllwOgeBpNNXC5UyUBDx0T/gUx2Oyo= -20240202195658_remove_image_hash.sql h1:+BFA1oBL0vovKU2uQuekSNywDNH378zJ0m+BihOGn5o= +20240202195658_remove_image_hash.sql h1:NKp3hBH792xsGZvlkinuBnr44L9Bi9a0RS5CO+tIDE4= +20240614195816_add_image_dimensions.sql h1:CErHJ7Umz3qO3v0/EyxkvasRIp2zV042F/yaxozzh3w= diff --git a/internal/database/schema/image.go b/internal/database/schema/image.go index bd624d1..741f86e 100644 --- a/internal/database/schema/image.go +++ b/internal/database/schema/image.go @@ -25,6 +25,8 @@ func (Image) Annotations() []schema.Annotation { func (Image) Fields() []ent.Field { return []ent.Field{ field.UUID("id", uuid.UUID{}).Default(uuid.New).Immutable(), + field.Int("width").Positive(), + field.Int("height").Positive(), } } diff --git a/internal/graphql/gqlserver/generated.go b/internal/graphql/gqlserver/generated.go index 73ed7bd..c66009e 100644 --- a/internal/graphql/gqlserver/generated.go +++ b/internal/graphql/gqlserver/generated.go @@ -76,8 +76,10 @@ type ComplexityRoot struct { } Image struct { + Height func(childComplexity int) int ID func(childComplexity int) int Review func(childComplexity int) int + Width func(childComplexity int) int } Location struct { @@ -103,6 +105,7 @@ type ComplexityRoot struct { LoginUser func(childComplexity int, input models.LoginUserInput) int RemoveSideDishFromOccurrence func(childComplexity int, input models.RemoveSideDishFromOccurrenceInput) int RemoveTagFromOccurrence func(childComplexity int, input models.RemoveTagFromOccurrenceInput) int + UpdateDimensions func(childComplexity int, input models.UpdateDimensionsInput) int UpdateDish func(childComplexity int, input models.UpdateDishInput) int UpdateOccurrence func(childComplexity int, input models.UpdateOccurrenceInput) int UpdateReview func(childComplexity int, input models.UpdateReviewInput) int @@ -241,6 +244,7 @@ type MutationResolver interface { DeleteReview(ctx context.Context, input models.DeleteReviewInput) (*ent.Review, error) AddImagesToReview(ctx context.Context, input models.AddImagesToReviewInput) (*ent.Review, error) DeleteImagesFromReview(ctx context.Context, input models.DeleteImagesFromReviewInput) (*ent.Review, error) + UpdateDimensions(ctx context.Context, input models.UpdateDimensionsInput) (*ent.Image, error) } type OccurrenceResolver interface { Location(ctx context.Context, obj *ent.Occurrence) (*ent.Location, error) @@ -352,6 +356,13 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.DishAlias.NormalizedAliasName(childComplexity), true + case "Image.height": + if e.complexity.Image.Height == nil { + break + } + + return e.complexity.Image.Height(childComplexity), true + case "Image.id": if e.complexity.Image.ID == nil { break @@ -366,6 +377,13 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.Image.Review(childComplexity), true + case "Image.width": + if e.complexity.Image.Width == nil { + break + } + + return e.complexity.Image.Width(childComplexity), true + case "Location.externalId": if e.complexity.Location.ExternalID == nil { break @@ -574,6 +592,18 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.Mutation.RemoveTagFromOccurrence(childComplexity, args["input"].(models.RemoveTagFromOccurrenceInput)), true + case "Mutation.updateDimensions": + if e.complexity.Mutation.UpdateDimensions == nil { + break + } + + args, err := ec.field_Mutation_updateDimensions_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Mutation.UpdateDimensions(childComplexity, args["input"].(models.UpdateDimensionsInput)), true + case "Mutation.updateDish": if e.complexity.Mutation.UpdateDish == nil { break @@ -1104,6 +1134,7 @@ func (e *executableSchema) Exec(ctx context.Context) graphql.ResponseHandler { ec.unmarshalInputRemoveSideDishFromOccurrenceInput, ec.unmarshalInputRemoveTagFromOccurrenceInput, ec.unmarshalInputReviewFilter, + ec.unmarshalInputUpdateDimensionsInput, ec.unmarshalInputUpdateDishInput, ec.unmarshalInputUpdateOccurrenceInput, ec.unmarshalInputUpdateReviewInput, @@ -1412,6 +1443,12 @@ input DeleteImagesFromReviewInput { images: [UUID!]! } +input UpdateDimensionsInput { + id: UUID! + width: Int! + height: Int! +} + # Location @@ -1456,6 +1493,7 @@ input LocationFilter { # Image addImagesToReview(input: AddImagesToReviewInput!): Review! deleteImagesFromReview(input: DeleteImagesFromReviewInput!): Review! + updateDimensions(input: UpdateDimensionsInput!): Image! @authenticated } `, BuiltIn: false}, {Name: "../schema/queries.graphql", Input: `type Query { @@ -1606,6 +1644,8 @@ type Review { type Image { id: UUID! review: Review! + width: Int! + height: Int! } type User { @@ -1866,6 +1906,21 @@ func (ec *executionContext) field_Mutation_removeTagFromOccurrence_args(ctx cont return args, nil } +func (ec *executionContext) field_Mutation_updateDimensions_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { + var err error + args := map[string]interface{}{} + var arg0 models.UpdateDimensionsInput + if tmp, ok := rawArgs["input"]; ok { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("input")) + arg0, err = ec.unmarshalNUpdateDimensionsInput2githubᚗcomᚋmensattᚋbackendᚋinternalᚋgraphqlᚋmodelsᚐUpdateDimensionsInput(ctx, tmp) + if err != nil { + return nil, err + } + } + args["input"] = arg0 + return args, nil +} + func (ec *executionContext) field_Mutation_updateDish_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { var err error args := map[string]interface{}{} @@ -2535,6 +2590,94 @@ func (ec *executionContext) fieldContext_Image_review(_ context.Context, field g return fc, nil } +func (ec *executionContext) _Image_width(ctx context.Context, field graphql.CollectedField, obj *ent.Image) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Image_width(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Width, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalNInt2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Image_width(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Image", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Int does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Image_height(ctx context.Context, field graphql.CollectedField, obj *ent.Image) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Image_height(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Height, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalNInt2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Image_height(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Image", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Int does not have child fields") + }, + } + return fc, nil +} + func (ec *executionContext) _Location_id(ctx context.Context, field graphql.CollectedField, obj *ent.Location) (ret graphql.Marshaler) { fc, err := ec.fieldContext_Location_id(ctx, field) if err != nil { @@ -4285,6 +4428,91 @@ func (ec *executionContext) fieldContext_Mutation_deleteImagesFromReview(ctx con return fc, nil } +func (ec *executionContext) _Mutation_updateDimensions(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Mutation_updateDimensions(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + directive0 := func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return ec.resolvers.Mutation().UpdateDimensions(rctx, fc.Args["input"].(models.UpdateDimensionsInput)) + } + directive1 := func(ctx context.Context) (interface{}, error) { + if ec.directives.Authenticated == nil { + return nil, errors.New("directive authenticated is not implemented") + } + return ec.directives.Authenticated(ctx, nil, directive0) + } + + tmp, err := directive1(rctx) + if err != nil { + return nil, graphql.ErrorOnPath(ctx, err) + } + if tmp == nil { + return nil, nil + } + if data, ok := tmp.(*ent.Image); ok { + return data, nil + } + return nil, fmt.Errorf(`unexpected type %T from directive, should be *github.com/mensatt/backend/internal/database/ent.Image`, tmp) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*ent.Image) + fc.Result = res + return ec.marshalNImage2ᚖgithubᚗcomᚋmensattᚋbackendᚋinternalᚋdatabaseᚋentᚐImage(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Mutation_updateDimensions(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_Image_id(ctx, field) + case "review": + return ec.fieldContext_Image_review(ctx, field) + case "width": + return ec.fieldContext_Image_width(ctx, field) + case "height": + return ec.fieldContext_Image_height(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type Image", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_updateDimensions_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + func (ec *executionContext) _Occurrence_id(ctx context.Context, field graphql.CollectedField, obj *ent.Occurrence) (ret graphql.Marshaler) { fc, err := ec.fieldContext_Occurrence_id(ctx, field) if err != nil { @@ -6280,6 +6508,10 @@ func (ec *executionContext) fieldContext_Review_images(_ context.Context, field return ec.fieldContext_Image_id(ctx, field) case "review": return ec.fieldContext_Image_review(ctx, field) + case "width": + return ec.fieldContext_Image_width(ctx, field) + case "height": + return ec.fieldContext_Image_height(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type Image", field.Name) }, @@ -6608,6 +6840,10 @@ func (ec *executionContext) fieldContext_ReviewDataDish_images(_ context.Context return ec.fieldContext_Image_id(ctx, field) case "review": return ec.fieldContext_Image_review(ctx, field) + case "width": + return ec.fieldContext_Image_width(ctx, field) + case "height": + return ec.fieldContext_Image_height(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type Image", field.Name) }, @@ -6772,6 +7008,10 @@ func (ec *executionContext) fieldContext_ReviewDataOccurrence_images(_ context.C return ec.fieldContext_Image_id(ctx, field) case "review": return ec.fieldContext_Image_review(ctx, field) + case "width": + return ec.fieldContext_Image_width(ctx, field) + case "height": + return ec.fieldContext_Image_height(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type Image", field.Name) }, @@ -10258,6 +10498,47 @@ func (ec *executionContext) unmarshalInputReviewFilter(ctx context.Context, obj return it, nil } +func (ec *executionContext) unmarshalInputUpdateDimensionsInput(ctx context.Context, obj interface{}) (models.UpdateDimensionsInput, error) { + var it models.UpdateDimensionsInput + asMap := map[string]interface{}{} + for k, v := range obj.(map[string]interface{}) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"id", "width", "height"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "id": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) + data, err := ec.unmarshalNUUID2githubᚗcomᚋgoogleᚋuuidᚐUUID(ctx, v) + if err != nil { + return it, err + } + it.ID = data + case "width": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("width")) + data, err := ec.unmarshalNInt2int(ctx, v) + if err != nil { + return it, err + } + it.Width = data + case "height": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("height")) + data, err := ec.unmarshalNInt2int(ctx, v) + if err != nil { + return it, err + } + it.Height = data + } + } + + return it, nil +} + func (ec *executionContext) unmarshalInputUpdateDishInput(ctx context.Context, obj interface{}) (models.UpdateDishInput, error) { var it models.UpdateDishInput asMap := map[string]interface{}{} @@ -10775,6 +11056,16 @@ func (ec *executionContext) _Image(ctx context.Context, sel ast.SelectionSet, ob } out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + case "width": + out.Values[i] = ec._Image_width(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "height": + out.Values[i] = ec._Image_height(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } default: panic("unknown field " + strconv.Quote(field.Name)) } @@ -10997,6 +11288,13 @@ func (ec *executionContext) _Mutation(ctx context.Context, sel ast.SelectionSet) if out.Values[i] == graphql.Null { out.Invalids++ } + case "updateDimensions": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_updateDimensions(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ + } default: panic("unknown field " + strconv.Quote(field.Name)) } @@ -12607,6 +12905,10 @@ func (ec *executionContext) marshalNDishAlias2ᚖgithubᚗcomᚋmensattᚋbacken return ec._DishAlias(ctx, sel, v) } +func (ec *executionContext) marshalNImage2githubᚗcomᚋmensattᚋbackendᚋinternalᚋdatabaseᚋentᚐImage(ctx context.Context, sel ast.SelectionSet, v ent.Image) graphql.Marshaler { + return ec._Image(ctx, sel, &v) +} + func (ec *executionContext) marshalNImage2ᚕᚖgithubᚗcomᚋmensattᚋbackendᚋinternalᚋdatabaseᚋentᚐImageᚄ(ctx context.Context, sel ast.SelectionSet, v []*ent.Image) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup @@ -13114,6 +13416,11 @@ func (ec *executionContext) marshalNUUID2ᚕgithubᚗcomᚋgoogleᚋuuidᚐUUID return ret } +func (ec *executionContext) unmarshalNUpdateDimensionsInput2githubᚗcomᚋmensattᚋbackendᚋinternalᚋgraphqlᚋmodelsᚐUpdateDimensionsInput(ctx context.Context, v interface{}) (models.UpdateDimensionsInput, error) { + res, err := ec.unmarshalInputUpdateDimensionsInput(ctx, v) + return res, graphql.ErrorOnPath(ctx, err) +} + func (ec *executionContext) unmarshalNUpdateDishInput2githubᚗcomᚋmensattᚋbackendᚋinternalᚋgraphqlᚋmodelsᚐUpdateDishInput(ctx context.Context, v interface{}) (models.UpdateDishInput, error) { res, err := ec.unmarshalInputUpdateDishInput(ctx, v) return res, graphql.ErrorOnPath(ctx, err) diff --git a/internal/graphql/models/generated.go b/internal/graphql/models/generated.go index 045fba4..9680482 100644 --- a/internal/graphql/models/generated.go +++ b/internal/graphql/models/generated.go @@ -170,6 +170,12 @@ type ReviewMetadataOccurrence struct { type Subscription struct { } +type UpdateDimensionsInput struct { + ID uuid.UUID `json:"id"` + Width int `json:"width"` + Height int `json:"height"` +} + type UpdateDishInput struct { ID uuid.UUID `json:"id"` NameDe *string `json:"nameDe,omitempty"` diff --git a/internal/graphql/resolvers/mutations.resolvers.go b/internal/graphql/resolvers/mutations.resolvers.go index fc549b5..8bef9b4 100644 --- a/internal/graphql/resolvers/mutations.resolvers.go +++ b/internal/graphql/resolvers/mutations.resolvers.go @@ -562,6 +562,8 @@ func (r *mutationResolver) AddImagesToReview(ctx context.Context, input models.A _, err := r.Database.Image.Create(). SetID(image). SetReviewID(review.ID). + SetWidth(0). // todo: read from image service + SetHeight(0). // todo: read from image service Save(ctx) if err != nil { continue // if one image fails to store, allow the remaining images to be stored @@ -598,6 +600,18 @@ func (r *mutationResolver) DeleteImagesFromReview(ctx context.Context, input mod return review, nil } +// UpdateDimensions is the resolver for the updateDimensions field. +func (r *mutationResolver) UpdateDimensions(ctx context.Context, input models.UpdateDimensionsInput) (*ent.Image, error) { + image, err := r.Database.Image.Get(ctx, input.ID) + if err != nil { + return nil, err + } + + queryBuilder := r.Database.Image.UpdateOne(image).SetHeight(input.Height).SetWidth(input.Width) + + return queryBuilder.Save(ctx) +} + // Mutation returns gqlserver.MutationResolver implementation. func (r *Resolver) Mutation() gqlserver.MutationResolver { return &mutationResolver{r} } diff --git a/internal/graphql/schema/inputs.graphql b/internal/graphql/schema/inputs.graphql index 75f1ccd..0ecc99c 100644 --- a/internal/graphql/schema/inputs.graphql +++ b/internal/graphql/schema/inputs.graphql @@ -173,6 +173,12 @@ input DeleteImagesFromReviewInput { images: [UUID!]! } +input UpdateDimensionsInput { + id: UUID! + width: Int! + height: Int! +} + # Location diff --git a/internal/graphql/schema/mutations.graphql b/internal/graphql/schema/mutations.graphql index 6c2b746..c2b2199 100644 --- a/internal/graphql/schema/mutations.graphql +++ b/internal/graphql/schema/mutations.graphql @@ -32,4 +32,5 @@ type Mutation { # Image addImagesToReview(input: AddImagesToReviewInput!): Review! deleteImagesFromReview(input: DeleteImagesFromReviewInput!): Review! + updateDimensions(input: UpdateDimensionsInput!): Image! @authenticated } diff --git a/internal/graphql/schema/types.graphql b/internal/graphql/schema/types.graphql index da7d2ae..8d303c9 100644 --- a/internal/graphql/schema/types.graphql +++ b/internal/graphql/schema/types.graphql @@ -105,6 +105,8 @@ type Review { type Image { id: UUID! review: Review! + width: Int! + height: Int! } type User {