diff --git a/Dockerfile b/Dockerfile index e1b879c..5419c31 100644 --- a/Dockerfile +++ b/Dockerfile @@ -13,7 +13,7 @@ RUN go mod download RUN go build . # Generate orm -RUN go generate ./ent +RUN go generate ./database/ent # Expose port 8080 for incoming traffic EXPOSE 4002 diff --git a/README.md b/README.md new file mode 100644 index 0000000..e0009ab --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +Portfolio project backend api \ No newline at end of file diff --git a/error-handlers.go b/api/handler/errorHandlers.go similarity index 96% rename from error-handlers.go rename to api/handler/errorHandlers.go index b3d2098..a198e59 100644 --- a/error-handlers.go +++ b/api/handler/errorHandlers.go @@ -1,4 +1,4 @@ -package main +package handler import "net/http" diff --git a/api/handler/mainHandler.go b/api/handler/mainHandler.go new file mode 100644 index 0000000..8bd2cab --- /dev/null +++ b/api/handler/mainHandler.go @@ -0,0 +1,27 @@ +package handler + +import ( + "net/http" +) + +func CatchAllHandler(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusGone) + _, err := w.Write([]byte("Bad endpoint")) + if err != nil { + InternalServerErrorHandler(w, r) + } +} + +func TestHandler(w http.ResponseWriter, r *http.Request) { + _, err := w.Write([]byte("test")) + if err != nil { + InternalServerErrorHandler(w, r) + } +} + +func Test2Handler(w http.ResponseWriter, r *http.Request) { + _, err := w.Write([]byte("test2")) + if err != nil { + InternalServerErrorHandler(w, r) + } +} diff --git a/api/handler/projectHandler.go b/api/handler/projectHandler.go new file mode 100644 index 0000000..abeebd1 --- /dev/null +++ b/api/handler/projectHandler.go @@ -0,0 +1 @@ +package handler diff --git a/api/handler/userHandler.go b/api/handler/userHandler.go new file mode 100644 index 0000000..abeebd1 --- /dev/null +++ b/api/handler/userHandler.go @@ -0,0 +1 @@ +package handler diff --git a/DB.go b/database/database.go similarity index 90% rename from DB.go rename to database/database.go index aad15e9..66da877 100644 --- a/DB.go +++ b/database/database.go @@ -1,11 +1,11 @@ -package main +package database import ( "context" "github.com/joho/godotenv" "log" "os" - "portfolio-backend/ent" + "portfolio-backend/database/ent" _ "github.com/go-sql-driver/mysql" ) diff --git a/ent/client.go b/database/ent/client.go similarity index 93% rename from ent/client.go rename to database/ent/client.go index 751dbb2..45a4b11 100644 --- a/ent/client.go +++ b/database/ent/client.go @@ -9,11 +9,11 @@ import ( "log" "reflect" - "portfolio-backend/ent/migrate" + "portfolio-backend/database/ent/migrate" - "portfolio-backend/ent/project" - "portfolio-backend/ent/team" - "portfolio-backend/ent/user" + "portfolio-backend/database/ent/project" + "portfolio-backend/database/ent/team" + "portfolio-backend/database/ent/user" "entgo.io/ent" "entgo.io/ent/dialect" @@ -475,15 +475,31 @@ func (c *TeamClient) GetX(ctx context.Context, id int) *Team { return obj } -// QueryProjects queries the projects edge of a Team. -func (c *TeamClient) QueryProjects(t *Team) *ProjectQuery { +// QueryProject queries the project edge of a Team. +func (c *TeamClient) QueryProject(t *Team) *ProjectQuery { query := (&ProjectClient{config: c.config}).Query() query.path = func(context.Context) (fromV *sql.Selector, _ error) { id := t.ID step := sqlgraph.NewStep( sqlgraph.From(team.Table, team.FieldID, id), sqlgraph.To(project.Table, project.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, team.ProjectsTable, team.ProjectsColumn), + sqlgraph.Edge(sqlgraph.O2M, false, team.ProjectTable, team.ProjectColumn), + ) + fromV = sqlgraph.Neighbors(t.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryUsers queries the users edge of a Team. +func (c *TeamClient) QueryUsers(t *Team) *UserQuery { + query := (&UserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := t.ID + step := sqlgraph.NewStep( + sqlgraph.From(team.Table, team.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, team.UsersTable, team.UsersPrimaryKey...), ) fromV = sqlgraph.Neighbors(t.driver.Dialect(), step) return fromV, nil @@ -624,6 +640,22 @@ func (c *UserClient) GetX(ctx context.Context, id int) *User { return obj } +// QueryTeams queries the teams edge of a User. +func (c *UserClient) QueryTeams(u *User) *TeamQuery { + query := (&TeamClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := u.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(team.Table, team.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, user.TeamsTable, user.TeamsPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) + return fromV, nil + } + return query +} + // Hooks returns the client hooks. func (c *UserClient) Hooks() []Hook { return c.hooks.User diff --git a/ent/ent.go b/database/ent/ent.go similarity index 99% rename from ent/ent.go rename to database/ent/ent.go index b1f3384..eb6f3ca 100644 --- a/ent/ent.go +++ b/database/ent/ent.go @@ -6,9 +6,9 @@ import ( "context" "errors" "fmt" - "portfolio-backend/ent/project" - "portfolio-backend/ent/team" - "portfolio-backend/ent/user" + "portfolio-backend/database/ent/project" + "portfolio-backend/database/ent/team" + "portfolio-backend/database/ent/user" "reflect" "sync" diff --git a/ent/enttest/enttest.go b/database/ent/enttest/enttest.go similarity index 93% rename from ent/enttest/enttest.go rename to database/ent/enttest/enttest.go index 7416652..8aea551 100644 --- a/ent/enttest/enttest.go +++ b/database/ent/enttest/enttest.go @@ -4,11 +4,11 @@ package enttest import ( "context" - "portfolio-backend/ent" + "portfolio-backend/database/ent" // required by schema hooks. - _ "portfolio-backend/ent/runtime" + _ "portfolio-backend/database/ent/runtime" - "portfolio-backend/ent/migrate" + "portfolio-backend/database/ent/migrate" "entgo.io/ent/dialect/sql/schema" ) diff --git a/ent/generate.go b/database/ent/generate.go similarity index 100% rename from ent/generate.go rename to database/ent/generate.go diff --git a/ent/hook/hook.go b/database/ent/hook/hook.go similarity index 99% rename from ent/hook/hook.go rename to database/ent/hook/hook.go index 85b89e3..56eaa66 100644 --- a/ent/hook/hook.go +++ b/database/ent/hook/hook.go @@ -5,7 +5,7 @@ package hook import ( "context" "fmt" - "portfolio-backend/ent" + "portfolio-backend/database/ent" ) // The ProjectFunc type is an adapter to allow the use of ordinary diff --git a/ent/migrate/migrate.go b/database/ent/migrate/migrate.go similarity index 100% rename from ent/migrate/migrate.go rename to database/ent/migrate/migrate.go diff --git a/ent/migrate/schema.go b/database/ent/migrate/schema.go similarity index 62% rename from ent/migrate/schema.go rename to database/ent/migrate/schema.go index 72ac67b..f0bd4f8 100644 --- a/ent/migrate/schema.go +++ b/database/ent/migrate/schema.go @@ -12,7 +12,7 @@ var ( ProjectsColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, {Name: "name", Type: field.TypeString, Unique: true}, - {Name: "team_projects", Type: field.TypeInt, Nullable: true}, + {Name: "team_project", Type: field.TypeInt, Nullable: true}, } // ProjectsTable holds the schema information for the "projects" table. ProjectsTable = &schema.Table{ @@ -21,7 +21,7 @@ var ( PrimaryKey: []*schema.Column{ProjectsColumns[0]}, ForeignKeys: []*schema.ForeignKey{ { - Symbol: "projects_teams_projects", + Symbol: "projects_teams_project", Columns: []*schema.Column{ProjectsColumns[2]}, RefColumns: []*schema.Column{TeamsColumns[0]}, OnDelete: schema.SetNull, @@ -51,14 +51,42 @@ var ( Columns: UsersColumns, PrimaryKey: []*schema.Column{UsersColumns[0]}, } + // UserTeamsColumns holds the columns for the "user_teams" table. + UserTeamsColumns = []*schema.Column{ + {Name: "user_id", Type: field.TypeInt}, + {Name: "team_id", Type: field.TypeInt}, + } + // UserTeamsTable holds the schema information for the "user_teams" table. + UserTeamsTable = &schema.Table{ + Name: "user_teams", + Columns: UserTeamsColumns, + PrimaryKey: []*schema.Column{UserTeamsColumns[0], UserTeamsColumns[1]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "user_teams_user_id", + Columns: []*schema.Column{UserTeamsColumns[0]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "user_teams_team_id", + Columns: []*schema.Column{UserTeamsColumns[1]}, + RefColumns: []*schema.Column{TeamsColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + } // Tables holds all the tables in the schema. Tables = []*schema.Table{ ProjectsTable, TeamsTable, UsersTable, + UserTeamsTable, } ) func init() { ProjectsTable.ForeignKeys[0].RefTable = TeamsTable + UserTeamsTable.ForeignKeys[0].RefTable = UsersTable + UserTeamsTable.ForeignKeys[1].RefTable = TeamsTable } diff --git a/ent/mutation.go b/database/ent/mutation.go similarity index 83% rename from ent/mutation.go rename to database/ent/mutation.go index c221aef..c2913e8 100644 --- a/ent/mutation.go +++ b/database/ent/mutation.go @@ -6,10 +6,10 @@ import ( "context" "errors" "fmt" - "portfolio-backend/ent/predicate" - "portfolio-backend/ent/project" - "portfolio-backend/ent/team" - "portfolio-backend/ent/user" + "portfolio-backend/database/ent/predicate" + "portfolio-backend/database/ent/project" + "portfolio-backend/database/ent/team" + "portfolio-backend/database/ent/user" "sync" "entgo.io/ent" @@ -426,17 +426,20 @@ func (m *ProjectMutation) ResetEdge(name string) error { // TeamMutation represents an operation that mutates the Team nodes in the graph. type TeamMutation struct { config - op Op - typ string - id *int - name *string - clearedFields map[string]struct{} - projects map[int]struct{} - removedprojects map[int]struct{} - clearedprojects bool - done bool - oldValue func(context.Context) (*Team, error) - predicates []predicate.Team + op Op + typ string + id *int + name *string + clearedFields map[string]struct{} + project map[int]struct{} + removedproject map[int]struct{} + clearedproject bool + users map[int]struct{} + removedusers map[int]struct{} + clearedusers bool + done bool + oldValue func(context.Context) (*Team, error) + predicates []predicate.Team } var _ ent.Mutation = (*TeamMutation)(nil) @@ -573,58 +576,112 @@ func (m *TeamMutation) ResetName() { m.name = nil } -// AddProjectIDs adds the "projects" edge to the Project entity by ids. +// AddProjectIDs adds the "project" edge to the Project entity by ids. func (m *TeamMutation) AddProjectIDs(ids ...int) { - if m.projects == nil { - m.projects = make(map[int]struct{}) + if m.project == nil { + m.project = make(map[int]struct{}) } for i := range ids { - m.projects[ids[i]] = struct{}{} + m.project[ids[i]] = struct{}{} } } -// ClearProjects clears the "projects" edge to the Project entity. -func (m *TeamMutation) ClearProjects() { - m.clearedprojects = true +// ClearProject clears the "project" edge to the Project entity. +func (m *TeamMutation) ClearProject() { + m.clearedproject = true } -// ProjectsCleared reports if the "projects" edge to the Project entity was cleared. -func (m *TeamMutation) ProjectsCleared() bool { - return m.clearedprojects +// ProjectCleared reports if the "project" edge to the Project entity was cleared. +func (m *TeamMutation) ProjectCleared() bool { + return m.clearedproject } -// RemoveProjectIDs removes the "projects" edge to the Project entity by IDs. +// RemoveProjectIDs removes the "project" edge to the Project entity by IDs. func (m *TeamMutation) RemoveProjectIDs(ids ...int) { - if m.removedprojects == nil { - m.removedprojects = make(map[int]struct{}) + if m.removedproject == nil { + m.removedproject = make(map[int]struct{}) } for i := range ids { - delete(m.projects, ids[i]) - m.removedprojects[ids[i]] = struct{}{} + delete(m.project, ids[i]) + m.removedproject[ids[i]] = struct{}{} } } -// RemovedProjects returns the removed IDs of the "projects" edge to the Project entity. -func (m *TeamMutation) RemovedProjectsIDs() (ids []int) { - for id := range m.removedprojects { +// RemovedProject returns the removed IDs of the "project" edge to the Project entity. +func (m *TeamMutation) RemovedProjectIDs() (ids []int) { + for id := range m.removedproject { ids = append(ids, id) } return } -// ProjectsIDs returns the "projects" edge IDs in the mutation. -func (m *TeamMutation) ProjectsIDs() (ids []int) { - for id := range m.projects { +// ProjectIDs returns the "project" edge IDs in the mutation. +func (m *TeamMutation) ProjectIDs() (ids []int) { + for id := range m.project { ids = append(ids, id) } return } -// ResetProjects resets all changes to the "projects" edge. -func (m *TeamMutation) ResetProjects() { - m.projects = nil - m.clearedprojects = false - m.removedprojects = nil +// ResetProject resets all changes to the "project" edge. +func (m *TeamMutation) ResetProject() { + m.project = nil + m.clearedproject = false + m.removedproject = nil +} + +// AddUserIDs adds the "users" edge to the User entity by ids. +func (m *TeamMutation) AddUserIDs(ids ...int) { + if m.users == nil { + m.users = make(map[int]struct{}) + } + for i := range ids { + m.users[ids[i]] = struct{}{} + } +} + +// ClearUsers clears the "users" edge to the User entity. +func (m *TeamMutation) ClearUsers() { + m.clearedusers = true +} + +// UsersCleared reports if the "users" edge to the User entity was cleared. +func (m *TeamMutation) UsersCleared() bool { + return m.clearedusers +} + +// RemoveUserIDs removes the "users" edge to the User entity by IDs. +func (m *TeamMutation) RemoveUserIDs(ids ...int) { + if m.removedusers == nil { + m.removedusers = make(map[int]struct{}) + } + for i := range ids { + delete(m.users, ids[i]) + m.removedusers[ids[i]] = struct{}{} + } +} + +// RemovedUsers returns the removed IDs of the "users" edge to the User entity. +func (m *TeamMutation) RemovedUsersIDs() (ids []int) { + for id := range m.removedusers { + ids = append(ids, id) + } + return +} + +// UsersIDs returns the "users" edge IDs in the mutation. +func (m *TeamMutation) UsersIDs() (ids []int) { + for id := range m.users { + ids = append(ids, id) + } + return +} + +// ResetUsers resets all changes to the "users" edge. +func (m *TeamMutation) ResetUsers() { + m.users = nil + m.clearedusers = false + m.removedusers = nil } // Where appends a list predicates to the TeamMutation builder. @@ -760,9 +817,12 @@ func (m *TeamMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *TeamMutation) AddedEdges() []string { - edges := make([]string, 0, 1) - if m.projects != nil { - edges = append(edges, team.EdgeProjects) + edges := make([]string, 0, 2) + if m.project != nil { + edges = append(edges, team.EdgeProject) + } + if m.users != nil { + edges = append(edges, team.EdgeUsers) } return edges } @@ -771,9 +831,15 @@ func (m *TeamMutation) AddedEdges() []string { // name in this mutation. func (m *TeamMutation) AddedIDs(name string) []ent.Value { switch name { - case team.EdgeProjects: - ids := make([]ent.Value, 0, len(m.projects)) - for id := range m.projects { + case team.EdgeProject: + ids := make([]ent.Value, 0, len(m.project)) + for id := range m.project { + ids = append(ids, id) + } + return ids + case team.EdgeUsers: + ids := make([]ent.Value, 0, len(m.users)) + for id := range m.users { ids = append(ids, id) } return ids @@ -783,9 +849,12 @@ func (m *TeamMutation) AddedIDs(name string) []ent.Value { // RemovedEdges returns all edge names that were removed in this mutation. func (m *TeamMutation) RemovedEdges() []string { - edges := make([]string, 0, 1) - if m.removedprojects != nil { - edges = append(edges, team.EdgeProjects) + edges := make([]string, 0, 2) + if m.removedproject != nil { + edges = append(edges, team.EdgeProject) + } + if m.removedusers != nil { + edges = append(edges, team.EdgeUsers) } return edges } @@ -794,9 +863,15 @@ func (m *TeamMutation) RemovedEdges() []string { // the given name in this mutation. func (m *TeamMutation) RemovedIDs(name string) []ent.Value { switch name { - case team.EdgeProjects: - ids := make([]ent.Value, 0, len(m.removedprojects)) - for id := range m.removedprojects { + case team.EdgeProject: + ids := make([]ent.Value, 0, len(m.removedproject)) + for id := range m.removedproject { + ids = append(ids, id) + } + return ids + case team.EdgeUsers: + ids := make([]ent.Value, 0, len(m.removedusers)) + for id := range m.removedusers { ids = append(ids, id) } return ids @@ -806,9 +881,12 @@ func (m *TeamMutation) RemovedIDs(name string) []ent.Value { // ClearedEdges returns all edge names that were cleared in this mutation. func (m *TeamMutation) ClearedEdges() []string { - edges := make([]string, 0, 1) - if m.clearedprojects { - edges = append(edges, team.EdgeProjects) + edges := make([]string, 0, 2) + if m.clearedproject { + edges = append(edges, team.EdgeProject) + } + if m.clearedusers { + edges = append(edges, team.EdgeUsers) } return edges } @@ -817,8 +895,10 @@ func (m *TeamMutation) ClearedEdges() []string { // was cleared in this mutation. func (m *TeamMutation) EdgeCleared(name string) bool { switch name { - case team.EdgeProjects: - return m.clearedprojects + case team.EdgeProject: + return m.clearedproject + case team.EdgeUsers: + return m.clearedusers } return false } @@ -835,8 +915,11 @@ func (m *TeamMutation) ClearEdge(name string) error { // It returns an error if the edge is not defined in the schema. func (m *TeamMutation) ResetEdge(name string) error { switch name { - case team.EdgeProjects: - m.ResetProjects() + case team.EdgeProject: + m.ResetProject() + return nil + case team.EdgeUsers: + m.ResetUsers() return nil } return fmt.Errorf("unknown Team edge %s", name) @@ -851,6 +934,9 @@ type UserMutation struct { name *string role *user.Role clearedFields map[string]struct{} + teams map[int]struct{} + removedteams map[int]struct{} + clearedteams bool done bool oldValue func(context.Context) (*User, error) predicates []predicate.User @@ -1026,6 +1112,60 @@ func (m *UserMutation) ResetRole() { m.role = nil } +// AddTeamIDs adds the "teams" edge to the Team entity by ids. +func (m *UserMutation) AddTeamIDs(ids ...int) { + if m.teams == nil { + m.teams = make(map[int]struct{}) + } + for i := range ids { + m.teams[ids[i]] = struct{}{} + } +} + +// ClearTeams clears the "teams" edge to the Team entity. +func (m *UserMutation) ClearTeams() { + m.clearedteams = true +} + +// TeamsCleared reports if the "teams" edge to the Team entity was cleared. +func (m *UserMutation) TeamsCleared() bool { + return m.clearedteams +} + +// RemoveTeamIDs removes the "teams" edge to the Team entity by IDs. +func (m *UserMutation) RemoveTeamIDs(ids ...int) { + if m.removedteams == nil { + m.removedteams = make(map[int]struct{}) + } + for i := range ids { + delete(m.teams, ids[i]) + m.removedteams[ids[i]] = struct{}{} + } +} + +// RemovedTeams returns the removed IDs of the "teams" edge to the Team entity. +func (m *UserMutation) RemovedTeamsIDs() (ids []int) { + for id := range m.removedteams { + ids = append(ids, id) + } + return +} + +// TeamsIDs returns the "teams" edge IDs in the mutation. +func (m *UserMutation) TeamsIDs() (ids []int) { + for id := range m.teams { + ids = append(ids, id) + } + return +} + +// ResetTeams resets all changes to the "teams" edge. +func (m *UserMutation) ResetTeams() { + m.teams = nil + m.clearedteams = false + m.removedteams = nil +} + // Where appends a list predicates to the UserMutation builder. func (m *UserMutation) Where(ps ...predicate.User) { m.predicates = append(m.predicates, ps...) @@ -1176,48 +1316,84 @@ func (m *UserMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *UserMutation) AddedEdges() []string { - edges := make([]string, 0, 0) + edges := make([]string, 0, 1) + if m.teams != nil { + edges = append(edges, user.EdgeTeams) + } return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. func (m *UserMutation) AddedIDs(name string) []ent.Value { + switch name { + case user.EdgeTeams: + ids := make([]ent.Value, 0, len(m.teams)) + for id := range m.teams { + ids = append(ids, id) + } + return ids + } return nil } // RemovedEdges returns all edge names that were removed in this mutation. func (m *UserMutation) RemovedEdges() []string { - edges := make([]string, 0, 0) + edges := make([]string, 0, 1) + if m.removedteams != nil { + edges = append(edges, user.EdgeTeams) + } return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. func (m *UserMutation) RemovedIDs(name string) []ent.Value { + switch name { + case user.EdgeTeams: + ids := make([]ent.Value, 0, len(m.removedteams)) + for id := range m.removedteams { + ids = append(ids, id) + } + return ids + } return nil } // ClearedEdges returns all edge names that were cleared in this mutation. func (m *UserMutation) ClearedEdges() []string { - edges := make([]string, 0, 0) + edges := make([]string, 0, 1) + if m.clearedteams { + edges = append(edges, user.EdgeTeams) + } return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. func (m *UserMutation) EdgeCleared(name string) bool { + switch name { + case user.EdgeTeams: + return m.clearedteams + } return false } // ClearEdge clears the value of the edge with the given name. It returns an error // if that edge is not defined in the schema. func (m *UserMutation) ClearEdge(name string) error { + switch name { + } return fmt.Errorf("unknown User unique edge %s", name) } // ResetEdge resets all changes to the edge with the given name in this mutation. // It returns an error if the edge is not defined in the schema. func (m *UserMutation) ResetEdge(name string) error { + switch name { + case user.EdgeTeams: + m.ResetTeams() + return nil + } return fmt.Errorf("unknown User edge %s", name) } diff --git a/ent/predicate/predicate.go b/database/ent/predicate/predicate.go similarity index 100% rename from ent/predicate/predicate.go rename to database/ent/predicate/predicate.go diff --git a/ent/project.go b/database/ent/project.go similarity index 93% rename from ent/project.go rename to database/ent/project.go index c8ae6d6..a9ca534 100644 --- a/ent/project.go +++ b/database/ent/project.go @@ -4,8 +4,8 @@ package ent import ( "fmt" - "portfolio-backend/ent/project" - "portfolio-backend/ent/team" + "portfolio-backend/database/ent/project" + "portfolio-backend/database/ent/team" "strings" "entgo.io/ent" @@ -21,9 +21,9 @@ type Project struct { Name string `json:"name,omitempty"` // Edges holds the relations/edges for other nodes in the graph. // The values are being populated by the ProjectQuery when eager-loading is set. - Edges ProjectEdges `json:"edges"` - team_projects *int - selectValues sql.SelectValues + Edges ProjectEdges `json:"edges"` + team_project *int + selectValues sql.SelectValues } // ProjectEdges holds the relations/edges for other nodes in the graph. @@ -57,7 +57,7 @@ func (*Project) scanValues(columns []string) ([]any, error) { values[i] = new(sql.NullInt64) case project.FieldName: values[i] = new(sql.NullString) - case project.ForeignKeys[0]: // team_projects + case project.ForeignKeys[0]: // team_project values[i] = new(sql.NullInt64) default: values[i] = new(sql.UnknownType) @@ -88,10 +88,10 @@ func (pr *Project) assignValues(columns []string, values []any) error { } case project.ForeignKeys[0]: if value, ok := values[i].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for edge-field team_projects", value) + return fmt.Errorf("unexpected type %T for edge-field team_project", value) } else if value.Valid { - pr.team_projects = new(int) - *pr.team_projects = int(value.Int64) + pr.team_project = new(int) + *pr.team_project = int(value.Int64) } default: pr.selectValues.Set(columns[i], values[i]) diff --git a/ent/project/project.go b/database/ent/project/project.go similarity index 98% rename from ent/project/project.go rename to database/ent/project/project.go index 26b23a1..9d18f4f 100644 --- a/ent/project/project.go +++ b/database/ent/project/project.go @@ -24,7 +24,7 @@ const ( // It exists in this package in order to avoid circular dependency with the "team" package. TeamInverseTable = "teams" // TeamColumn is the table column denoting the team relation/edge. - TeamColumn = "team_projects" + TeamColumn = "team_project" ) // Columns holds all SQL columns for project fields. @@ -36,7 +36,7 @@ var Columns = []string{ // ForeignKeys holds the SQL foreign-keys that are owned by the "projects" // table and are not defined as standalone fields in the schema. var ForeignKeys = []string{ - "team_projects", + "team_project", } // ValidColumn reports if the column name is valid (part of the table columns). diff --git a/ent/project/where.go b/database/ent/project/where.go similarity index 99% rename from ent/project/where.go rename to database/ent/project/where.go index 46bf898..946fb3a 100644 --- a/ent/project/where.go +++ b/database/ent/project/where.go @@ -3,7 +3,7 @@ package project import ( - "portfolio-backend/ent/predicate" + "portfolio-backend/database/ent/predicate" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" diff --git a/ent/project_create.go b/database/ent/project_create.go similarity index 98% rename from ent/project_create.go rename to database/ent/project_create.go index ae55729..452be84 100644 --- a/ent/project_create.go +++ b/database/ent/project_create.go @@ -6,8 +6,8 @@ import ( "context" "errors" "fmt" - "portfolio-backend/ent/project" - "portfolio-backend/ent/team" + "portfolio-backend/database/ent/project" + "portfolio-backend/database/ent/team" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" @@ -126,7 +126,7 @@ func (pc *ProjectCreate) createSpec() (*Project, *sqlgraph.CreateSpec) { for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } - _node.team_projects = &nodes[0] + _node.team_project = &nodes[0] _spec.Edges = append(_spec.Edges, edge) } return _node, _spec diff --git a/ent/project_delete.go b/database/ent/project_delete.go similarity index 96% rename from ent/project_delete.go rename to database/ent/project_delete.go index dc6fbcc..80118ea 100644 --- a/ent/project_delete.go +++ b/database/ent/project_delete.go @@ -4,8 +4,8 @@ package ent import ( "context" - "portfolio-backend/ent/predicate" - "portfolio-backend/ent/project" + "portfolio-backend/database/ent/predicate" + "portfolio-backend/database/ent/project" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" diff --git a/ent/project_query.go b/database/ent/project_query.go similarity index 98% rename from ent/project_query.go rename to database/ent/project_query.go index a5df4ab..6a34782 100644 --- a/ent/project_query.go +++ b/database/ent/project_query.go @@ -6,9 +6,9 @@ import ( "context" "fmt" "math" - "portfolio-backend/ent/predicate" - "portfolio-backend/ent/project" - "portfolio-backend/ent/team" + "portfolio-backend/database/ent/predicate" + "portfolio-backend/database/ent/project" + "portfolio-backend/database/ent/team" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" @@ -412,10 +412,10 @@ func (pq *ProjectQuery) loadTeam(ctx context.Context, query *TeamQuery, nodes [] ids := make([]int, 0, len(nodes)) nodeids := make(map[int][]*Project) for i := range nodes { - if nodes[i].team_projects == nil { + if nodes[i].team_project == nil { continue } - fk := *nodes[i].team_projects + fk := *nodes[i].team_project if _, ok := nodeids[fk]; !ok { ids = append(ids, fk) } @@ -432,7 +432,7 @@ func (pq *ProjectQuery) loadTeam(ctx context.Context, query *TeamQuery, nodes [] for _, n := range neighbors { nodes, ok := nodeids[n.ID] if !ok { - return fmt.Errorf(`unexpected foreign-key "team_projects" returned %v`, n.ID) + return fmt.Errorf(`unexpected foreign-key "team_project" returned %v`, n.ID) } for i := range nodes { assign(nodes[i], n) diff --git a/ent/project_update.go b/database/ent/project_update.go similarity index 98% rename from ent/project_update.go rename to database/ent/project_update.go index c38d0fb..8f9690f 100644 --- a/ent/project_update.go +++ b/database/ent/project_update.go @@ -6,9 +6,9 @@ import ( "context" "errors" "fmt" - "portfolio-backend/ent/predicate" - "portfolio-backend/ent/project" - "portfolio-backend/ent/team" + "portfolio-backend/database/ent/predicate" + "portfolio-backend/database/ent/project" + "portfolio-backend/database/ent/team" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" diff --git a/ent/runtime.go b/database/ent/runtime.go similarity index 86% rename from ent/runtime.go rename to database/ent/runtime.go index b934a52..0a81043 100644 --- a/ent/runtime.go +++ b/database/ent/runtime.go @@ -3,8 +3,8 @@ package ent import ( - "portfolio-backend/ent/schema" - "portfolio-backend/ent/user" + "portfolio-backend/database/ent/schema" + "portfolio-backend/database/ent/user" ) // The init function reads all schema descriptors with runtime code diff --git a/ent/runtime/runtime.go b/database/ent/runtime/runtime.go similarity index 92% rename from ent/runtime/runtime.go rename to database/ent/runtime/runtime.go index 82dd458..a14c7ef 100644 --- a/ent/runtime/runtime.go +++ b/database/ent/runtime/runtime.go @@ -2,7 +2,7 @@ package runtime -// The schema-stitching logic is generated in portfolio-backend/ent/runtime.go +// The schema-stitching logic is generated in portfolio-backend/database/ent/runtime.go const ( Version = "v0.13.0" // Version of ent codegen. diff --git a/ent/schema/project.go b/database/ent/schema/project.go similarity index 95% rename from ent/schema/project.go rename to database/ent/schema/project.go index d291acf..c85bba2 100644 --- a/ent/schema/project.go +++ b/database/ent/schema/project.go @@ -23,7 +23,7 @@ func (Project) Fields() []ent.Field { func (Project) Edges() []ent.Edge { return []ent.Edge{ edge.From("team", Team.Type). - Ref("projects"). + Ref("project"). Unique(), } } diff --git a/ent/schema/team.go b/database/ent/schema/team.go similarity index 81% rename from ent/schema/team.go rename to database/ent/schema/team.go index 4ec2c58..24fa322 100644 --- a/ent/schema/team.go +++ b/database/ent/schema/team.go @@ -21,6 +21,8 @@ func (Team) Fields() []ent.Field { // Edges of the Team. func (Team) Edges() []ent.Edge { return []ent.Edge{ - edge.To("projects", Project.Type), + edge.To("project", Project.Type), + edge.From("users", User.Type). + Ref("teams"), } } diff --git a/ent/schema/user.go b/database/ent/schema/user.go similarity index 83% rename from ent/schema/user.go rename to database/ent/schema/user.go index 8686136..59a6b4e 100644 --- a/ent/schema/user.go +++ b/database/ent/schema/user.go @@ -2,6 +2,7 @@ package schema import ( "entgo.io/ent" + "entgo.io/ent/schema/edge" "entgo.io/ent/schema/field" ) @@ -22,5 +23,7 @@ func (User) Fields() []ent.Field { // Edges of the User. func (User) Edges() []ent.Edge { - return nil + return []ent.Edge{ + edge.To("teams", Team.Type), + } } diff --git a/ent/team.go b/database/ent/team.go similarity index 77% rename from ent/team.go rename to database/ent/team.go index 2347d28..98d7c00 100644 --- a/ent/team.go +++ b/database/ent/team.go @@ -4,7 +4,7 @@ package ent import ( "fmt" - "portfolio-backend/ent/team" + "portfolio-backend/database/ent/team" "strings" "entgo.io/ent" @@ -26,20 +26,31 @@ type Team struct { // TeamEdges holds the relations/edges for other nodes in the graph. type TeamEdges struct { - // Projects holds the value of the projects edge. - Projects []*Project `json:"projects,omitempty"` + // Project holds the value of the project edge. + Project []*Project `json:"project,omitempty"` + // Users holds the value of the users edge. + Users []*User `json:"users,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [1]bool + loadedTypes [2]bool } -// ProjectsOrErr returns the Projects value or an error if the edge +// ProjectOrErr returns the Project value or an error if the edge // was not loaded in eager-loading. -func (e TeamEdges) ProjectsOrErr() ([]*Project, error) { +func (e TeamEdges) ProjectOrErr() ([]*Project, error) { if e.loadedTypes[0] { - return e.Projects, nil + return e.Project, nil } - return nil, &NotLoadedError{edge: "projects"} + return nil, &NotLoadedError{edge: "project"} +} + +// UsersOrErr returns the Users value or an error if the edge +// was not loaded in eager-loading. +func (e TeamEdges) UsersOrErr() ([]*User, error) { + if e.loadedTypes[1] { + return e.Users, nil + } + return nil, &NotLoadedError{edge: "users"} } // scanValues returns the types for scanning values from sql.Rows. @@ -91,9 +102,14 @@ func (t *Team) Value(name string) (ent.Value, error) { return t.selectValues.Get(name) } -// QueryProjects queries the "projects" edge of the Team entity. -func (t *Team) QueryProjects() *ProjectQuery { - return NewTeamClient(t.config).QueryProjects(t) +// QueryProject queries the "project" edge of the Team entity. +func (t *Team) QueryProject() *ProjectQuery { + return NewTeamClient(t.config).QueryProject(t) +} + +// QueryUsers queries the "users" edge of the Team entity. +func (t *Team) QueryUsers() *UserQuery { + return NewTeamClient(t.config).QueryUsers(t) } // Update returns a builder for updating this Team. diff --git a/database/ent/team/team.go b/database/ent/team/team.go new file mode 100644 index 0000000..f5b112e --- /dev/null +++ b/database/ent/team/team.go @@ -0,0 +1,112 @@ +// Code generated by ent, DO NOT EDIT. + +package team + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the team type in the database. + Label = "team" + // 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" + // EdgeProject holds the string denoting the project edge name in mutations. + EdgeProject = "project" + // EdgeUsers holds the string denoting the users edge name in mutations. + EdgeUsers = "users" + // Table holds the table name of the team in the database. + Table = "teams" + // ProjectTable is the table that holds the project relation/edge. + ProjectTable = "projects" + // ProjectInverseTable is the table name for the Project entity. + // It exists in this package in order to avoid circular dependency with the "project" package. + ProjectInverseTable = "projects" + // ProjectColumn is the table column denoting the project relation/edge. + ProjectColumn = "team_project" + // UsersTable is the table that holds the users relation/edge. The primary key declared below. + UsersTable = "user_teams" + // UsersInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + UsersInverseTable = "users" +) + +// Columns holds all SQL columns for team fields. +var Columns = []string{ + FieldID, + FieldName, +} + +var ( + // UsersPrimaryKey and UsersColumn2 are the table columns denoting the + // primary key for the users relation (M2M). + UsersPrimaryKey = []string{"user_id", "team_id"} +) + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +// OrderOption defines the ordering options for the Team 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() +} + +// ByProjectCount orders the results by project count. +func ByProjectCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newProjectStep(), opts...) + } +} + +// ByProject orders the results by project terms. +func ByProject(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newProjectStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByUsersCount orders the results by users count. +func ByUsersCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newUsersStep(), opts...) + } +} + +// ByUsers orders the results by users terms. +func ByUsers(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUsersStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newProjectStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ProjectInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ProjectTable, ProjectColumn), + ) +} +func newUsersStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UsersInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, UsersTable, UsersPrimaryKey...), + ) +} diff --git a/ent/team/where.go b/database/ent/team/where.go similarity index 80% rename from ent/team/where.go rename to database/ent/team/where.go index 0b00e50..7932f1f 100644 --- a/ent/team/where.go +++ b/database/ent/team/where.go @@ -3,7 +3,7 @@ package team import ( - "portfolio-backend/ent/predicate" + "portfolio-backend/database/ent/predicate" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" @@ -124,21 +124,44 @@ func NameContainsFold(v string) predicate.Team { return predicate.Team(sql.FieldContainsFold(FieldName, v)) } -// HasProjects applies the HasEdge predicate on the "projects" edge. -func HasProjects() predicate.Team { +// HasProject applies the HasEdge predicate on the "project" edge. +func HasProject() predicate.Team { return predicate.Team(func(s *sql.Selector) { step := sqlgraph.NewStep( sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, ProjectsTable, ProjectsColumn), + sqlgraph.Edge(sqlgraph.O2M, false, ProjectTable, ProjectColumn), ) sqlgraph.HasNeighbors(s, step) }) } -// HasProjectsWith applies the HasEdge predicate on the "projects" edge with a given conditions (other predicates). -func HasProjectsWith(preds ...predicate.Project) predicate.Team { +// HasProjectWith applies the HasEdge predicate on the "project" edge with a given conditions (other predicates). +func HasProjectWith(preds ...predicate.Project) predicate.Team { return predicate.Team(func(s *sql.Selector) { - step := newProjectsStep() + step := newProjectStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasUsers applies the HasEdge predicate on the "users" edge. +func HasUsers() predicate.Team { + return predicate.Team(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, UsersTable, UsersPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUsersWith applies the HasEdge predicate on the "users" edge with a given conditions (other predicates). +func HasUsersWith(preds ...predicate.User) predicate.Team { + return predicate.Team(func(s *sql.Selector) { + step := newUsersStep() sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { for _, p := range preds { p(s) diff --git a/ent/team_create.go b/database/ent/team_create.go similarity index 80% rename from ent/team_create.go rename to database/ent/team_create.go index bc46b7c..4b78967 100644 --- a/ent/team_create.go +++ b/database/ent/team_create.go @@ -6,8 +6,9 @@ import ( "context" "errors" "fmt" - "portfolio-backend/ent/project" - "portfolio-backend/ent/team" + "portfolio-backend/database/ent/project" + "portfolio-backend/database/ent/team" + "portfolio-backend/database/ent/user" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" @@ -26,14 +27,14 @@ func (tc *TeamCreate) SetName(s string) *TeamCreate { return tc } -// AddProjectIDs adds the "projects" edge to the Project entity by IDs. +// AddProjectIDs adds the "project" edge to the Project entity by IDs. func (tc *TeamCreate) AddProjectIDs(ids ...int) *TeamCreate { tc.mutation.AddProjectIDs(ids...) return tc } -// AddProjects adds the "projects" edges to the Project entity. -func (tc *TeamCreate) AddProjects(p ...*Project) *TeamCreate { +// AddProject adds the "project" edges to the Project entity. +func (tc *TeamCreate) AddProject(p ...*Project) *TeamCreate { ids := make([]int, len(p)) for i := range p { ids[i] = p[i].ID @@ -41,6 +42,21 @@ func (tc *TeamCreate) AddProjects(p ...*Project) *TeamCreate { return tc.AddProjectIDs(ids...) } +// AddUserIDs adds the "users" edge to the User entity by IDs. +func (tc *TeamCreate) AddUserIDs(ids ...int) *TeamCreate { + tc.mutation.AddUserIDs(ids...) + return tc +} + +// AddUsers adds the "users" edges to the User entity. +func (tc *TeamCreate) AddUsers(u ...*User) *TeamCreate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return tc.AddUserIDs(ids...) +} + // Mutation returns the TeamMutation object of the builder. func (tc *TeamCreate) Mutation() *TeamMutation { return tc.mutation @@ -108,12 +124,12 @@ func (tc *TeamCreate) createSpec() (*Team, *sqlgraph.CreateSpec) { _spec.SetField(team.FieldName, field.TypeString, value) _node.Name = value } - if nodes := tc.mutation.ProjectsIDs(); len(nodes) > 0 { + if nodes := tc.mutation.ProjectIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, Inverse: false, - Table: team.ProjectsTable, - Columns: []string{team.ProjectsColumn}, + Table: team.ProjectTable, + Columns: []string{team.ProjectColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: sqlgraph.NewFieldSpec(project.FieldID, field.TypeInt), @@ -124,6 +140,22 @@ func (tc *TeamCreate) createSpec() (*Team, *sqlgraph.CreateSpec) { } _spec.Edges = append(_spec.Edges, edge) } + if nodes := tc.mutation.UsersIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: team.UsersTable, + Columns: team.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } return _node, _spec } diff --git a/ent/team_delete.go b/database/ent/team_delete.go similarity index 96% rename from ent/team_delete.go rename to database/ent/team_delete.go index 1c0f4f3..190572b 100644 --- a/ent/team_delete.go +++ b/database/ent/team_delete.go @@ -4,8 +4,8 @@ package ent import ( "context" - "portfolio-backend/ent/predicate" - "portfolio-backend/ent/team" + "portfolio-backend/database/ent/predicate" + "portfolio-backend/database/ent/team" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" diff --git a/ent/team_query.go b/database/ent/team_query.go similarity index 75% rename from ent/team_query.go rename to database/ent/team_query.go index 42d730b..21406fa 100644 --- a/ent/team_query.go +++ b/database/ent/team_query.go @@ -7,9 +7,10 @@ import ( "database/sql/driver" "fmt" "math" - "portfolio-backend/ent/predicate" - "portfolio-backend/ent/project" - "portfolio-backend/ent/team" + "portfolio-backend/database/ent/predicate" + "portfolio-backend/database/ent/project" + "portfolio-backend/database/ent/team" + "portfolio-backend/database/ent/user" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" @@ -19,11 +20,12 @@ import ( // TeamQuery is the builder for querying Team entities. type TeamQuery struct { config - ctx *QueryContext - order []team.OrderOption - inters []Interceptor - predicates []predicate.Team - withProjects *ProjectQuery + ctx *QueryContext + order []team.OrderOption + inters []Interceptor + predicates []predicate.Team + withProject *ProjectQuery + withUsers *UserQuery // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -60,8 +62,8 @@ func (tq *TeamQuery) Order(o ...team.OrderOption) *TeamQuery { return tq } -// QueryProjects chains the current query on the "projects" edge. -func (tq *TeamQuery) QueryProjects() *ProjectQuery { +// QueryProject chains the current query on the "project" edge. +func (tq *TeamQuery) QueryProject() *ProjectQuery { query := (&ProjectClient{config: tq.config}).Query() query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { if err := tq.prepareQuery(ctx); err != nil { @@ -74,7 +76,29 @@ func (tq *TeamQuery) QueryProjects() *ProjectQuery { step := sqlgraph.NewStep( sqlgraph.From(team.Table, team.FieldID, selector), sqlgraph.To(project.Table, project.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, team.ProjectsTable, team.ProjectsColumn), + sqlgraph.Edge(sqlgraph.O2M, false, team.ProjectTable, team.ProjectColumn), + ) + fromU = sqlgraph.SetNeighbors(tq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryUsers chains the current query on the "users" edge. +func (tq *TeamQuery) QueryUsers() *UserQuery { + query := (&UserClient{config: tq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := tq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := tq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(team.Table, team.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, team.UsersTable, team.UsersPrimaryKey...), ) fromU = sqlgraph.SetNeighbors(tq.driver.Dialect(), step) return fromU, nil @@ -269,26 +293,38 @@ func (tq *TeamQuery) Clone() *TeamQuery { return nil } return &TeamQuery{ - config: tq.config, - ctx: tq.ctx.Clone(), - order: append([]team.OrderOption{}, tq.order...), - inters: append([]Interceptor{}, tq.inters...), - predicates: append([]predicate.Team{}, tq.predicates...), - withProjects: tq.withProjects.Clone(), + config: tq.config, + ctx: tq.ctx.Clone(), + order: append([]team.OrderOption{}, tq.order...), + inters: append([]Interceptor{}, tq.inters...), + predicates: append([]predicate.Team{}, tq.predicates...), + withProject: tq.withProject.Clone(), + withUsers: tq.withUsers.Clone(), // clone intermediate query. sql: tq.sql.Clone(), path: tq.path, } } -// WithProjects tells the query-builder to eager-load the nodes that are connected to -// the "projects" edge. The optional arguments are used to configure the query builder of the edge. -func (tq *TeamQuery) WithProjects(opts ...func(*ProjectQuery)) *TeamQuery { +// WithProject tells the query-builder to eager-load the nodes that are connected to +// the "project" edge. The optional arguments are used to configure the query builder of the edge. +func (tq *TeamQuery) WithProject(opts ...func(*ProjectQuery)) *TeamQuery { query := (&ProjectClient{config: tq.config}).Query() for _, opt := range opts { opt(query) } - tq.withProjects = query + tq.withProject = query + return tq +} + +// WithUsers tells the query-builder to eager-load the nodes that are connected to +// the "users" edge. The optional arguments are used to configure the query builder of the edge. +func (tq *TeamQuery) WithUsers(opts ...func(*UserQuery)) *TeamQuery { + query := (&UserClient{config: tq.config}).Query() + for _, opt := range opts { + opt(query) + } + tq.withUsers = query return tq } @@ -370,8 +406,9 @@ func (tq *TeamQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Team, e var ( nodes = []*Team{} _spec = tq.querySpec() - loadedTypes = [1]bool{ - tq.withProjects != nil, + loadedTypes = [2]bool{ + tq.withProject != nil, + tq.withUsers != nil, } ) _spec.ScanValues = func(columns []string) ([]any, error) { @@ -392,17 +429,24 @@ func (tq *TeamQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Team, e if len(nodes) == 0 { return nodes, nil } - if query := tq.withProjects; query != nil { - if err := tq.loadProjects(ctx, query, nodes, - func(n *Team) { n.Edges.Projects = []*Project{} }, - func(n *Team, e *Project) { n.Edges.Projects = append(n.Edges.Projects, e) }); err != nil { + if query := tq.withProject; query != nil { + if err := tq.loadProject(ctx, query, nodes, + func(n *Team) { n.Edges.Project = []*Project{} }, + func(n *Team, e *Project) { n.Edges.Project = append(n.Edges.Project, e) }); err != nil { + return nil, err + } + } + if query := tq.withUsers; query != nil { + if err := tq.loadUsers(ctx, query, nodes, + func(n *Team) { n.Edges.Users = []*User{} }, + func(n *Team, e *User) { n.Edges.Users = append(n.Edges.Users, e) }); err != nil { return nil, err } } return nodes, nil } -func (tq *TeamQuery) loadProjects(ctx context.Context, query *ProjectQuery, nodes []*Team, init func(*Team), assign func(*Team, *Project)) error { +func (tq *TeamQuery) loadProject(ctx context.Context, query *ProjectQuery, nodes []*Team, init func(*Team), assign func(*Team, *Project)) error { fks := make([]driver.Value, 0, len(nodes)) nodeids := make(map[int]*Team) for i := range nodes { @@ -414,25 +458,86 @@ func (tq *TeamQuery) loadProjects(ctx context.Context, query *ProjectQuery, node } query.withFKs = true query.Where(predicate.Project(func(s *sql.Selector) { - s.Where(sql.InValues(s.C(team.ProjectsColumn), fks...)) + s.Where(sql.InValues(s.C(team.ProjectColumn), fks...)) })) neighbors, err := query.All(ctx) if err != nil { return err } for _, n := range neighbors { - fk := n.team_projects + fk := n.team_project if fk == nil { - return fmt.Errorf(`foreign-key "team_projects" is nil for node %v`, n.ID) + return fmt.Errorf(`foreign-key "team_project" is nil for node %v`, n.ID) } node, ok := nodeids[*fk] if !ok { - return fmt.Errorf(`unexpected referenced foreign-key "team_projects" returned %v for node %v`, *fk, n.ID) + return fmt.Errorf(`unexpected referenced foreign-key "team_project" returned %v for node %v`, *fk, n.ID) } assign(node, n) } return nil } +func (tq *TeamQuery) loadUsers(ctx context.Context, query *UserQuery, nodes []*Team, init func(*Team), assign func(*Team, *User)) error { + edgeIDs := make([]driver.Value, len(nodes)) + byID := make(map[int]*Team) + nids := make(map[int]map[*Team]struct{}) + for i, node := range nodes { + edgeIDs[i] = node.ID + byID[node.ID] = node + if init != nil { + init(node) + } + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(team.UsersTable) + s.Join(joinT).On(s.C(user.FieldID), joinT.C(team.UsersPrimaryKey[0])) + s.Where(sql.InValues(joinT.C(team.UsersPrimaryKey[1]), edgeIDs...)) + columns := s.SelectedColumns() + s.Select(joinT.C(team.UsersPrimaryKey[1])) + s.AppendSelect(columns...) + s.SetDistinct(false) + }) + if err := query.prepareQuery(ctx); err != nil { + return err + } + qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) { + assign := spec.Assign + values := spec.ScanValues + spec.ScanValues = func(columns []string) ([]any, error) { + values, err := values(columns[1:]) + if err != nil { + return nil, err + } + return append([]any{new(sql.NullInt64)}, values...), nil + } + spec.Assign = func(columns []string, values []any) error { + outValue := int(values[0].(*sql.NullInt64).Int64) + inValue := int(values[1].(*sql.NullInt64).Int64) + if nids[inValue] == nil { + nids[inValue] = map[*Team]struct{}{byID[outValue]: {}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byID[outValue]] = struct{}{} + return nil + } + }) + }) + neighbors, err := withInterceptors[[]*User](ctx, query, qr, query.inters) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nids[n.ID] + if !ok { + return fmt.Errorf(`unexpected "users" node returned %v`, n.ID) + } + for kn := range nodes { + assign(kn, n) + } + } + return nil +} func (tq *TeamQuery) sqlCount(ctx context.Context) (int, error) { _spec := tq.querySpec() diff --git a/ent/team_update.go b/database/ent/team_update.go similarity index 56% rename from ent/team_update.go rename to database/ent/team_update.go index 319dc24..986d7f2 100644 --- a/ent/team_update.go +++ b/database/ent/team_update.go @@ -6,9 +6,10 @@ import ( "context" "errors" "fmt" - "portfolio-backend/ent/predicate" - "portfolio-backend/ent/project" - "portfolio-backend/ent/team" + "portfolio-backend/database/ent/predicate" + "portfolio-backend/database/ent/project" + "portfolio-backend/database/ent/team" + "portfolio-backend/database/ent/user" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" @@ -42,14 +43,14 @@ func (tu *TeamUpdate) SetNillableName(s *string) *TeamUpdate { return tu } -// AddProjectIDs adds the "projects" edge to the Project entity by IDs. +// AddProjectIDs adds the "project" edge to the Project entity by IDs. func (tu *TeamUpdate) AddProjectIDs(ids ...int) *TeamUpdate { tu.mutation.AddProjectIDs(ids...) return tu } -// AddProjects adds the "projects" edges to the Project entity. -func (tu *TeamUpdate) AddProjects(p ...*Project) *TeamUpdate { +// AddProject adds the "project" edges to the Project entity. +func (tu *TeamUpdate) AddProject(p ...*Project) *TeamUpdate { ids := make([]int, len(p)) for i := range p { ids[i] = p[i].ID @@ -57,25 +58,40 @@ func (tu *TeamUpdate) AddProjects(p ...*Project) *TeamUpdate { return tu.AddProjectIDs(ids...) } +// AddUserIDs adds the "users" edge to the User entity by IDs. +func (tu *TeamUpdate) AddUserIDs(ids ...int) *TeamUpdate { + tu.mutation.AddUserIDs(ids...) + return tu +} + +// AddUsers adds the "users" edges to the User entity. +func (tu *TeamUpdate) AddUsers(u ...*User) *TeamUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return tu.AddUserIDs(ids...) +} + // Mutation returns the TeamMutation object of the builder. func (tu *TeamUpdate) Mutation() *TeamMutation { return tu.mutation } -// ClearProjects clears all "projects" edges to the Project entity. -func (tu *TeamUpdate) ClearProjects() *TeamUpdate { - tu.mutation.ClearProjects() +// ClearProject clears all "project" edges to the Project entity. +func (tu *TeamUpdate) ClearProject() *TeamUpdate { + tu.mutation.ClearProject() return tu } -// RemoveProjectIDs removes the "projects" edge to Project entities by IDs. +// RemoveProjectIDs removes the "project" edge to Project entities by IDs. func (tu *TeamUpdate) RemoveProjectIDs(ids ...int) *TeamUpdate { tu.mutation.RemoveProjectIDs(ids...) return tu } -// RemoveProjects removes "projects" edges to Project entities. -func (tu *TeamUpdate) RemoveProjects(p ...*Project) *TeamUpdate { +// RemoveProject removes "project" edges to Project entities. +func (tu *TeamUpdate) RemoveProject(p ...*Project) *TeamUpdate { ids := make([]int, len(p)) for i := range p { ids[i] = p[i].ID @@ -83,6 +99,27 @@ func (tu *TeamUpdate) RemoveProjects(p ...*Project) *TeamUpdate { return tu.RemoveProjectIDs(ids...) } +// ClearUsers clears all "users" edges to the User entity. +func (tu *TeamUpdate) ClearUsers() *TeamUpdate { + tu.mutation.ClearUsers() + return tu +} + +// RemoveUserIDs removes the "users" edge to User entities by IDs. +func (tu *TeamUpdate) RemoveUserIDs(ids ...int) *TeamUpdate { + tu.mutation.RemoveUserIDs(ids...) + return tu +} + +// RemoveUsers removes "users" edges to User entities. +func (tu *TeamUpdate) RemoveUsers(u ...*User) *TeamUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return tu.RemoveUserIDs(ids...) +} + // Save executes the query and returns the number of nodes affected by the update operation. func (tu *TeamUpdate) Save(ctx context.Context) (int, error) { return withHooks(ctx, tu.sqlSave, tu.mutation, tu.hooks) @@ -122,12 +159,12 @@ func (tu *TeamUpdate) sqlSave(ctx context.Context) (n int, err error) { if value, ok := tu.mutation.Name(); ok { _spec.SetField(team.FieldName, field.TypeString, value) } - if tu.mutation.ProjectsCleared() { + if tu.mutation.ProjectCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, Inverse: false, - Table: team.ProjectsTable, - Columns: []string{team.ProjectsColumn}, + Table: team.ProjectTable, + Columns: []string{team.ProjectColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: sqlgraph.NewFieldSpec(project.FieldID, field.TypeInt), @@ -135,12 +172,12 @@ func (tu *TeamUpdate) sqlSave(ctx context.Context) (n int, err error) { } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) } - if nodes := tu.mutation.RemovedProjectsIDs(); len(nodes) > 0 && !tu.mutation.ProjectsCleared() { + if nodes := tu.mutation.RemovedProjectIDs(); len(nodes) > 0 && !tu.mutation.ProjectCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, Inverse: false, - Table: team.ProjectsTable, - Columns: []string{team.ProjectsColumn}, + Table: team.ProjectTable, + Columns: []string{team.ProjectColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: sqlgraph.NewFieldSpec(project.FieldID, field.TypeInt), @@ -151,12 +188,12 @@ func (tu *TeamUpdate) sqlSave(ctx context.Context) (n int, err error) { } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) } - if nodes := tu.mutation.ProjectsIDs(); len(nodes) > 0 { + if nodes := tu.mutation.ProjectIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, Inverse: false, - Table: team.ProjectsTable, - Columns: []string{team.ProjectsColumn}, + Table: team.ProjectTable, + Columns: []string{team.ProjectColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: sqlgraph.NewFieldSpec(project.FieldID, field.TypeInt), @@ -167,6 +204,51 @@ func (tu *TeamUpdate) sqlSave(ctx context.Context) (n int, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if tu.mutation.UsersCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: team.UsersTable, + Columns: team.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tu.mutation.RemovedUsersIDs(); len(nodes) > 0 && !tu.mutation.UsersCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: team.UsersTable, + Columns: team.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tu.mutation.UsersIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: team.UsersTable, + Columns: team.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if n, err = sqlgraph.UpdateNodes(ctx, tu.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{team.Label} @@ -201,14 +283,14 @@ func (tuo *TeamUpdateOne) SetNillableName(s *string) *TeamUpdateOne { return tuo } -// AddProjectIDs adds the "projects" edge to the Project entity by IDs. +// AddProjectIDs adds the "project" edge to the Project entity by IDs. func (tuo *TeamUpdateOne) AddProjectIDs(ids ...int) *TeamUpdateOne { tuo.mutation.AddProjectIDs(ids...) return tuo } -// AddProjects adds the "projects" edges to the Project entity. -func (tuo *TeamUpdateOne) AddProjects(p ...*Project) *TeamUpdateOne { +// AddProject adds the "project" edges to the Project entity. +func (tuo *TeamUpdateOne) AddProject(p ...*Project) *TeamUpdateOne { ids := make([]int, len(p)) for i := range p { ids[i] = p[i].ID @@ -216,25 +298,40 @@ func (tuo *TeamUpdateOne) AddProjects(p ...*Project) *TeamUpdateOne { return tuo.AddProjectIDs(ids...) } +// AddUserIDs adds the "users" edge to the User entity by IDs. +func (tuo *TeamUpdateOne) AddUserIDs(ids ...int) *TeamUpdateOne { + tuo.mutation.AddUserIDs(ids...) + return tuo +} + +// AddUsers adds the "users" edges to the User entity. +func (tuo *TeamUpdateOne) AddUsers(u ...*User) *TeamUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return tuo.AddUserIDs(ids...) +} + // Mutation returns the TeamMutation object of the builder. func (tuo *TeamUpdateOne) Mutation() *TeamMutation { return tuo.mutation } -// ClearProjects clears all "projects" edges to the Project entity. -func (tuo *TeamUpdateOne) ClearProjects() *TeamUpdateOne { - tuo.mutation.ClearProjects() +// ClearProject clears all "project" edges to the Project entity. +func (tuo *TeamUpdateOne) ClearProject() *TeamUpdateOne { + tuo.mutation.ClearProject() return tuo } -// RemoveProjectIDs removes the "projects" edge to Project entities by IDs. +// RemoveProjectIDs removes the "project" edge to Project entities by IDs. func (tuo *TeamUpdateOne) RemoveProjectIDs(ids ...int) *TeamUpdateOne { tuo.mutation.RemoveProjectIDs(ids...) return tuo } -// RemoveProjects removes "projects" edges to Project entities. -func (tuo *TeamUpdateOne) RemoveProjects(p ...*Project) *TeamUpdateOne { +// RemoveProject removes "project" edges to Project entities. +func (tuo *TeamUpdateOne) RemoveProject(p ...*Project) *TeamUpdateOne { ids := make([]int, len(p)) for i := range p { ids[i] = p[i].ID @@ -242,6 +339,27 @@ func (tuo *TeamUpdateOne) RemoveProjects(p ...*Project) *TeamUpdateOne { return tuo.RemoveProjectIDs(ids...) } +// ClearUsers clears all "users" edges to the User entity. +func (tuo *TeamUpdateOne) ClearUsers() *TeamUpdateOne { + tuo.mutation.ClearUsers() + return tuo +} + +// RemoveUserIDs removes the "users" edge to User entities by IDs. +func (tuo *TeamUpdateOne) RemoveUserIDs(ids ...int) *TeamUpdateOne { + tuo.mutation.RemoveUserIDs(ids...) + return tuo +} + +// RemoveUsers removes "users" edges to User entities. +func (tuo *TeamUpdateOne) RemoveUsers(u ...*User) *TeamUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return tuo.RemoveUserIDs(ids...) +} + // Where appends a list predicates to the TeamUpdate builder. func (tuo *TeamUpdateOne) Where(ps ...predicate.Team) *TeamUpdateOne { tuo.mutation.Where(ps...) @@ -311,12 +429,12 @@ func (tuo *TeamUpdateOne) sqlSave(ctx context.Context) (_node *Team, err error) if value, ok := tuo.mutation.Name(); ok { _spec.SetField(team.FieldName, field.TypeString, value) } - if tuo.mutation.ProjectsCleared() { + if tuo.mutation.ProjectCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, Inverse: false, - Table: team.ProjectsTable, - Columns: []string{team.ProjectsColumn}, + Table: team.ProjectTable, + Columns: []string{team.ProjectColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: sqlgraph.NewFieldSpec(project.FieldID, field.TypeInt), @@ -324,12 +442,12 @@ func (tuo *TeamUpdateOne) sqlSave(ctx context.Context) (_node *Team, err error) } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) } - if nodes := tuo.mutation.RemovedProjectsIDs(); len(nodes) > 0 && !tuo.mutation.ProjectsCleared() { + if nodes := tuo.mutation.RemovedProjectIDs(); len(nodes) > 0 && !tuo.mutation.ProjectCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, Inverse: false, - Table: team.ProjectsTable, - Columns: []string{team.ProjectsColumn}, + Table: team.ProjectTable, + Columns: []string{team.ProjectColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: sqlgraph.NewFieldSpec(project.FieldID, field.TypeInt), @@ -340,12 +458,12 @@ func (tuo *TeamUpdateOne) sqlSave(ctx context.Context) (_node *Team, err error) } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) } - if nodes := tuo.mutation.ProjectsIDs(); len(nodes) > 0 { + if nodes := tuo.mutation.ProjectIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, Inverse: false, - Table: team.ProjectsTable, - Columns: []string{team.ProjectsColumn}, + Table: team.ProjectTable, + Columns: []string{team.ProjectColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: sqlgraph.NewFieldSpec(project.FieldID, field.TypeInt), @@ -356,6 +474,51 @@ func (tuo *TeamUpdateOne) sqlSave(ctx context.Context) (_node *Team, err error) } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if tuo.mutation.UsersCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: team.UsersTable, + Columns: team.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tuo.mutation.RemovedUsersIDs(); len(nodes) > 0 && !tuo.mutation.UsersCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: team.UsersTable, + Columns: team.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tuo.mutation.UsersIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: team.UsersTable, + Columns: team.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _node = &Team{config: tuo.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/ent/tx.go b/database/ent/tx.go similarity index 100% rename from ent/tx.go rename to database/ent/tx.go diff --git a/ent/user.go b/database/ent/user.go similarity index 76% rename from ent/user.go rename to database/ent/user.go index 37aa033..5741312 100644 --- a/ent/user.go +++ b/database/ent/user.go @@ -4,7 +4,7 @@ package ent import ( "fmt" - "portfolio-backend/ent/user" + "portfolio-backend/database/ent/user" "strings" "entgo.io/ent" @@ -19,10 +19,31 @@ type User struct { // Name holds the value of the "name" field. Name string `json:"name,omitempty"` // Role holds the value of the "role" field. - Role user.Role `json:"role,omitempty"` + Role user.Role `json:"role,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the UserQuery when eager-loading is set. + Edges UserEdges `json:"edges"` selectValues sql.SelectValues } +// UserEdges holds the relations/edges for other nodes in the graph. +type UserEdges struct { + // Teams holds the value of the teams edge. + Teams []*Team `json:"teams,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// TeamsOrErr returns the Teams value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) TeamsOrErr() ([]*Team, error) { + if e.loadedTypes[0] { + return e.Teams, nil + } + return nil, &NotLoadedError{edge: "teams"} +} + // scanValues returns the types for scanning values from sql.Rows. func (*User) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) @@ -78,6 +99,11 @@ func (u *User) Value(name string) (ent.Value, error) { return u.selectValues.Get(name) } +// QueryTeams queries the "teams" edge of the User entity. +func (u *User) QueryTeams() *TeamQuery { + return NewUserClient(u.config).QueryTeams(u) +} + // Update returns a builder for updating this User. // Note that you need to call User.Unwrap() before calling this method if this User // was returned from a transaction, and the transaction was committed or rolled back. diff --git a/ent/user/user.go b/database/ent/user/user.go similarity index 61% rename from ent/user/user.go rename to database/ent/user/user.go index 3d04946..4499533 100644 --- a/ent/user/user.go +++ b/database/ent/user/user.go @@ -6,6 +6,7 @@ import ( "fmt" "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" ) const ( @@ -17,8 +18,15 @@ const ( FieldName = "name" // FieldRole holds the string denoting the role field in the database. FieldRole = "role" + // EdgeTeams holds the string denoting the teams edge name in mutations. + EdgeTeams = "teams" // Table holds the table name of the user in the database. Table = "users" + // TeamsTable is the table that holds the teams relation/edge. The primary key declared below. + TeamsTable = "user_teams" + // TeamsInverseTable is the table name for the Team entity. + // It exists in this package in order to avoid circular dependency with the "team" package. + TeamsInverseTable = "teams" ) // Columns holds all SQL columns for user fields. @@ -28,6 +36,12 @@ var Columns = []string{ FieldRole, } +var ( + // TeamsPrimaryKey and TeamsColumn2 are the table columns denoting the + // primary key for the teams relation (M2M). + TeamsPrimaryKey = []string{"user_id", "team_id"} +) + // ValidColumn reports if the column name is valid (part of the table columns). func ValidColumn(column string) bool { for i := range Columns { @@ -84,3 +98,24 @@ func ByName(opts ...sql.OrderTermOption) OrderOption { func ByRole(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldRole, opts...).ToFunc() } + +// ByTeamsCount orders the results by teams count. +func ByTeamsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newTeamsStep(), opts...) + } +} + +// ByTeams orders the results by teams terms. +func ByTeams(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newTeamsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newTeamsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TeamsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, TeamsTable, TeamsPrimaryKey...), + ) +} diff --git a/ent/user/where.go b/database/ent/user/where.go similarity index 86% rename from ent/user/where.go rename to database/ent/user/where.go index 2ad1ae0..9b4ae6c 100644 --- a/ent/user/where.go +++ b/database/ent/user/where.go @@ -3,9 +3,10 @@ package user import ( - "portfolio-backend/ent/predicate" + "portfolio-backend/database/ent/predicate" "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" ) // ID filters vertices based on their ID field. @@ -143,6 +144,29 @@ func RoleNotIn(vs ...Role) predicate.User { return predicate.User(sql.FieldNotIn(FieldRole, vs...)) } +// HasTeams applies the HasEdge predicate on the "teams" edge. +func HasTeams() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, TeamsTable, TeamsPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTeamsWith applies the HasEdge predicate on the "teams" edge with a given conditions (other predicates). +func HasTeamsWith(preds ...predicate.Team) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := newTeamsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + // And groups predicates with the AND operator between them. func And(predicates ...predicate.User) predicate.User { return predicate.User(sql.AndPredicates(predicates...)) diff --git a/ent/user_create.go b/database/ent/user_create.go similarity index 86% rename from ent/user_create.go rename to database/ent/user_create.go index 53b3fbe..4279492 100644 --- a/ent/user_create.go +++ b/database/ent/user_create.go @@ -6,7 +6,8 @@ import ( "context" "errors" "fmt" - "portfolio-backend/ent/user" + "portfolio-backend/database/ent/team" + "portfolio-backend/database/ent/user" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" @@ -39,6 +40,21 @@ func (uc *UserCreate) SetRole(u user.Role) *UserCreate { return uc } +// AddTeamIDs adds the "teams" edge to the Team entity by IDs. +func (uc *UserCreate) AddTeamIDs(ids ...int) *UserCreate { + uc.mutation.AddTeamIDs(ids...) + return uc +} + +// AddTeams adds the "teams" edges to the Team entity. +func (uc *UserCreate) AddTeams(t ...*Team) *UserCreate { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return uc.AddTeamIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (uc *UserCreate) Mutation() *UserMutation { return uc.mutation @@ -127,6 +143,22 @@ func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { _spec.SetField(user.FieldRole, field.TypeEnum, value) _node.Role = value } + if nodes := uc.mutation.TeamsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.TeamsTable, + Columns: user.TeamsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(team.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } return _node, _spec } diff --git a/ent/user_delete.go b/database/ent/user_delete.go similarity index 96% rename from ent/user_delete.go rename to database/ent/user_delete.go index 17f5922..7c3ae9d 100644 --- a/ent/user_delete.go +++ b/database/ent/user_delete.go @@ -4,8 +4,8 @@ package ent import ( "context" - "portfolio-backend/ent/predicate" - "portfolio-backend/ent/user" + "portfolio-backend/database/ent/predicate" + "portfolio-backend/database/ent/user" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" diff --git a/ent/user_query.go b/database/ent/user_query.go similarity index 79% rename from ent/user_query.go rename to database/ent/user_query.go index 3cecfe7..7eaff23 100644 --- a/ent/user_query.go +++ b/database/ent/user_query.go @@ -4,10 +4,12 @@ package ent import ( "context" + "database/sql/driver" "fmt" "math" - "portfolio-backend/ent/predicate" - "portfolio-backend/ent/user" + "portfolio-backend/database/ent/predicate" + "portfolio-backend/database/ent/team" + "portfolio-backend/database/ent/user" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" @@ -21,6 +23,7 @@ type UserQuery struct { order []user.OrderOption inters []Interceptor predicates []predicate.User + withTeams *TeamQuery // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -57,6 +60,28 @@ func (uq *UserQuery) Order(o ...user.OrderOption) *UserQuery { return uq } +// QueryTeams chains the current query on the "teams" edge. +func (uq *UserQuery) QueryTeams() *TeamQuery { + query := (&TeamClient{config: uq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := uq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(team.Table, team.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, user.TeamsTable, user.TeamsPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step) + return fromU, nil + } + return query +} + // First returns the first User entity from the query. // Returns a *NotFoundError when no User was found. func (uq *UserQuery) First(ctx context.Context) (*User, error) { @@ -249,12 +274,24 @@ func (uq *UserQuery) Clone() *UserQuery { order: append([]user.OrderOption{}, uq.order...), inters: append([]Interceptor{}, uq.inters...), predicates: append([]predicate.User{}, uq.predicates...), + withTeams: uq.withTeams.Clone(), // clone intermediate query. sql: uq.sql.Clone(), path: uq.path, } } +// WithTeams tells the query-builder to eager-load the nodes that are connected to +// the "teams" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithTeams(opts ...func(*TeamQuery)) *UserQuery { + query := (&TeamClient{config: uq.config}).Query() + for _, opt := range opts { + opt(query) + } + uq.withTeams = query + return uq +} + // GroupBy is used to group vertices by one or more fields/columns. // It is often used with aggregate functions, like: count, max, mean, min, sum. // @@ -331,8 +368,11 @@ func (uq *UserQuery) prepareQuery(ctx context.Context) error { func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, error) { var ( - nodes = []*User{} - _spec = uq.querySpec() + nodes = []*User{} + _spec = uq.querySpec() + loadedTypes = [1]bool{ + uq.withTeams != nil, + } ) _spec.ScanValues = func(columns []string) ([]any, error) { return (*User).scanValues(nil, columns) @@ -340,6 +380,7 @@ func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e _spec.Assign = func(columns []string, values []any) error { node := &User{config: uq.config} nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes return node.assignValues(columns, values) } for i := range hooks { @@ -351,9 +392,78 @@ func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e if len(nodes) == 0 { return nodes, nil } + if query := uq.withTeams; query != nil { + if err := uq.loadTeams(ctx, query, nodes, + func(n *User) { n.Edges.Teams = []*Team{} }, + func(n *User, e *Team) { n.Edges.Teams = append(n.Edges.Teams, e) }); err != nil { + return nil, err + } + } return nodes, nil } +func (uq *UserQuery) loadTeams(ctx context.Context, query *TeamQuery, nodes []*User, init func(*User), assign func(*User, *Team)) error { + edgeIDs := make([]driver.Value, len(nodes)) + byID := make(map[int]*User) + nids := make(map[int]map[*User]struct{}) + for i, node := range nodes { + edgeIDs[i] = node.ID + byID[node.ID] = node + if init != nil { + init(node) + } + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(user.TeamsTable) + s.Join(joinT).On(s.C(team.FieldID), joinT.C(user.TeamsPrimaryKey[1])) + s.Where(sql.InValues(joinT.C(user.TeamsPrimaryKey[0]), edgeIDs...)) + columns := s.SelectedColumns() + s.Select(joinT.C(user.TeamsPrimaryKey[0])) + s.AppendSelect(columns...) + s.SetDistinct(false) + }) + if err := query.prepareQuery(ctx); err != nil { + return err + } + qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) { + assign := spec.Assign + values := spec.ScanValues + spec.ScanValues = func(columns []string) ([]any, error) { + values, err := values(columns[1:]) + if err != nil { + return nil, err + } + return append([]any{new(sql.NullInt64)}, values...), nil + } + spec.Assign = func(columns []string, values []any) error { + outValue := int(values[0].(*sql.NullInt64).Int64) + inValue := int(values[1].(*sql.NullInt64).Int64) + if nids[inValue] == nil { + nids[inValue] = map[*User]struct{}{byID[outValue]: {}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byID[outValue]] = struct{}{} + return nil + } + }) + }) + neighbors, err := withInterceptors[[]*Team](ctx, query, qr, query.inters) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nids[n.ID] + if !ok { + return fmt.Errorf(`unexpected "teams" node returned %v`, n.ID) + } + for kn := range nodes { + assign(kn, n) + } + } + return nil +} + func (uq *UserQuery) sqlCount(ctx context.Context) (int, error) { _spec := uq.querySpec() _spec.Node.Columns = uq.ctx.Fields diff --git a/ent/user_update.go b/database/ent/user_update.go similarity index 61% rename from ent/user_update.go rename to database/ent/user_update.go index 55ac668..fdab1a1 100644 --- a/ent/user_update.go +++ b/database/ent/user_update.go @@ -6,8 +6,9 @@ import ( "context" "errors" "fmt" - "portfolio-backend/ent/predicate" - "portfolio-backend/ent/user" + "portfolio-backend/database/ent/predicate" + "portfolio-backend/database/ent/team" + "portfolio-backend/database/ent/user" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" @@ -55,11 +56,47 @@ func (uu *UserUpdate) SetNillableRole(u *user.Role) *UserUpdate { return uu } +// AddTeamIDs adds the "teams" edge to the Team entity by IDs. +func (uu *UserUpdate) AddTeamIDs(ids ...int) *UserUpdate { + uu.mutation.AddTeamIDs(ids...) + return uu +} + +// AddTeams adds the "teams" edges to the Team entity. +func (uu *UserUpdate) AddTeams(t ...*Team) *UserUpdate { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return uu.AddTeamIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (uu *UserUpdate) Mutation() *UserMutation { return uu.mutation } +// ClearTeams clears all "teams" edges to the Team entity. +func (uu *UserUpdate) ClearTeams() *UserUpdate { + uu.mutation.ClearTeams() + return uu +} + +// RemoveTeamIDs removes the "teams" edge to Team entities by IDs. +func (uu *UserUpdate) RemoveTeamIDs(ids ...int) *UserUpdate { + uu.mutation.RemoveTeamIDs(ids...) + return uu +} + +// RemoveTeams removes "teams" edges to Team entities. +func (uu *UserUpdate) RemoveTeams(t ...*Team) *UserUpdate { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return uu.RemoveTeamIDs(ids...) +} + // Save executes the query and returns the number of nodes affected by the update operation. func (uu *UserUpdate) Save(ctx context.Context) (int, error) { return withHooks(ctx, uu.sqlSave, uu.mutation, uu.hooks) @@ -115,6 +152,51 @@ func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) { if value, ok := uu.mutation.Role(); ok { _spec.SetField(user.FieldRole, field.TypeEnum, value) } + if uu.mutation.TeamsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.TeamsTable, + Columns: user.TeamsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(team.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.RemovedTeamsIDs(); len(nodes) > 0 && !uu.mutation.TeamsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.TeamsTable, + Columns: user.TeamsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(team.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.TeamsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.TeamsTable, + Columns: user.TeamsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(team.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if n, err = sqlgraph.UpdateNodes(ctx, uu.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{user.Label} @@ -163,11 +245,47 @@ func (uuo *UserUpdateOne) SetNillableRole(u *user.Role) *UserUpdateOne { return uuo } +// AddTeamIDs adds the "teams" edge to the Team entity by IDs. +func (uuo *UserUpdateOne) AddTeamIDs(ids ...int) *UserUpdateOne { + uuo.mutation.AddTeamIDs(ids...) + return uuo +} + +// AddTeams adds the "teams" edges to the Team entity. +func (uuo *UserUpdateOne) AddTeams(t ...*Team) *UserUpdateOne { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return uuo.AddTeamIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (uuo *UserUpdateOne) Mutation() *UserMutation { return uuo.mutation } +// ClearTeams clears all "teams" edges to the Team entity. +func (uuo *UserUpdateOne) ClearTeams() *UserUpdateOne { + uuo.mutation.ClearTeams() + return uuo +} + +// RemoveTeamIDs removes the "teams" edge to Team entities by IDs. +func (uuo *UserUpdateOne) RemoveTeamIDs(ids ...int) *UserUpdateOne { + uuo.mutation.RemoveTeamIDs(ids...) + return uuo +} + +// RemoveTeams removes "teams" edges to Team entities. +func (uuo *UserUpdateOne) RemoveTeams(t ...*Team) *UserUpdateOne { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return uuo.RemoveTeamIDs(ids...) +} + // Where appends a list predicates to the UserUpdate builder. func (uuo *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne { uuo.mutation.Where(ps...) @@ -253,6 +371,51 @@ func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) if value, ok := uuo.mutation.Role(); ok { _spec.SetField(user.FieldRole, field.TypeEnum, value) } + if uuo.mutation.TeamsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.TeamsTable, + Columns: user.TeamsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(team.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.RemovedTeamsIDs(); len(nodes) > 0 && !uuo.mutation.TeamsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.TeamsTable, + Columns: user.TeamsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(team.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.TeamsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.TeamsTable, + Columns: user.TeamsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(team.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _node = &User{config: uuo.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/ent/team/team.go b/ent/team/team.go deleted file mode 100644 index 7501a32..0000000 --- a/ent/team/team.go +++ /dev/null @@ -1,78 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package team - -import ( - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" -) - -const ( - // Label holds the string label denoting the team type in the database. - Label = "team" - // 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" - // EdgeProjects holds the string denoting the projects edge name in mutations. - EdgeProjects = "projects" - // Table holds the table name of the team in the database. - Table = "teams" - // ProjectsTable is the table that holds the projects relation/edge. - ProjectsTable = "projects" - // ProjectsInverseTable is the table name for the Project entity. - // It exists in this package in order to avoid circular dependency with the "project" package. - ProjectsInverseTable = "projects" - // ProjectsColumn is the table column denoting the projects relation/edge. - ProjectsColumn = "team_projects" -) - -// Columns holds all SQL columns for team fields. -var Columns = []string{ - FieldID, - FieldName, -} - -// ValidColumn reports if the column name is valid (part of the table columns). -func ValidColumn(column string) bool { - for i := range Columns { - if column == Columns[i] { - return true - } - } - return false -} - -// OrderOption defines the ordering options for the Team 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() -} - -// ByProjectsCount orders the results by projects count. -func ByProjectsCount(opts ...sql.OrderTermOption) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborsCount(s, newProjectsStep(), opts...) - } -} - -// ByProjects orders the results by projects terms. -func ByProjects(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborTerms(s, newProjectsStep(), append([]sql.OrderTerm{term}, terms...)...) - } -} -func newProjectsStep() *sqlgraph.Step { - return sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(ProjectsInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, ProjectsTable, ProjectsColumn), - ) -} diff --git a/go.sum b/go.sum index b5f681a..2f60d4e 100644 --- a/go.sum +++ b/go.sum @@ -22,8 +22,6 @@ 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.19.1 h1://i05Jqznmb2EXqa39Nsvyan2o5XyMowW5fnCKW5RPI= github.com/hashicorp/hcl/v2 v2.19.1/go.mod h1:ThLC89FV4p9MPW804KVbe/cEXoQ8NZEh+JtMeeGErHE= -github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= -github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= @@ -32,22 +30,14 @@ 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/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0= -github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= 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 v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0= -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/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.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/zclconf/go-cty v1.14.2 h1:kTG7lqmBou0Zkx35r6HJHUQTvaRPr5bIAf3AoHS0izI= @@ -56,7 +46,5 @@ golang.org/x/mod v0.15.0 h1:SernR4v+D55NyBH2QiEQrlBAnj1ECL6AGrA5+dPaMY8= golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/tools v0.17.0 h1:FvmRgNOcs3kOa+T20R1uhfP9F6HgG2mfxDv1vrx1Htc= -golang.org/x/tools v0.17.0/go.mod h1:xsh6VxdV005rRVaS6SSAf9oiAqljS7UZUacMZ8Bnsps= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/main.go b/main.go index 8e9dfb2..65e6889 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,11 @@ package main -import "net/http" +import ( + "net/http" + "portfolio-backend/database" + + "portfolio-backend/api/handler" +) func main() { @@ -9,35 +14,13 @@ func main() { mux := http.NewServeMux() //connect to database and migrate - DB() + database.DB() // Register the routes and handlers - mux.HandleFunc("/", catchAllHandler) - mux.HandleFunc("/test", testHandler) - mux.HandleFunc("/test2", test2Handler) + mux.HandleFunc("/", handler.CatchAllHandler) + mux.HandleFunc("/test", handler.TestHandler) + mux.HandleFunc("/test2", handler.Test2Handler) // Run the server http.ListenAndServe(":4002", mux) } - -func catchAllHandler(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusGone) - _, err := w.Write([]byte("Bad endpoint")) - if err != nil { - InternalServerErrorHandler(w, r) - } -} - -func testHandler(w http.ResponseWriter, r *http.Request) { - _, err := w.Write([]byte("test")) - if err != nil { - InternalServerErrorHandler(w, r) - } -} - -func test2Handler(w http.ResponseWriter, r *http.Request) { - _, err := w.Write([]byte("test2")) - if err != nil { - InternalServerErrorHandler(w, r) - } -}