diff --git a/internal/api/auth.go b/internal/api/auth.go new file mode 100644 index 0000000..274564c --- /dev/null +++ b/internal/api/auth.go @@ -0,0 +1,314 @@ +package api + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "time" + + "home-vue-go/internal/config" + "home-vue-go/internal/database" + "home-vue-go/internal/ent/user" + + "github.com/gin-gonic/gin" + "github.com/golang-jwt/jwt/v5" + "golang.org/x/crypto/bcrypt" +) + +type LoginRequest struct { + Username string `json:"username" binding:"required"` + Password string `json:"password" binding:"required"` +} + +type Claims struct { + Username string `json:"username"` + jwt.RegisteredClaims +} + +func Login(db *database.Database, cfg *config.Config) gin.HandlerFunc { + return func(c *gin.Context) { + var req LoginRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "用户名和密码不能为空"}) + return + } + + ctx := c.Request.Context() + user, err := db.Client.User.Query().Where(user.UsernameEQ(req.Username)).First(ctx) + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "用户名或密码错误"}) + return + } + + // 验证密码 + if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password)); err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "用户名或密码错误"}) + return + } + + // 获取登录IP和用户代理 + ip := c.ClientIP() + userAgent := c.GetHeader("User-Agent") + + // 查询IP地理位置 + location := queryIPLocation(ip) + + // 记录登录历史到内存 + addLoginHistory(user.Username, ip, location, userAgent, true) + + // 生成JWT token + claims := Claims{ + Username: user.Username, + RegisteredClaims: jwt.RegisteredClaims{ + ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)), + IssuedAt: jwt.NewNumericDate(time.Now()), + }, + } + + token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) + tokenString, err := token.SignedString([]byte(cfg.JWTSecret)) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "生成token失败"}) + return + } + + c.JSON(http.StatusOK, gin.H{ + "token": tokenString, + }) + } +} + +func ChangePassword(db *database.Database) gin.HandlerFunc { + return func(c *gin.Context) { + var req struct { + OldPassword string `json:"oldPassword" binding:"required"` + NewPassword string `json:"newPassword" binding:"required,min=8"` + } + + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "旧密码和新密码不能为空,且新密码至少8位"}) + return + } + + // 从JWT中获取用户名 + username, exists := c.Get("username") + if !exists { + c.JSON(http.StatusUnauthorized, gin.H{"error": "未找到用户信息"}) + return + } + + usernameStr := username.(string) + ctx := c.Request.Context() + + // 查询用户 + user, err := db.Client.User.Query().Where(user.UsernameEQ(usernameStr)).First(ctx) + if err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "用户不存在"}) + return + } + + // 验证旧密码 + if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.OldPassword)); err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": "旧密码错误"}) + return + } + + // 加密新密码 + hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "密码加密失败"}) + return + } + + // 更新密码到数据库 + updatedUser, err := db.Client.User.UpdateOneID(user.ID).SetPassword(string(hashedPassword)).Save(ctx) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "密码更新失败: " + err.Error()}) + return + } + + // 验证密码已保存(可选,用于调试) + if updatedUser == nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "密码更新失败: 未返回更新后的用户"}) + return + } + + c.JSON(http.StatusOK, gin.H{"message": "密码修改成功"}) + } +} + +func JWTAuthMiddleware(secret string) gin.HandlerFunc { + return func(c *gin.Context) { + tokenString := c.GetHeader("Authorization") + if tokenString == "" { + c.JSON(http.StatusUnauthorized, gin.H{"error": "未提供认证token"}) + c.Abort() + return + } + + // 移除 "Bearer " 前缀 + if len(tokenString) > 7 && tokenString[:7] == "Bearer " { + tokenString = tokenString[7:] + } + + claims := &Claims{} + token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) { + return []byte(secret), nil + }) + + if err != nil || !token.Valid { + // Token失效时,记录登录IP(用于统计) + ip := c.ClientIP() + userAgent := c.GetHeader("User-Agent") + location := queryIPLocation(ip) + // 记录为失败的登录尝试(token失效) + addLoginHistory("", ip, location, userAgent, false) + + c.JSON(http.StatusUnauthorized, gin.H{"error": "无效的token"}) + c.Abort() + return + } + + c.Set("username", claims.Username) + c.Next() + } +} + +// 查询IP地理位置(使用多个公共API) +func queryIPLocation(ip string) string { + if ip == "" || ip == "::1" || ip == "127.0.0.1" { + return "本地" + } + + // 尝试多个IP查询服务 + apis := []struct { + name string + url string + }{ + {"ipapi", fmt.Sprintf("http://ip-api.com/json/%s?lang=zh-CN", ip)}, + {"ipapi.co", fmt.Sprintf("https://ipapi.co/%s/json/", ip)}, + {"ip.sb", fmt.Sprintf("https://api.ip.sb/geoip/%s", ip)}, + } + + for _, api := range apis { + if location := queryIPFromAPI(api.url, api.name); location != "" { + return location + } + } + + return "未知" +} + +func queryIPFromAPI(url, apiName string) string { + client := &http.Client{Timeout: 3 * time.Second} + resp, err := client.Get(url) + if err != nil { + return "" + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return "" + } + + var result map[string]interface{} + if err := json.Unmarshal(body, &result); err != nil { + return "" + } + + switch apiName { + case "ipapi": + if country, ok := result["country"].(string); ok { + region := "" + if r, ok := result["regionName"].(string); ok { + region = r + } + city := "" + if c, ok := result["city"].(string); ok { + city = c + } + parts := []string{country} + if region != "" { + parts = append(parts, region) + } + if city != "" { + parts = append(parts, city) + } + return strings.Join(parts, " ") + } + case "ipapi.co": + if country, ok := result["country_name"].(string); ok { + city := "" + if c, ok := result["city"].(string); ok { + city = c + } + if city != "" { + return fmt.Sprintf("%s %s", country, city) + } + return country + } + case "ip.sb": + if country, ok := result["country"].(string); ok { + city := "" + if c, ok := result["city"].(string); ok { + city = c + } + if city != "" { + return fmt.Sprintf("%s %s", country, city) + } + return country + } + } + + return "" +} + +// 获取登录历史 +func GetLoginHistory(db *database.Database) gin.HandlerFunc { + return func(c *gin.Context) { + limit := c.DefaultQuery("limit", "20") + limitInt := 20 + if n, err := parseInt(limit); err == nil && n > 0 { + limitInt = n + if limitInt > 100 { + limitInt = 100 + } + } + + // 从内存获取登录历史 + histories := getLoginHistoryRecords(limitInt) + + result := make([]gin.H, 0, len(histories)) + for _, h := range histories { + result = append(result, gin.H{ + "username": h.Username, + "ip": h.IP, + "location": h.Location, + "userAgent": h.UserAgent, + "loginTime": h.LoginTime.Format("2006-01-02 15:04:05"), + "success": h.Success, + }) + } + + c.JSON(http.StatusOK, gin.H{ + "data": result, + "count": len(result), + }) + } +} + +// 简单的整数解析 +func parseInt(s string) (int, error) { + var n int + for _, char := range s { + if char >= '0' && char <= '9' { + n = n*10 + int(char-'0') + } else { + return 0, fmt.Errorf("invalid number") + } + } + return n, nil +} diff --git a/internal/api/config.go b/internal/api/config.go new file mode 100644 index 0000000..08b7a28 --- /dev/null +++ b/internal/api/config.go @@ -0,0 +1,279 @@ +package api + +import ( + "net/http" + + "home-vue-go/internal/config" + "home-vue-go/internal/database" + + "github.com/gin-gonic/gin" +) + +// GetSiteConfig 获取站点配置(含底部年份配置) +func GetSiteConfig(db *database.Database, cfg *config.Config) gin.HandlerFunc { + return func(c *gin.Context) { + ctx := c.Request.Context() + + footerCfg, _ := cfg.LoadFooterYear() + visitTimerCfg, _ := cfg.LoadVisitTimer() + + siteCfg, err := db.Client.SiteConfig.Get(ctx, 1) + if err != nil { + // 如果不存在,返回默认值 + 年份配置 + c.JSON(http.StatusOK, gin.H{ + "siteName": "个人主页", + "siteURL": "https://example.com", + "siteIcon": "/favicon.ico", + "siteDescription": "一个基于Vue3的个人主页", + "siteKeywords": "个人主页,Vue3", + "userName": "用户", + "profileImageURL": "", + "icpNumber": "暂未填写", + "policeNumber": "暂未填写", + "pageTitle": "个人主页", + "favicon": "/favicon.ico", + "umamiScript": "", + "umamiWebsiteId": "", + "iconLibrary": "//lib.baomitu.com/font-awesome/6.5.0/css/all.min.css", + "fontLibrary": "", + "showVisitTimer": visitTimerCfg.ShowVisitTimer, + "footerYearStart": footerCfg.Start, + "footerYearEnd": footerCfg.End, + }) + return + } + + c.JSON(http.StatusOK, gin.H{ + "siteName": siteCfg.SiteName, + "siteURL": siteCfg.SiteURL, + "siteIcon": siteCfg.SiteIcon, + "siteDescription": siteCfg.SiteDescription, + "siteKeywords": siteCfg.SiteKeywords, + "userName": siteCfg.UserName, + "profileImageURL": siteCfg.ProfileImageURL, + "icpNumber": siteCfg.IcpNumber, + "policeNumber": siteCfg.PoliceNumber, + "pageTitle": siteCfg.PageTitle, + "favicon": siteCfg.Favicon, + "umamiScript": siteCfg.UmamiScript, + "umamiWebsiteId": siteCfg.UmamiWebsiteID, + "iconLibrary": siteCfg.IconLibrary, + "fontLibrary": siteCfg.FontLibrary, + "showVisitTimer": visitTimerCfg.ShowVisitTimer, + "footerYearStart": footerCfg.Start, + "footerYearEnd": footerCfg.End, + }) + } +} + +// UpdateSiteConfig 更新站点配置(含底部年份配置) +func UpdateSiteConfig(db *database.Database, cfg *config.Config) gin.HandlerFunc { + return func(c *gin.Context) { + var req struct { + SiteName string `json:"siteName"` + SiteURL string `json:"siteURL"` + SiteIcon string `json:"siteIcon"` + SiteDescription string `json:"siteDescription"` + SiteKeywords string `json:"siteKeywords"` + UserName string `json:"userName"` + ProfileImageURL string `json:"profileImageURL"` + ICPNumber string `json:"icpNumber"` + PoliceNumber string `json:"policeNumber"` + PageTitle string `json:"pageTitle"` + Favicon string `json:"favicon"` + UmamiScript string `json:"umamiScript"` + UmamiWebsiteId string `json:"umamiWebsiteId"` + IconLibrary string `json:"iconLibrary"` + FontLibrary string `json:"fontLibrary"` + ShowVisitTimer *bool `json:"showVisitTimer"` + + FooterYearStart string `json:"footerYearStart"` + FooterYearEnd string `json:"footerYearEnd"` + } + + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + ctx := c.Request.Context() + update := db.Client.SiteConfig.UpdateOneID(1) + + if req.SiteName != "" { + update.SetSiteName(req.SiteName) + } + if req.SiteURL != "" { + update.SetSiteURL(req.SiteURL) + } + if req.SiteIcon != "" { + update.SetSiteIcon(req.SiteIcon) + } + if req.SiteDescription != "" { + update.SetSiteDescription(req.SiteDescription) + } + if req.SiteKeywords != "" { + update.SetSiteKeywords(req.SiteKeywords) + } + if req.UserName != "" { + update.SetUserName(req.UserName) + } + if req.ProfileImageURL != "" { + update.SetProfileImageURL(req.ProfileImageURL) + } + if req.ICPNumber != "" { + update.SetIcpNumber(req.ICPNumber) + } + if req.PoliceNumber != "" { + update.SetPoliceNumber(req.PoliceNumber) + } + if req.PageTitle != "" { + update.SetPageTitle(req.PageTitle) + } + if req.Favicon != "" { + update.SetFavicon(req.Favicon) + } + if req.UmamiScript != "" { + update.SetUmamiScript(req.UmamiScript) + } + if req.UmamiWebsiteId != "" { + update.SetUmamiWebsiteID(req.UmamiWebsiteId) + } + if req.IconLibrary != "" { + update.SetIconLibrary(req.IconLibrary) + } + if req.FontLibrary != "" { + update.SetFontLibrary(req.FontLibrary) + } + + siteCfg, err := update.Save(ctx) + if err != nil { + // 如果不存在,创建新的 + create := db.Client.SiteConfig.Create(). + SetSiteName(req.SiteName). + SetSiteURL(req.SiteURL). + SetSiteIcon(req.SiteIcon). + SetSiteDescription(req.SiteDescription). + SetSiteKeywords(req.SiteKeywords). + SetUserName(req.UserName) + if req.ProfileImageURL != "" { + create.SetProfileImageURL(req.ProfileImageURL) + } + if req.ICPNumber != "" { + create.SetIcpNumber(req.ICPNumber) + } + if req.PoliceNumber != "" { + create.SetPoliceNumber(req.PoliceNumber) + } + if req.PageTitle != "" { + create.SetPageTitle(req.PageTitle) + } + if req.Favicon != "" { + create.SetFavicon(req.Favicon) + } + if req.UmamiScript != "" { + create.SetUmamiScript(req.UmamiScript) + } + if req.UmamiWebsiteId != "" { + create.SetUmamiWebsiteID(req.UmamiWebsiteId) + } + if req.IconLibrary != "" { + create.SetIconLibrary(req.IconLibrary) + } + if req.FontLibrary != "" { + create.SetFontLibrary(req.FontLibrary) + } + siteCfg, err = create.Save(ctx) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + } + + // 保存底部年份配置到独立文件 + _ = cfg.SaveFooterYear(&config.FooterYearConfig{ + Start: req.FooterYearStart, + End: req.FooterYearEnd, + }) + + // 保存访问时间显示配置 + if req.ShowVisitTimer != nil { + _ = cfg.SaveVisitTimer(&config.VisitTimerConfig{ + ShowVisitTimer: *req.ShowVisitTimer, + }) + } + + // 读取最新的配置用于返回 + footerCfg, _ := cfg.LoadFooterYear() + visitTimerCfg, _ := cfg.LoadVisitTimer() + + c.JSON(http.StatusOK, gin.H{ + "siteName": siteCfg.SiteName, + "siteURL": siteCfg.SiteURL, + "siteIcon": siteCfg.SiteIcon, + "siteDescription": siteCfg.SiteDescription, + "siteKeywords": siteCfg.SiteKeywords, + "userName": siteCfg.UserName, + "profileImageURL": siteCfg.ProfileImageURL, + "icpNumber": siteCfg.IcpNumber, + "policeNumber": siteCfg.PoliceNumber, + "pageTitle": siteCfg.PageTitle, + "favicon": siteCfg.Favicon, + "umamiScript": siteCfg.UmamiScript, + "umamiWebsiteId": siteCfg.UmamiWebsiteID, + "iconLibrary": siteCfg.IconLibrary, + "fontLibrary": siteCfg.FontLibrary, + "showVisitTimer": visitTimerCfg.ShowVisitTimer, + "footerYearStart": footerCfg.Start, + "footerYearEnd": footerCfg.End, + }) + } +} + +// GetRotatingTexts 获取轮换文本配置 +func GetRotatingTexts(cfg *config.Config) gin.HandlerFunc { + return func(c *gin.Context) { + textsCfg, err := cfg.LoadRotatingTexts() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "加载轮换文本配置失败: " + err.Error()}) + return + } + + c.JSON(http.StatusOK, gin.H{ + "texts": textsCfg.Texts, + }) + } +} + +// UpdateRotatingTexts 更新轮换文本配置 +func UpdateRotatingTexts(cfg *config.Config) gin.HandlerFunc { + return func(c *gin.Context) { + var req struct { + Texts []string `json:"texts"` + } + + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + // 限制最多8条文本 + if len(req.Texts) > 8 { + req.Texts = req.Texts[:8] + } + + textsCfg := &config.RotatingTextsConfig{ + Texts: req.Texts, + } + + if err := cfg.SaveRotatingTexts(textsCfg); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "保存轮换文本配置失败: " + err.Error()}) + return + } + + c.JSON(http.StatusOK, gin.H{ + "message": "轮换文本配置已保存", + "texts": textsCfg.Texts, + }) + } +} + diff --git a/internal/api/contacts.go b/internal/api/contacts.go new file mode 100644 index 0000000..3e1ec6b --- /dev/null +++ b/internal/api/contacts.go @@ -0,0 +1,180 @@ +package api + +import ( + "net/http" + "strconv" + + "home-vue-go/internal/database" + "home-vue-go/internal/ent/contact" + + "github.com/gin-gonic/gin" +) + +func GetContacts(db *database.Database) gin.HandlerFunc { + return func(c *gin.Context) { + ctx := c.Request.Context() + contacts, err := db.Client.Contact.Query().Order(contact.BySortOrder(), contact.ByID()).All(ctx) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + result := make([]gin.H, len(contacts)) + for i, contact := range contacts { + result[i] = gin.H{ + "id": contact.ID, + "type": contact.Type, + "icon": contact.Icon, + "url": contact.URL, + "qrCode": contact.QrCode, + "hoverColor": contact.HoverColor, + "sortOrder": contact.SortOrder, + } + } + + c.JSON(http.StatusOK, result) + } +} + +func CreateContact(db *database.Database) gin.HandlerFunc { + return func(c *gin.Context) { + var req struct { + Type string `json:"type" binding:"required"` + Icon string `json:"icon" binding:"required"` + URL string `json:"url"` + QrCode string `json:"qrCode"` + HoverColor string `json:"hoverColor"` + SortOrder int `json:"sortOrder"` + } + + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + // 验证Email类型必须是mailto格式 + if req.Type == "Email" && req.URL != "" { + if len(req.URL) < 7 || req.URL[:7] != "mailto:" { + c.JSON(http.StatusBadRequest, gin.H{"error": "Email URL必须是mailto:格式"}) + return + } + } + + ctx := c.Request.Context() + create := db.Client.Contact.Create(). + SetType(req.Type). + SetIcon(req.Icon). + SetSortOrder(req.SortOrder) + + if req.URL != "" { + create.SetURL(req.URL) + } + if req.QrCode != "" { + create.SetQrCode(req.QrCode) + } + if req.HoverColor != "" { + create.SetHoverColor(req.HoverColor) + } + + contact, err := create.Save(ctx) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, gin.H{ + "id": contact.ID, + "type": contact.Type, + "icon": contact.Icon, + "url": contact.URL, + "qrCode": contact.QrCode, + "hoverColor": contact.HoverColor, + "sortOrder": contact.SortOrder, + }) + } +} + +func UpdateContact(db *database.Database) gin.HandlerFunc { + return func(c *gin.Context) { + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的ID"}) + return + } + + var req struct { + Type string `json:"type"` + Icon string `json:"icon"` + URL string `json:"url"` + QrCode string `json:"qrCode"` + HoverColor string `json:"hoverColor"` + SortOrder int `json:"sortOrder"` + } + + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + // 验证Email类型必须是mailto格式 + if req.Type == "Email" && req.URL != "" { + if len(req.URL) < 7 || req.URL[:7] != "mailto:" { + c.JSON(http.StatusBadRequest, gin.H{"error": "Email URL必须是mailto:格式"}) + return + } + } + + ctx := c.Request.Context() + update := db.Client.Contact.UpdateOneID(id) + if req.Type != "" { + update.SetType(req.Type) + } + if req.Icon != "" { + update.SetIcon(req.Icon) + } + if req.URL != "" { + update.SetURL(req.URL) + } + if req.QrCode != "" { + update.SetQrCode(req.QrCode) + } + if req.HoverColor != "" { + update.SetHoverColor(req.HoverColor) + } + update.SetSortOrder(req.SortOrder) + + contact, err := update.Save(ctx) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, gin.H{ + "id": contact.ID, + "type": contact.Type, + "icon": contact.Icon, + "url": contact.URL, + "qrCode": contact.QrCode, + "hoverColor": contact.HoverColor, + "sortOrder": contact.SortOrder, + }) + } +} + +func DeleteContact(db *database.Database) gin.HandlerFunc { + return func(c *gin.Context) { + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的ID"}) + return + } + + ctx := c.Request.Context() + if err := db.Client.Contact.DeleteOneID(id).Exec(ctx); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, gin.H{"message": "删除成功"}) + } +} diff --git a/internal/api/frontend_config.go b/internal/api/frontend_config.go new file mode 100644 index 0000000..3c4a46a --- /dev/null +++ b/internal/api/frontend_config.go @@ -0,0 +1,58 @@ +package api + +import ( + "net/http" + + "home-vue-go/internal/database" + + "github.com/gin-gonic/gin" +) + +// GetFrontendConfig 获取前端配置(用于index.html等) +func GetFrontendConfig(db *database.Database) gin.HandlerFunc { + return func(c *gin.Context) { + ctx := c.Request.Context() + config, err := db.Client.SiteConfig.Get(ctx, 1) + if err != nil { + // 如果不存在,返回默认值 + c.JSON(http.StatusOK, gin.H{ + "title": "个人主页", + "keywords": "个人主页,Vue3", + "description": "一个基于Vue3的个人主页", + "favicon": "/favicon.ico", + "umamiScript": "", + "umamiWebsiteId": "", + "iconLibrary": "//lib.baomitu.com/font-awesome/6.5.0/css/all.min.css", + "fontLibrary": "", + }) + return + } + + pageTitle := config.PageTitle + if pageTitle == "" { + pageTitle = "个人主页" + } + favicon := config.Favicon + if favicon == "" { + favicon = "/favicon.ico" + } + iconLibrary := config.IconLibrary + if iconLibrary == "" { + iconLibrary = "//lib.baomitu.com/font-awesome/6.5.0/css/all.min.css" + } + + // 确保返回完整的配置信息,包括站点名称和URL + c.JSON(http.StatusOK, gin.H{ + "title": pageTitle, + "siteName": config.SiteName, + "siteURL": config.SiteURL, + "keywords": config.SiteKeywords, + "description": config.SiteDescription, + "favicon": favicon, + "umamiScript": config.UmamiScript, + "umamiWebsiteId": config.UmamiWebsiteID, + "iconLibrary": iconLibrary, + "fontLibrary": config.FontLibrary, + }) + } +} diff --git a/internal/api/login_history_memory.go b/internal/api/login_history_memory.go new file mode 100644 index 0000000..a26489f --- /dev/null +++ b/internal/api/login_history_memory.go @@ -0,0 +1,70 @@ +package api + +import ( + "sync" + "time" +) + +// 内存存储登录历史(临时方案,等Ent代码生成后改用数据库) +type LoginHistoryRecord struct { + Username string + IP string + Location string + UserAgent string + LoginTime time.Time + Success bool +} + +var ( + loginHistoryRecords []LoginHistoryRecord + loginHistoryMutex sync.RWMutex + maxLoginHistory = 1000 // 最多保存1000条登录记录 +) + +// 添加登录历史记录 +func addLoginHistory(username, ip, location, userAgent string, success bool) { + loginHistoryMutex.Lock() + defer loginHistoryMutex.Unlock() + + loginHistoryRecords = append(loginHistoryRecords, LoginHistoryRecord{ + Username: username, + IP: ip, + Location: location, + UserAgent: userAgent, + LoginTime: time.Now(), + Success: success, + }) + + // 限制记录数量 + if len(loginHistoryRecords) > maxLoginHistory { + loginHistoryRecords = loginHistoryRecords[len(loginHistoryRecords)-maxLoginHistory:] + } +} + +// 获取登录历史记录 +func getLoginHistoryRecords(limit int) []LoginHistoryRecord { + loginHistoryMutex.RLock() + defer loginHistoryMutex.RUnlock() + + if limit <= 0 || limit > len(loginHistoryRecords) { + limit = len(loginHistoryRecords) + } + + // 返回最后limit条记录(最新的) + start := len(loginHistoryRecords) - limit + if start < 0 { + start = 0 + } + + result := make([]LoginHistoryRecord, 0, limit) + for i := len(loginHistoryRecords) - 1; i >= start; i-- { + result = append(result, loginHistoryRecords[i]) + } + + // 反转顺序,使最新的在前 + for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 { + result[i], result[j] = result[j], result[i] + } + + return result +} diff --git a/internal/api/logs.go b/internal/api/logs.go new file mode 100644 index 0000000..2ce2533 --- /dev/null +++ b/internal/api/logs.go @@ -0,0 +1,167 @@ +package api + +import ( + "bufio" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "time" + + "home-vue-go/internal/config" + + "github.com/gin-gonic/gin" +) + +var logBuffer []string +var maxLogLines = 1000 + +// 初始化日志缓冲区 +func InitLogBuffer() { + logBuffer = make([]string, 0, maxLogLines) +} + +// 添加日志到缓冲区 +func AddLogToBuffer(logLine string) { + logBuffer = append(logBuffer, logLine) + if len(logBuffer) > maxLogLines { + logBuffer = logBuffer[len(logBuffer)-maxLogLines:] + } +} + +// 获取后端日志 +func GetBackendLogs(cfg *config.Config) gin.HandlerFunc { + return func(c *gin.Context) { + lines := c.DefaultQuery("lines", "100") + linesInt := 100 + if lines == "all" { + linesInt = maxLogLines + } else { + // 尝试解析lines参数 + if n, err := parseIntLogs(lines); err == nil && n > 0 { + linesInt = n + if linesInt > maxLogLines { + linesInt = maxLogLines + } + } + } + + // 从缓冲区获取日志 + logs := make([]string, 0) + if len(logBuffer) > linesInt { + logs = logBuffer[len(logBuffer)-linesInt:] + } else { + logs = logBuffer + } + + // 尝试从日志文件读取(如果存在) + logFile := filepath.Join(cfg.DataDir, "app.log") + if fileLogs, err := readLogFile(logFile, linesInt); err == nil && len(fileLogs) > 0 { + // 合并文件日志和缓冲区日志 + allLogs := append(fileLogs, logs...) + // 去重并排序 + logs = deduplicateLogs(allLogs) + if len(logs) > linesInt { + logs = logs[len(logs)-linesInt:] + } + } + + c.JSON(http.StatusOK, gin.H{ + "logs": logs, + "count": len(logs), + }) + } +} + +// 读取日志文件 +func readLogFile(filePath string, maxLines int) ([]string, error) { + file, err := os.Open(filePath) + if err != nil { + return nil, err + } + defer file.Close() + + var lines []string + scanner := bufio.NewScanner(file) + for scanner.Scan() { + lines = append(lines, scanner.Text()) + if len(lines) >= maxLines*2 { + // 只保留最后maxLines行 + lines = lines[len(lines)-maxLines:] + } + } + + if err := scanner.Err(); err != nil { + return nil, err + } + + // 返回最后maxLines行 + if len(lines) > maxLines { + return lines[len(lines)-maxLines:], nil + } + return lines, nil +} + +// 去重日志 +func deduplicateLogs(logs []string) []string { + seen := make(map[string]bool) + result := make([]string, 0) + for i := len(logs) - 1; i >= 0; i-- { + if !seen[logs[i]] { + seen[logs[i]] = true + result = append([]string{logs[i]}, result...) + } + } + return result +} + +// 简单的整数解析(logs.go专用) +func parseIntLogs(s string) (int, error) { + var n int + for _, char := range s { + if char >= '0' && char <= '9' { + n = n*10 + int(char-'0') + } else { + return 0, io.EOF + } + } + return n, nil +} + +// 日志中间件 - 记录请求日志 +func LoggingMiddleware() gin.HandlerFunc { + return func(c *gin.Context) { + start := time.Now() + path := c.Request.URL.Path + query := c.Request.URL.RawQuery + ip := c.ClientIP() + + c.Next() + + latency := time.Since(start) + method := c.Request.Method + statusCode := c.Writer.Status() + + logLine := formatLogLine(start, method, statusCode, latency, path, query, ip) + AddLogToBuffer(logLine) + } +} + +func formatLogLine(timestamp time.Time, method string, statusCode int, latency time.Duration, path, query, ip string) string { + if query != "" { + path = path + "?" + query + } + // 使用Asia/Shanghai时区格式化时间 + loc, _ := time.LoadLocation("Asia/Shanghai") + shanghaiTime := timestamp.In(loc) + // 格式化日志:只包含一个时间戳 + return fmt.Sprintf("[%s] %s %s :: %s %d %s", + shanghaiTime.Format("2006-01-02 15:04:05"), + method, + path, + ip, + statusCode, + latency.String(), + ) +} diff --git a/internal/api/routes.go b/internal/api/routes.go new file mode 100644 index 0000000..4057688 --- /dev/null +++ b/internal/api/routes.go @@ -0,0 +1,81 @@ +package api + +import ( + "home-vue-go/internal/config" + "home-vue-go/internal/database" + + "github.com/gin-gonic/gin" +) + +func SetupRoutes(r *gin.Engine, db *database.Database, cfg *config.Config) { + // 初始化日志缓冲区 + InitLogBuffer() + + // 添加日志中间件 + r.Use(LoggingMiddleware()) + + api := r.Group("/api") + { + // 公开API - 获取数据 + api.GET("/sites", GetSites(db)) + api.GET("/contacts", GetContacts(db)) + api.GET("/config", GetSiteConfig(db, cfg)) + api.GET("/frontend-config", GetFrontendConfig(db)) + api.GET("/rotating-texts", GetRotatingTexts(cfg)) + + // 访问统计API(公开,用于记录访问) + api.POST("/track-visit", TrackVisit(db)) + + // 认证API + auth := api.Group("/auth") + { + auth.POST("/login", Login(db, cfg)) + } + + // 受保护的管理API + admin := api.Group("/admin") + admin.Use(JWTAuthMiddleware(cfg.JWTSecret)) + { + // 站点管理 + admin.GET("/sites", GetSites(db)) + admin.POST("/sites", CreateSite(db)) + admin.PUT("/sites/:id", UpdateSite(db)) + admin.DELETE("/sites/:id", DeleteSite(db)) + + // 联系方式管理 + admin.GET("/contacts", GetContacts(db)) + admin.POST("/contacts", CreateContact(db)) + admin.PUT("/contacts/:id", UpdateContact(db)) + admin.DELETE("/contacts/:id", DeleteContact(db)) + + // 站点配置管理 + admin.GET("/config", GetSiteConfig(db, cfg)) + admin.PUT("/config", UpdateSiteConfig(db, cfg)) + + // 轮换文本配置 + admin.GET("/rotating-texts", GetRotatingTexts(cfg)) + admin.PUT("/rotating-texts", UpdateRotatingTexts(cfg)) + + // 文件上传 + admin.POST("/upload", UploadFile(cfg)) + + // 统计API + admin.GET("/stats", GetStats(db)) + admin.GET("/charts", GetChartData(db)) + admin.GET("/recent-visits", GetRecentVisits(db)) + admin.POST("/notify-update", NotifyConfigUpdate()) + + // 用户管理 + admin.PUT("/change-password", ChangePassword(db)) + + // 日志API + admin.GET("/logs", GetBackendLogs(cfg)) + + // 登录历史API + admin.GET("/login-history", GetLoginHistory(db)) + } + } + + // 静态文件服务 - 提供上传的图片 + r.Static("/uploads", cfg.UploadDir) +} diff --git a/internal/api/sites.go b/internal/api/sites.go new file mode 100644 index 0000000..6ebab5a --- /dev/null +++ b/internal/api/sites.go @@ -0,0 +1,139 @@ +package api + +import ( + "net/http" + "strconv" + + "home-vue-go/internal/database" + "home-vue-go/internal/ent/site" + + "github.com/gin-gonic/gin" +) + +func GetSites(db *database.Database) gin.HandlerFunc { + return func(c *gin.Context) { + ctx := c.Request.Context() + sites, err := db.Client.Site.Query().Order(site.BySortOrder(), site.ByID()).All(ctx) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + result := make([]gin.H, len(sites)) + for i, site := range sites { + result[i] = gin.H{ + "id": site.ID, + "name": site.Name, + "url": site.URL, + "icon": site.Icon, + "sortOrder": site.SortOrder, + } + } + + c.JSON(http.StatusOK, result) + } +} + +func CreateSite(db *database.Database) gin.HandlerFunc { + return func(c *gin.Context) { + var req struct { + Name string `json:"name" binding:"required"` + URL string `json:"url" binding:"required"` + Icon string `json:"icon" binding:"required"` + SortOrder int `json:"sortOrder"` + } + + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + ctx := c.Request.Context() + site, err := db.Client.Site.Create(). + SetName(req.Name). + SetURL(req.URL). + SetIcon(req.Icon). + SetSortOrder(req.SortOrder). + Save(ctx) + + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, gin.H{ + "id": site.ID, + "name": site.Name, + "url": site.URL, + "icon": site.Icon, + "sortOrder": site.SortOrder, + }) + } +} + +func UpdateSite(db *database.Database) gin.HandlerFunc { + return func(c *gin.Context) { + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的ID"}) + return + } + + var req struct { + Name string `json:"name"` + URL string `json:"url"` + Icon string `json:"icon"` + SortOrder int `json:"sortOrder"` + } + + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + ctx := c.Request.Context() + update := db.Client.Site.UpdateOneID(id) + if req.Name != "" { + update.SetName(req.Name) + } + if req.URL != "" { + update.SetURL(req.URL) + } + if req.Icon != "" { + update.SetIcon(req.Icon) + } + update.SetSortOrder(req.SortOrder) + + site, err := update.Save(ctx) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, gin.H{ + "id": site.ID, + "name": site.Name, + "url": site.URL, + "icon": site.Icon, + "sortOrder": site.SortOrder, + }) + } +} + +func DeleteSite(db *database.Database) gin.HandlerFunc { + return func(c *gin.Context) { + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的ID"}) + return + } + + ctx := c.Request.Context() + if err := db.Client.Site.DeleteOneID(id).Exec(ctx); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, gin.H{"message": "删除成功"}) + } +} diff --git a/internal/api/stats.go b/internal/api/stats.go new file mode 100644 index 0000000..72047da --- /dev/null +++ b/internal/api/stats.go @@ -0,0 +1,193 @@ +package api + +import ( + "fmt" + "net/http" + "strings" + "time" + + "home-vue-go/internal/database" + + "github.com/gin-gonic/gin" +) + +// GetStats 获取统计数据 +func GetStats(db *database.Database) gin.HandlerFunc { + return func(c *gin.Context) { + ctx := c.Request.Context() + + // 获取站点数量 + sites, _ := db.Client.Site.Query().All(ctx) + totalSites := len(sites) + + // 获取总访问量(从内存记录) + records := getVisitRecords() + totalViews := len(records) + + // 获取独立访客数(去重IP) + uniqueIPs := make(map[string]bool) + for _, r := range records { + uniqueIPs[r.IP] = true + } + uniqueVisitors := len(uniqueIPs) + + // 获取今日访问量 + today := time.Now() + todayStart := time.Date(today.Year(), today.Month(), today.Day(), 0, 0, 0, 0, today.Location()) + todayViews := 0 + for _, r := range records { + if r.VisitTime.After(todayStart) { + todayViews++ + } + } + + stats := gin.H{ + "totalViews": totalViews, + "uniqueVisitors": uniqueVisitors, + "todayViews": todayViews, + "totalSites": totalSites, + } + + c.JSON(http.StatusOK, stats) + } +} + +// GetChartData 获取图表数据 +func GetChartData(db *database.Database) gin.HandlerFunc { + return func(c *gin.Context) { + period := c.DefaultQuery("period", "7") + + // 根据period确定天数 + periodDays := 7 + if period == "30" { + periodDays = 30 + } else if period == "90" { + periodDays = 90 + } + + // 获取真实趋势数据(从内存记录) + records := getVisitRecords() + trend := []gin.H{} + now := time.Now() + + for i := 0; i < periodDays; i++ { + date := now.AddDate(0, 0, -(periodDays-1-i)) + dayStart := time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, date.Location()) + dayEnd := dayStart.Add(24 * time.Hour) + + // 统计当天的访问量 + count := 0 + for _, r := range records { + if r.VisitTime.After(dayStart) && r.VisitTime.Before(dayEnd) { + count++ + } + } + + trend = append(trend, gin.H{ + "label": date.Format("1/2"), + "value": count, + }) + } + + // 获取访问来源数据(基于referer) + sourceMap := make(map[string]int) + total := len(records) + + for _, r := range records { + ref := strings.ToLower(r.Referer) + if ref == "" { + sourceMap["直接访问"]++ + } else if strings.Contains(ref, "google") || strings.Contains(ref, "baidu") || strings.Contains(ref, "bing") || strings.Contains(ref, "yahoo") || strings.Contains(ref, "sogou") { + sourceMap["搜索引擎"]++ + } else if strings.Contains(ref, "twitter") || strings.Contains(ref, "facebook") || strings.Contains(ref, "weibo") || strings.Contains(ref, "wechat") || strings.Contains(ref, "qq") { + sourceMap["社交媒体"]++ + } else { + sourceMap["其他"]++ + } + } + + sources := []gin.H{} + if total > 0 { + for label, count := range sourceMap { + sources = append(sources, gin.H{ + "label": label, + "value": (count * 100) / total, // 转换为百分比 + }) + } + } else { + // 如果没有数据,返回默认值 + sources = []gin.H{ + {"label": "直接访问", "value": 100}, + } + } + + c.JSON(http.StatusOK, gin.H{ + "trend": trend, + "sources": sources, + }) + } +} + + +// GetRecentVisits 获取最近访问记录 +func GetRecentVisits(db *database.Database) gin.HandlerFunc { + return func(c *gin.Context) { + // 支持通过 query 参数自定义条数,默认 5,最大 50 + limit := 5 + if q := c.DefaultQuery("limit", "5"); q != "" { + if n, err := parseInt(q); err == nil && n > 0 { + limit = n + if limit > 50 { + limit = 50 + } + } + } + + // 从内存记录获取最近访问 + records := getVisitRecords() + result := make([]gin.H, 0, limit) + now := time.Now() + + // 取最近 limit 条 + start := len(records) - limit + if start < 0 { + start = 0 + } + + for i := len(records) - 1; i >= start && i >= 0; i-- { + r := records[i] + + // 计算相对时间 + diff := now.Sub(r.VisitTime) + var timeStr string + if diff < time.Minute { + timeStr = "刚刚" + } else if diff < time.Hour { + timeStr = fmt.Sprintf("%.0f分钟前", diff.Minutes()) + } else if diff < 24*time.Hour { + timeStr = fmt.Sprintf("%.0f小时前", diff.Hours()) + } else { + timeStr = fmt.Sprintf("%.0f天前", diff.Hours()/24) + } + + result = append(result, gin.H{ + "path": r.Path, + "ip": r.IP, + "time": timeStr, + }) + } + + c.JSON(http.StatusOK, result) + } +} + +// NotifyConfigUpdate 通知配置更新(用于热重载) +func NotifyConfigUpdate() gin.HandlerFunc { + return func(c *gin.Context) { + // 这里可以添加通知逻辑,比如通过WebSocket或SSE通知前端 + // 目前简单返回成功 + c.JSON(http.StatusOK, gin.H{ + "message": "配置更新通知已发送", + }) + } +} diff --git a/internal/api/track.go b/internal/api/track.go new file mode 100644 index 0000000..997363c --- /dev/null +++ b/internal/api/track.go @@ -0,0 +1,76 @@ +package api + +import ( + "net/http" + "sync" + "time" + + "home-vue-go/internal/database" + + "github.com/gin-gonic/gin" +) + +// VisitRecord 表示一次访问记录(暂存在内存中) +type VisitRecord struct { + Path string + IP string + UserAgent string + Referer string + VisitTime time.Time +} + +// 简单的内存存储与读写锁 +var ( + visitMutex sync.RWMutex + visitRecords []VisitRecord + maxVisits = 1000 // 最多保留的访问记录条数 +) + +// TrackVisit 记录访问 +func TrackVisit(db *database.Database) gin.HandlerFunc { + return func(c *gin.Context) { + var req struct { + Path string `json:"path"` + Referer string `json:"referer"` + } + + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"}) + return + } + + ip := c.ClientIP() + userAgent := c.GetHeader("User-Agent") + + // 记录访问到内存 + visitMutex.Lock() + visitRecords = append(visitRecords, VisitRecord{ + Path: req.Path, + IP: ip, + UserAgent: userAgent, + Referer: req.Referer, + VisitTime: time.Now(), + }) + + // 限制记录数量 + if len(visitRecords) > maxVisits { + visitRecords = visitRecords[len(visitRecords)-maxVisits:] + } + visitMutex.Unlock() + + // TODO: 等Ent代码生成后,改用数据库存储 + // ctx := c.Request.Context() + // if db.Client.Visit != nil { + // db.Client.Visit.Create()... + // } + + c.JSON(http.StatusOK, gin.H{"message": "访问已记录"}) + } +} + +// 获取访问记录(从内存) +func getVisitRecords() []VisitRecord { + visitMutex.RLock() + defer visitMutex.RUnlock() + return visitRecords +} diff --git a/internal/api/upload.go b/internal/api/upload.go new file mode 100644 index 0000000..d169249 --- /dev/null +++ b/internal/api/upload.go @@ -0,0 +1,69 @@ +package api + +import ( + "fmt" + "net/http" + "path/filepath" + "strings" + "time" + + "home-vue-go/internal/config" + + "github.com/gin-gonic/gin" +) + +var allowedImageExtensions = map[string]bool{ + ".jpg": true, + ".jpeg": true, + ".png": true, + ".gif": true, + ".webp": true, + ".avif": true, + ".svg": true, + ".bmp": true, + ".ico": true, +} + +func UploadFile(cfg *config.Config) gin.HandlerFunc { + return func(c *gin.Context) { + file, err := c.FormFile("file") + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "文件上传失败: " + err.Error()}) + return + } + + // 检查文件扩展名 + ext := strings.ToLower(filepath.Ext(file.Filename)) + if !allowedImageExtensions[ext] { + c.JSON(http.StatusBadRequest, gin.H{ + "error": fmt.Sprintf("不支持的文件格式。支持的格式: %v", getKeys(allowedImageExtensions)), + }) + return + } + + // 生成唯一文件名 + filename := fmt.Sprintf("%d%s", time.Now().UnixNano(), ext) + dst := filepath.Join(cfg.UploadDir, filename) + + // 保存文件 + if err := c.SaveUploadedFile(file, dst); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "文件保存失败: " + err.Error()}) + return + } + + // 返回文件URL(相对于uploads目录) + fileURL := fmt.Sprintf("/uploads/%s", filename) + c.JSON(http.StatusOK, gin.H{ + "url": fileURL, + "path": fileURL, + }) + } +} + +func getKeys(m map[string]bool) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + return keys +} diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..1016bb3 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,35 @@ +package config + +import ( + "os" + "path/filepath" +) + +type Config struct { + DataDir string + DatabasePath string + UploadDir string + JWTSecret string +} + +func New(dataDir string) *Config { + // 确保data目录存在 + os.MkdirAll(dataDir, 0755) + + // 创建上传目录 + uploadDir := filepath.Join(dataDir, "uploads") + os.MkdirAll(uploadDir, 0755) + + // 从环境变量获取JWT密钥,如果没有则使用默认值 + jwtSecret := os.Getenv("JWT_SECRET") + if jwtSecret == "" { + jwtSecret = "your-secret-key-change-in-production" + } + + return &Config{ + DataDir: dataDir, + DatabasePath: filepath.Join(dataDir, "home.db"), + UploadDir: uploadDir, + JWTSecret: jwtSecret, + } +} diff --git a/internal/config/footer_year.go b/internal/config/footer_year.go new file mode 100644 index 0000000..1a3be49 --- /dev/null +++ b/internal/config/footer_year.go @@ -0,0 +1,58 @@ +package config + +import ( + "encoding/json" + "os" + "path/filepath" +) + +// FooterYearConfig 用于存储底部版权年份配置 +type FooterYearConfig struct { + Start string `json:"start"` + End string `json:"end"` +} + +// footerYearConfigPath 返回年份配置文件路径 +func (c *Config) footerYearConfigPath() string { + return filepath.Join(c.DataDir, "footer_year.json") +} + +// LoadFooterYear 读取底部年份配置(文件不存在时返回空配置而不是报错) +func (c *Config) LoadFooterYear() (*FooterYearConfig, error) { + path := c.footerYearConfigPath() + + data, err := os.ReadFile(path) + if err != nil { + if os.IsNotExist(err) { + // 没有配置文件时返回空配置 + return &FooterYearConfig{}, nil + } + return nil, err + } + + var cfg FooterYearConfig + if err := json.Unmarshal(data, &cfg); err != nil { + // 解析失败时返回空配置,但把错误也返回方便日志排查 + return &FooterYearConfig{}, err + } + return &cfg, nil +} + +// SaveFooterYear 保存底部年份配置 +func (c *Config) SaveFooterYear(cfg *FooterYearConfig) error { + if cfg == nil { + cfg = &FooterYearConfig{} + } + + data, err := json.MarshalIndent(cfg, "", " ") + if err != nil { + return err + } + + path := c.footerYearConfigPath() + if err := os.WriteFile(path, data, 0644); err != nil { + return err + } + return nil +} + diff --git a/internal/config/rotating_texts.go b/internal/config/rotating_texts.go new file mode 100644 index 0000000..512fc70 --- /dev/null +++ b/internal/config/rotating_texts.go @@ -0,0 +1,85 @@ +package config + +import ( + "encoding/json" + "os" + "path/filepath" +) + +// RotatingTextsConfig 轮换文本配置 +type RotatingTextsConfig struct { + Texts []string `json:"texts"` +} + +// rotatingTextsConfigPath 返回轮换文本配置文件路径 +func (c *Config) rotatingTextsConfigPath() string { + return filepath.Join(c.DataDir, "rotating_texts.json") +} + +// LoadRotatingTexts 加载轮换文本配置 +func (c *Config) LoadRotatingTexts() (*RotatingTextsConfig, error) { + path := c.rotatingTextsConfigPath() + + // 如果文件不存在,返回默认值 + if _, err := os.Stat(path); os.IsNotExist(err) { + defaultTexts := &RotatingTextsConfig{ + Texts: []string{ + "你好鸭,欢迎来到我的主页!!", + "随时可以联系我,期待与你交流。", + "愿你历尽千帆,归来仍是少年。", + "梦想还是要有的,万一实现了呢?", + "I hope you have a happy day every day.", + }, + } + return defaultTexts, nil + } + + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + + var cfg RotatingTextsConfig + if err := json.Unmarshal(data, &cfg); err != nil { + return nil, err + } + + // 确保至少有默认文本 + if len(cfg.Texts) == 0 { + cfg.Texts = []string{ + "你好鸭,欢迎来到我的主页!!", + "随时可以联系我,期待与你交流。", + "愿你历尽千帆,归来仍是少年。", + "梦想还是要有的,万一实现了呢?", + "I hope you have a happy day every day.", + } + } + + return &cfg, nil +} + +// SaveRotatingTexts 保存轮换文本配置 +func (c *Config) SaveRotatingTexts(cfg *RotatingTextsConfig) error { + path := c.rotatingTextsConfigPath() + + // 限制最多8条文本 + if len(cfg.Texts) > 8 { + cfg.Texts = cfg.Texts[:8] + } + + // 过滤空文本 + filteredTexts := make([]string, 0, len(cfg.Texts)) + for _, text := range cfg.Texts { + if text != "" { + filteredTexts = append(filteredTexts, text) + } + } + cfg.Texts = filteredTexts + + data, err := json.MarshalIndent(cfg, "", " ") + if err != nil { + return err + } + + return os.WriteFile(path, data, 0644) +} diff --git a/internal/config/visit_timer.go b/internal/config/visit_timer.go new file mode 100644 index 0000000..7d09835 --- /dev/null +++ b/internal/config/visit_timer.go @@ -0,0 +1,56 @@ +package config + +import ( + "encoding/json" + "os" + "path/filepath" +) + +// VisitTimerConfig 用于存储访问时间显示配置 +type VisitTimerConfig struct { + ShowVisitTimer bool `json:"showVisitTimer"` +} + +// visitTimerConfigPath 返回访问时间配置文件路径 +func (c *Config) visitTimerConfigPath() string { + return filepath.Join(c.DataDir, "visit_timer.json") +} + +// LoadVisitTimer 读取访问时间显示配置(文件不存在时返回默认配置) +func (c *Config) LoadVisitTimer() (*VisitTimerConfig, error) { + path := c.visitTimerConfigPath() + + data, err := os.ReadFile(path) + if err != nil { + if os.IsNotExist(err) { + // 没有配置文件时返回默认配置(显示) + return &VisitTimerConfig{ShowVisitTimer: true}, nil + } + return nil, err + } + + var cfg VisitTimerConfig + if err := json.Unmarshal(data, &cfg); err != nil { + // 解析失败时返回默认配置 + return &VisitTimerConfig{ShowVisitTimer: true}, err + } + return &cfg, nil +} + +// SaveVisitTimer 保存访问时间显示配置 +func (c *Config) SaveVisitTimer(cfg *VisitTimerConfig) error { + if cfg == nil { + cfg = &VisitTimerConfig{ShowVisitTimer: true} + } + + data, err := json.MarshalIndent(cfg, "", " ") + if err != nil { + return err + } + + path := c.visitTimerConfigPath() + if err := os.WriteFile(path, data, 0644); err != nil { + return err + } + return nil +} diff --git a/internal/database/database.go b/internal/database/database.go new file mode 100644 index 0000000..715e6e9 --- /dev/null +++ b/internal/database/database.go @@ -0,0 +1,99 @@ +package database + +import ( + "context" + "database/sql" + "log" + + "entgo.io/ent/dialect" + entsql "entgo.io/ent/dialect/sql" + "home-vue-go/internal/ent" + "home-vue-go/internal/ent/migrate" + + _ "github.com/mattn/go-sqlite3" + "golang.org/x/crypto/bcrypt" +) + +type Database struct { + Client *ent.Client +} + +func Init(dbPath string) (*Database, error) { + db, err := sql.Open("sqlite3", dbPath+"?_fk=1") + if err != nil { + return nil, err + } + + drv := entsql.OpenDB(dialect.SQLite, db) + client := ent.NewClient(ent.Driver(drv)) + + // 运行数据库迁移 + ctx := context.Background() + if err := client.Schema.Create(ctx, migrate.WithForeignKeys(false)); err != nil { + log.Fatalf("数据库迁移失败: %v", err) + } + + // 初始化默认数据 + if err := initDefaultData(ctx, client); err != nil { + log.Printf("初始化默认数据失败: %v", err) + } + + return &Database{Client: client}, nil +} + +func (d *Database) Close() error { + return d.Client.Close() +} + +func initDefaultData(ctx context.Context, client *ent.Client) error { + // 检查是否已有站点配置 + _, err := client.SiteConfig.Get(ctx, 1) + if err == nil { + // 已存在配置,不初始化 + return nil + } + + // 创建默认站点配置 + _, err = client.SiteConfig.Create(). + SetSiteName("个人主页"). + SetSiteURL("https://example.com"). + SetSiteIcon("/favicon.ico"). + SetSiteDescription("一个基于Vue3的个人主页"). + SetSiteKeywords("个人主页,Vue3"). + SetUserName("用户"). + SetProfileImageURL(""). + SetIcpNumber(""). + SetPoliceNumber(""). + SetPageTitle("个人主页"). + SetFavicon("/favicon.ico"). + SetUmamiScript(""). + SetUmamiWebsiteID(""). + SetIconLibrary("//lib.baomitu.com/font-awesome/6.5.0/css/all.min.css"). + SetFontLibrary(""). + Save(ctx) + if err != nil { + return err + } + + // 检查是否已有用户,如果没有才创建默认管理员用户 + userCount, err := client.User.Query().Count(ctx) + if err != nil { + return err + } + + // 只有在没有任何用户时才创建默认管理员 + if userCount == 0 { + hashedPassword, err := bcrypt.GenerateFromPassword([]byte("admin123"), bcrypt.DefaultCost) + if err != nil { + return err + } + + _, err = client.User.Create(). + SetUsername("admin"). + SetPassword(string(hashedPassword)). + Save(ctx) + return err + } + + return nil +} diff --git a/internal/ent/README.md b/internal/ent/README.md new file mode 100644 index 0000000..ce4beef --- /dev/null +++ b/internal/ent/README.md @@ -0,0 +1,25 @@ +# Ent代码生成说明 + +## 生成Ent代码 + +在项目根目录运行以下命令来生成Ent代码: + +```bash +cd internal/ent +go generate ./... +``` + +或者使用项目根目录的Makefile: + +```bash +make generate +``` + +这将根据 `schema/` 目录中的schema定义自动生成所有必要的Ent代码。 + +## Schema文件 + +- `site.go` - 站点实体 +- `contact.go` - 联系方式实体 +- `site_config.go` - 站点配置实体 +- `user.go` - 用户实体 diff --git a/internal/ent/client.go b/internal/ent/client.go new file mode 100644 index 0000000..ddd4ec6 --- /dev/null +++ b/internal/ent/client.go @@ -0,0 +1,1054 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "log" + "reflect" + + "home-vue-go/internal/ent/migrate" + + "home-vue-go/internal/ent/contact" + "home-vue-go/internal/ent/loginhistory" + "home-vue-go/internal/ent/site" + "home-vue-go/internal/ent/siteconfig" + "home-vue-go/internal/ent/user" + "home-vue-go/internal/ent/visit" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" +) + +// Client is the client that holds all ent builders. +type Client struct { + config + // Schema is the client for creating, migrating and dropping schema. + Schema *migrate.Schema + // Contact is the client for interacting with the Contact builders. + Contact *ContactClient + // LoginHistory is the client for interacting with the LoginHistory builders. + LoginHistory *LoginHistoryClient + // Site is the client for interacting with the Site builders. + Site *SiteClient + // SiteConfig is the client for interacting with the SiteConfig builders. + SiteConfig *SiteConfigClient + // User is the client for interacting with the User builders. + User *UserClient + // Visit is the client for interacting with the Visit builders. + Visit *VisitClient +} + +// NewClient creates a new client configured with the given options. +func NewClient(opts ...Option) *Client { + client := &Client{config: newConfig(opts...)} + client.init() + return client +} + +func (c *Client) init() { + c.Schema = migrate.NewSchema(c.driver) + c.Contact = NewContactClient(c.config) + c.LoginHistory = NewLoginHistoryClient(c.config) + c.Site = NewSiteClient(c.config) + c.SiteConfig = NewSiteConfigClient(c.config) + c.User = NewUserClient(c.config) + c.Visit = NewVisitClient(c.config) +} + +type ( + // config is the configuration for the client and its builder. + config struct { + // driver used for executing database requests. + driver dialect.Driver + // debug enable a debug logging. + debug bool + // log used for logging on debug mode. + log func(...any) + // hooks to execute on mutations. + hooks *hooks + // interceptors to execute on queries. + inters *inters + } + // Option function to configure the client. + Option func(*config) +) + +// newConfig creates a new config for the client. +func newConfig(opts ...Option) config { + cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}} + cfg.options(opts...) + return cfg +} + +// options applies the options on the config object. +func (c *config) options(opts ...Option) { + for _, opt := range opts { + opt(c) + } + if c.debug { + c.driver = dialect.Debug(c.driver, c.log) + } +} + +// Debug enables debug logging on the ent.Driver. +func Debug() Option { + return func(c *config) { + c.debug = true + } +} + +// Log sets the logging function for debug mode. +func Log(fn func(...any)) Option { + return func(c *config) { + c.log = fn + } +} + +// Driver configures the client driver. +func Driver(driver dialect.Driver) Option { + return func(c *config) { + c.driver = driver + } +} + +// Open opens a database/sql.DB specified by the driver name and +// the data source name, and returns a new client attached to it. +// Optional parameters can be added for configuring the client. +func Open(driverName, dataSourceName string, options ...Option) (*Client, error) { + switch driverName { + case dialect.MySQL, dialect.Postgres, dialect.SQLite: + drv, err := sql.Open(driverName, dataSourceName) + if err != nil { + return nil, err + } + return NewClient(append(options, Driver(drv))...), nil + default: + return nil, fmt.Errorf("unsupported driver: %q", driverName) + } +} + +// ErrTxStarted is returned when trying to start a new transaction from a transactional client. +var ErrTxStarted = errors.New("ent: cannot start a transaction within a transaction") + +// Tx returns a new transactional client. The provided context +// is used until the transaction is committed or rolled back. +func (c *Client) Tx(ctx context.Context) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, ErrTxStarted + } + tx, err := newTx(ctx, c.driver) + if err != nil { + return nil, fmt.Errorf("ent: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = tx + return &Tx{ + ctx: ctx, + config: cfg, + Contact: NewContactClient(cfg), + LoginHistory: NewLoginHistoryClient(cfg), + Site: NewSiteClient(cfg), + SiteConfig: NewSiteConfigClient(cfg), + User: NewUserClient(cfg), + Visit: NewVisitClient(cfg), + }, nil +} + +// BeginTx returns a transactional client with specified options. +func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, errors.New("ent: cannot start a transaction within a transaction") + } + tx, err := c.driver.(interface { + BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error) + }).BeginTx(ctx, opts) + if err != nil { + return nil, fmt.Errorf("ent: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = &txDriver{tx: tx, drv: c.driver} + return &Tx{ + ctx: ctx, + config: cfg, + Contact: NewContactClient(cfg), + LoginHistory: NewLoginHistoryClient(cfg), + Site: NewSiteClient(cfg), + SiteConfig: NewSiteConfigClient(cfg), + User: NewUserClient(cfg), + Visit: NewVisitClient(cfg), + }, nil +} + +// Debug returns a new debug-client. It's used to get verbose logging on specific operations. +// +// client.Debug(). +// Contact. +// Query(). +// Count(ctx) +func (c *Client) Debug() *Client { + if c.debug { + return c + } + cfg := c.config + cfg.driver = dialect.Debug(c.driver, c.log) + client := &Client{config: cfg} + client.init() + return client +} + +// Close closes the database connection and prevents new queries from starting. +func (c *Client) Close() error { + return c.driver.Close() +} + +// Use adds the mutation hooks to all the entity clients. +// In order to add hooks to a specific client, call: `client.Node.Use(...)`. +func (c *Client) Use(hooks ...Hook) { + for _, n := range []interface{ Use(...Hook) }{ + c.Contact, c.LoginHistory, c.Site, c.SiteConfig, c.User, c.Visit, + } { + n.Use(hooks...) + } +} + +// Intercept adds the query interceptors to all the entity clients. +// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. +func (c *Client) Intercept(interceptors ...Interceptor) { + for _, n := range []interface{ Intercept(...Interceptor) }{ + c.Contact, c.LoginHistory, c.Site, c.SiteConfig, c.User, c.Visit, + } { + n.Intercept(interceptors...) + } +} + +// Mutate implements the ent.Mutator interface. +func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { + switch m := m.(type) { + case *ContactMutation: + return c.Contact.mutate(ctx, m) + case *LoginHistoryMutation: + return c.LoginHistory.mutate(ctx, m) + case *SiteMutation: + return c.Site.mutate(ctx, m) + case *SiteConfigMutation: + return c.SiteConfig.mutate(ctx, m) + case *UserMutation: + return c.User.mutate(ctx, m) + case *VisitMutation: + return c.Visit.mutate(ctx, m) + default: + return nil, fmt.Errorf("ent: unknown mutation type %T", m) + } +} + +// ContactClient is a client for the Contact schema. +type ContactClient struct { + config +} + +// NewContactClient returns a client for the Contact from the given config. +func NewContactClient(c config) *ContactClient { + return &ContactClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `contact.Hooks(f(g(h())))`. +func (c *ContactClient) Use(hooks ...Hook) { + c.hooks.Contact = append(c.hooks.Contact, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `contact.Intercept(f(g(h())))`. +func (c *ContactClient) Intercept(interceptors ...Interceptor) { + c.inters.Contact = append(c.inters.Contact, interceptors...) +} + +// Create returns a builder for creating a Contact entity. +func (c *ContactClient) Create() *ContactCreate { + mutation := newContactMutation(c.config, OpCreate) + return &ContactCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Contact entities. +func (c *ContactClient) CreateBulk(builders ...*ContactCreate) *ContactCreateBulk { + return &ContactCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *ContactClient) MapCreateBulk(slice any, setFunc func(*ContactCreate, int)) *ContactCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ContactCreateBulk{err: fmt.Errorf("calling to ContactClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ContactCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ContactCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Contact. +func (c *ContactClient) Update() *ContactUpdate { + mutation := newContactMutation(c.config, OpUpdate) + return &ContactUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ContactClient) UpdateOne(_m *Contact) *ContactUpdateOne { + mutation := newContactMutation(c.config, OpUpdateOne, withContact(_m)) + return &ContactUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ContactClient) UpdateOneID(id int) *ContactUpdateOne { + mutation := newContactMutation(c.config, OpUpdateOne, withContactID(id)) + return &ContactUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Contact. +func (c *ContactClient) Delete() *ContactDelete { + mutation := newContactMutation(c.config, OpDelete) + return &ContactDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ContactClient) DeleteOne(_m *Contact) *ContactDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ContactClient) DeleteOneID(id int) *ContactDeleteOne { + builder := c.Delete().Where(contact.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ContactDeleteOne{builder} +} + +// Query returns a query builder for Contact. +func (c *ContactClient) Query() *ContactQuery { + return &ContactQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeContact}, + inters: c.Interceptors(), + } +} + +// Get returns a Contact entity by its id. +func (c *ContactClient) Get(ctx context.Context, id int) (*Contact, error) { + return c.Query().Where(contact.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ContactClient) GetX(ctx context.Context, id int) *Contact { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *ContactClient) Hooks() []Hook { + return c.hooks.Contact +} + +// Interceptors returns the client interceptors. +func (c *ContactClient) Interceptors() []Interceptor { + return c.inters.Contact +} + +func (c *ContactClient) mutate(ctx context.Context, m *ContactMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ContactCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ContactUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ContactUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ContactDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Contact mutation op: %q", m.Op()) + } +} + +// LoginHistoryClient is a client for the LoginHistory schema. +type LoginHistoryClient struct { + config +} + +// NewLoginHistoryClient returns a client for the LoginHistory from the given config. +func NewLoginHistoryClient(c config) *LoginHistoryClient { + return &LoginHistoryClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `loginhistory.Hooks(f(g(h())))`. +func (c *LoginHistoryClient) Use(hooks ...Hook) { + c.hooks.LoginHistory = append(c.hooks.LoginHistory, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `loginhistory.Intercept(f(g(h())))`. +func (c *LoginHistoryClient) Intercept(interceptors ...Interceptor) { + c.inters.LoginHistory = append(c.inters.LoginHistory, interceptors...) +} + +// Create returns a builder for creating a LoginHistory entity. +func (c *LoginHistoryClient) Create() *LoginHistoryCreate { + mutation := newLoginHistoryMutation(c.config, OpCreate) + return &LoginHistoryCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of LoginHistory entities. +func (c *LoginHistoryClient) CreateBulk(builders ...*LoginHistoryCreate) *LoginHistoryCreateBulk { + return &LoginHistoryCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *LoginHistoryClient) MapCreateBulk(slice any, setFunc func(*LoginHistoryCreate, int)) *LoginHistoryCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &LoginHistoryCreateBulk{err: fmt.Errorf("calling to LoginHistoryClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*LoginHistoryCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &LoginHistoryCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for LoginHistory. +func (c *LoginHistoryClient) Update() *LoginHistoryUpdate { + mutation := newLoginHistoryMutation(c.config, OpUpdate) + return &LoginHistoryUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *LoginHistoryClient) UpdateOne(_m *LoginHistory) *LoginHistoryUpdateOne { + mutation := newLoginHistoryMutation(c.config, OpUpdateOne, withLoginHistory(_m)) + return &LoginHistoryUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *LoginHistoryClient) UpdateOneID(id int) *LoginHistoryUpdateOne { + mutation := newLoginHistoryMutation(c.config, OpUpdateOne, withLoginHistoryID(id)) + return &LoginHistoryUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for LoginHistory. +func (c *LoginHistoryClient) Delete() *LoginHistoryDelete { + mutation := newLoginHistoryMutation(c.config, OpDelete) + return &LoginHistoryDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *LoginHistoryClient) DeleteOne(_m *LoginHistory) *LoginHistoryDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *LoginHistoryClient) DeleteOneID(id int) *LoginHistoryDeleteOne { + builder := c.Delete().Where(loginhistory.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &LoginHistoryDeleteOne{builder} +} + +// Query returns a query builder for LoginHistory. +func (c *LoginHistoryClient) Query() *LoginHistoryQuery { + return &LoginHistoryQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeLoginHistory}, + inters: c.Interceptors(), + } +} + +// Get returns a LoginHistory entity by its id. +func (c *LoginHistoryClient) Get(ctx context.Context, id int) (*LoginHistory, error) { + return c.Query().Where(loginhistory.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *LoginHistoryClient) GetX(ctx context.Context, id int) *LoginHistory { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *LoginHistoryClient) Hooks() []Hook { + return c.hooks.LoginHistory +} + +// Interceptors returns the client interceptors. +func (c *LoginHistoryClient) Interceptors() []Interceptor { + return c.inters.LoginHistory +} + +func (c *LoginHistoryClient) mutate(ctx context.Context, m *LoginHistoryMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&LoginHistoryCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&LoginHistoryUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&LoginHistoryUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&LoginHistoryDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown LoginHistory mutation op: %q", m.Op()) + } +} + +// SiteClient is a client for the Site schema. +type SiteClient struct { + config +} + +// NewSiteClient returns a client for the Site from the given config. +func NewSiteClient(c config) *SiteClient { + return &SiteClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `site.Hooks(f(g(h())))`. +func (c *SiteClient) Use(hooks ...Hook) { + c.hooks.Site = append(c.hooks.Site, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `site.Intercept(f(g(h())))`. +func (c *SiteClient) Intercept(interceptors ...Interceptor) { + c.inters.Site = append(c.inters.Site, interceptors...) +} + +// Create returns a builder for creating a Site entity. +func (c *SiteClient) Create() *SiteCreate { + mutation := newSiteMutation(c.config, OpCreate) + return &SiteCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Site entities. +func (c *SiteClient) CreateBulk(builders ...*SiteCreate) *SiteCreateBulk { + return &SiteCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *SiteClient) MapCreateBulk(slice any, setFunc func(*SiteCreate, int)) *SiteCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &SiteCreateBulk{err: fmt.Errorf("calling to SiteClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*SiteCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &SiteCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Site. +func (c *SiteClient) Update() *SiteUpdate { + mutation := newSiteMutation(c.config, OpUpdate) + return &SiteUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *SiteClient) UpdateOne(_m *Site) *SiteUpdateOne { + mutation := newSiteMutation(c.config, OpUpdateOne, withSite(_m)) + return &SiteUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *SiteClient) UpdateOneID(id int) *SiteUpdateOne { + mutation := newSiteMutation(c.config, OpUpdateOne, withSiteID(id)) + return &SiteUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Site. +func (c *SiteClient) Delete() *SiteDelete { + mutation := newSiteMutation(c.config, OpDelete) + return &SiteDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *SiteClient) DeleteOne(_m *Site) *SiteDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *SiteClient) DeleteOneID(id int) *SiteDeleteOne { + builder := c.Delete().Where(site.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &SiteDeleteOne{builder} +} + +// Query returns a query builder for Site. +func (c *SiteClient) Query() *SiteQuery { + return &SiteQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeSite}, + inters: c.Interceptors(), + } +} + +// Get returns a Site entity by its id. +func (c *SiteClient) Get(ctx context.Context, id int) (*Site, error) { + return c.Query().Where(site.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *SiteClient) GetX(ctx context.Context, id int) *Site { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *SiteClient) Hooks() []Hook { + return c.hooks.Site +} + +// Interceptors returns the client interceptors. +func (c *SiteClient) Interceptors() []Interceptor { + return c.inters.Site +} + +func (c *SiteClient) mutate(ctx context.Context, m *SiteMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&SiteCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&SiteUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&SiteUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&SiteDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Site mutation op: %q", m.Op()) + } +} + +// SiteConfigClient is a client for the SiteConfig schema. +type SiteConfigClient struct { + config +} + +// NewSiteConfigClient returns a client for the SiteConfig from the given config. +func NewSiteConfigClient(c config) *SiteConfigClient { + return &SiteConfigClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `siteconfig.Hooks(f(g(h())))`. +func (c *SiteConfigClient) Use(hooks ...Hook) { + c.hooks.SiteConfig = append(c.hooks.SiteConfig, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `siteconfig.Intercept(f(g(h())))`. +func (c *SiteConfigClient) Intercept(interceptors ...Interceptor) { + c.inters.SiteConfig = append(c.inters.SiteConfig, interceptors...) +} + +// Create returns a builder for creating a SiteConfig entity. +func (c *SiteConfigClient) Create() *SiteConfigCreate { + mutation := newSiteConfigMutation(c.config, OpCreate) + return &SiteConfigCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of SiteConfig entities. +func (c *SiteConfigClient) CreateBulk(builders ...*SiteConfigCreate) *SiteConfigCreateBulk { + return &SiteConfigCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *SiteConfigClient) MapCreateBulk(slice any, setFunc func(*SiteConfigCreate, int)) *SiteConfigCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &SiteConfigCreateBulk{err: fmt.Errorf("calling to SiteConfigClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*SiteConfigCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &SiteConfigCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for SiteConfig. +func (c *SiteConfigClient) Update() *SiteConfigUpdate { + mutation := newSiteConfigMutation(c.config, OpUpdate) + return &SiteConfigUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *SiteConfigClient) UpdateOne(_m *SiteConfig) *SiteConfigUpdateOne { + mutation := newSiteConfigMutation(c.config, OpUpdateOne, withSiteConfig(_m)) + return &SiteConfigUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *SiteConfigClient) UpdateOneID(id int) *SiteConfigUpdateOne { + mutation := newSiteConfigMutation(c.config, OpUpdateOne, withSiteConfigID(id)) + return &SiteConfigUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for SiteConfig. +func (c *SiteConfigClient) Delete() *SiteConfigDelete { + mutation := newSiteConfigMutation(c.config, OpDelete) + return &SiteConfigDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *SiteConfigClient) DeleteOne(_m *SiteConfig) *SiteConfigDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *SiteConfigClient) DeleteOneID(id int) *SiteConfigDeleteOne { + builder := c.Delete().Where(siteconfig.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &SiteConfigDeleteOne{builder} +} + +// Query returns a query builder for SiteConfig. +func (c *SiteConfigClient) Query() *SiteConfigQuery { + return &SiteConfigQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeSiteConfig}, + inters: c.Interceptors(), + } +} + +// Get returns a SiteConfig entity by its id. +func (c *SiteConfigClient) Get(ctx context.Context, id int) (*SiteConfig, error) { + return c.Query().Where(siteconfig.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *SiteConfigClient) GetX(ctx context.Context, id int) *SiteConfig { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *SiteConfigClient) Hooks() []Hook { + return c.hooks.SiteConfig +} + +// Interceptors returns the client interceptors. +func (c *SiteConfigClient) Interceptors() []Interceptor { + return c.inters.SiteConfig +} + +func (c *SiteConfigClient) mutate(ctx context.Context, m *SiteConfigMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&SiteConfigCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&SiteConfigUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&SiteConfigUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&SiteConfigDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown SiteConfig mutation op: %q", m.Op()) + } +} + +// UserClient is a client for the User schema. +type UserClient struct { + config +} + +// NewUserClient returns a client for the User from the given config. +func NewUserClient(c config) *UserClient { + return &UserClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `user.Hooks(f(g(h())))`. +func (c *UserClient) Use(hooks ...Hook) { + c.hooks.User = append(c.hooks.User, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `user.Intercept(f(g(h())))`. +func (c *UserClient) Intercept(interceptors ...Interceptor) { + c.inters.User = append(c.inters.User, interceptors...) +} + +// Create returns a builder for creating a User entity. +func (c *UserClient) Create() *UserCreate { + mutation := newUserMutation(c.config, OpCreate) + return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of User entities. +func (c *UserClient) CreateBulk(builders ...*UserCreate) *UserCreateBulk { + return &UserCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *UserClient) MapCreateBulk(slice any, setFunc func(*UserCreate, int)) *UserCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &UserCreateBulk{err: fmt.Errorf("calling to UserClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*UserCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &UserCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for User. +func (c *UserClient) Update() *UserUpdate { + mutation := newUserMutation(c.config, OpUpdate) + return &UserUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *UserClient) UpdateOne(_m *User) *UserUpdateOne { + mutation := newUserMutation(c.config, OpUpdateOne, withUser(_m)) + return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *UserClient) UpdateOneID(id int) *UserUpdateOne { + mutation := newUserMutation(c.config, OpUpdateOne, withUserID(id)) + return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for User. +func (c *UserClient) Delete() *UserDelete { + mutation := newUserMutation(c.config, OpDelete) + return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *UserClient) DeleteOne(_m *User) *UserDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { + builder := c.Delete().Where(user.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &UserDeleteOne{builder} +} + +// Query returns a query builder for User. +func (c *UserClient) Query() *UserQuery { + return &UserQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeUser}, + inters: c.Interceptors(), + } +} + +// Get returns a User entity by its id. +func (c *UserClient) Get(ctx context.Context, id int) (*User, error) { + return c.Query().Where(user.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *UserClient) GetX(ctx context.Context, id int) *User { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *UserClient) Hooks() []Hook { + return c.hooks.User +} + +// Interceptors returns the client interceptors. +func (c *UserClient) Interceptors() []Interceptor { + return c.inters.User +} + +func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&UserCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&UserUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&UserDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown User mutation op: %q", m.Op()) + } +} + +// VisitClient is a client for the Visit schema. +type VisitClient struct { + config +} + +// NewVisitClient returns a client for the Visit from the given config. +func NewVisitClient(c config) *VisitClient { + return &VisitClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `visit.Hooks(f(g(h())))`. +func (c *VisitClient) Use(hooks ...Hook) { + c.hooks.Visit = append(c.hooks.Visit, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `visit.Intercept(f(g(h())))`. +func (c *VisitClient) Intercept(interceptors ...Interceptor) { + c.inters.Visit = append(c.inters.Visit, interceptors...) +} + +// Create returns a builder for creating a Visit entity. +func (c *VisitClient) Create() *VisitCreate { + mutation := newVisitMutation(c.config, OpCreate) + return &VisitCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Visit entities. +func (c *VisitClient) CreateBulk(builders ...*VisitCreate) *VisitCreateBulk { + return &VisitCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *VisitClient) MapCreateBulk(slice any, setFunc func(*VisitCreate, int)) *VisitCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &VisitCreateBulk{err: fmt.Errorf("calling to VisitClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*VisitCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &VisitCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Visit. +func (c *VisitClient) Update() *VisitUpdate { + mutation := newVisitMutation(c.config, OpUpdate) + return &VisitUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *VisitClient) UpdateOne(_m *Visit) *VisitUpdateOne { + mutation := newVisitMutation(c.config, OpUpdateOne, withVisit(_m)) + return &VisitUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *VisitClient) UpdateOneID(id int) *VisitUpdateOne { + mutation := newVisitMutation(c.config, OpUpdateOne, withVisitID(id)) + return &VisitUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Visit. +func (c *VisitClient) Delete() *VisitDelete { + mutation := newVisitMutation(c.config, OpDelete) + return &VisitDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *VisitClient) DeleteOne(_m *Visit) *VisitDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *VisitClient) DeleteOneID(id int) *VisitDeleteOne { + builder := c.Delete().Where(visit.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &VisitDeleteOne{builder} +} + +// Query returns a query builder for Visit. +func (c *VisitClient) Query() *VisitQuery { + return &VisitQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeVisit}, + inters: c.Interceptors(), + } +} + +// Get returns a Visit entity by its id. +func (c *VisitClient) Get(ctx context.Context, id int) (*Visit, error) { + return c.Query().Where(visit.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *VisitClient) GetX(ctx context.Context, id int) *Visit { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *VisitClient) Hooks() []Hook { + return c.hooks.Visit +} + +// Interceptors returns the client interceptors. +func (c *VisitClient) Interceptors() []Interceptor { + return c.inters.Visit +} + +func (c *VisitClient) mutate(ctx context.Context, m *VisitMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&VisitCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&VisitUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&VisitUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&VisitDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Visit mutation op: %q", m.Op()) + } +} + +// hooks and interceptors per client, for fast access. +type ( + hooks struct { + Contact, LoginHistory, Site, SiteConfig, User, Visit []ent.Hook + } + inters struct { + Contact, LoginHistory, Site, SiteConfig, User, Visit []ent.Interceptor + } +) diff --git a/internal/ent/contact.go b/internal/ent/contact.go new file mode 100644 index 0000000..2f2b3bc --- /dev/null +++ b/internal/ent/contact.go @@ -0,0 +1,158 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "home-vue-go/internal/ent/contact" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// Contact is the model entity for the Contact schema. +type Contact struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // 联系方式类型(Email, Github, 支付宝, 微信等) + Type string `json:"type,omitempty"` + // 图标类名 + Icon string `json:"icon,omitempty"` + // 链接URL(mailto:或https://) + URL string `json:"url,omitempty"` + // 二维码图片URL或路径 + QrCode string `json:"qr_code,omitempty"` + // 悬停颜色 + HoverColor string `json:"hover_color,omitempty"` + // 排序顺序 + SortOrder int `json:"sort_order,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Contact) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case contact.FieldID, contact.FieldSortOrder: + values[i] = new(sql.NullInt64) + case contact.FieldType, contact.FieldIcon, contact.FieldURL, contact.FieldQrCode, contact.FieldHoverColor: + values[i] = new(sql.NullString) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Contact fields. +func (_m *Contact) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case contact.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int(value.Int64) + case contact.FieldType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field type", values[i]) + } else if value.Valid { + _m.Type = value.String + } + case contact.FieldIcon: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field icon", values[i]) + } else if value.Valid { + _m.Icon = value.String + } + case contact.FieldURL: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field url", values[i]) + } else if value.Valid { + _m.URL = value.String + } + case contact.FieldQrCode: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field qr_code", values[i]) + } else if value.Valid { + _m.QrCode = value.String + } + case contact.FieldHoverColor: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field hover_color", values[i]) + } else if value.Valid { + _m.HoverColor = value.String + } + case contact.FieldSortOrder: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field sort_order", values[i]) + } else if value.Valid { + _m.SortOrder = int(value.Int64) + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Contact. +// This includes values selected through modifiers, order, etc. +func (_m *Contact) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this Contact. +// Note that you need to call Contact.Unwrap() before calling this method if this Contact +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Contact) Update() *ContactUpdateOne { + return NewContactClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Contact entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *Contact) Unwrap() *Contact { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: Contact is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Contact) String() string { + var builder strings.Builder + builder.WriteString("Contact(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("type=") + builder.WriteString(_m.Type) + builder.WriteString(", ") + builder.WriteString("icon=") + builder.WriteString(_m.Icon) + builder.WriteString(", ") + builder.WriteString("url=") + builder.WriteString(_m.URL) + builder.WriteString(", ") + builder.WriteString("qr_code=") + builder.WriteString(_m.QrCode) + builder.WriteString(", ") + builder.WriteString("hover_color=") + builder.WriteString(_m.HoverColor) + builder.WriteString(", ") + builder.WriteString("sort_order=") + builder.WriteString(fmt.Sprintf("%v", _m.SortOrder)) + builder.WriteByte(')') + return builder.String() +} + +// Contacts is a parsable slice of Contact. +type Contacts []*Contact diff --git a/internal/ent/contact/contact.go b/internal/ent/contact/contact.go new file mode 100644 index 0000000..baaec9d --- /dev/null +++ b/internal/ent/contact/contact.go @@ -0,0 +1,92 @@ +// Code generated by ent, DO NOT EDIT. + +package contact + +import ( + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the contact type in the database. + Label = "contact" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldType holds the string denoting the type field in the database. + FieldType = "type" + // FieldIcon holds the string denoting the icon field in the database. + FieldIcon = "icon" + // FieldURL holds the string denoting the url field in the database. + FieldURL = "url" + // FieldQrCode holds the string denoting the qr_code field in the database. + FieldQrCode = "qr_code" + // FieldHoverColor holds the string denoting the hover_color field in the database. + FieldHoverColor = "hover_color" + // FieldSortOrder holds the string denoting the sort_order field in the database. + FieldSortOrder = "sort_order" + // Table holds the table name of the contact in the database. + Table = "contacts" +) + +// Columns holds all SQL columns for contact fields. +var Columns = []string{ + FieldID, + FieldType, + FieldIcon, + FieldURL, + FieldQrCode, + FieldHoverColor, + FieldSortOrder, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultSortOrder holds the default value on creation for the "sort_order" field. + DefaultSortOrder int +) + +// OrderOption defines the ordering options for the Contact 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() +} + +// ByType orders the results by the type field. +func ByType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldType, opts...).ToFunc() +} + +// ByIcon orders the results by the icon field. +func ByIcon(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIcon, opts...).ToFunc() +} + +// ByURL orders the results by the url field. +func ByURL(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldURL, opts...).ToFunc() +} + +// ByQrCode orders the results by the qr_code field. +func ByQrCode(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldQrCode, opts...).ToFunc() +} + +// ByHoverColor orders the results by the hover_color field. +func ByHoverColor(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldHoverColor, opts...).ToFunc() +} + +// BySortOrder orders the results by the sort_order field. +func BySortOrder(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSortOrder, opts...).ToFunc() +} diff --git a/internal/ent/contact/where.go b/internal/ent/contact/where.go new file mode 100644 index 0000000..3e4b103 --- /dev/null +++ b/internal/ent/contact/where.go @@ -0,0 +1,494 @@ +// Code generated by ent, DO NOT EDIT. + +package contact + +import ( + "home-vue-go/internal/ent/predicate" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.Contact { + return predicate.Contact(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.Contact { + return predicate.Contact(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.Contact { + return predicate.Contact(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.Contact { + return predicate.Contact(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.Contact { + return predicate.Contact(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.Contact { + return predicate.Contact(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.Contact { + return predicate.Contact(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.Contact { + return predicate.Contact(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.Contact { + return predicate.Contact(sql.FieldLTE(FieldID, id)) +} + +// Type applies equality check predicate on the "type" field. It's identical to TypeEQ. +func Type(v string) predicate.Contact { + return predicate.Contact(sql.FieldEQ(FieldType, v)) +} + +// Icon applies equality check predicate on the "icon" field. It's identical to IconEQ. +func Icon(v string) predicate.Contact { + return predicate.Contact(sql.FieldEQ(FieldIcon, v)) +} + +// URL applies equality check predicate on the "url" field. It's identical to URLEQ. +func URL(v string) predicate.Contact { + return predicate.Contact(sql.FieldEQ(FieldURL, v)) +} + +// QrCode applies equality check predicate on the "qr_code" field. It's identical to QrCodeEQ. +func QrCode(v string) predicate.Contact { + return predicate.Contact(sql.FieldEQ(FieldQrCode, v)) +} + +// HoverColor applies equality check predicate on the "hover_color" field. It's identical to HoverColorEQ. +func HoverColor(v string) predicate.Contact { + return predicate.Contact(sql.FieldEQ(FieldHoverColor, v)) +} + +// SortOrder applies equality check predicate on the "sort_order" field. It's identical to SortOrderEQ. +func SortOrder(v int) predicate.Contact { + return predicate.Contact(sql.FieldEQ(FieldSortOrder, v)) +} + +// TypeEQ applies the EQ predicate on the "type" field. +func TypeEQ(v string) predicate.Contact { + return predicate.Contact(sql.FieldEQ(FieldType, v)) +} + +// TypeNEQ applies the NEQ predicate on the "type" field. +func TypeNEQ(v string) predicate.Contact { + return predicate.Contact(sql.FieldNEQ(FieldType, v)) +} + +// TypeIn applies the In predicate on the "type" field. +func TypeIn(vs ...string) predicate.Contact { + return predicate.Contact(sql.FieldIn(FieldType, vs...)) +} + +// TypeNotIn applies the NotIn predicate on the "type" field. +func TypeNotIn(vs ...string) predicate.Contact { + return predicate.Contact(sql.FieldNotIn(FieldType, vs...)) +} + +// TypeGT applies the GT predicate on the "type" field. +func TypeGT(v string) predicate.Contact { + return predicate.Contact(sql.FieldGT(FieldType, v)) +} + +// TypeGTE applies the GTE predicate on the "type" field. +func TypeGTE(v string) predicate.Contact { + return predicate.Contact(sql.FieldGTE(FieldType, v)) +} + +// TypeLT applies the LT predicate on the "type" field. +func TypeLT(v string) predicate.Contact { + return predicate.Contact(sql.FieldLT(FieldType, v)) +} + +// TypeLTE applies the LTE predicate on the "type" field. +func TypeLTE(v string) predicate.Contact { + return predicate.Contact(sql.FieldLTE(FieldType, v)) +} + +// TypeContains applies the Contains predicate on the "type" field. +func TypeContains(v string) predicate.Contact { + return predicate.Contact(sql.FieldContains(FieldType, v)) +} + +// TypeHasPrefix applies the HasPrefix predicate on the "type" field. +func TypeHasPrefix(v string) predicate.Contact { + return predicate.Contact(sql.FieldHasPrefix(FieldType, v)) +} + +// TypeHasSuffix applies the HasSuffix predicate on the "type" field. +func TypeHasSuffix(v string) predicate.Contact { + return predicate.Contact(sql.FieldHasSuffix(FieldType, v)) +} + +// TypeEqualFold applies the EqualFold predicate on the "type" field. +func TypeEqualFold(v string) predicate.Contact { + return predicate.Contact(sql.FieldEqualFold(FieldType, v)) +} + +// TypeContainsFold applies the ContainsFold predicate on the "type" field. +func TypeContainsFold(v string) predicate.Contact { + return predicate.Contact(sql.FieldContainsFold(FieldType, v)) +} + +// IconEQ applies the EQ predicate on the "icon" field. +func IconEQ(v string) predicate.Contact { + return predicate.Contact(sql.FieldEQ(FieldIcon, v)) +} + +// IconNEQ applies the NEQ predicate on the "icon" field. +func IconNEQ(v string) predicate.Contact { + return predicate.Contact(sql.FieldNEQ(FieldIcon, v)) +} + +// IconIn applies the In predicate on the "icon" field. +func IconIn(vs ...string) predicate.Contact { + return predicate.Contact(sql.FieldIn(FieldIcon, vs...)) +} + +// IconNotIn applies the NotIn predicate on the "icon" field. +func IconNotIn(vs ...string) predicate.Contact { + return predicate.Contact(sql.FieldNotIn(FieldIcon, vs...)) +} + +// IconGT applies the GT predicate on the "icon" field. +func IconGT(v string) predicate.Contact { + return predicate.Contact(sql.FieldGT(FieldIcon, v)) +} + +// IconGTE applies the GTE predicate on the "icon" field. +func IconGTE(v string) predicate.Contact { + return predicate.Contact(sql.FieldGTE(FieldIcon, v)) +} + +// IconLT applies the LT predicate on the "icon" field. +func IconLT(v string) predicate.Contact { + return predicate.Contact(sql.FieldLT(FieldIcon, v)) +} + +// IconLTE applies the LTE predicate on the "icon" field. +func IconLTE(v string) predicate.Contact { + return predicate.Contact(sql.FieldLTE(FieldIcon, v)) +} + +// IconContains applies the Contains predicate on the "icon" field. +func IconContains(v string) predicate.Contact { + return predicate.Contact(sql.FieldContains(FieldIcon, v)) +} + +// IconHasPrefix applies the HasPrefix predicate on the "icon" field. +func IconHasPrefix(v string) predicate.Contact { + return predicate.Contact(sql.FieldHasPrefix(FieldIcon, v)) +} + +// IconHasSuffix applies the HasSuffix predicate on the "icon" field. +func IconHasSuffix(v string) predicate.Contact { + return predicate.Contact(sql.FieldHasSuffix(FieldIcon, v)) +} + +// IconEqualFold applies the EqualFold predicate on the "icon" field. +func IconEqualFold(v string) predicate.Contact { + return predicate.Contact(sql.FieldEqualFold(FieldIcon, v)) +} + +// IconContainsFold applies the ContainsFold predicate on the "icon" field. +func IconContainsFold(v string) predicate.Contact { + return predicate.Contact(sql.FieldContainsFold(FieldIcon, v)) +} + +// URLEQ applies the EQ predicate on the "url" field. +func URLEQ(v string) predicate.Contact { + return predicate.Contact(sql.FieldEQ(FieldURL, v)) +} + +// URLNEQ applies the NEQ predicate on the "url" field. +func URLNEQ(v string) predicate.Contact { + return predicate.Contact(sql.FieldNEQ(FieldURL, v)) +} + +// URLIn applies the In predicate on the "url" field. +func URLIn(vs ...string) predicate.Contact { + return predicate.Contact(sql.FieldIn(FieldURL, vs...)) +} + +// URLNotIn applies the NotIn predicate on the "url" field. +func URLNotIn(vs ...string) predicate.Contact { + return predicate.Contact(sql.FieldNotIn(FieldURL, vs...)) +} + +// URLGT applies the GT predicate on the "url" field. +func URLGT(v string) predicate.Contact { + return predicate.Contact(sql.FieldGT(FieldURL, v)) +} + +// URLGTE applies the GTE predicate on the "url" field. +func URLGTE(v string) predicate.Contact { + return predicate.Contact(sql.FieldGTE(FieldURL, v)) +} + +// URLLT applies the LT predicate on the "url" field. +func URLLT(v string) predicate.Contact { + return predicate.Contact(sql.FieldLT(FieldURL, v)) +} + +// URLLTE applies the LTE predicate on the "url" field. +func URLLTE(v string) predicate.Contact { + return predicate.Contact(sql.FieldLTE(FieldURL, v)) +} + +// URLContains applies the Contains predicate on the "url" field. +func URLContains(v string) predicate.Contact { + return predicate.Contact(sql.FieldContains(FieldURL, v)) +} + +// URLHasPrefix applies the HasPrefix predicate on the "url" field. +func URLHasPrefix(v string) predicate.Contact { + return predicate.Contact(sql.FieldHasPrefix(FieldURL, v)) +} + +// URLHasSuffix applies the HasSuffix predicate on the "url" field. +func URLHasSuffix(v string) predicate.Contact { + return predicate.Contact(sql.FieldHasSuffix(FieldURL, v)) +} + +// URLIsNil applies the IsNil predicate on the "url" field. +func URLIsNil() predicate.Contact { + return predicate.Contact(sql.FieldIsNull(FieldURL)) +} + +// URLNotNil applies the NotNil predicate on the "url" field. +func URLNotNil() predicate.Contact { + return predicate.Contact(sql.FieldNotNull(FieldURL)) +} + +// URLEqualFold applies the EqualFold predicate on the "url" field. +func URLEqualFold(v string) predicate.Contact { + return predicate.Contact(sql.FieldEqualFold(FieldURL, v)) +} + +// URLContainsFold applies the ContainsFold predicate on the "url" field. +func URLContainsFold(v string) predicate.Contact { + return predicate.Contact(sql.FieldContainsFold(FieldURL, v)) +} + +// QrCodeEQ applies the EQ predicate on the "qr_code" field. +func QrCodeEQ(v string) predicate.Contact { + return predicate.Contact(sql.FieldEQ(FieldQrCode, v)) +} + +// QrCodeNEQ applies the NEQ predicate on the "qr_code" field. +func QrCodeNEQ(v string) predicate.Contact { + return predicate.Contact(sql.FieldNEQ(FieldQrCode, v)) +} + +// QrCodeIn applies the In predicate on the "qr_code" field. +func QrCodeIn(vs ...string) predicate.Contact { + return predicate.Contact(sql.FieldIn(FieldQrCode, vs...)) +} + +// QrCodeNotIn applies the NotIn predicate on the "qr_code" field. +func QrCodeNotIn(vs ...string) predicate.Contact { + return predicate.Contact(sql.FieldNotIn(FieldQrCode, vs...)) +} + +// QrCodeGT applies the GT predicate on the "qr_code" field. +func QrCodeGT(v string) predicate.Contact { + return predicate.Contact(sql.FieldGT(FieldQrCode, v)) +} + +// QrCodeGTE applies the GTE predicate on the "qr_code" field. +func QrCodeGTE(v string) predicate.Contact { + return predicate.Contact(sql.FieldGTE(FieldQrCode, v)) +} + +// QrCodeLT applies the LT predicate on the "qr_code" field. +func QrCodeLT(v string) predicate.Contact { + return predicate.Contact(sql.FieldLT(FieldQrCode, v)) +} + +// QrCodeLTE applies the LTE predicate on the "qr_code" field. +func QrCodeLTE(v string) predicate.Contact { + return predicate.Contact(sql.FieldLTE(FieldQrCode, v)) +} + +// QrCodeContains applies the Contains predicate on the "qr_code" field. +func QrCodeContains(v string) predicate.Contact { + return predicate.Contact(sql.FieldContains(FieldQrCode, v)) +} + +// QrCodeHasPrefix applies the HasPrefix predicate on the "qr_code" field. +func QrCodeHasPrefix(v string) predicate.Contact { + return predicate.Contact(sql.FieldHasPrefix(FieldQrCode, v)) +} + +// QrCodeHasSuffix applies the HasSuffix predicate on the "qr_code" field. +func QrCodeHasSuffix(v string) predicate.Contact { + return predicate.Contact(sql.FieldHasSuffix(FieldQrCode, v)) +} + +// QrCodeIsNil applies the IsNil predicate on the "qr_code" field. +func QrCodeIsNil() predicate.Contact { + return predicate.Contact(sql.FieldIsNull(FieldQrCode)) +} + +// QrCodeNotNil applies the NotNil predicate on the "qr_code" field. +func QrCodeNotNil() predicate.Contact { + return predicate.Contact(sql.FieldNotNull(FieldQrCode)) +} + +// QrCodeEqualFold applies the EqualFold predicate on the "qr_code" field. +func QrCodeEqualFold(v string) predicate.Contact { + return predicate.Contact(sql.FieldEqualFold(FieldQrCode, v)) +} + +// QrCodeContainsFold applies the ContainsFold predicate on the "qr_code" field. +func QrCodeContainsFold(v string) predicate.Contact { + return predicate.Contact(sql.FieldContainsFold(FieldQrCode, v)) +} + +// HoverColorEQ applies the EQ predicate on the "hover_color" field. +func HoverColorEQ(v string) predicate.Contact { + return predicate.Contact(sql.FieldEQ(FieldHoverColor, v)) +} + +// HoverColorNEQ applies the NEQ predicate on the "hover_color" field. +func HoverColorNEQ(v string) predicate.Contact { + return predicate.Contact(sql.FieldNEQ(FieldHoverColor, v)) +} + +// HoverColorIn applies the In predicate on the "hover_color" field. +func HoverColorIn(vs ...string) predicate.Contact { + return predicate.Contact(sql.FieldIn(FieldHoverColor, vs...)) +} + +// HoverColorNotIn applies the NotIn predicate on the "hover_color" field. +func HoverColorNotIn(vs ...string) predicate.Contact { + return predicate.Contact(sql.FieldNotIn(FieldHoverColor, vs...)) +} + +// HoverColorGT applies the GT predicate on the "hover_color" field. +func HoverColorGT(v string) predicate.Contact { + return predicate.Contact(sql.FieldGT(FieldHoverColor, v)) +} + +// HoverColorGTE applies the GTE predicate on the "hover_color" field. +func HoverColorGTE(v string) predicate.Contact { + return predicate.Contact(sql.FieldGTE(FieldHoverColor, v)) +} + +// HoverColorLT applies the LT predicate on the "hover_color" field. +func HoverColorLT(v string) predicate.Contact { + return predicate.Contact(sql.FieldLT(FieldHoverColor, v)) +} + +// HoverColorLTE applies the LTE predicate on the "hover_color" field. +func HoverColorLTE(v string) predicate.Contact { + return predicate.Contact(sql.FieldLTE(FieldHoverColor, v)) +} + +// HoverColorContains applies the Contains predicate on the "hover_color" field. +func HoverColorContains(v string) predicate.Contact { + return predicate.Contact(sql.FieldContains(FieldHoverColor, v)) +} + +// HoverColorHasPrefix applies the HasPrefix predicate on the "hover_color" field. +func HoverColorHasPrefix(v string) predicate.Contact { + return predicate.Contact(sql.FieldHasPrefix(FieldHoverColor, v)) +} + +// HoverColorHasSuffix applies the HasSuffix predicate on the "hover_color" field. +func HoverColorHasSuffix(v string) predicate.Contact { + return predicate.Contact(sql.FieldHasSuffix(FieldHoverColor, v)) +} + +// HoverColorIsNil applies the IsNil predicate on the "hover_color" field. +func HoverColorIsNil() predicate.Contact { + return predicate.Contact(sql.FieldIsNull(FieldHoverColor)) +} + +// HoverColorNotNil applies the NotNil predicate on the "hover_color" field. +func HoverColorNotNil() predicate.Contact { + return predicate.Contact(sql.FieldNotNull(FieldHoverColor)) +} + +// HoverColorEqualFold applies the EqualFold predicate on the "hover_color" field. +func HoverColorEqualFold(v string) predicate.Contact { + return predicate.Contact(sql.FieldEqualFold(FieldHoverColor, v)) +} + +// HoverColorContainsFold applies the ContainsFold predicate on the "hover_color" field. +func HoverColorContainsFold(v string) predicate.Contact { + return predicate.Contact(sql.FieldContainsFold(FieldHoverColor, v)) +} + +// SortOrderEQ applies the EQ predicate on the "sort_order" field. +func SortOrderEQ(v int) predicate.Contact { + return predicate.Contact(sql.FieldEQ(FieldSortOrder, v)) +} + +// SortOrderNEQ applies the NEQ predicate on the "sort_order" field. +func SortOrderNEQ(v int) predicate.Contact { + return predicate.Contact(sql.FieldNEQ(FieldSortOrder, v)) +} + +// SortOrderIn applies the In predicate on the "sort_order" field. +func SortOrderIn(vs ...int) predicate.Contact { + return predicate.Contact(sql.FieldIn(FieldSortOrder, vs...)) +} + +// SortOrderNotIn applies the NotIn predicate on the "sort_order" field. +func SortOrderNotIn(vs ...int) predicate.Contact { + return predicate.Contact(sql.FieldNotIn(FieldSortOrder, vs...)) +} + +// SortOrderGT applies the GT predicate on the "sort_order" field. +func SortOrderGT(v int) predicate.Contact { + return predicate.Contact(sql.FieldGT(FieldSortOrder, v)) +} + +// SortOrderGTE applies the GTE predicate on the "sort_order" field. +func SortOrderGTE(v int) predicate.Contact { + return predicate.Contact(sql.FieldGTE(FieldSortOrder, v)) +} + +// SortOrderLT applies the LT predicate on the "sort_order" field. +func SortOrderLT(v int) predicate.Contact { + return predicate.Contact(sql.FieldLT(FieldSortOrder, v)) +} + +// SortOrderLTE applies the LTE predicate on the "sort_order" field. +func SortOrderLTE(v int) predicate.Contact { + return predicate.Contact(sql.FieldLTE(FieldSortOrder, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Contact) predicate.Contact { + return predicate.Contact(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Contact) predicate.Contact { + return predicate.Contact(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Contact) predicate.Contact { + return predicate.Contact(sql.NotPredicates(p)) +} diff --git a/internal/ent/contact_create.go b/internal/ent/contact_create.go new file mode 100644 index 0000000..614de6f --- /dev/null +++ b/internal/ent/contact_create.go @@ -0,0 +1,293 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "home-vue-go/internal/ent/contact" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// ContactCreate is the builder for creating a Contact entity. +type ContactCreate struct { + config + mutation *ContactMutation + hooks []Hook +} + +// SetType sets the "type" field. +func (_c *ContactCreate) SetType(v string) *ContactCreate { + _c.mutation.SetType(v) + return _c +} + +// SetIcon sets the "icon" field. +func (_c *ContactCreate) SetIcon(v string) *ContactCreate { + _c.mutation.SetIcon(v) + return _c +} + +// SetURL sets the "url" field. +func (_c *ContactCreate) SetURL(v string) *ContactCreate { + _c.mutation.SetURL(v) + return _c +} + +// SetNillableURL sets the "url" field if the given value is not nil. +func (_c *ContactCreate) SetNillableURL(v *string) *ContactCreate { + if v != nil { + _c.SetURL(*v) + } + return _c +} + +// SetQrCode sets the "qr_code" field. +func (_c *ContactCreate) SetQrCode(v string) *ContactCreate { + _c.mutation.SetQrCode(v) + return _c +} + +// SetNillableQrCode sets the "qr_code" field if the given value is not nil. +func (_c *ContactCreate) SetNillableQrCode(v *string) *ContactCreate { + if v != nil { + _c.SetQrCode(*v) + } + return _c +} + +// SetHoverColor sets the "hover_color" field. +func (_c *ContactCreate) SetHoverColor(v string) *ContactCreate { + _c.mutation.SetHoverColor(v) + return _c +} + +// SetNillableHoverColor sets the "hover_color" field if the given value is not nil. +func (_c *ContactCreate) SetNillableHoverColor(v *string) *ContactCreate { + if v != nil { + _c.SetHoverColor(*v) + } + return _c +} + +// SetSortOrder sets the "sort_order" field. +func (_c *ContactCreate) SetSortOrder(v int) *ContactCreate { + _c.mutation.SetSortOrder(v) + return _c +} + +// SetNillableSortOrder sets the "sort_order" field if the given value is not nil. +func (_c *ContactCreate) SetNillableSortOrder(v *int) *ContactCreate { + if v != nil { + _c.SetSortOrder(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *ContactCreate) SetID(v int) *ContactCreate { + _c.mutation.SetID(v) + return _c +} + +// Mutation returns the ContactMutation object of the builder. +func (_c *ContactCreate) Mutation() *ContactMutation { + return _c.mutation +} + +// Save creates the Contact in the database. +func (_c *ContactCreate) Save(ctx context.Context) (*Contact, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ContactCreate) SaveX(ctx context.Context) *Contact { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ContactCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ContactCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *ContactCreate) defaults() { + if _, ok := _c.mutation.SortOrder(); !ok { + v := contact.DefaultSortOrder + _c.mutation.SetSortOrder(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ContactCreate) check() error { + if _, ok := _c.mutation.GetType(); !ok { + return &ValidationError{Name: "type", err: errors.New(`ent: missing required field "Contact.type"`)} + } + if _, ok := _c.mutation.Icon(); !ok { + return &ValidationError{Name: "icon", err: errors.New(`ent: missing required field "Contact.icon"`)} + } + if _, ok := _c.mutation.SortOrder(); !ok { + return &ValidationError{Name: "sort_order", err: errors.New(`ent: missing required field "Contact.sort_order"`)} + } + return nil +} + +func (_c *ContactCreate) sqlSave(ctx context.Context) (*Contact, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != _node.ID { + id := _spec.ID.Value.(int64) + _node.ID = int(id) + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ContactCreate) createSpec() (*Contact, *sqlgraph.CreateSpec) { + var ( + _node = &Contact{config: _c.config} + _spec = sqlgraph.NewCreateSpec(contact.Table, sqlgraph.NewFieldSpec(contact.FieldID, field.TypeInt)) + ) + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.GetType(); ok { + _spec.SetField(contact.FieldType, field.TypeString, value) + _node.Type = value + } + if value, ok := _c.mutation.Icon(); ok { + _spec.SetField(contact.FieldIcon, field.TypeString, value) + _node.Icon = value + } + if value, ok := _c.mutation.URL(); ok { + _spec.SetField(contact.FieldURL, field.TypeString, value) + _node.URL = value + } + if value, ok := _c.mutation.QrCode(); ok { + _spec.SetField(contact.FieldQrCode, field.TypeString, value) + _node.QrCode = value + } + if value, ok := _c.mutation.HoverColor(); ok { + _spec.SetField(contact.FieldHoverColor, field.TypeString, value) + _node.HoverColor = value + } + if value, ok := _c.mutation.SortOrder(); ok { + _spec.SetField(contact.FieldSortOrder, field.TypeInt, value) + _node.SortOrder = value + } + return _node, _spec +} + +// ContactCreateBulk is the builder for creating many Contact entities in bulk. +type ContactCreateBulk struct { + config + err error + builders []*ContactCreate +} + +// Save creates the Contact entities in the database. +func (_c *ContactCreateBulk) Save(ctx context.Context) ([]*Contact, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Contact, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*ContactMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil && nodes[i].ID == 0 { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *ContactCreateBulk) SaveX(ctx context.Context) []*Contact { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ContactCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ContactCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/ent/contact_delete.go b/internal/ent/contact_delete.go new file mode 100644 index 0000000..33278a6 --- /dev/null +++ b/internal/ent/contact_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "home-vue-go/internal/ent/contact" + "home-vue-go/internal/ent/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// ContactDelete is the builder for deleting a Contact entity. +type ContactDelete struct { + config + hooks []Hook + mutation *ContactMutation +} + +// Where appends a list predicates to the ContactDelete builder. +func (_d *ContactDelete) Where(ps ...predicate.Contact) *ContactDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ContactDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ContactDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ContactDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(contact.Table, sqlgraph.NewFieldSpec(contact.FieldID, field.TypeInt)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// ContactDeleteOne is the builder for deleting a single Contact entity. +type ContactDeleteOne struct { + _d *ContactDelete +} + +// Where appends a list predicates to the ContactDelete builder. +func (_d *ContactDeleteOne) Where(ps ...predicate.Contact) *ContactDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ContactDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{contact.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ContactDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/ent/contact_query.go b/internal/ent/contact_query.go new file mode 100644 index 0000000..4b3de48 --- /dev/null +++ b/internal/ent/contact_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "home-vue-go/internal/ent/contact" + "home-vue-go/internal/ent/predicate" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// ContactQuery is the builder for querying Contact entities. +type ContactQuery struct { + config + ctx *QueryContext + order []contact.OrderOption + inters []Interceptor + predicates []predicate.Contact + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the ContactQuery builder. +func (_q *ContactQuery) Where(ps ...predicate.Contact) *ContactQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ContactQuery) Limit(limit int) *ContactQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ContactQuery) Offset(offset int) *ContactQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *ContactQuery) Unique(unique bool) *ContactQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ContactQuery) Order(o ...contact.OrderOption) *ContactQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first Contact entity from the query. +// Returns a *NotFoundError when no Contact was found. +func (_q *ContactQuery) First(ctx context.Context) (*Contact, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{contact.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ContactQuery) FirstX(ctx context.Context) *Contact { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Contact ID from the query. +// Returns a *NotFoundError when no Contact ID was found. +func (_q *ContactQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{contact.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ContactQuery) FirstIDX(ctx context.Context) int { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Contact entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Contact entity is found. +// Returns a *NotFoundError when no Contact entities are found. +func (_q *ContactQuery) Only(ctx context.Context) (*Contact, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{contact.Label} + default: + return nil, &NotSingularError{contact.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ContactQuery) OnlyX(ctx context.Context) *Contact { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Contact ID in the query. +// Returns a *NotSingularError when more than one Contact ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ContactQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{contact.Label} + default: + err = &NotSingularError{contact.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ContactQuery) OnlyIDX(ctx context.Context) int { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Contacts. +func (_q *ContactQuery) All(ctx context.Context) ([]*Contact, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Contact, *ContactQuery]() + return withInterceptors[[]*Contact](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ContactQuery) AllX(ctx context.Context) []*Contact { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Contact IDs. +func (_q *ContactQuery) IDs(ctx context.Context) (ids []int, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(contact.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ContactQuery) IDsX(ctx context.Context) []int { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *ContactQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*ContactQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ContactQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *ContactQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *ContactQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ContactQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *ContactQuery) Clone() *ContactQuery { + if _q == nil { + return nil + } + return &ContactQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]contact.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Contact{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Type string `json:"type,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Contact.Query(). +// GroupBy(contact.FieldType). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *ContactQuery) GroupBy(field string, fields ...string) *ContactGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ContactGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = contact.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// Type string `json:"type,omitempty"` +// } +// +// client.Contact.Query(). +// Select(contact.FieldType). +// Scan(ctx, &v) +func (_q *ContactQuery) Select(fields ...string) *ContactSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ContactSelect{ContactQuery: _q} + sbuild.label = contact.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ContactSelect configured with the given aggregations. +func (_q *ContactQuery) Aggregate(fns ...AggregateFunc) *ContactSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ContactQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !contact.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *ContactQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Contact, error) { + var ( + nodes = []*Contact{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Contact).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Contact{config: _q.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (_q *ContactQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *ContactQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(contact.Table, contact.Columns, sqlgraph.NewFieldSpec(contact.FieldID, field.TypeInt)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, contact.FieldID) + for i := range fields { + if fields[i] != contact.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *ContactQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(contact.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = contact.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// ContactGroupBy is the group-by builder for Contact entities. +type ContactGroupBy struct { + selector + build *ContactQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ContactGroupBy) Aggregate(fns ...AggregateFunc) *ContactGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ContactGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ContactQuery, *ContactGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ContactGroupBy) sqlScan(ctx context.Context, root *ContactQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// ContactSelect is the builder for selecting fields of Contact entities. +type ContactSelect struct { + *ContactQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ContactSelect) Aggregate(fns ...AggregateFunc) *ContactSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ContactSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ContactQuery, *ContactSelect](ctx, _s.ContactQuery, _s, _s.inters, v) +} + +func (_s *ContactSelect) sqlScan(ctx context.Context, root *ContactQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/internal/ent/contact_update.go b/internal/ent/contact_update.go new file mode 100644 index 0000000..a28cfcc --- /dev/null +++ b/internal/ent/contact_update.go @@ -0,0 +1,453 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "home-vue-go/internal/ent/contact" + "home-vue-go/internal/ent/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// ContactUpdate is the builder for updating Contact entities. +type ContactUpdate struct { + config + hooks []Hook + mutation *ContactMutation +} + +// Where appends a list predicates to the ContactUpdate builder. +func (_u *ContactUpdate) Where(ps ...predicate.Contact) *ContactUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetType sets the "type" field. +func (_u *ContactUpdate) SetType(v string) *ContactUpdate { + _u.mutation.SetType(v) + return _u +} + +// SetNillableType sets the "type" field if the given value is not nil. +func (_u *ContactUpdate) SetNillableType(v *string) *ContactUpdate { + if v != nil { + _u.SetType(*v) + } + return _u +} + +// SetIcon sets the "icon" field. +func (_u *ContactUpdate) SetIcon(v string) *ContactUpdate { + _u.mutation.SetIcon(v) + return _u +} + +// SetNillableIcon sets the "icon" field if the given value is not nil. +func (_u *ContactUpdate) SetNillableIcon(v *string) *ContactUpdate { + if v != nil { + _u.SetIcon(*v) + } + return _u +} + +// SetURL sets the "url" field. +func (_u *ContactUpdate) SetURL(v string) *ContactUpdate { + _u.mutation.SetURL(v) + return _u +} + +// SetNillableURL sets the "url" field if the given value is not nil. +func (_u *ContactUpdate) SetNillableURL(v *string) *ContactUpdate { + if v != nil { + _u.SetURL(*v) + } + return _u +} + +// ClearURL clears the value of the "url" field. +func (_u *ContactUpdate) ClearURL() *ContactUpdate { + _u.mutation.ClearURL() + return _u +} + +// SetQrCode sets the "qr_code" field. +func (_u *ContactUpdate) SetQrCode(v string) *ContactUpdate { + _u.mutation.SetQrCode(v) + return _u +} + +// SetNillableQrCode sets the "qr_code" field if the given value is not nil. +func (_u *ContactUpdate) SetNillableQrCode(v *string) *ContactUpdate { + if v != nil { + _u.SetQrCode(*v) + } + return _u +} + +// ClearQrCode clears the value of the "qr_code" field. +func (_u *ContactUpdate) ClearQrCode() *ContactUpdate { + _u.mutation.ClearQrCode() + return _u +} + +// SetHoverColor sets the "hover_color" field. +func (_u *ContactUpdate) SetHoverColor(v string) *ContactUpdate { + _u.mutation.SetHoverColor(v) + return _u +} + +// SetNillableHoverColor sets the "hover_color" field if the given value is not nil. +func (_u *ContactUpdate) SetNillableHoverColor(v *string) *ContactUpdate { + if v != nil { + _u.SetHoverColor(*v) + } + return _u +} + +// ClearHoverColor clears the value of the "hover_color" field. +func (_u *ContactUpdate) ClearHoverColor() *ContactUpdate { + _u.mutation.ClearHoverColor() + return _u +} + +// SetSortOrder sets the "sort_order" field. +func (_u *ContactUpdate) SetSortOrder(v int) *ContactUpdate { + _u.mutation.ResetSortOrder() + _u.mutation.SetSortOrder(v) + return _u +} + +// SetNillableSortOrder sets the "sort_order" field if the given value is not nil. +func (_u *ContactUpdate) SetNillableSortOrder(v *int) *ContactUpdate { + if v != nil { + _u.SetSortOrder(*v) + } + return _u +} + +// AddSortOrder adds value to the "sort_order" field. +func (_u *ContactUpdate) AddSortOrder(v int) *ContactUpdate { + _u.mutation.AddSortOrder(v) + return _u +} + +// Mutation returns the ContactMutation object of the builder. +func (_u *ContactUpdate) Mutation() *ContactMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ContactUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ContactUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ContactUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ContactUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *ContactUpdate) sqlSave(ctx context.Context) (_node int, err error) { + _spec := sqlgraph.NewUpdateSpec(contact.Table, contact.Columns, sqlgraph.NewFieldSpec(contact.FieldID, field.TypeInt)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.GetType(); ok { + _spec.SetField(contact.FieldType, field.TypeString, value) + } + if value, ok := _u.mutation.Icon(); ok { + _spec.SetField(contact.FieldIcon, field.TypeString, value) + } + if value, ok := _u.mutation.URL(); ok { + _spec.SetField(contact.FieldURL, field.TypeString, value) + } + if _u.mutation.URLCleared() { + _spec.ClearField(contact.FieldURL, field.TypeString) + } + if value, ok := _u.mutation.QrCode(); ok { + _spec.SetField(contact.FieldQrCode, field.TypeString, value) + } + if _u.mutation.QrCodeCleared() { + _spec.ClearField(contact.FieldQrCode, field.TypeString) + } + if value, ok := _u.mutation.HoverColor(); ok { + _spec.SetField(contact.FieldHoverColor, field.TypeString, value) + } + if _u.mutation.HoverColorCleared() { + _spec.ClearField(contact.FieldHoverColor, field.TypeString) + } + if value, ok := _u.mutation.SortOrder(); ok { + _spec.SetField(contact.FieldSortOrder, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedSortOrder(); ok { + _spec.AddField(contact.FieldSortOrder, field.TypeInt, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{contact.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ContactUpdateOne is the builder for updating a single Contact entity. +type ContactUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ContactMutation +} + +// SetType sets the "type" field. +func (_u *ContactUpdateOne) SetType(v string) *ContactUpdateOne { + _u.mutation.SetType(v) + return _u +} + +// SetNillableType sets the "type" field if the given value is not nil. +func (_u *ContactUpdateOne) SetNillableType(v *string) *ContactUpdateOne { + if v != nil { + _u.SetType(*v) + } + return _u +} + +// SetIcon sets the "icon" field. +func (_u *ContactUpdateOne) SetIcon(v string) *ContactUpdateOne { + _u.mutation.SetIcon(v) + return _u +} + +// SetNillableIcon sets the "icon" field if the given value is not nil. +func (_u *ContactUpdateOne) SetNillableIcon(v *string) *ContactUpdateOne { + if v != nil { + _u.SetIcon(*v) + } + return _u +} + +// SetURL sets the "url" field. +func (_u *ContactUpdateOne) SetURL(v string) *ContactUpdateOne { + _u.mutation.SetURL(v) + return _u +} + +// SetNillableURL sets the "url" field if the given value is not nil. +func (_u *ContactUpdateOne) SetNillableURL(v *string) *ContactUpdateOne { + if v != nil { + _u.SetURL(*v) + } + return _u +} + +// ClearURL clears the value of the "url" field. +func (_u *ContactUpdateOne) ClearURL() *ContactUpdateOne { + _u.mutation.ClearURL() + return _u +} + +// SetQrCode sets the "qr_code" field. +func (_u *ContactUpdateOne) SetQrCode(v string) *ContactUpdateOne { + _u.mutation.SetQrCode(v) + return _u +} + +// SetNillableQrCode sets the "qr_code" field if the given value is not nil. +func (_u *ContactUpdateOne) SetNillableQrCode(v *string) *ContactUpdateOne { + if v != nil { + _u.SetQrCode(*v) + } + return _u +} + +// ClearQrCode clears the value of the "qr_code" field. +func (_u *ContactUpdateOne) ClearQrCode() *ContactUpdateOne { + _u.mutation.ClearQrCode() + return _u +} + +// SetHoverColor sets the "hover_color" field. +func (_u *ContactUpdateOne) SetHoverColor(v string) *ContactUpdateOne { + _u.mutation.SetHoverColor(v) + return _u +} + +// SetNillableHoverColor sets the "hover_color" field if the given value is not nil. +func (_u *ContactUpdateOne) SetNillableHoverColor(v *string) *ContactUpdateOne { + if v != nil { + _u.SetHoverColor(*v) + } + return _u +} + +// ClearHoverColor clears the value of the "hover_color" field. +func (_u *ContactUpdateOne) ClearHoverColor() *ContactUpdateOne { + _u.mutation.ClearHoverColor() + return _u +} + +// SetSortOrder sets the "sort_order" field. +func (_u *ContactUpdateOne) SetSortOrder(v int) *ContactUpdateOne { + _u.mutation.ResetSortOrder() + _u.mutation.SetSortOrder(v) + return _u +} + +// SetNillableSortOrder sets the "sort_order" field if the given value is not nil. +func (_u *ContactUpdateOne) SetNillableSortOrder(v *int) *ContactUpdateOne { + if v != nil { + _u.SetSortOrder(*v) + } + return _u +} + +// AddSortOrder adds value to the "sort_order" field. +func (_u *ContactUpdateOne) AddSortOrder(v int) *ContactUpdateOne { + _u.mutation.AddSortOrder(v) + return _u +} + +// Mutation returns the ContactMutation object of the builder. +func (_u *ContactUpdateOne) Mutation() *ContactMutation { + return _u.mutation +} + +// Where appends a list predicates to the ContactUpdate builder. +func (_u *ContactUpdateOne) Where(ps ...predicate.Contact) *ContactUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *ContactUpdateOne) Select(field string, fields ...string) *ContactUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Contact entity. +func (_u *ContactUpdateOne) Save(ctx context.Context) (*Contact, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ContactUpdateOne) SaveX(ctx context.Context) *Contact { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ContactUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ContactUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *ContactUpdateOne) sqlSave(ctx context.Context) (_node *Contact, err error) { + _spec := sqlgraph.NewUpdateSpec(contact.Table, contact.Columns, sqlgraph.NewFieldSpec(contact.FieldID, field.TypeInt)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Contact.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, contact.FieldID) + for _, f := range fields { + if !contact.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != contact.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.GetType(); ok { + _spec.SetField(contact.FieldType, field.TypeString, value) + } + if value, ok := _u.mutation.Icon(); ok { + _spec.SetField(contact.FieldIcon, field.TypeString, value) + } + if value, ok := _u.mutation.URL(); ok { + _spec.SetField(contact.FieldURL, field.TypeString, value) + } + if _u.mutation.URLCleared() { + _spec.ClearField(contact.FieldURL, field.TypeString) + } + if value, ok := _u.mutation.QrCode(); ok { + _spec.SetField(contact.FieldQrCode, field.TypeString, value) + } + if _u.mutation.QrCodeCleared() { + _spec.ClearField(contact.FieldQrCode, field.TypeString) + } + if value, ok := _u.mutation.HoverColor(); ok { + _spec.SetField(contact.FieldHoverColor, field.TypeString, value) + } + if _u.mutation.HoverColorCleared() { + _spec.ClearField(contact.FieldHoverColor, field.TypeString) + } + if value, ok := _u.mutation.SortOrder(); ok { + _spec.SetField(contact.FieldSortOrder, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedSortOrder(); ok { + _spec.AddField(contact.FieldSortOrder, field.TypeInt, value) + } + _node = &Contact{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{contact.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/internal/ent/ent.go b/internal/ent/ent.go new file mode 100644 index 0000000..98a34de --- /dev/null +++ b/internal/ent/ent.go @@ -0,0 +1,618 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "home-vue-go/internal/ent/contact" + "home-vue-go/internal/ent/loginhistory" + "home-vue-go/internal/ent/site" + "home-vue-go/internal/ent/siteconfig" + "home-vue-go/internal/ent/user" + "home-vue-go/internal/ent/visit" + "reflect" + "sync" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// ent aliases to avoid import conflicts in user's code. +type ( + Op = ent.Op + Hook = ent.Hook + Value = ent.Value + Query = ent.Query + QueryContext = ent.QueryContext + Querier = ent.Querier + QuerierFunc = ent.QuerierFunc + Interceptor = ent.Interceptor + InterceptFunc = ent.InterceptFunc + Traverser = ent.Traverser + TraverseFunc = ent.TraverseFunc + Policy = ent.Policy + Mutator = ent.Mutator + Mutation = ent.Mutation + MutateFunc = ent.MutateFunc +) + +type clientCtxKey struct{} + +// FromContext returns a Client stored inside a context, or nil if there isn't one. +func FromContext(ctx context.Context) *Client { + c, _ := ctx.Value(clientCtxKey{}).(*Client) + return c +} + +// NewContext returns a new context with the given Client attached. +func NewContext(parent context.Context, c *Client) context.Context { + return context.WithValue(parent, clientCtxKey{}, c) +} + +type txCtxKey struct{} + +// TxFromContext returns a Tx stored inside a context, or nil if there isn't one. +func TxFromContext(ctx context.Context) *Tx { + tx, _ := ctx.Value(txCtxKey{}).(*Tx) + return tx +} + +// NewTxContext returns a new context with the given Tx attached. +func NewTxContext(parent context.Context, tx *Tx) context.Context { + return context.WithValue(parent, txCtxKey{}, tx) +} + +// OrderFunc applies an ordering on the sql selector. +// Deprecated: Use Asc/Desc functions or the package builders instead. +type OrderFunc func(*sql.Selector) + +var ( + initCheck sync.Once + columnCheck sql.ColumnCheck +) + +// checkColumn checks if the column exists in the given table. +func checkColumn(t, c string) error { + initCheck.Do(func() { + columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ + contact.Table: contact.ValidColumn, + loginhistory.Table: loginhistory.ValidColumn, + site.Table: site.ValidColumn, + siteconfig.Table: siteconfig.ValidColumn, + user.Table: user.ValidColumn, + visit.Table: visit.ValidColumn, + }) + }) + return columnCheck(t, c) +} + +// Asc applies the given fields in ASC order. +func Asc(fields ...string) func(*sql.Selector) { + return func(s *sql.Selector) { + for _, f := range fields { + if err := checkColumn(s.TableName(), f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)}) + } + s.OrderBy(sql.Asc(s.C(f))) + } + } +} + +// Desc applies the given fields in DESC order. +func Desc(fields ...string) func(*sql.Selector) { + return func(s *sql.Selector) { + for _, f := range fields { + if err := checkColumn(s.TableName(), f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)}) + } + s.OrderBy(sql.Desc(s.C(f))) + } + } +} + +// AggregateFunc applies an aggregation step on the group-by traversal/selector. +type AggregateFunc func(*sql.Selector) string + +// As is a pseudo aggregation function for renaming another other functions with custom names. For example: +// +// GroupBy(field1, field2). +// Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")). +// Scan(ctx, &v) +func As(fn AggregateFunc, end string) AggregateFunc { + return func(s *sql.Selector) string { + return sql.As(fn(s), end) + } +} + +// Count applies the "count" aggregation function on each group. +func Count() AggregateFunc { + return func(s *sql.Selector) string { + return sql.Count("*") + } +} + +// Max applies the "max" aggregation function on the given field of each group. +func Max(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) + return "" + } + return sql.Max(s.C(field)) + } +} + +// Mean applies the "mean" aggregation function on the given field of each group. +func Mean(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) + return "" + } + return sql.Avg(s.C(field)) + } +} + +// Min applies the "min" aggregation function on the given field of each group. +func Min(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) + return "" + } + return sql.Min(s.C(field)) + } +} + +// Sum applies the "sum" aggregation function on the given field of each group. +func Sum(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) + return "" + } + return sql.Sum(s.C(field)) + } +} + +// ValidationError returns when validating a field or edge fails. +type ValidationError struct { + Name string // Field or edge name. + err error +} + +// Error implements the error interface. +func (e *ValidationError) Error() string { + return e.err.Error() +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ValidationError) Unwrap() error { + return e.err +} + +// IsValidationError returns a boolean indicating whether the error is a validation error. +func IsValidationError(err error) bool { + if err == nil { + return false + } + var e *ValidationError + return errors.As(err, &e) +} + +// NotFoundError returns when trying to fetch a specific entity and it was not found in the database. +type NotFoundError struct { + label string +} + +// Error implements the error interface. +func (e *NotFoundError) Error() string { + return "ent: " + e.label + " not found" +} + +// IsNotFound returns a boolean indicating whether the error is a not found error. +func IsNotFound(err error) bool { + if err == nil { + return false + } + var e *NotFoundError + return errors.As(err, &e) +} + +// MaskNotFound masks not found error. +func MaskNotFound(err error) error { + if IsNotFound(err) { + return nil + } + return err +} + +// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database. +type NotSingularError struct { + label string +} + +// Error implements the error interface. +func (e *NotSingularError) Error() string { + return "ent: " + e.label + " not singular" +} + +// IsNotSingular returns a boolean indicating whether the error is a not singular error. +func IsNotSingular(err error) bool { + if err == nil { + return false + } + var e *NotSingularError + return errors.As(err, &e) +} + +// NotLoadedError returns when trying to get a node that was not loaded by the query. +type NotLoadedError struct { + edge string +} + +// Error implements the error interface. +func (e *NotLoadedError) Error() string { + return "ent: " + e.edge + " edge was not loaded" +} + +// IsNotLoaded returns a boolean indicating whether the error is a not loaded error. +func IsNotLoaded(err error) bool { + if err == nil { + return false + } + var e *NotLoadedError + return errors.As(err, &e) +} + +// ConstraintError returns when trying to create/update one or more entities and +// one or more of their constraints failed. For example, violation of edge or +// field uniqueness. +type ConstraintError struct { + msg string + wrap error +} + +// Error implements the error interface. +func (e ConstraintError) Error() string { + return "ent: constraint failed: " + e.msg +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ConstraintError) Unwrap() error { + return e.wrap +} + +// IsConstraintError returns a boolean indicating whether the error is a constraint failure. +func IsConstraintError(err error) bool { + if err == nil { + return false + } + var e *ConstraintError + return errors.As(err, &e) +} + +// selector embedded by the different Select/GroupBy builders. +type selector struct { + label string + flds *[]string + fns []AggregateFunc + scan func(context.Context, any) error +} + +// ScanX is like Scan, but panics if an error occurs. +func (s *selector) ScanX(ctx context.Context, v any) { + if err := s.scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (s *selector) Strings(ctx context.Context) ([]string, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (s *selector) StringsX(ctx context.Context) []string { + v, err := s.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (s *selector) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = s.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (s *selector) StringX(ctx context.Context) string { + v, err := s.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (s *selector) Ints(ctx context.Context) ([]int, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (s *selector) IntsX(ctx context.Context) []int { + v, err := s.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (s *selector) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = s.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (s *selector) IntX(ctx context.Context) int { + v, err := s.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (s *selector) Float64s(ctx context.Context) ([]float64, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (s *selector) Float64sX(ctx context.Context) []float64 { + v, err := s.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (s *selector) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = s.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (s *selector) Float64X(ctx context.Context) float64 { + v, err := s.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (s *selector) Bools(ctx context.Context) ([]bool, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (s *selector) BoolsX(ctx context.Context) []bool { + v, err := s.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (s *selector) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = s.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (s *selector) BoolX(ctx context.Context) bool { + v, err := s.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +// withHooks invokes the builder operation with the given hooks, if any. +func withHooks[V Value, M any, PM interface { + *M + Mutation +}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) { + if len(hooks) == 0 { + return exec(ctx) + } + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutationT, ok := any(m).(PM) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + // Set the mutation to the builder. + *mutation = *mutationT + return exec(ctx) + }) + for i := len(hooks) - 1; i >= 0; i-- { + if hooks[i] == nil { + return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = hooks[i](mut) + } + v, err := mut.Mutate(ctx, mutation) + if err != nil { + return value, err + } + nv, ok := v.(V) + if !ok { + return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation) + } + return nv, nil +} + +// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist. +func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context { + if ent.QueryFromContext(ctx) == nil { + qc.Op = op + ctx = ent.NewQueryContext(ctx, qc) + } + return ctx +} + +func querierAll[V Value, Q interface { + sqlAll(context.Context, ...queryHook) (V, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlAll(ctx) + }) +} + +func querierCount[Q interface { + sqlCount(context.Context) (int, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlCount(ctx) + }) +} + +func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) { + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + rv, err := qr.Query(ctx, q) + if err != nil { + return v, err + } + vt, ok := rv.(V) + if !ok { + return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v) + } + return vt, nil +} + +func scanWithInterceptors[Q1 ent.Query, Q2 interface { + sqlScan(context.Context, Q1, any) error +}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error { + rv := reflect.ValueOf(v) + var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q1) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + if err := selectOrGroup.sqlScan(ctx, query, v); err != nil { + return nil, err + } + if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() { + return rv.Elem().Interface(), nil + } + return v, nil + }) + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + vv, err := qr.Query(ctx, rootQuery) + if err != nil { + return err + } + switch rv2 := reflect.ValueOf(vv); { + case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer: + case rv.Type() == rv2.Type(): + rv.Elem().Set(rv2.Elem()) + case rv.Elem().Type() == rv2.Type(): + rv.Elem().Set(rv2) + } + return nil +} + +// queryHook describes an internal hook for the different sqlAll methods. +type queryHook func(context.Context, *sqlgraph.QuerySpec) diff --git a/internal/ent/enttest/enttest.go b/internal/ent/enttest/enttest.go new file mode 100644 index 0000000..29f983d --- /dev/null +++ b/internal/ent/enttest/enttest.go @@ -0,0 +1,85 @@ +// Code generated by ent, DO NOT EDIT. + +package enttest + +import ( + "context" + + "home-vue-go/internal/ent" + // required by schema hooks. + _ "home-vue-go/internal/ent/runtime" + + "home-vue-go/internal/ent/migrate" + + "entgo.io/ent/dialect/sql/schema" +) + +type ( + // TestingT is the interface that is shared between + // testing.T and testing.B and used by enttest. + TestingT interface { + FailNow() + Error(...any) + } + + // Option configures client creation. + Option func(*options) + + options struct { + opts []ent.Option + migrateOpts []schema.MigrateOption + } +) + +// WithOptions forwards options to client creation. +func WithOptions(opts ...ent.Option) Option { + return func(o *options) { + o.opts = append(o.opts, opts...) + } +} + +// WithMigrateOptions forwards options to auto migration. +func WithMigrateOptions(opts ...schema.MigrateOption) Option { + return func(o *options) { + o.migrateOpts = append(o.migrateOpts, opts...) + } +} + +func newOptions(opts []Option) *options { + o := &options{} + for _, opt := range opts { + opt(o) + } + return o +} + +// Open calls ent.Open and auto-run migration. +func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Client { + o := newOptions(opts) + c, err := ent.Open(driverName, dataSourceName, o.opts...) + if err != nil { + t.Error(err) + t.FailNow() + } + migrateSchema(t, c, o) + return c +} + +// NewClient calls ent.NewClient and auto-run migration. +func NewClient(t TestingT, opts ...Option) *ent.Client { + o := newOptions(opts) + c := ent.NewClient(o.opts...) + migrateSchema(t, c, o) + return c +} +func migrateSchema(t TestingT, c *ent.Client, o *options) { + tables, err := schema.CopyTables(migrate.Tables) + if err != nil { + t.Error(err) + t.FailNow() + } + if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil { + t.Error(err) + t.FailNow() + } +} diff --git a/internal/ent/generate.go b/internal/ent/generate.go new file mode 100644 index 0000000..0b4f35c --- /dev/null +++ b/internal/ent/generate.go @@ -0,0 +1,3 @@ +package ent + +//go:generate go run -mod=mod entgo.io/ent/cmd/ent@latest generate ./schema diff --git a/internal/ent/hook/hook.go b/internal/ent/hook/hook.go new file mode 100644 index 0000000..a11538a --- /dev/null +++ b/internal/ent/hook/hook.go @@ -0,0 +1,258 @@ +// Code generated by ent, DO NOT EDIT. + +package hook + +import ( + "context" + "fmt" + "home-vue-go/internal/ent" +) + +// The ContactFunc type is an adapter to allow the use of ordinary +// function as Contact mutator. +type ContactFunc func(context.Context, *ent.ContactMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f ContactFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.ContactMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ContactMutation", m) +} + +// The LoginHistoryFunc type is an adapter to allow the use of ordinary +// function as LoginHistory mutator. +type LoginHistoryFunc func(context.Context, *ent.LoginHistoryMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f LoginHistoryFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.LoginHistoryMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.LoginHistoryMutation", m) +} + +// The SiteFunc type is an adapter to allow the use of ordinary +// function as Site mutator. +type SiteFunc func(context.Context, *ent.SiteMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f SiteFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.SiteMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.SiteMutation", m) +} + +// The SiteConfigFunc type is an adapter to allow the use of ordinary +// function as SiteConfig mutator. +type SiteConfigFunc func(context.Context, *ent.SiteConfigMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f SiteConfigFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.SiteConfigMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.SiteConfigMutation", m) +} + +// The UserFunc type is an adapter to allow the use of ordinary +// function as User mutator. +type UserFunc func(context.Context, *ent.UserMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f UserFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.UserMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserMutation", m) +} + +// The VisitFunc type is an adapter to allow the use of ordinary +// function as Visit mutator. +type VisitFunc func(context.Context, *ent.VisitMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f VisitFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.VisitMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.VisitMutation", m) +} + +// Condition is a hook condition function. +type Condition func(context.Context, ent.Mutation) bool + +// And groups conditions with the AND operator. +func And(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m ent.Mutation) bool { + if !first(ctx, m) || !second(ctx, m) { + return false + } + for _, cond := range rest { + if !cond(ctx, m) { + return false + } + } + return true + } +} + +// Or groups conditions with the OR operator. +func Or(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m ent.Mutation) bool { + if first(ctx, m) || second(ctx, m) { + return true + } + for _, cond := range rest { + if cond(ctx, m) { + return true + } + } + return false + } +} + +// Not negates a given condition. +func Not(cond Condition) Condition { + return func(ctx context.Context, m ent.Mutation) bool { + return !cond(ctx, m) + } +} + +// HasOp is a condition testing mutation operation. +func HasOp(op ent.Op) Condition { + return func(_ context.Context, m ent.Mutation) bool { + return m.Op().Is(op) + } +} + +// HasAddedFields is a condition validating `.AddedField` on fields. +func HasAddedFields(field string, fields ...string) Condition { + return func(_ context.Context, m ent.Mutation) bool { + if _, exists := m.AddedField(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.AddedField(field); !exists { + return false + } + } + return true + } +} + +// HasClearedFields is a condition validating `.FieldCleared` on fields. +func HasClearedFields(field string, fields ...string) Condition { + return func(_ context.Context, m ent.Mutation) bool { + if exists := m.FieldCleared(field); !exists { + return false + } + for _, field := range fields { + if exists := m.FieldCleared(field); !exists { + return false + } + } + return true + } +} + +// HasFields is a condition validating `.Field` on fields. +func HasFields(field string, fields ...string) Condition { + return func(_ context.Context, m ent.Mutation) bool { + if _, exists := m.Field(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.Field(field); !exists { + return false + } + } + return true + } +} + +// If executes the given hook under condition. +// +// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) +func If(hk ent.Hook, cond Condition) ent.Hook { + return func(next ent.Mutator) ent.Mutator { + return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if cond(ctx, m) { + return hk(next).Mutate(ctx, m) + } + return next.Mutate(ctx, m) + }) + } +} + +// On executes the given hook only for the given operation. +// +// hook.On(Log, ent.Delete|ent.Create) +func On(hk ent.Hook, op ent.Op) ent.Hook { + return If(hk, HasOp(op)) +} + +// Unless skips the given hook only for the given operation. +// +// hook.Unless(Log, ent.Update|ent.UpdateOne) +func Unless(hk ent.Hook, op ent.Op) ent.Hook { + return If(hk, Not(HasOp(op))) +} + +// FixedError is a hook returning a fixed error. +func FixedError(err error) ent.Hook { + return func(ent.Mutator) ent.Mutator { + return ent.MutateFunc(func(context.Context, ent.Mutation) (ent.Value, error) { + return nil, err + }) + } +} + +// Reject returns a hook that rejects all operations that match op. +// +// func (T) Hooks() []ent.Hook { +// return []ent.Hook{ +// Reject(ent.Delete|ent.Update), +// } +// } +func Reject(op ent.Op) ent.Hook { + hk := FixedError(fmt.Errorf("%s operation is not allowed", op)) + return On(hk, op) +} + +// Chain acts as a list of hooks and is effectively immutable. +// Once created, it will always hold the same set of hooks in the same order. +type Chain struct { + hooks []ent.Hook +} + +// NewChain creates a new chain of hooks. +func NewChain(hooks ...ent.Hook) Chain { + return Chain{append([]ent.Hook(nil), hooks...)} +} + +// Hook chains the list of hooks and returns the final hook. +func (c Chain) Hook() ent.Hook { + return func(mutator ent.Mutator) ent.Mutator { + for i := len(c.hooks) - 1; i >= 0; i-- { + mutator = c.hooks[i](mutator) + } + return mutator + } +} + +// Append extends a chain, adding the specified hook +// as the last ones in the mutation flow. +func (c Chain) Append(hooks ...ent.Hook) Chain { + newHooks := make([]ent.Hook, 0, len(c.hooks)+len(hooks)) + newHooks = append(newHooks, c.hooks...) + newHooks = append(newHooks, hooks...) + return Chain{newHooks} +} + +// Extend extends a chain, adding the specified chain +// as the last ones in the mutation flow. +func (c Chain) Extend(chain Chain) Chain { + return c.Append(chain.hooks...) +} diff --git a/internal/ent/loginhistory.go b/internal/ent/loginhistory.go new file mode 100644 index 0000000..29cba6f --- /dev/null +++ b/internal/ent/loginhistory.go @@ -0,0 +1,163 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "home-vue-go/internal/ent/loginhistory" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// LoginHistory is the model entity for the LoginHistory schema. +type LoginHistory struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // 用户名 + Username string `json:"username,omitempty"` + // 登录IP地址 + IP string `json:"ip,omitempty"` + // IP地理位置 + Location string `json:"location,omitempty"` + // 用户代理 + UserAgent string `json:"user_agent,omitempty"` + // 登录时间 + LoginTime time.Time `json:"login_time,omitempty"` + // 登录是否成功 + Success bool `json:"success,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*LoginHistory) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case loginhistory.FieldSuccess: + values[i] = new(sql.NullBool) + case loginhistory.FieldID: + values[i] = new(sql.NullInt64) + case loginhistory.FieldUsername, loginhistory.FieldIP, loginhistory.FieldLocation, loginhistory.FieldUserAgent: + values[i] = new(sql.NullString) + case loginhistory.FieldLoginTime: + values[i] = new(sql.NullTime) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the LoginHistory fields. +func (_m *LoginHistory) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case loginhistory.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int(value.Int64) + case loginhistory.FieldUsername: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field username", values[i]) + } else if value.Valid { + _m.Username = value.String + } + case loginhistory.FieldIP: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field ip", values[i]) + } else if value.Valid { + _m.IP = value.String + } + case loginhistory.FieldLocation: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field location", values[i]) + } else if value.Valid { + _m.Location = value.String + } + case loginhistory.FieldUserAgent: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field user_agent", values[i]) + } else if value.Valid { + _m.UserAgent = value.String + } + case loginhistory.FieldLoginTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field login_time", values[i]) + } else if value.Valid { + _m.LoginTime = value.Time + } + case loginhistory.FieldSuccess: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field success", values[i]) + } else if value.Valid { + _m.Success = value.Bool + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the LoginHistory. +// This includes values selected through modifiers, order, etc. +func (_m *LoginHistory) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this LoginHistory. +// Note that you need to call LoginHistory.Unwrap() before calling this method if this LoginHistory +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *LoginHistory) Update() *LoginHistoryUpdateOne { + return NewLoginHistoryClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the LoginHistory entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *LoginHistory) Unwrap() *LoginHistory { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: LoginHistory is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *LoginHistory) String() string { + var builder strings.Builder + builder.WriteString("LoginHistory(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("username=") + builder.WriteString(_m.Username) + builder.WriteString(", ") + builder.WriteString("ip=") + builder.WriteString(_m.IP) + builder.WriteString(", ") + builder.WriteString("location=") + builder.WriteString(_m.Location) + builder.WriteString(", ") + builder.WriteString("user_agent=") + builder.WriteString(_m.UserAgent) + builder.WriteString(", ") + builder.WriteString("login_time=") + builder.WriteString(_m.LoginTime.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("success=") + builder.WriteString(fmt.Sprintf("%v", _m.Success)) + builder.WriteByte(')') + return builder.String() +} + +// LoginHistories is a parsable slice of LoginHistory. +type LoginHistories []*LoginHistory diff --git a/internal/ent/loginhistory/loginhistory.go b/internal/ent/loginhistory/loginhistory.go new file mode 100644 index 0000000..635685d --- /dev/null +++ b/internal/ent/loginhistory/loginhistory.go @@ -0,0 +1,96 @@ +// Code generated by ent, DO NOT EDIT. + +package loginhistory + +import ( + "time" + + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the loginhistory type in the database. + Label = "login_history" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldUsername holds the string denoting the username field in the database. + FieldUsername = "username" + // FieldIP holds the string denoting the ip field in the database. + FieldIP = "ip" + // FieldLocation holds the string denoting the location field in the database. + FieldLocation = "location" + // FieldUserAgent holds the string denoting the user_agent field in the database. + FieldUserAgent = "user_agent" + // FieldLoginTime holds the string denoting the login_time field in the database. + FieldLoginTime = "login_time" + // FieldSuccess holds the string denoting the success field in the database. + FieldSuccess = "success" + // Table holds the table name of the loginhistory in the database. + Table = "login_histories" +) + +// Columns holds all SQL columns for loginhistory fields. +var Columns = []string{ + FieldID, + FieldUsername, + FieldIP, + FieldLocation, + FieldUserAgent, + FieldLoginTime, + FieldSuccess, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultLoginTime holds the default value on creation for the "login_time" field. + DefaultLoginTime func() time.Time + // DefaultSuccess holds the default value on creation for the "success" field. + DefaultSuccess bool +) + +// OrderOption defines the ordering options for the LoginHistory 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() +} + +// ByUsername orders the results by the username field. +func ByUsername(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUsername, opts...).ToFunc() +} + +// ByIP orders the results by the ip field. +func ByIP(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIP, opts...).ToFunc() +} + +// ByLocation orders the results by the location field. +func ByLocation(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLocation, opts...).ToFunc() +} + +// ByUserAgent orders the results by the user_agent field. +func ByUserAgent(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUserAgent, opts...).ToFunc() +} + +// ByLoginTime orders the results by the login_time field. +func ByLoginTime(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldLoginTime, opts...).ToFunc() +} + +// BySuccess orders the results by the success field. +func BySuccess(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSuccess, opts...).ToFunc() +} diff --git a/internal/ent/loginhistory/where.go b/internal/ent/loginhistory/where.go new file mode 100644 index 0000000..8da5a62 --- /dev/null +++ b/internal/ent/loginhistory/where.go @@ -0,0 +1,430 @@ +// Code generated by ent, DO NOT EDIT. + +package loginhistory + +import ( + "home-vue-go/internal/ent/predicate" + "time" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldLTE(FieldID, id)) +} + +// Username applies equality check predicate on the "username" field. It's identical to UsernameEQ. +func Username(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldEQ(FieldUsername, v)) +} + +// IP applies equality check predicate on the "ip" field. It's identical to IPEQ. +func IP(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldEQ(FieldIP, v)) +} + +// Location applies equality check predicate on the "location" field. It's identical to LocationEQ. +func Location(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldEQ(FieldLocation, v)) +} + +// UserAgent applies equality check predicate on the "user_agent" field. It's identical to UserAgentEQ. +func UserAgent(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldEQ(FieldUserAgent, v)) +} + +// LoginTime applies equality check predicate on the "login_time" field. It's identical to LoginTimeEQ. +func LoginTime(v time.Time) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldEQ(FieldLoginTime, v)) +} + +// Success applies equality check predicate on the "success" field. It's identical to SuccessEQ. +func Success(v bool) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldEQ(FieldSuccess, v)) +} + +// UsernameEQ applies the EQ predicate on the "username" field. +func UsernameEQ(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldEQ(FieldUsername, v)) +} + +// UsernameNEQ applies the NEQ predicate on the "username" field. +func UsernameNEQ(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldNEQ(FieldUsername, v)) +} + +// UsernameIn applies the In predicate on the "username" field. +func UsernameIn(vs ...string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldIn(FieldUsername, vs...)) +} + +// UsernameNotIn applies the NotIn predicate on the "username" field. +func UsernameNotIn(vs ...string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldNotIn(FieldUsername, vs...)) +} + +// UsernameGT applies the GT predicate on the "username" field. +func UsernameGT(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldGT(FieldUsername, v)) +} + +// UsernameGTE applies the GTE predicate on the "username" field. +func UsernameGTE(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldGTE(FieldUsername, v)) +} + +// UsernameLT applies the LT predicate on the "username" field. +func UsernameLT(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldLT(FieldUsername, v)) +} + +// UsernameLTE applies the LTE predicate on the "username" field. +func UsernameLTE(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldLTE(FieldUsername, v)) +} + +// UsernameContains applies the Contains predicate on the "username" field. +func UsernameContains(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldContains(FieldUsername, v)) +} + +// UsernameHasPrefix applies the HasPrefix predicate on the "username" field. +func UsernameHasPrefix(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldHasPrefix(FieldUsername, v)) +} + +// UsernameHasSuffix applies the HasSuffix predicate on the "username" field. +func UsernameHasSuffix(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldHasSuffix(FieldUsername, v)) +} + +// UsernameEqualFold applies the EqualFold predicate on the "username" field. +func UsernameEqualFold(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldEqualFold(FieldUsername, v)) +} + +// UsernameContainsFold applies the ContainsFold predicate on the "username" field. +func UsernameContainsFold(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldContainsFold(FieldUsername, v)) +} + +// IPEQ applies the EQ predicate on the "ip" field. +func IPEQ(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldEQ(FieldIP, v)) +} + +// IPNEQ applies the NEQ predicate on the "ip" field. +func IPNEQ(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldNEQ(FieldIP, v)) +} + +// IPIn applies the In predicate on the "ip" field. +func IPIn(vs ...string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldIn(FieldIP, vs...)) +} + +// IPNotIn applies the NotIn predicate on the "ip" field. +func IPNotIn(vs ...string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldNotIn(FieldIP, vs...)) +} + +// IPGT applies the GT predicate on the "ip" field. +func IPGT(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldGT(FieldIP, v)) +} + +// IPGTE applies the GTE predicate on the "ip" field. +func IPGTE(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldGTE(FieldIP, v)) +} + +// IPLT applies the LT predicate on the "ip" field. +func IPLT(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldLT(FieldIP, v)) +} + +// IPLTE applies the LTE predicate on the "ip" field. +func IPLTE(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldLTE(FieldIP, v)) +} + +// IPContains applies the Contains predicate on the "ip" field. +func IPContains(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldContains(FieldIP, v)) +} + +// IPHasPrefix applies the HasPrefix predicate on the "ip" field. +func IPHasPrefix(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldHasPrefix(FieldIP, v)) +} + +// IPHasSuffix applies the HasSuffix predicate on the "ip" field. +func IPHasSuffix(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldHasSuffix(FieldIP, v)) +} + +// IPEqualFold applies the EqualFold predicate on the "ip" field. +func IPEqualFold(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldEqualFold(FieldIP, v)) +} + +// IPContainsFold applies the ContainsFold predicate on the "ip" field. +func IPContainsFold(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldContainsFold(FieldIP, v)) +} + +// LocationEQ applies the EQ predicate on the "location" field. +func LocationEQ(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldEQ(FieldLocation, v)) +} + +// LocationNEQ applies the NEQ predicate on the "location" field. +func LocationNEQ(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldNEQ(FieldLocation, v)) +} + +// LocationIn applies the In predicate on the "location" field. +func LocationIn(vs ...string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldIn(FieldLocation, vs...)) +} + +// LocationNotIn applies the NotIn predicate on the "location" field. +func LocationNotIn(vs ...string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldNotIn(FieldLocation, vs...)) +} + +// LocationGT applies the GT predicate on the "location" field. +func LocationGT(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldGT(FieldLocation, v)) +} + +// LocationGTE applies the GTE predicate on the "location" field. +func LocationGTE(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldGTE(FieldLocation, v)) +} + +// LocationLT applies the LT predicate on the "location" field. +func LocationLT(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldLT(FieldLocation, v)) +} + +// LocationLTE applies the LTE predicate on the "location" field. +func LocationLTE(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldLTE(FieldLocation, v)) +} + +// LocationContains applies the Contains predicate on the "location" field. +func LocationContains(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldContains(FieldLocation, v)) +} + +// LocationHasPrefix applies the HasPrefix predicate on the "location" field. +func LocationHasPrefix(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldHasPrefix(FieldLocation, v)) +} + +// LocationHasSuffix applies the HasSuffix predicate on the "location" field. +func LocationHasSuffix(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldHasSuffix(FieldLocation, v)) +} + +// LocationIsNil applies the IsNil predicate on the "location" field. +func LocationIsNil() predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldIsNull(FieldLocation)) +} + +// LocationNotNil applies the NotNil predicate on the "location" field. +func LocationNotNil() predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldNotNull(FieldLocation)) +} + +// LocationEqualFold applies the EqualFold predicate on the "location" field. +func LocationEqualFold(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldEqualFold(FieldLocation, v)) +} + +// LocationContainsFold applies the ContainsFold predicate on the "location" field. +func LocationContainsFold(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldContainsFold(FieldLocation, v)) +} + +// UserAgentEQ applies the EQ predicate on the "user_agent" field. +func UserAgentEQ(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldEQ(FieldUserAgent, v)) +} + +// UserAgentNEQ applies the NEQ predicate on the "user_agent" field. +func UserAgentNEQ(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldNEQ(FieldUserAgent, v)) +} + +// UserAgentIn applies the In predicate on the "user_agent" field. +func UserAgentIn(vs ...string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldIn(FieldUserAgent, vs...)) +} + +// UserAgentNotIn applies the NotIn predicate on the "user_agent" field. +func UserAgentNotIn(vs ...string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldNotIn(FieldUserAgent, vs...)) +} + +// UserAgentGT applies the GT predicate on the "user_agent" field. +func UserAgentGT(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldGT(FieldUserAgent, v)) +} + +// UserAgentGTE applies the GTE predicate on the "user_agent" field. +func UserAgentGTE(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldGTE(FieldUserAgent, v)) +} + +// UserAgentLT applies the LT predicate on the "user_agent" field. +func UserAgentLT(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldLT(FieldUserAgent, v)) +} + +// UserAgentLTE applies the LTE predicate on the "user_agent" field. +func UserAgentLTE(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldLTE(FieldUserAgent, v)) +} + +// UserAgentContains applies the Contains predicate on the "user_agent" field. +func UserAgentContains(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldContains(FieldUserAgent, v)) +} + +// UserAgentHasPrefix applies the HasPrefix predicate on the "user_agent" field. +func UserAgentHasPrefix(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldHasPrefix(FieldUserAgent, v)) +} + +// UserAgentHasSuffix applies the HasSuffix predicate on the "user_agent" field. +func UserAgentHasSuffix(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldHasSuffix(FieldUserAgent, v)) +} + +// UserAgentIsNil applies the IsNil predicate on the "user_agent" field. +func UserAgentIsNil() predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldIsNull(FieldUserAgent)) +} + +// UserAgentNotNil applies the NotNil predicate on the "user_agent" field. +func UserAgentNotNil() predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldNotNull(FieldUserAgent)) +} + +// UserAgentEqualFold applies the EqualFold predicate on the "user_agent" field. +func UserAgentEqualFold(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldEqualFold(FieldUserAgent, v)) +} + +// UserAgentContainsFold applies the ContainsFold predicate on the "user_agent" field. +func UserAgentContainsFold(v string) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldContainsFold(FieldUserAgent, v)) +} + +// LoginTimeEQ applies the EQ predicate on the "login_time" field. +func LoginTimeEQ(v time.Time) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldEQ(FieldLoginTime, v)) +} + +// LoginTimeNEQ applies the NEQ predicate on the "login_time" field. +func LoginTimeNEQ(v time.Time) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldNEQ(FieldLoginTime, v)) +} + +// LoginTimeIn applies the In predicate on the "login_time" field. +func LoginTimeIn(vs ...time.Time) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldIn(FieldLoginTime, vs...)) +} + +// LoginTimeNotIn applies the NotIn predicate on the "login_time" field. +func LoginTimeNotIn(vs ...time.Time) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldNotIn(FieldLoginTime, vs...)) +} + +// LoginTimeGT applies the GT predicate on the "login_time" field. +func LoginTimeGT(v time.Time) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldGT(FieldLoginTime, v)) +} + +// LoginTimeGTE applies the GTE predicate on the "login_time" field. +func LoginTimeGTE(v time.Time) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldGTE(FieldLoginTime, v)) +} + +// LoginTimeLT applies the LT predicate on the "login_time" field. +func LoginTimeLT(v time.Time) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldLT(FieldLoginTime, v)) +} + +// LoginTimeLTE applies the LTE predicate on the "login_time" field. +func LoginTimeLTE(v time.Time) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldLTE(FieldLoginTime, v)) +} + +// SuccessEQ applies the EQ predicate on the "success" field. +func SuccessEQ(v bool) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldEQ(FieldSuccess, v)) +} + +// SuccessNEQ applies the NEQ predicate on the "success" field. +func SuccessNEQ(v bool) predicate.LoginHistory { + return predicate.LoginHistory(sql.FieldNEQ(FieldSuccess, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.LoginHistory) predicate.LoginHistory { + return predicate.LoginHistory(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.LoginHistory) predicate.LoginHistory { + return predicate.LoginHistory(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.LoginHistory) predicate.LoginHistory { + return predicate.LoginHistory(sql.NotPredicates(p)) +} diff --git a/internal/ent/loginhistory_create.go b/internal/ent/loginhistory_create.go new file mode 100644 index 0000000..51c5640 --- /dev/null +++ b/internal/ent/loginhistory_create.go @@ -0,0 +1,301 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "home-vue-go/internal/ent/loginhistory" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LoginHistoryCreate is the builder for creating a LoginHistory entity. +type LoginHistoryCreate struct { + config + mutation *LoginHistoryMutation + hooks []Hook +} + +// SetUsername sets the "username" field. +func (_c *LoginHistoryCreate) SetUsername(v string) *LoginHistoryCreate { + _c.mutation.SetUsername(v) + return _c +} + +// SetIP sets the "ip" field. +func (_c *LoginHistoryCreate) SetIP(v string) *LoginHistoryCreate { + _c.mutation.SetIP(v) + return _c +} + +// SetLocation sets the "location" field. +func (_c *LoginHistoryCreate) SetLocation(v string) *LoginHistoryCreate { + _c.mutation.SetLocation(v) + return _c +} + +// SetNillableLocation sets the "location" field if the given value is not nil. +func (_c *LoginHistoryCreate) SetNillableLocation(v *string) *LoginHistoryCreate { + if v != nil { + _c.SetLocation(*v) + } + return _c +} + +// SetUserAgent sets the "user_agent" field. +func (_c *LoginHistoryCreate) SetUserAgent(v string) *LoginHistoryCreate { + _c.mutation.SetUserAgent(v) + return _c +} + +// SetNillableUserAgent sets the "user_agent" field if the given value is not nil. +func (_c *LoginHistoryCreate) SetNillableUserAgent(v *string) *LoginHistoryCreate { + if v != nil { + _c.SetUserAgent(*v) + } + return _c +} + +// SetLoginTime sets the "login_time" field. +func (_c *LoginHistoryCreate) SetLoginTime(v time.Time) *LoginHistoryCreate { + _c.mutation.SetLoginTime(v) + return _c +} + +// SetNillableLoginTime sets the "login_time" field if the given value is not nil. +func (_c *LoginHistoryCreate) SetNillableLoginTime(v *time.Time) *LoginHistoryCreate { + if v != nil { + _c.SetLoginTime(*v) + } + return _c +} + +// SetSuccess sets the "success" field. +func (_c *LoginHistoryCreate) SetSuccess(v bool) *LoginHistoryCreate { + _c.mutation.SetSuccess(v) + return _c +} + +// SetNillableSuccess sets the "success" field if the given value is not nil. +func (_c *LoginHistoryCreate) SetNillableSuccess(v *bool) *LoginHistoryCreate { + if v != nil { + _c.SetSuccess(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *LoginHistoryCreate) SetID(v int) *LoginHistoryCreate { + _c.mutation.SetID(v) + return _c +} + +// Mutation returns the LoginHistoryMutation object of the builder. +func (_c *LoginHistoryCreate) Mutation() *LoginHistoryMutation { + return _c.mutation +} + +// Save creates the LoginHistory in the database. +func (_c *LoginHistoryCreate) Save(ctx context.Context) (*LoginHistory, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *LoginHistoryCreate) SaveX(ctx context.Context) *LoginHistory { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *LoginHistoryCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *LoginHistoryCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *LoginHistoryCreate) defaults() { + if _, ok := _c.mutation.LoginTime(); !ok { + v := loginhistory.DefaultLoginTime() + _c.mutation.SetLoginTime(v) + } + if _, ok := _c.mutation.Success(); !ok { + v := loginhistory.DefaultSuccess + _c.mutation.SetSuccess(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *LoginHistoryCreate) check() error { + if _, ok := _c.mutation.Username(); !ok { + return &ValidationError{Name: "username", err: errors.New(`ent: missing required field "LoginHistory.username"`)} + } + if _, ok := _c.mutation.IP(); !ok { + return &ValidationError{Name: "ip", err: errors.New(`ent: missing required field "LoginHistory.ip"`)} + } + if _, ok := _c.mutation.LoginTime(); !ok { + return &ValidationError{Name: "login_time", err: errors.New(`ent: missing required field "LoginHistory.login_time"`)} + } + if _, ok := _c.mutation.Success(); !ok { + return &ValidationError{Name: "success", err: errors.New(`ent: missing required field "LoginHistory.success"`)} + } + return nil +} + +func (_c *LoginHistoryCreate) sqlSave(ctx context.Context) (*LoginHistory, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != _node.ID { + id := _spec.ID.Value.(int64) + _node.ID = int(id) + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *LoginHistoryCreate) createSpec() (*LoginHistory, *sqlgraph.CreateSpec) { + var ( + _node = &LoginHistory{config: _c.config} + _spec = sqlgraph.NewCreateSpec(loginhistory.Table, sqlgraph.NewFieldSpec(loginhistory.FieldID, field.TypeInt)) + ) + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.Username(); ok { + _spec.SetField(loginhistory.FieldUsername, field.TypeString, value) + _node.Username = value + } + if value, ok := _c.mutation.IP(); ok { + _spec.SetField(loginhistory.FieldIP, field.TypeString, value) + _node.IP = value + } + if value, ok := _c.mutation.Location(); ok { + _spec.SetField(loginhistory.FieldLocation, field.TypeString, value) + _node.Location = value + } + if value, ok := _c.mutation.UserAgent(); ok { + _spec.SetField(loginhistory.FieldUserAgent, field.TypeString, value) + _node.UserAgent = value + } + if value, ok := _c.mutation.LoginTime(); ok { + _spec.SetField(loginhistory.FieldLoginTime, field.TypeTime, value) + _node.LoginTime = value + } + if value, ok := _c.mutation.Success(); ok { + _spec.SetField(loginhistory.FieldSuccess, field.TypeBool, value) + _node.Success = value + } + return _node, _spec +} + +// LoginHistoryCreateBulk is the builder for creating many LoginHistory entities in bulk. +type LoginHistoryCreateBulk struct { + config + err error + builders []*LoginHistoryCreate +} + +// Save creates the LoginHistory entities in the database. +func (_c *LoginHistoryCreateBulk) Save(ctx context.Context) ([]*LoginHistory, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*LoginHistory, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*LoginHistoryMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil && nodes[i].ID == 0 { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *LoginHistoryCreateBulk) SaveX(ctx context.Context) []*LoginHistory { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *LoginHistoryCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *LoginHistoryCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/ent/loginhistory_delete.go b/internal/ent/loginhistory_delete.go new file mode 100644 index 0000000..6d74309 --- /dev/null +++ b/internal/ent/loginhistory_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "home-vue-go/internal/ent/loginhistory" + "home-vue-go/internal/ent/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LoginHistoryDelete is the builder for deleting a LoginHistory entity. +type LoginHistoryDelete struct { + config + hooks []Hook + mutation *LoginHistoryMutation +} + +// Where appends a list predicates to the LoginHistoryDelete builder. +func (_d *LoginHistoryDelete) Where(ps ...predicate.LoginHistory) *LoginHistoryDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *LoginHistoryDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *LoginHistoryDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *LoginHistoryDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(loginhistory.Table, sqlgraph.NewFieldSpec(loginhistory.FieldID, field.TypeInt)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// LoginHistoryDeleteOne is the builder for deleting a single LoginHistory entity. +type LoginHistoryDeleteOne struct { + _d *LoginHistoryDelete +} + +// Where appends a list predicates to the LoginHistoryDelete builder. +func (_d *LoginHistoryDeleteOne) Where(ps ...predicate.LoginHistory) *LoginHistoryDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *LoginHistoryDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{loginhistory.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *LoginHistoryDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/ent/loginhistory_query.go b/internal/ent/loginhistory_query.go new file mode 100644 index 0000000..3ebf5d0 --- /dev/null +++ b/internal/ent/loginhistory_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "home-vue-go/internal/ent/loginhistory" + "home-vue-go/internal/ent/predicate" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LoginHistoryQuery is the builder for querying LoginHistory entities. +type LoginHistoryQuery struct { + config + ctx *QueryContext + order []loginhistory.OrderOption + inters []Interceptor + predicates []predicate.LoginHistory + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the LoginHistoryQuery builder. +func (_q *LoginHistoryQuery) Where(ps ...predicate.LoginHistory) *LoginHistoryQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *LoginHistoryQuery) Limit(limit int) *LoginHistoryQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *LoginHistoryQuery) Offset(offset int) *LoginHistoryQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *LoginHistoryQuery) Unique(unique bool) *LoginHistoryQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *LoginHistoryQuery) Order(o ...loginhistory.OrderOption) *LoginHistoryQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first LoginHistory entity from the query. +// Returns a *NotFoundError when no LoginHistory was found. +func (_q *LoginHistoryQuery) First(ctx context.Context) (*LoginHistory, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{loginhistory.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *LoginHistoryQuery) FirstX(ctx context.Context) *LoginHistory { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first LoginHistory ID from the query. +// Returns a *NotFoundError when no LoginHistory ID was found. +func (_q *LoginHistoryQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{loginhistory.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *LoginHistoryQuery) FirstIDX(ctx context.Context) int { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single LoginHistory entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one LoginHistory entity is found. +// Returns a *NotFoundError when no LoginHistory entities are found. +func (_q *LoginHistoryQuery) Only(ctx context.Context) (*LoginHistory, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{loginhistory.Label} + default: + return nil, &NotSingularError{loginhistory.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *LoginHistoryQuery) OnlyX(ctx context.Context) *LoginHistory { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only LoginHistory ID in the query. +// Returns a *NotSingularError when more than one LoginHistory ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *LoginHistoryQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{loginhistory.Label} + default: + err = &NotSingularError{loginhistory.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *LoginHistoryQuery) OnlyIDX(ctx context.Context) int { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of LoginHistories. +func (_q *LoginHistoryQuery) All(ctx context.Context) ([]*LoginHistory, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*LoginHistory, *LoginHistoryQuery]() + return withInterceptors[[]*LoginHistory](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *LoginHistoryQuery) AllX(ctx context.Context) []*LoginHistory { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of LoginHistory IDs. +func (_q *LoginHistoryQuery) IDs(ctx context.Context) (ids []int, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(loginhistory.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *LoginHistoryQuery) IDsX(ctx context.Context) []int { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *LoginHistoryQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*LoginHistoryQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *LoginHistoryQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *LoginHistoryQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *LoginHistoryQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the LoginHistoryQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *LoginHistoryQuery) Clone() *LoginHistoryQuery { + if _q == nil { + return nil + } + return &LoginHistoryQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]loginhistory.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.LoginHistory{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Username string `json:"username,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.LoginHistory.Query(). +// GroupBy(loginhistory.FieldUsername). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *LoginHistoryQuery) GroupBy(field string, fields ...string) *LoginHistoryGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &LoginHistoryGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = loginhistory.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// Username string `json:"username,omitempty"` +// } +// +// client.LoginHistory.Query(). +// Select(loginhistory.FieldUsername). +// Scan(ctx, &v) +func (_q *LoginHistoryQuery) Select(fields ...string) *LoginHistorySelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &LoginHistorySelect{LoginHistoryQuery: _q} + sbuild.label = loginhistory.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a LoginHistorySelect configured with the given aggregations. +func (_q *LoginHistoryQuery) Aggregate(fns ...AggregateFunc) *LoginHistorySelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *LoginHistoryQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !loginhistory.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *LoginHistoryQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*LoginHistory, error) { + var ( + nodes = []*LoginHistory{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*LoginHistory).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &LoginHistory{config: _q.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (_q *LoginHistoryQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *LoginHistoryQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(loginhistory.Table, loginhistory.Columns, sqlgraph.NewFieldSpec(loginhistory.FieldID, field.TypeInt)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, loginhistory.FieldID) + for i := range fields { + if fields[i] != loginhistory.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *LoginHistoryQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(loginhistory.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = loginhistory.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// LoginHistoryGroupBy is the group-by builder for LoginHistory entities. +type LoginHistoryGroupBy struct { + selector + build *LoginHistoryQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *LoginHistoryGroupBy) Aggregate(fns ...AggregateFunc) *LoginHistoryGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *LoginHistoryGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*LoginHistoryQuery, *LoginHistoryGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *LoginHistoryGroupBy) sqlScan(ctx context.Context, root *LoginHistoryQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// LoginHistorySelect is the builder for selecting fields of LoginHistory entities. +type LoginHistorySelect struct { + *LoginHistoryQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *LoginHistorySelect) Aggregate(fns ...AggregateFunc) *LoginHistorySelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *LoginHistorySelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*LoginHistoryQuery, *LoginHistorySelect](ctx, _s.LoginHistoryQuery, _s, _s.inters, v) +} + +func (_s *LoginHistorySelect) sqlScan(ctx context.Context, root *LoginHistoryQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/internal/ent/loginhistory_update.go b/internal/ent/loginhistory_update.go new file mode 100644 index 0000000..c2f1d31 --- /dev/null +++ b/internal/ent/loginhistory_update.go @@ -0,0 +1,416 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "home-vue-go/internal/ent/loginhistory" + "home-vue-go/internal/ent/predicate" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// LoginHistoryUpdate is the builder for updating LoginHistory entities. +type LoginHistoryUpdate struct { + config + hooks []Hook + mutation *LoginHistoryMutation +} + +// Where appends a list predicates to the LoginHistoryUpdate builder. +func (_u *LoginHistoryUpdate) Where(ps ...predicate.LoginHistory) *LoginHistoryUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUsername sets the "username" field. +func (_u *LoginHistoryUpdate) SetUsername(v string) *LoginHistoryUpdate { + _u.mutation.SetUsername(v) + return _u +} + +// SetNillableUsername sets the "username" field if the given value is not nil. +func (_u *LoginHistoryUpdate) SetNillableUsername(v *string) *LoginHistoryUpdate { + if v != nil { + _u.SetUsername(*v) + } + return _u +} + +// SetIP sets the "ip" field. +func (_u *LoginHistoryUpdate) SetIP(v string) *LoginHistoryUpdate { + _u.mutation.SetIP(v) + return _u +} + +// SetNillableIP sets the "ip" field if the given value is not nil. +func (_u *LoginHistoryUpdate) SetNillableIP(v *string) *LoginHistoryUpdate { + if v != nil { + _u.SetIP(*v) + } + return _u +} + +// SetLocation sets the "location" field. +func (_u *LoginHistoryUpdate) SetLocation(v string) *LoginHistoryUpdate { + _u.mutation.SetLocation(v) + return _u +} + +// SetNillableLocation sets the "location" field if the given value is not nil. +func (_u *LoginHistoryUpdate) SetNillableLocation(v *string) *LoginHistoryUpdate { + if v != nil { + _u.SetLocation(*v) + } + return _u +} + +// ClearLocation clears the value of the "location" field. +func (_u *LoginHistoryUpdate) ClearLocation() *LoginHistoryUpdate { + _u.mutation.ClearLocation() + return _u +} + +// SetUserAgent sets the "user_agent" field. +func (_u *LoginHistoryUpdate) SetUserAgent(v string) *LoginHistoryUpdate { + _u.mutation.SetUserAgent(v) + return _u +} + +// SetNillableUserAgent sets the "user_agent" field if the given value is not nil. +func (_u *LoginHistoryUpdate) SetNillableUserAgent(v *string) *LoginHistoryUpdate { + if v != nil { + _u.SetUserAgent(*v) + } + return _u +} + +// ClearUserAgent clears the value of the "user_agent" field. +func (_u *LoginHistoryUpdate) ClearUserAgent() *LoginHistoryUpdate { + _u.mutation.ClearUserAgent() + return _u +} + +// SetLoginTime sets the "login_time" field. +func (_u *LoginHistoryUpdate) SetLoginTime(v time.Time) *LoginHistoryUpdate { + _u.mutation.SetLoginTime(v) + return _u +} + +// SetNillableLoginTime sets the "login_time" field if the given value is not nil. +func (_u *LoginHistoryUpdate) SetNillableLoginTime(v *time.Time) *LoginHistoryUpdate { + if v != nil { + _u.SetLoginTime(*v) + } + return _u +} + +// SetSuccess sets the "success" field. +func (_u *LoginHistoryUpdate) SetSuccess(v bool) *LoginHistoryUpdate { + _u.mutation.SetSuccess(v) + return _u +} + +// SetNillableSuccess sets the "success" field if the given value is not nil. +func (_u *LoginHistoryUpdate) SetNillableSuccess(v *bool) *LoginHistoryUpdate { + if v != nil { + _u.SetSuccess(*v) + } + return _u +} + +// Mutation returns the LoginHistoryMutation object of the builder. +func (_u *LoginHistoryUpdate) Mutation() *LoginHistoryMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *LoginHistoryUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *LoginHistoryUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *LoginHistoryUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *LoginHistoryUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *LoginHistoryUpdate) sqlSave(ctx context.Context) (_node int, err error) { + _spec := sqlgraph.NewUpdateSpec(loginhistory.Table, loginhistory.Columns, sqlgraph.NewFieldSpec(loginhistory.FieldID, field.TypeInt)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Username(); ok { + _spec.SetField(loginhistory.FieldUsername, field.TypeString, value) + } + if value, ok := _u.mutation.IP(); ok { + _spec.SetField(loginhistory.FieldIP, field.TypeString, value) + } + if value, ok := _u.mutation.Location(); ok { + _spec.SetField(loginhistory.FieldLocation, field.TypeString, value) + } + if _u.mutation.LocationCleared() { + _spec.ClearField(loginhistory.FieldLocation, field.TypeString) + } + if value, ok := _u.mutation.UserAgent(); ok { + _spec.SetField(loginhistory.FieldUserAgent, field.TypeString, value) + } + if _u.mutation.UserAgentCleared() { + _spec.ClearField(loginhistory.FieldUserAgent, field.TypeString) + } + if value, ok := _u.mutation.LoginTime(); ok { + _spec.SetField(loginhistory.FieldLoginTime, field.TypeTime, value) + } + if value, ok := _u.mutation.Success(); ok { + _spec.SetField(loginhistory.FieldSuccess, field.TypeBool, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{loginhistory.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// LoginHistoryUpdateOne is the builder for updating a single LoginHistory entity. +type LoginHistoryUpdateOne struct { + config + fields []string + hooks []Hook + mutation *LoginHistoryMutation +} + +// SetUsername sets the "username" field. +func (_u *LoginHistoryUpdateOne) SetUsername(v string) *LoginHistoryUpdateOne { + _u.mutation.SetUsername(v) + return _u +} + +// SetNillableUsername sets the "username" field if the given value is not nil. +func (_u *LoginHistoryUpdateOne) SetNillableUsername(v *string) *LoginHistoryUpdateOne { + if v != nil { + _u.SetUsername(*v) + } + return _u +} + +// SetIP sets the "ip" field. +func (_u *LoginHistoryUpdateOne) SetIP(v string) *LoginHistoryUpdateOne { + _u.mutation.SetIP(v) + return _u +} + +// SetNillableIP sets the "ip" field if the given value is not nil. +func (_u *LoginHistoryUpdateOne) SetNillableIP(v *string) *LoginHistoryUpdateOne { + if v != nil { + _u.SetIP(*v) + } + return _u +} + +// SetLocation sets the "location" field. +func (_u *LoginHistoryUpdateOne) SetLocation(v string) *LoginHistoryUpdateOne { + _u.mutation.SetLocation(v) + return _u +} + +// SetNillableLocation sets the "location" field if the given value is not nil. +func (_u *LoginHistoryUpdateOne) SetNillableLocation(v *string) *LoginHistoryUpdateOne { + if v != nil { + _u.SetLocation(*v) + } + return _u +} + +// ClearLocation clears the value of the "location" field. +func (_u *LoginHistoryUpdateOne) ClearLocation() *LoginHistoryUpdateOne { + _u.mutation.ClearLocation() + return _u +} + +// SetUserAgent sets the "user_agent" field. +func (_u *LoginHistoryUpdateOne) SetUserAgent(v string) *LoginHistoryUpdateOne { + _u.mutation.SetUserAgent(v) + return _u +} + +// SetNillableUserAgent sets the "user_agent" field if the given value is not nil. +func (_u *LoginHistoryUpdateOne) SetNillableUserAgent(v *string) *LoginHistoryUpdateOne { + if v != nil { + _u.SetUserAgent(*v) + } + return _u +} + +// ClearUserAgent clears the value of the "user_agent" field. +func (_u *LoginHistoryUpdateOne) ClearUserAgent() *LoginHistoryUpdateOne { + _u.mutation.ClearUserAgent() + return _u +} + +// SetLoginTime sets the "login_time" field. +func (_u *LoginHistoryUpdateOne) SetLoginTime(v time.Time) *LoginHistoryUpdateOne { + _u.mutation.SetLoginTime(v) + return _u +} + +// SetNillableLoginTime sets the "login_time" field if the given value is not nil. +func (_u *LoginHistoryUpdateOne) SetNillableLoginTime(v *time.Time) *LoginHistoryUpdateOne { + if v != nil { + _u.SetLoginTime(*v) + } + return _u +} + +// SetSuccess sets the "success" field. +func (_u *LoginHistoryUpdateOne) SetSuccess(v bool) *LoginHistoryUpdateOne { + _u.mutation.SetSuccess(v) + return _u +} + +// SetNillableSuccess sets the "success" field if the given value is not nil. +func (_u *LoginHistoryUpdateOne) SetNillableSuccess(v *bool) *LoginHistoryUpdateOne { + if v != nil { + _u.SetSuccess(*v) + } + return _u +} + +// Mutation returns the LoginHistoryMutation object of the builder. +func (_u *LoginHistoryUpdateOne) Mutation() *LoginHistoryMutation { + return _u.mutation +} + +// Where appends a list predicates to the LoginHistoryUpdate builder. +func (_u *LoginHistoryUpdateOne) Where(ps ...predicate.LoginHistory) *LoginHistoryUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *LoginHistoryUpdateOne) Select(field string, fields ...string) *LoginHistoryUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated LoginHistory entity. +func (_u *LoginHistoryUpdateOne) Save(ctx context.Context) (*LoginHistory, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *LoginHistoryUpdateOne) SaveX(ctx context.Context) *LoginHistory { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *LoginHistoryUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *LoginHistoryUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *LoginHistoryUpdateOne) sqlSave(ctx context.Context) (_node *LoginHistory, err error) { + _spec := sqlgraph.NewUpdateSpec(loginhistory.Table, loginhistory.Columns, sqlgraph.NewFieldSpec(loginhistory.FieldID, field.TypeInt)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "LoginHistory.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, loginhistory.FieldID) + for _, f := range fields { + if !loginhistory.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != loginhistory.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Username(); ok { + _spec.SetField(loginhistory.FieldUsername, field.TypeString, value) + } + if value, ok := _u.mutation.IP(); ok { + _spec.SetField(loginhistory.FieldIP, field.TypeString, value) + } + if value, ok := _u.mutation.Location(); ok { + _spec.SetField(loginhistory.FieldLocation, field.TypeString, value) + } + if _u.mutation.LocationCleared() { + _spec.ClearField(loginhistory.FieldLocation, field.TypeString) + } + if value, ok := _u.mutation.UserAgent(); ok { + _spec.SetField(loginhistory.FieldUserAgent, field.TypeString, value) + } + if _u.mutation.UserAgentCleared() { + _spec.ClearField(loginhistory.FieldUserAgent, field.TypeString) + } + if value, ok := _u.mutation.LoginTime(); ok { + _spec.SetField(loginhistory.FieldLoginTime, field.TypeTime, value) + } + if value, ok := _u.mutation.Success(); ok { + _spec.SetField(loginhistory.FieldSuccess, field.TypeBool, value) + } + _node = &LoginHistory{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{loginhistory.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/internal/ent/migrate/migrate.go b/internal/ent/migrate/migrate.go new file mode 100644 index 0000000..1956a6b --- /dev/null +++ b/internal/ent/migrate/migrate.go @@ -0,0 +1,64 @@ +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "context" + "fmt" + "io" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql/schema" +) + +var ( + // WithGlobalUniqueID sets the universal ids options to the migration. + // If this option is enabled, ent migration will allocate a 1<<32 range + // for the ids of each entity (table). + // Note that this option cannot be applied on tables that already exist. + WithGlobalUniqueID = schema.WithGlobalUniqueID + // WithDropColumn sets the drop column option to the migration. + // If this option is enabled, ent migration will drop old columns + // that were used for both fields and edges. This defaults to false. + WithDropColumn = schema.WithDropColumn + // WithDropIndex sets the drop index option to the migration. + // If this option is enabled, ent migration will drop old indexes + // that were defined in the schema. This defaults to false. + // Note that unique constraints are defined using `UNIQUE INDEX`, + // and therefore, it's recommended to enable this option to get more + // flexibility in the schema changes. + WithDropIndex = schema.WithDropIndex + // WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true. + WithForeignKeys = schema.WithForeignKeys +) + +// Schema is the API for creating, migrating and dropping a schema. +type Schema struct { + drv dialect.Driver +} + +// NewSchema creates a new schema client. +func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} } + +// Create creates all schema resources. +func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error { + return Create(ctx, s, Tables, opts...) +} + +// Create creates all table resources using the given schema driver. +func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error { + migrate, err := schema.NewMigrate(s.drv, opts...) + if err != nil { + return fmt.Errorf("ent/migrate: %w", err) + } + return migrate.Create(ctx, tables...) +} + +// WriteTo writes the schema changes to w instead of running them against the database. +// +// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { +// log.Fatal(err) +// } +func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error { + return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...) +} diff --git a/internal/ent/migrate/schema.go b/internal/ent/migrate/schema.go new file mode 100644 index 0000000..ba49816 --- /dev/null +++ b/internal/ent/migrate/schema.go @@ -0,0 +1,121 @@ +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/schema/field" +) + +var ( + // ContactsColumns holds the columns for the "contacts" table. + ContactsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "type", Type: field.TypeString}, + {Name: "icon", Type: field.TypeString}, + {Name: "url", Type: field.TypeString, Nullable: true}, + {Name: "qr_code", Type: field.TypeString, Nullable: true}, + {Name: "hover_color", Type: field.TypeString, Nullable: true}, + {Name: "sort_order", Type: field.TypeInt, Default: 0}, + } + // ContactsTable holds the schema information for the "contacts" table. + ContactsTable = &schema.Table{ + Name: "contacts", + Columns: ContactsColumns, + PrimaryKey: []*schema.Column{ContactsColumns[0]}, + } + // LoginHistoriesColumns holds the columns for the "login_histories" table. + LoginHistoriesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "username", Type: field.TypeString}, + {Name: "ip", Type: field.TypeString}, + {Name: "location", Type: field.TypeString, Nullable: true}, + {Name: "user_agent", Type: field.TypeString, Nullable: true}, + {Name: "login_time", Type: field.TypeTime}, + {Name: "success", Type: field.TypeBool, Default: true}, + } + // LoginHistoriesTable holds the schema information for the "login_histories" table. + LoginHistoriesTable = &schema.Table{ + Name: "login_histories", + Columns: LoginHistoriesColumns, + PrimaryKey: []*schema.Column{LoginHistoriesColumns[0]}, + } + // SitesColumns holds the columns for the "sites" table. + SitesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "name", Type: field.TypeString}, + {Name: "url", Type: field.TypeString}, + {Name: "icon", Type: field.TypeString}, + {Name: "sort_order", Type: field.TypeInt, Default: 0}, + } + // SitesTable holds the schema information for the "sites" table. + SitesTable = &schema.Table{ + Name: "sites", + Columns: SitesColumns, + PrimaryKey: []*schema.Column{SitesColumns[0]}, + } + // SiteConfigsColumns holds the columns for the "site_configs" table. + SiteConfigsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "site_name", Type: field.TypeString}, + {Name: "site_url", Type: field.TypeString}, + {Name: "site_icon", Type: field.TypeString}, + {Name: "site_description", Type: field.TypeString}, + {Name: "site_keywords", Type: field.TypeString}, + {Name: "user_name", Type: field.TypeString}, + {Name: "profile_image_url", Type: field.TypeString, Nullable: true}, + {Name: "icp_number", Type: field.TypeString, Nullable: true}, + {Name: "police_number", Type: field.TypeString, Nullable: true}, + {Name: "page_title", Type: field.TypeString, Nullable: true}, + {Name: "favicon", Type: field.TypeString, Nullable: true}, + {Name: "umami_script", Type: field.TypeString, Nullable: true}, + {Name: "umami_website_id", Type: field.TypeString, Nullable: true}, + {Name: "icon_library", Type: field.TypeString, Nullable: true}, + {Name: "font_library", Type: field.TypeString, Nullable: true}, + } + // SiteConfigsTable holds the schema information for the "site_configs" table. + SiteConfigsTable = &schema.Table{ + Name: "site_configs", + Columns: SiteConfigsColumns, + PrimaryKey: []*schema.Column{SiteConfigsColumns[0]}, + } + // UsersColumns holds the columns for the "users" table. + UsersColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "username", Type: field.TypeString, Unique: true}, + {Name: "password", Type: field.TypeString}, + } + // UsersTable holds the schema information for the "users" table. + UsersTable = &schema.Table{ + Name: "users", + Columns: UsersColumns, + PrimaryKey: []*schema.Column{UsersColumns[0]}, + } + // VisitsColumns holds the columns for the "visits" table. + VisitsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "path", Type: field.TypeString}, + {Name: "ip", Type: field.TypeString}, + {Name: "user_agent", Type: field.TypeString, Nullable: true}, + {Name: "referer", Type: field.TypeString, Nullable: true}, + {Name: "visit_time", Type: field.TypeTime}, + } + // VisitsTable holds the schema information for the "visits" table. + VisitsTable = &schema.Table{ + Name: "visits", + Columns: VisitsColumns, + PrimaryKey: []*schema.Column{VisitsColumns[0]}, + } + // Tables holds all the tables in the schema. + Tables = []*schema.Table{ + ContactsTable, + LoginHistoriesTable, + SitesTable, + SiteConfigsTable, + UsersTable, + VisitsTable, + } +) + +func init() { +} diff --git a/internal/ent/mutation.go b/internal/ent/mutation.go new file mode 100644 index 0000000..bfe1e47 --- /dev/null +++ b/internal/ent/mutation.go @@ -0,0 +1,4146 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "home-vue-go/internal/ent/contact" + "home-vue-go/internal/ent/loginhistory" + "home-vue-go/internal/ent/predicate" + "home-vue-go/internal/ent/site" + "home-vue-go/internal/ent/siteconfig" + "home-vue-go/internal/ent/user" + "home-vue-go/internal/ent/visit" + "sync" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +const ( + // Operation types. + OpCreate = ent.OpCreate + OpDelete = ent.OpDelete + OpDeleteOne = ent.OpDeleteOne + OpUpdate = ent.OpUpdate + OpUpdateOne = ent.OpUpdateOne + + // Node types. + TypeContact = "Contact" + TypeLoginHistory = "LoginHistory" + TypeSite = "Site" + TypeSiteConfig = "SiteConfig" + TypeUser = "User" + TypeVisit = "Visit" +) + +// ContactMutation represents an operation that mutates the Contact nodes in the graph. +type ContactMutation struct { + config + op Op + typ string + id *int + _type *string + icon *string + url *string + qr_code *string + hover_color *string + sort_order *int + addsort_order *int + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Contact, error) + predicates []predicate.Contact +} + +var _ ent.Mutation = (*ContactMutation)(nil) + +// contactOption allows management of the mutation configuration using functional options. +type contactOption func(*ContactMutation) + +// newContactMutation creates new mutation for the Contact entity. +func newContactMutation(c config, op Op, opts ...contactOption) *ContactMutation { + m := &ContactMutation{ + config: c, + op: op, + typ: TypeContact, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withContactID sets the ID field of the mutation. +func withContactID(id int) contactOption { + return func(m *ContactMutation) { + var ( + err error + once sync.Once + value *Contact + ) + m.oldValue = func(ctx context.Context) (*Contact, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Contact.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withContact sets the old Contact of the mutation. +func withContact(node *Contact) contactOption { + return func(m *ContactMutation) { + m.oldValue = func(context.Context) (*Contact, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m ContactMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m ContactMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of Contact entities. +func (m *ContactMutation) SetID(id int) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *ContactMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *ContactMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Contact.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetType sets the "type" field. +func (m *ContactMutation) SetType(s string) { + m._type = &s +} + +// GetType returns the value of the "type" field in the mutation. +func (m *ContactMutation) GetType() (r string, exists bool) { + v := m._type + if v == nil { + return + } + return *v, true +} + +// OldType returns the old "type" field's value of the Contact entity. +// If the Contact object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ContactMutation) OldType(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldType: %w", err) + } + return oldValue.Type, nil +} + +// ResetType resets all changes to the "type" field. +func (m *ContactMutation) ResetType() { + m._type = nil +} + +// SetIcon sets the "icon" field. +func (m *ContactMutation) SetIcon(s string) { + m.icon = &s +} + +// Icon returns the value of the "icon" field in the mutation. +func (m *ContactMutation) Icon() (r string, exists bool) { + v := m.icon + if v == nil { + return + } + return *v, true +} + +// OldIcon returns the old "icon" field's value of the Contact entity. +// If the Contact object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ContactMutation) OldIcon(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIcon is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIcon requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIcon: %w", err) + } + return oldValue.Icon, nil +} + +// ResetIcon resets all changes to the "icon" field. +func (m *ContactMutation) ResetIcon() { + m.icon = nil +} + +// SetURL sets the "url" field. +func (m *ContactMutation) SetURL(s string) { + m.url = &s +} + +// URL returns the value of the "url" field in the mutation. +func (m *ContactMutation) URL() (r string, exists bool) { + v := m.url + if v == nil { + return + } + return *v, true +} + +// OldURL returns the old "url" field's value of the Contact entity. +// If the Contact object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ContactMutation) OldURL(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldURL is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldURL requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldURL: %w", err) + } + return oldValue.URL, nil +} + +// ClearURL clears the value of the "url" field. +func (m *ContactMutation) ClearURL() { + m.url = nil + m.clearedFields[contact.FieldURL] = struct{}{} +} + +// URLCleared returns if the "url" field was cleared in this mutation. +func (m *ContactMutation) URLCleared() bool { + _, ok := m.clearedFields[contact.FieldURL] + return ok +} + +// ResetURL resets all changes to the "url" field. +func (m *ContactMutation) ResetURL() { + m.url = nil + delete(m.clearedFields, contact.FieldURL) +} + +// SetQrCode sets the "qr_code" field. +func (m *ContactMutation) SetQrCode(s string) { + m.qr_code = &s +} + +// QrCode returns the value of the "qr_code" field in the mutation. +func (m *ContactMutation) QrCode() (r string, exists bool) { + v := m.qr_code + if v == nil { + return + } + return *v, true +} + +// OldQrCode returns the old "qr_code" field's value of the Contact entity. +// If the Contact object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ContactMutation) OldQrCode(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldQrCode is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldQrCode requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldQrCode: %w", err) + } + return oldValue.QrCode, nil +} + +// ClearQrCode clears the value of the "qr_code" field. +func (m *ContactMutation) ClearQrCode() { + m.qr_code = nil + m.clearedFields[contact.FieldQrCode] = struct{}{} +} + +// QrCodeCleared returns if the "qr_code" field was cleared in this mutation. +func (m *ContactMutation) QrCodeCleared() bool { + _, ok := m.clearedFields[contact.FieldQrCode] + return ok +} + +// ResetQrCode resets all changes to the "qr_code" field. +func (m *ContactMutation) ResetQrCode() { + m.qr_code = nil + delete(m.clearedFields, contact.FieldQrCode) +} + +// SetHoverColor sets the "hover_color" field. +func (m *ContactMutation) SetHoverColor(s string) { + m.hover_color = &s +} + +// HoverColor returns the value of the "hover_color" field in the mutation. +func (m *ContactMutation) HoverColor() (r string, exists bool) { + v := m.hover_color + if v == nil { + return + } + return *v, true +} + +// OldHoverColor returns the old "hover_color" field's value of the Contact entity. +// If the Contact object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ContactMutation) OldHoverColor(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldHoverColor is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldHoverColor requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldHoverColor: %w", err) + } + return oldValue.HoverColor, nil +} + +// ClearHoverColor clears the value of the "hover_color" field. +func (m *ContactMutation) ClearHoverColor() { + m.hover_color = nil + m.clearedFields[contact.FieldHoverColor] = struct{}{} +} + +// HoverColorCleared returns if the "hover_color" field was cleared in this mutation. +func (m *ContactMutation) HoverColorCleared() bool { + _, ok := m.clearedFields[contact.FieldHoverColor] + return ok +} + +// ResetHoverColor resets all changes to the "hover_color" field. +func (m *ContactMutation) ResetHoverColor() { + m.hover_color = nil + delete(m.clearedFields, contact.FieldHoverColor) +} + +// SetSortOrder sets the "sort_order" field. +func (m *ContactMutation) SetSortOrder(i int) { + m.sort_order = &i + m.addsort_order = nil +} + +// SortOrder returns the value of the "sort_order" field in the mutation. +func (m *ContactMutation) SortOrder() (r int, exists bool) { + v := m.sort_order + if v == nil { + return + } + return *v, true +} + +// OldSortOrder returns the old "sort_order" field's value of the Contact entity. +// If the Contact object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ContactMutation) OldSortOrder(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSortOrder is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSortOrder requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSortOrder: %w", err) + } + return oldValue.SortOrder, nil +} + +// AddSortOrder adds i to the "sort_order" field. +func (m *ContactMutation) AddSortOrder(i int) { + if m.addsort_order != nil { + *m.addsort_order += i + } else { + m.addsort_order = &i + } +} + +// AddedSortOrder returns the value that was added to the "sort_order" field in this mutation. +func (m *ContactMutation) AddedSortOrder() (r int, exists bool) { + v := m.addsort_order + if v == nil { + return + } + return *v, true +} + +// ResetSortOrder resets all changes to the "sort_order" field. +func (m *ContactMutation) ResetSortOrder() { + m.sort_order = nil + m.addsort_order = nil +} + +// Where appends a list predicates to the ContactMutation builder. +func (m *ContactMutation) Where(ps ...predicate.Contact) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ContactMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ContactMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Contact, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ContactMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ContactMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Contact). +func (m *ContactMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *ContactMutation) Fields() []string { + fields := make([]string, 0, 6) + if m._type != nil { + fields = append(fields, contact.FieldType) + } + if m.icon != nil { + fields = append(fields, contact.FieldIcon) + } + if m.url != nil { + fields = append(fields, contact.FieldURL) + } + if m.qr_code != nil { + fields = append(fields, contact.FieldQrCode) + } + if m.hover_color != nil { + fields = append(fields, contact.FieldHoverColor) + } + if m.sort_order != nil { + fields = append(fields, contact.FieldSortOrder) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *ContactMutation) Field(name string) (ent.Value, bool) { + switch name { + case contact.FieldType: + return m.GetType() + case contact.FieldIcon: + return m.Icon() + case contact.FieldURL: + return m.URL() + case contact.FieldQrCode: + return m.QrCode() + case contact.FieldHoverColor: + return m.HoverColor() + case contact.FieldSortOrder: + return m.SortOrder() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *ContactMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case contact.FieldType: + return m.OldType(ctx) + case contact.FieldIcon: + return m.OldIcon(ctx) + case contact.FieldURL: + return m.OldURL(ctx) + case contact.FieldQrCode: + return m.OldQrCode(ctx) + case contact.FieldHoverColor: + return m.OldHoverColor(ctx) + case contact.FieldSortOrder: + return m.OldSortOrder(ctx) + } + return nil, fmt.Errorf("unknown Contact field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *ContactMutation) SetField(name string, value ent.Value) error { + switch name { + case contact.FieldType: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetType(v) + return nil + case contact.FieldIcon: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIcon(v) + return nil + case contact.FieldURL: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetURL(v) + return nil + case contact.FieldQrCode: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetQrCode(v) + return nil + case contact.FieldHoverColor: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetHoverColor(v) + return nil + case contact.FieldSortOrder: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSortOrder(v) + return nil + } + return fmt.Errorf("unknown Contact field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ContactMutation) AddedFields() []string { + var fields []string + if m.addsort_order != nil { + fields = append(fields, contact.FieldSortOrder) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *ContactMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case contact.FieldSortOrder: + return m.AddedSortOrder() + } + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *ContactMutation) AddField(name string, value ent.Value) error { + switch name { + case contact.FieldSortOrder: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddSortOrder(v) + return nil + } + return fmt.Errorf("unknown Contact numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ContactMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(contact.FieldURL) { + fields = append(fields, contact.FieldURL) + } + if m.FieldCleared(contact.FieldQrCode) { + fields = append(fields, contact.FieldQrCode) + } + if m.FieldCleared(contact.FieldHoverColor) { + fields = append(fields, contact.FieldHoverColor) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ContactMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *ContactMutation) ClearField(name string) error { + switch name { + case contact.FieldURL: + m.ClearURL() + return nil + case contact.FieldQrCode: + m.ClearQrCode() + return nil + case contact.FieldHoverColor: + m.ClearHoverColor() + return nil + } + return fmt.Errorf("unknown Contact nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *ContactMutation) ResetField(name string) error { + switch name { + case contact.FieldType: + m.ResetType() + return nil + case contact.FieldIcon: + m.ResetIcon() + return nil + case contact.FieldURL: + m.ResetURL() + return nil + case contact.FieldQrCode: + m.ResetQrCode() + return nil + case contact.FieldHoverColor: + m.ResetHoverColor() + return nil + case contact.FieldSortOrder: + m.ResetSortOrder() + return nil + } + return fmt.Errorf("unknown Contact field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ContactMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ContactMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ContactMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *ContactMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ContactMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ContactMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *ContactMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Contact 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 *ContactMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Contact edge %s", name) +} + +// LoginHistoryMutation represents an operation that mutates the LoginHistory nodes in the graph. +type LoginHistoryMutation struct { + config + op Op + typ string + id *int + username *string + ip *string + location *string + user_agent *string + login_time *time.Time + success *bool + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*LoginHistory, error) + predicates []predicate.LoginHistory +} + +var _ ent.Mutation = (*LoginHistoryMutation)(nil) + +// loginhistoryOption allows management of the mutation configuration using functional options. +type loginhistoryOption func(*LoginHistoryMutation) + +// newLoginHistoryMutation creates new mutation for the LoginHistory entity. +func newLoginHistoryMutation(c config, op Op, opts ...loginhistoryOption) *LoginHistoryMutation { + m := &LoginHistoryMutation{ + config: c, + op: op, + typ: TypeLoginHistory, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withLoginHistoryID sets the ID field of the mutation. +func withLoginHistoryID(id int) loginhistoryOption { + return func(m *LoginHistoryMutation) { + var ( + err error + once sync.Once + value *LoginHistory + ) + m.oldValue = func(ctx context.Context) (*LoginHistory, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().LoginHistory.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withLoginHistory sets the old LoginHistory of the mutation. +func withLoginHistory(node *LoginHistory) loginhistoryOption { + return func(m *LoginHistoryMutation) { + m.oldValue = func(context.Context) (*LoginHistory, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m LoginHistoryMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m LoginHistoryMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of LoginHistory entities. +func (m *LoginHistoryMutation) SetID(id int) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *LoginHistoryMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *LoginHistoryMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().LoginHistory.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetUsername sets the "username" field. +func (m *LoginHistoryMutation) SetUsername(s string) { + m.username = &s +} + +// Username returns the value of the "username" field in the mutation. +func (m *LoginHistoryMutation) Username() (r string, exists bool) { + v := m.username + if v == nil { + return + } + return *v, true +} + +// OldUsername returns the old "username" field's value of the LoginHistory entity. +// If the LoginHistory object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *LoginHistoryMutation) OldUsername(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUsername is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUsername requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUsername: %w", err) + } + return oldValue.Username, nil +} + +// ResetUsername resets all changes to the "username" field. +func (m *LoginHistoryMutation) ResetUsername() { + m.username = nil +} + +// SetIP sets the "ip" field. +func (m *LoginHistoryMutation) SetIP(s string) { + m.ip = &s +} + +// IP returns the value of the "ip" field in the mutation. +func (m *LoginHistoryMutation) IP() (r string, exists bool) { + v := m.ip + if v == nil { + return + } + return *v, true +} + +// OldIP returns the old "ip" field's value of the LoginHistory entity. +// If the LoginHistory object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *LoginHistoryMutation) OldIP(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIP is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIP requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIP: %w", err) + } + return oldValue.IP, nil +} + +// ResetIP resets all changes to the "ip" field. +func (m *LoginHistoryMutation) ResetIP() { + m.ip = nil +} + +// SetLocation sets the "location" field. +func (m *LoginHistoryMutation) SetLocation(s string) { + m.location = &s +} + +// Location returns the value of the "location" field in the mutation. +func (m *LoginHistoryMutation) Location() (r string, exists bool) { + v := m.location + if v == nil { + return + } + return *v, true +} + +// OldLocation returns the old "location" field's value of the LoginHistory entity. +// If the LoginHistory object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *LoginHistoryMutation) OldLocation(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLocation is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLocation requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLocation: %w", err) + } + return oldValue.Location, nil +} + +// ClearLocation clears the value of the "location" field. +func (m *LoginHistoryMutation) ClearLocation() { + m.location = nil + m.clearedFields[loginhistory.FieldLocation] = struct{}{} +} + +// LocationCleared returns if the "location" field was cleared in this mutation. +func (m *LoginHistoryMutation) LocationCleared() bool { + _, ok := m.clearedFields[loginhistory.FieldLocation] + return ok +} + +// ResetLocation resets all changes to the "location" field. +func (m *LoginHistoryMutation) ResetLocation() { + m.location = nil + delete(m.clearedFields, loginhistory.FieldLocation) +} + +// SetUserAgent sets the "user_agent" field. +func (m *LoginHistoryMutation) SetUserAgent(s string) { + m.user_agent = &s +} + +// UserAgent returns the value of the "user_agent" field in the mutation. +func (m *LoginHistoryMutation) UserAgent() (r string, exists bool) { + v := m.user_agent + if v == nil { + return + } + return *v, true +} + +// OldUserAgent returns the old "user_agent" field's value of the LoginHistory entity. +// If the LoginHistory object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *LoginHistoryMutation) OldUserAgent(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserAgent is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserAgent requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserAgent: %w", err) + } + return oldValue.UserAgent, nil +} + +// ClearUserAgent clears the value of the "user_agent" field. +func (m *LoginHistoryMutation) ClearUserAgent() { + m.user_agent = nil + m.clearedFields[loginhistory.FieldUserAgent] = struct{}{} +} + +// UserAgentCleared returns if the "user_agent" field was cleared in this mutation. +func (m *LoginHistoryMutation) UserAgentCleared() bool { + _, ok := m.clearedFields[loginhistory.FieldUserAgent] + return ok +} + +// ResetUserAgent resets all changes to the "user_agent" field. +func (m *LoginHistoryMutation) ResetUserAgent() { + m.user_agent = nil + delete(m.clearedFields, loginhistory.FieldUserAgent) +} + +// SetLoginTime sets the "login_time" field. +func (m *LoginHistoryMutation) SetLoginTime(t time.Time) { + m.login_time = &t +} + +// LoginTime returns the value of the "login_time" field in the mutation. +func (m *LoginHistoryMutation) LoginTime() (r time.Time, exists bool) { + v := m.login_time + if v == nil { + return + } + return *v, true +} + +// OldLoginTime returns the old "login_time" field's value of the LoginHistory entity. +// If the LoginHistory object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *LoginHistoryMutation) OldLoginTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLoginTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLoginTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLoginTime: %w", err) + } + return oldValue.LoginTime, nil +} + +// ResetLoginTime resets all changes to the "login_time" field. +func (m *LoginHistoryMutation) ResetLoginTime() { + m.login_time = nil +} + +// SetSuccess sets the "success" field. +func (m *LoginHistoryMutation) SetSuccess(b bool) { + m.success = &b +} + +// Success returns the value of the "success" field in the mutation. +func (m *LoginHistoryMutation) Success() (r bool, exists bool) { + v := m.success + if v == nil { + return + } + return *v, true +} + +// OldSuccess returns the old "success" field's value of the LoginHistory entity. +// If the LoginHistory object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *LoginHistoryMutation) OldSuccess(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSuccess is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSuccess requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSuccess: %w", err) + } + return oldValue.Success, nil +} + +// ResetSuccess resets all changes to the "success" field. +func (m *LoginHistoryMutation) ResetSuccess() { + m.success = nil +} + +// Where appends a list predicates to the LoginHistoryMutation builder. +func (m *LoginHistoryMutation) Where(ps ...predicate.LoginHistory) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the LoginHistoryMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *LoginHistoryMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.LoginHistory, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *LoginHistoryMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *LoginHistoryMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (LoginHistory). +func (m *LoginHistoryMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *LoginHistoryMutation) Fields() []string { + fields := make([]string, 0, 6) + if m.username != nil { + fields = append(fields, loginhistory.FieldUsername) + } + if m.ip != nil { + fields = append(fields, loginhistory.FieldIP) + } + if m.location != nil { + fields = append(fields, loginhistory.FieldLocation) + } + if m.user_agent != nil { + fields = append(fields, loginhistory.FieldUserAgent) + } + if m.login_time != nil { + fields = append(fields, loginhistory.FieldLoginTime) + } + if m.success != nil { + fields = append(fields, loginhistory.FieldSuccess) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *LoginHistoryMutation) Field(name string) (ent.Value, bool) { + switch name { + case loginhistory.FieldUsername: + return m.Username() + case loginhistory.FieldIP: + return m.IP() + case loginhistory.FieldLocation: + return m.Location() + case loginhistory.FieldUserAgent: + return m.UserAgent() + case loginhistory.FieldLoginTime: + return m.LoginTime() + case loginhistory.FieldSuccess: + return m.Success() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *LoginHistoryMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case loginhistory.FieldUsername: + return m.OldUsername(ctx) + case loginhistory.FieldIP: + return m.OldIP(ctx) + case loginhistory.FieldLocation: + return m.OldLocation(ctx) + case loginhistory.FieldUserAgent: + return m.OldUserAgent(ctx) + case loginhistory.FieldLoginTime: + return m.OldLoginTime(ctx) + case loginhistory.FieldSuccess: + return m.OldSuccess(ctx) + } + return nil, fmt.Errorf("unknown LoginHistory field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *LoginHistoryMutation) SetField(name string, value ent.Value) error { + switch name { + case loginhistory.FieldUsername: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUsername(v) + return nil + case loginhistory.FieldIP: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIP(v) + return nil + case loginhistory.FieldLocation: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLocation(v) + return nil + case loginhistory.FieldUserAgent: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserAgent(v) + return nil + case loginhistory.FieldLoginTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLoginTime(v) + return nil + case loginhistory.FieldSuccess: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSuccess(v) + return nil + } + return fmt.Errorf("unknown LoginHistory field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *LoginHistoryMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *LoginHistoryMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *LoginHistoryMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown LoginHistory numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *LoginHistoryMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(loginhistory.FieldLocation) { + fields = append(fields, loginhistory.FieldLocation) + } + if m.FieldCleared(loginhistory.FieldUserAgent) { + fields = append(fields, loginhistory.FieldUserAgent) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *LoginHistoryMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *LoginHistoryMutation) ClearField(name string) error { + switch name { + case loginhistory.FieldLocation: + m.ClearLocation() + return nil + case loginhistory.FieldUserAgent: + m.ClearUserAgent() + return nil + } + return fmt.Errorf("unknown LoginHistory nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *LoginHistoryMutation) ResetField(name string) error { + switch name { + case loginhistory.FieldUsername: + m.ResetUsername() + return nil + case loginhistory.FieldIP: + m.ResetIP() + return nil + case loginhistory.FieldLocation: + m.ResetLocation() + return nil + case loginhistory.FieldUserAgent: + m.ResetUserAgent() + return nil + case loginhistory.FieldLoginTime: + m.ResetLoginTime() + return nil + case loginhistory.FieldSuccess: + m.ResetSuccess() + return nil + } + return fmt.Errorf("unknown LoginHistory field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *LoginHistoryMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *LoginHistoryMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *LoginHistoryMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *LoginHistoryMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *LoginHistoryMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *LoginHistoryMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *LoginHistoryMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown LoginHistory 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 *LoginHistoryMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown LoginHistory edge %s", name) +} + +// SiteMutation represents an operation that mutates the Site nodes in the graph. +type SiteMutation struct { + config + op Op + typ string + id *int + name *string + url *string + icon *string + sort_order *int + addsort_order *int + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Site, error) + predicates []predicate.Site +} + +var _ ent.Mutation = (*SiteMutation)(nil) + +// siteOption allows management of the mutation configuration using functional options. +type siteOption func(*SiteMutation) + +// newSiteMutation creates new mutation for the Site entity. +func newSiteMutation(c config, op Op, opts ...siteOption) *SiteMutation { + m := &SiteMutation{ + config: c, + op: op, + typ: TypeSite, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withSiteID sets the ID field of the mutation. +func withSiteID(id int) siteOption { + return func(m *SiteMutation) { + var ( + err error + once sync.Once + value *Site + ) + m.oldValue = func(ctx context.Context) (*Site, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Site.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withSite sets the old Site of the mutation. +func withSite(node *Site) siteOption { + return func(m *SiteMutation) { + m.oldValue = func(context.Context) (*Site, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m SiteMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m SiteMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of Site entities. +func (m *SiteMutation) SetID(id int) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *SiteMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *SiteMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Site.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetName sets the "name" field. +func (m *SiteMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *SiteMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the Site entity. +// If the Site object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SiteMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *SiteMutation) ResetName() { + m.name = nil +} + +// SetURL sets the "url" field. +func (m *SiteMutation) SetURL(s string) { + m.url = &s +} + +// URL returns the value of the "url" field in the mutation. +func (m *SiteMutation) URL() (r string, exists bool) { + v := m.url + if v == nil { + return + } + return *v, true +} + +// OldURL returns the old "url" field's value of the Site entity. +// If the Site object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SiteMutation) OldURL(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldURL is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldURL requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldURL: %w", err) + } + return oldValue.URL, nil +} + +// ResetURL resets all changes to the "url" field. +func (m *SiteMutation) ResetURL() { + m.url = nil +} + +// SetIcon sets the "icon" field. +func (m *SiteMutation) SetIcon(s string) { + m.icon = &s +} + +// Icon returns the value of the "icon" field in the mutation. +func (m *SiteMutation) Icon() (r string, exists bool) { + v := m.icon + if v == nil { + return + } + return *v, true +} + +// OldIcon returns the old "icon" field's value of the Site entity. +// If the Site object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SiteMutation) OldIcon(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIcon is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIcon requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIcon: %w", err) + } + return oldValue.Icon, nil +} + +// ResetIcon resets all changes to the "icon" field. +func (m *SiteMutation) ResetIcon() { + m.icon = nil +} + +// SetSortOrder sets the "sort_order" field. +func (m *SiteMutation) SetSortOrder(i int) { + m.sort_order = &i + m.addsort_order = nil +} + +// SortOrder returns the value of the "sort_order" field in the mutation. +func (m *SiteMutation) SortOrder() (r int, exists bool) { + v := m.sort_order + if v == nil { + return + } + return *v, true +} + +// OldSortOrder returns the old "sort_order" field's value of the Site entity. +// If the Site object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SiteMutation) OldSortOrder(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSortOrder is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSortOrder requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSortOrder: %w", err) + } + return oldValue.SortOrder, nil +} + +// AddSortOrder adds i to the "sort_order" field. +func (m *SiteMutation) AddSortOrder(i int) { + if m.addsort_order != nil { + *m.addsort_order += i + } else { + m.addsort_order = &i + } +} + +// AddedSortOrder returns the value that was added to the "sort_order" field in this mutation. +func (m *SiteMutation) AddedSortOrder() (r int, exists bool) { + v := m.addsort_order + if v == nil { + return + } + return *v, true +} + +// ResetSortOrder resets all changes to the "sort_order" field. +func (m *SiteMutation) ResetSortOrder() { + m.sort_order = nil + m.addsort_order = nil +} + +// Where appends a list predicates to the SiteMutation builder. +func (m *SiteMutation) Where(ps ...predicate.Site) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the SiteMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *SiteMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Site, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *SiteMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *SiteMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Site). +func (m *SiteMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *SiteMutation) Fields() []string { + fields := make([]string, 0, 4) + if m.name != nil { + fields = append(fields, site.FieldName) + } + if m.url != nil { + fields = append(fields, site.FieldURL) + } + if m.icon != nil { + fields = append(fields, site.FieldIcon) + } + if m.sort_order != nil { + fields = append(fields, site.FieldSortOrder) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *SiteMutation) Field(name string) (ent.Value, bool) { + switch name { + case site.FieldName: + return m.Name() + case site.FieldURL: + return m.URL() + case site.FieldIcon: + return m.Icon() + case site.FieldSortOrder: + return m.SortOrder() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *SiteMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case site.FieldName: + return m.OldName(ctx) + case site.FieldURL: + return m.OldURL(ctx) + case site.FieldIcon: + return m.OldIcon(ctx) + case site.FieldSortOrder: + return m.OldSortOrder(ctx) + } + return nil, fmt.Errorf("unknown Site field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *SiteMutation) SetField(name string, value ent.Value) error { + switch name { + case site.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case site.FieldURL: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetURL(v) + return nil + case site.FieldIcon: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIcon(v) + return nil + case site.FieldSortOrder: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSortOrder(v) + return nil + } + return fmt.Errorf("unknown Site field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *SiteMutation) AddedFields() []string { + var fields []string + if m.addsort_order != nil { + fields = append(fields, site.FieldSortOrder) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *SiteMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case site.FieldSortOrder: + return m.AddedSortOrder() + } + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *SiteMutation) AddField(name string, value ent.Value) error { + switch name { + case site.FieldSortOrder: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddSortOrder(v) + return nil + } + return fmt.Errorf("unknown Site numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *SiteMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *SiteMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *SiteMutation) ClearField(name string) error { + return fmt.Errorf("unknown Site nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *SiteMutation) ResetField(name string) error { + switch name { + case site.FieldName: + m.ResetName() + return nil + case site.FieldURL: + m.ResetURL() + return nil + case site.FieldIcon: + m.ResetIcon() + return nil + case site.FieldSortOrder: + m.ResetSortOrder() + return nil + } + return fmt.Errorf("unknown Site field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *SiteMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *SiteMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *SiteMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *SiteMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *SiteMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *SiteMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *SiteMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Site 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 *SiteMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Site edge %s", name) +} + +// SiteConfigMutation represents an operation that mutates the SiteConfig nodes in the graph. +type SiteConfigMutation struct { + config + op Op + typ string + id *int + site_name *string + site_url *string + site_icon *string + site_description *string + site_keywords *string + user_name *string + profile_image_url *string + icp_number *string + police_number *string + page_title *string + favicon *string + umami_script *string + umami_website_id *string + icon_library *string + font_library *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*SiteConfig, error) + predicates []predicate.SiteConfig +} + +var _ ent.Mutation = (*SiteConfigMutation)(nil) + +// siteconfigOption allows management of the mutation configuration using functional options. +type siteconfigOption func(*SiteConfigMutation) + +// newSiteConfigMutation creates new mutation for the SiteConfig entity. +func newSiteConfigMutation(c config, op Op, opts ...siteconfigOption) *SiteConfigMutation { + m := &SiteConfigMutation{ + config: c, + op: op, + typ: TypeSiteConfig, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withSiteConfigID sets the ID field of the mutation. +func withSiteConfigID(id int) siteconfigOption { + return func(m *SiteConfigMutation) { + var ( + err error + once sync.Once + value *SiteConfig + ) + m.oldValue = func(ctx context.Context) (*SiteConfig, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().SiteConfig.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withSiteConfig sets the old SiteConfig of the mutation. +func withSiteConfig(node *SiteConfig) siteconfigOption { + return func(m *SiteConfigMutation) { + m.oldValue = func(context.Context) (*SiteConfig, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m SiteConfigMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m SiteConfigMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of SiteConfig entities. +func (m *SiteConfigMutation) SetID(id int) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *SiteConfigMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *SiteConfigMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().SiteConfig.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetSiteName sets the "site_name" field. +func (m *SiteConfigMutation) SetSiteName(s string) { + m.site_name = &s +} + +// SiteName returns the value of the "site_name" field in the mutation. +func (m *SiteConfigMutation) SiteName() (r string, exists bool) { + v := m.site_name + if v == nil { + return + } + return *v, true +} + +// OldSiteName returns the old "site_name" field's value of the SiteConfig entity. +// If the SiteConfig object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SiteConfigMutation) OldSiteName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSiteName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSiteName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSiteName: %w", err) + } + return oldValue.SiteName, nil +} + +// ResetSiteName resets all changes to the "site_name" field. +func (m *SiteConfigMutation) ResetSiteName() { + m.site_name = nil +} + +// SetSiteURL sets the "site_url" field. +func (m *SiteConfigMutation) SetSiteURL(s string) { + m.site_url = &s +} + +// SiteURL returns the value of the "site_url" field in the mutation. +func (m *SiteConfigMutation) SiteURL() (r string, exists bool) { + v := m.site_url + if v == nil { + return + } + return *v, true +} + +// OldSiteURL returns the old "site_url" field's value of the SiteConfig entity. +// If the SiteConfig object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SiteConfigMutation) OldSiteURL(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSiteURL is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSiteURL requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSiteURL: %w", err) + } + return oldValue.SiteURL, nil +} + +// ResetSiteURL resets all changes to the "site_url" field. +func (m *SiteConfigMutation) ResetSiteURL() { + m.site_url = nil +} + +// SetSiteIcon sets the "site_icon" field. +func (m *SiteConfigMutation) SetSiteIcon(s string) { + m.site_icon = &s +} + +// SiteIcon returns the value of the "site_icon" field in the mutation. +func (m *SiteConfigMutation) SiteIcon() (r string, exists bool) { + v := m.site_icon + if v == nil { + return + } + return *v, true +} + +// OldSiteIcon returns the old "site_icon" field's value of the SiteConfig entity. +// If the SiteConfig object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SiteConfigMutation) OldSiteIcon(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSiteIcon is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSiteIcon requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSiteIcon: %w", err) + } + return oldValue.SiteIcon, nil +} + +// ResetSiteIcon resets all changes to the "site_icon" field. +func (m *SiteConfigMutation) ResetSiteIcon() { + m.site_icon = nil +} + +// SetSiteDescription sets the "site_description" field. +func (m *SiteConfigMutation) SetSiteDescription(s string) { + m.site_description = &s +} + +// SiteDescription returns the value of the "site_description" field in the mutation. +func (m *SiteConfigMutation) SiteDescription() (r string, exists bool) { + v := m.site_description + if v == nil { + return + } + return *v, true +} + +// OldSiteDescription returns the old "site_description" field's value of the SiteConfig entity. +// If the SiteConfig object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SiteConfigMutation) OldSiteDescription(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSiteDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSiteDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSiteDescription: %w", err) + } + return oldValue.SiteDescription, nil +} + +// ResetSiteDescription resets all changes to the "site_description" field. +func (m *SiteConfigMutation) ResetSiteDescription() { + m.site_description = nil +} + +// SetSiteKeywords sets the "site_keywords" field. +func (m *SiteConfigMutation) SetSiteKeywords(s string) { + m.site_keywords = &s +} + +// SiteKeywords returns the value of the "site_keywords" field in the mutation. +func (m *SiteConfigMutation) SiteKeywords() (r string, exists bool) { + v := m.site_keywords + if v == nil { + return + } + return *v, true +} + +// OldSiteKeywords returns the old "site_keywords" field's value of the SiteConfig entity. +// If the SiteConfig object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SiteConfigMutation) OldSiteKeywords(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSiteKeywords is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSiteKeywords requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSiteKeywords: %w", err) + } + return oldValue.SiteKeywords, nil +} + +// ResetSiteKeywords resets all changes to the "site_keywords" field. +func (m *SiteConfigMutation) ResetSiteKeywords() { + m.site_keywords = nil +} + +// SetUserName sets the "user_name" field. +func (m *SiteConfigMutation) SetUserName(s string) { + m.user_name = &s +} + +// UserName returns the value of the "user_name" field in the mutation. +func (m *SiteConfigMutation) UserName() (r string, exists bool) { + v := m.user_name + if v == nil { + return + } + return *v, true +} + +// OldUserName returns the old "user_name" field's value of the SiteConfig entity. +// If the SiteConfig object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SiteConfigMutation) OldUserName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserName: %w", err) + } + return oldValue.UserName, nil +} + +// ResetUserName resets all changes to the "user_name" field. +func (m *SiteConfigMutation) ResetUserName() { + m.user_name = nil +} + +// SetProfileImageURL sets the "profile_image_url" field. +func (m *SiteConfigMutation) SetProfileImageURL(s string) { + m.profile_image_url = &s +} + +// ProfileImageURL returns the value of the "profile_image_url" field in the mutation. +func (m *SiteConfigMutation) ProfileImageURL() (r string, exists bool) { + v := m.profile_image_url + if v == nil { + return + } + return *v, true +} + +// OldProfileImageURL returns the old "profile_image_url" field's value of the SiteConfig entity. +// If the SiteConfig object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SiteConfigMutation) OldProfileImageURL(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldProfileImageURL is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldProfileImageURL requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldProfileImageURL: %w", err) + } + return oldValue.ProfileImageURL, nil +} + +// ClearProfileImageURL clears the value of the "profile_image_url" field. +func (m *SiteConfigMutation) ClearProfileImageURL() { + m.profile_image_url = nil + m.clearedFields[siteconfig.FieldProfileImageURL] = struct{}{} +} + +// ProfileImageURLCleared returns if the "profile_image_url" field was cleared in this mutation. +func (m *SiteConfigMutation) ProfileImageURLCleared() bool { + _, ok := m.clearedFields[siteconfig.FieldProfileImageURL] + return ok +} + +// ResetProfileImageURL resets all changes to the "profile_image_url" field. +func (m *SiteConfigMutation) ResetProfileImageURL() { + m.profile_image_url = nil + delete(m.clearedFields, siteconfig.FieldProfileImageURL) +} + +// SetIcpNumber sets the "icp_number" field. +func (m *SiteConfigMutation) SetIcpNumber(s string) { + m.icp_number = &s +} + +// IcpNumber returns the value of the "icp_number" field in the mutation. +func (m *SiteConfigMutation) IcpNumber() (r string, exists bool) { + v := m.icp_number + if v == nil { + return + } + return *v, true +} + +// OldIcpNumber returns the old "icp_number" field's value of the SiteConfig entity. +// If the SiteConfig object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SiteConfigMutation) OldIcpNumber(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIcpNumber is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIcpNumber requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIcpNumber: %w", err) + } + return oldValue.IcpNumber, nil +} + +// ClearIcpNumber clears the value of the "icp_number" field. +func (m *SiteConfigMutation) ClearIcpNumber() { + m.icp_number = nil + m.clearedFields[siteconfig.FieldIcpNumber] = struct{}{} +} + +// IcpNumberCleared returns if the "icp_number" field was cleared in this mutation. +func (m *SiteConfigMutation) IcpNumberCleared() bool { + _, ok := m.clearedFields[siteconfig.FieldIcpNumber] + return ok +} + +// ResetIcpNumber resets all changes to the "icp_number" field. +func (m *SiteConfigMutation) ResetIcpNumber() { + m.icp_number = nil + delete(m.clearedFields, siteconfig.FieldIcpNumber) +} + +// SetPoliceNumber sets the "police_number" field. +func (m *SiteConfigMutation) SetPoliceNumber(s string) { + m.police_number = &s +} + +// PoliceNumber returns the value of the "police_number" field in the mutation. +func (m *SiteConfigMutation) PoliceNumber() (r string, exists bool) { + v := m.police_number + if v == nil { + return + } + return *v, true +} + +// OldPoliceNumber returns the old "police_number" field's value of the SiteConfig entity. +// If the SiteConfig object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SiteConfigMutation) OldPoliceNumber(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPoliceNumber is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPoliceNumber requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPoliceNumber: %w", err) + } + return oldValue.PoliceNumber, nil +} + +// ClearPoliceNumber clears the value of the "police_number" field. +func (m *SiteConfigMutation) ClearPoliceNumber() { + m.police_number = nil + m.clearedFields[siteconfig.FieldPoliceNumber] = struct{}{} +} + +// PoliceNumberCleared returns if the "police_number" field was cleared in this mutation. +func (m *SiteConfigMutation) PoliceNumberCleared() bool { + _, ok := m.clearedFields[siteconfig.FieldPoliceNumber] + return ok +} + +// ResetPoliceNumber resets all changes to the "police_number" field. +func (m *SiteConfigMutation) ResetPoliceNumber() { + m.police_number = nil + delete(m.clearedFields, siteconfig.FieldPoliceNumber) +} + +// SetPageTitle sets the "page_title" field. +func (m *SiteConfigMutation) SetPageTitle(s string) { + m.page_title = &s +} + +// PageTitle returns the value of the "page_title" field in the mutation. +func (m *SiteConfigMutation) PageTitle() (r string, exists bool) { + v := m.page_title + if v == nil { + return + } + return *v, true +} + +// OldPageTitle returns the old "page_title" field's value of the SiteConfig entity. +// If the SiteConfig object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SiteConfigMutation) OldPageTitle(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPageTitle is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPageTitle requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPageTitle: %w", err) + } + return oldValue.PageTitle, nil +} + +// ClearPageTitle clears the value of the "page_title" field. +func (m *SiteConfigMutation) ClearPageTitle() { + m.page_title = nil + m.clearedFields[siteconfig.FieldPageTitle] = struct{}{} +} + +// PageTitleCleared returns if the "page_title" field was cleared in this mutation. +func (m *SiteConfigMutation) PageTitleCleared() bool { + _, ok := m.clearedFields[siteconfig.FieldPageTitle] + return ok +} + +// ResetPageTitle resets all changes to the "page_title" field. +func (m *SiteConfigMutation) ResetPageTitle() { + m.page_title = nil + delete(m.clearedFields, siteconfig.FieldPageTitle) +} + +// SetFavicon sets the "favicon" field. +func (m *SiteConfigMutation) SetFavicon(s string) { + m.favicon = &s +} + +// Favicon returns the value of the "favicon" field in the mutation. +func (m *SiteConfigMutation) Favicon() (r string, exists bool) { + v := m.favicon + if v == nil { + return + } + return *v, true +} + +// OldFavicon returns the old "favicon" field's value of the SiteConfig entity. +// If the SiteConfig object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SiteConfigMutation) OldFavicon(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFavicon is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFavicon requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFavicon: %w", err) + } + return oldValue.Favicon, nil +} + +// ClearFavicon clears the value of the "favicon" field. +func (m *SiteConfigMutation) ClearFavicon() { + m.favicon = nil + m.clearedFields[siteconfig.FieldFavicon] = struct{}{} +} + +// FaviconCleared returns if the "favicon" field was cleared in this mutation. +func (m *SiteConfigMutation) FaviconCleared() bool { + _, ok := m.clearedFields[siteconfig.FieldFavicon] + return ok +} + +// ResetFavicon resets all changes to the "favicon" field. +func (m *SiteConfigMutation) ResetFavicon() { + m.favicon = nil + delete(m.clearedFields, siteconfig.FieldFavicon) +} + +// SetUmamiScript sets the "umami_script" field. +func (m *SiteConfigMutation) SetUmamiScript(s string) { + m.umami_script = &s +} + +// UmamiScript returns the value of the "umami_script" field in the mutation. +func (m *SiteConfigMutation) UmamiScript() (r string, exists bool) { + v := m.umami_script + if v == nil { + return + } + return *v, true +} + +// OldUmamiScript returns the old "umami_script" field's value of the SiteConfig entity. +// If the SiteConfig object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SiteConfigMutation) OldUmamiScript(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUmamiScript is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUmamiScript requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUmamiScript: %w", err) + } + return oldValue.UmamiScript, nil +} + +// ClearUmamiScript clears the value of the "umami_script" field. +func (m *SiteConfigMutation) ClearUmamiScript() { + m.umami_script = nil + m.clearedFields[siteconfig.FieldUmamiScript] = struct{}{} +} + +// UmamiScriptCleared returns if the "umami_script" field was cleared in this mutation. +func (m *SiteConfigMutation) UmamiScriptCleared() bool { + _, ok := m.clearedFields[siteconfig.FieldUmamiScript] + return ok +} + +// ResetUmamiScript resets all changes to the "umami_script" field. +func (m *SiteConfigMutation) ResetUmamiScript() { + m.umami_script = nil + delete(m.clearedFields, siteconfig.FieldUmamiScript) +} + +// SetUmamiWebsiteID sets the "umami_website_id" field. +func (m *SiteConfigMutation) SetUmamiWebsiteID(s string) { + m.umami_website_id = &s +} + +// UmamiWebsiteID returns the value of the "umami_website_id" field in the mutation. +func (m *SiteConfigMutation) UmamiWebsiteID() (r string, exists bool) { + v := m.umami_website_id + if v == nil { + return + } + return *v, true +} + +// OldUmamiWebsiteID returns the old "umami_website_id" field's value of the SiteConfig entity. +// If the SiteConfig object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SiteConfigMutation) OldUmamiWebsiteID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUmamiWebsiteID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUmamiWebsiteID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUmamiWebsiteID: %w", err) + } + return oldValue.UmamiWebsiteID, nil +} + +// ClearUmamiWebsiteID clears the value of the "umami_website_id" field. +func (m *SiteConfigMutation) ClearUmamiWebsiteID() { + m.umami_website_id = nil + m.clearedFields[siteconfig.FieldUmamiWebsiteID] = struct{}{} +} + +// UmamiWebsiteIDCleared returns if the "umami_website_id" field was cleared in this mutation. +func (m *SiteConfigMutation) UmamiWebsiteIDCleared() bool { + _, ok := m.clearedFields[siteconfig.FieldUmamiWebsiteID] + return ok +} + +// ResetUmamiWebsiteID resets all changes to the "umami_website_id" field. +func (m *SiteConfigMutation) ResetUmamiWebsiteID() { + m.umami_website_id = nil + delete(m.clearedFields, siteconfig.FieldUmamiWebsiteID) +} + +// SetIconLibrary sets the "icon_library" field. +func (m *SiteConfigMutation) SetIconLibrary(s string) { + m.icon_library = &s +} + +// IconLibrary returns the value of the "icon_library" field in the mutation. +func (m *SiteConfigMutation) IconLibrary() (r string, exists bool) { + v := m.icon_library + if v == nil { + return + } + return *v, true +} + +// OldIconLibrary returns the old "icon_library" field's value of the SiteConfig entity. +// If the SiteConfig object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SiteConfigMutation) OldIconLibrary(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIconLibrary is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIconLibrary requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIconLibrary: %w", err) + } + return oldValue.IconLibrary, nil +} + +// ClearIconLibrary clears the value of the "icon_library" field. +func (m *SiteConfigMutation) ClearIconLibrary() { + m.icon_library = nil + m.clearedFields[siteconfig.FieldIconLibrary] = struct{}{} +} + +// IconLibraryCleared returns if the "icon_library" field was cleared in this mutation. +func (m *SiteConfigMutation) IconLibraryCleared() bool { + _, ok := m.clearedFields[siteconfig.FieldIconLibrary] + return ok +} + +// ResetIconLibrary resets all changes to the "icon_library" field. +func (m *SiteConfigMutation) ResetIconLibrary() { + m.icon_library = nil + delete(m.clearedFields, siteconfig.FieldIconLibrary) +} + +// SetFontLibrary sets the "font_library" field. +func (m *SiteConfigMutation) SetFontLibrary(s string) { + m.font_library = &s +} + +// FontLibrary returns the value of the "font_library" field in the mutation. +func (m *SiteConfigMutation) FontLibrary() (r string, exists bool) { + v := m.font_library + if v == nil { + return + } + return *v, true +} + +// OldFontLibrary returns the old "font_library" field's value of the SiteConfig entity. +// If the SiteConfig object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SiteConfigMutation) OldFontLibrary(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFontLibrary is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFontLibrary requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFontLibrary: %w", err) + } + return oldValue.FontLibrary, nil +} + +// ClearFontLibrary clears the value of the "font_library" field. +func (m *SiteConfigMutation) ClearFontLibrary() { + m.font_library = nil + m.clearedFields[siteconfig.FieldFontLibrary] = struct{}{} +} + +// FontLibraryCleared returns if the "font_library" field was cleared in this mutation. +func (m *SiteConfigMutation) FontLibraryCleared() bool { + _, ok := m.clearedFields[siteconfig.FieldFontLibrary] + return ok +} + +// ResetFontLibrary resets all changes to the "font_library" field. +func (m *SiteConfigMutation) ResetFontLibrary() { + m.font_library = nil + delete(m.clearedFields, siteconfig.FieldFontLibrary) +} + +// Where appends a list predicates to the SiteConfigMutation builder. +func (m *SiteConfigMutation) Where(ps ...predicate.SiteConfig) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the SiteConfigMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *SiteConfigMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.SiteConfig, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *SiteConfigMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *SiteConfigMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (SiteConfig). +func (m *SiteConfigMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *SiteConfigMutation) Fields() []string { + fields := make([]string, 0, 15) + if m.site_name != nil { + fields = append(fields, siteconfig.FieldSiteName) + } + if m.site_url != nil { + fields = append(fields, siteconfig.FieldSiteURL) + } + if m.site_icon != nil { + fields = append(fields, siteconfig.FieldSiteIcon) + } + if m.site_description != nil { + fields = append(fields, siteconfig.FieldSiteDescription) + } + if m.site_keywords != nil { + fields = append(fields, siteconfig.FieldSiteKeywords) + } + if m.user_name != nil { + fields = append(fields, siteconfig.FieldUserName) + } + if m.profile_image_url != nil { + fields = append(fields, siteconfig.FieldProfileImageURL) + } + if m.icp_number != nil { + fields = append(fields, siteconfig.FieldIcpNumber) + } + if m.police_number != nil { + fields = append(fields, siteconfig.FieldPoliceNumber) + } + if m.page_title != nil { + fields = append(fields, siteconfig.FieldPageTitle) + } + if m.favicon != nil { + fields = append(fields, siteconfig.FieldFavicon) + } + if m.umami_script != nil { + fields = append(fields, siteconfig.FieldUmamiScript) + } + if m.umami_website_id != nil { + fields = append(fields, siteconfig.FieldUmamiWebsiteID) + } + if m.icon_library != nil { + fields = append(fields, siteconfig.FieldIconLibrary) + } + if m.font_library != nil { + fields = append(fields, siteconfig.FieldFontLibrary) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *SiteConfigMutation) Field(name string) (ent.Value, bool) { + switch name { + case siteconfig.FieldSiteName: + return m.SiteName() + case siteconfig.FieldSiteURL: + return m.SiteURL() + case siteconfig.FieldSiteIcon: + return m.SiteIcon() + case siteconfig.FieldSiteDescription: + return m.SiteDescription() + case siteconfig.FieldSiteKeywords: + return m.SiteKeywords() + case siteconfig.FieldUserName: + return m.UserName() + case siteconfig.FieldProfileImageURL: + return m.ProfileImageURL() + case siteconfig.FieldIcpNumber: + return m.IcpNumber() + case siteconfig.FieldPoliceNumber: + return m.PoliceNumber() + case siteconfig.FieldPageTitle: + return m.PageTitle() + case siteconfig.FieldFavicon: + return m.Favicon() + case siteconfig.FieldUmamiScript: + return m.UmamiScript() + case siteconfig.FieldUmamiWebsiteID: + return m.UmamiWebsiteID() + case siteconfig.FieldIconLibrary: + return m.IconLibrary() + case siteconfig.FieldFontLibrary: + return m.FontLibrary() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *SiteConfigMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case siteconfig.FieldSiteName: + return m.OldSiteName(ctx) + case siteconfig.FieldSiteURL: + return m.OldSiteURL(ctx) + case siteconfig.FieldSiteIcon: + return m.OldSiteIcon(ctx) + case siteconfig.FieldSiteDescription: + return m.OldSiteDescription(ctx) + case siteconfig.FieldSiteKeywords: + return m.OldSiteKeywords(ctx) + case siteconfig.FieldUserName: + return m.OldUserName(ctx) + case siteconfig.FieldProfileImageURL: + return m.OldProfileImageURL(ctx) + case siteconfig.FieldIcpNumber: + return m.OldIcpNumber(ctx) + case siteconfig.FieldPoliceNumber: + return m.OldPoliceNumber(ctx) + case siteconfig.FieldPageTitle: + return m.OldPageTitle(ctx) + case siteconfig.FieldFavicon: + return m.OldFavicon(ctx) + case siteconfig.FieldUmamiScript: + return m.OldUmamiScript(ctx) + case siteconfig.FieldUmamiWebsiteID: + return m.OldUmamiWebsiteID(ctx) + case siteconfig.FieldIconLibrary: + return m.OldIconLibrary(ctx) + case siteconfig.FieldFontLibrary: + return m.OldFontLibrary(ctx) + } + return nil, fmt.Errorf("unknown SiteConfig field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *SiteConfigMutation) SetField(name string, value ent.Value) error { + switch name { + case siteconfig.FieldSiteName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSiteName(v) + return nil + case siteconfig.FieldSiteURL: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSiteURL(v) + return nil + case siteconfig.FieldSiteIcon: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSiteIcon(v) + return nil + case siteconfig.FieldSiteDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSiteDescription(v) + return nil + case siteconfig.FieldSiteKeywords: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSiteKeywords(v) + return nil + case siteconfig.FieldUserName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserName(v) + return nil + case siteconfig.FieldProfileImageURL: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetProfileImageURL(v) + return nil + case siteconfig.FieldIcpNumber: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIcpNumber(v) + return nil + case siteconfig.FieldPoliceNumber: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPoliceNumber(v) + return nil + case siteconfig.FieldPageTitle: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPageTitle(v) + return nil + case siteconfig.FieldFavicon: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFavicon(v) + return nil + case siteconfig.FieldUmamiScript: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUmamiScript(v) + return nil + case siteconfig.FieldUmamiWebsiteID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUmamiWebsiteID(v) + return nil + case siteconfig.FieldIconLibrary: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIconLibrary(v) + return nil + case siteconfig.FieldFontLibrary: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFontLibrary(v) + return nil + } + return fmt.Errorf("unknown SiteConfig field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *SiteConfigMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *SiteConfigMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *SiteConfigMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown SiteConfig numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *SiteConfigMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(siteconfig.FieldProfileImageURL) { + fields = append(fields, siteconfig.FieldProfileImageURL) + } + if m.FieldCleared(siteconfig.FieldIcpNumber) { + fields = append(fields, siteconfig.FieldIcpNumber) + } + if m.FieldCleared(siteconfig.FieldPoliceNumber) { + fields = append(fields, siteconfig.FieldPoliceNumber) + } + if m.FieldCleared(siteconfig.FieldPageTitle) { + fields = append(fields, siteconfig.FieldPageTitle) + } + if m.FieldCleared(siteconfig.FieldFavicon) { + fields = append(fields, siteconfig.FieldFavicon) + } + if m.FieldCleared(siteconfig.FieldUmamiScript) { + fields = append(fields, siteconfig.FieldUmamiScript) + } + if m.FieldCleared(siteconfig.FieldUmamiWebsiteID) { + fields = append(fields, siteconfig.FieldUmamiWebsiteID) + } + if m.FieldCleared(siteconfig.FieldIconLibrary) { + fields = append(fields, siteconfig.FieldIconLibrary) + } + if m.FieldCleared(siteconfig.FieldFontLibrary) { + fields = append(fields, siteconfig.FieldFontLibrary) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *SiteConfigMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *SiteConfigMutation) ClearField(name string) error { + switch name { + case siteconfig.FieldProfileImageURL: + m.ClearProfileImageURL() + return nil + case siteconfig.FieldIcpNumber: + m.ClearIcpNumber() + return nil + case siteconfig.FieldPoliceNumber: + m.ClearPoliceNumber() + return nil + case siteconfig.FieldPageTitle: + m.ClearPageTitle() + return nil + case siteconfig.FieldFavicon: + m.ClearFavicon() + return nil + case siteconfig.FieldUmamiScript: + m.ClearUmamiScript() + return nil + case siteconfig.FieldUmamiWebsiteID: + m.ClearUmamiWebsiteID() + return nil + case siteconfig.FieldIconLibrary: + m.ClearIconLibrary() + return nil + case siteconfig.FieldFontLibrary: + m.ClearFontLibrary() + return nil + } + return fmt.Errorf("unknown SiteConfig nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *SiteConfigMutation) ResetField(name string) error { + switch name { + case siteconfig.FieldSiteName: + m.ResetSiteName() + return nil + case siteconfig.FieldSiteURL: + m.ResetSiteURL() + return nil + case siteconfig.FieldSiteIcon: + m.ResetSiteIcon() + return nil + case siteconfig.FieldSiteDescription: + m.ResetSiteDescription() + return nil + case siteconfig.FieldSiteKeywords: + m.ResetSiteKeywords() + return nil + case siteconfig.FieldUserName: + m.ResetUserName() + return nil + case siteconfig.FieldProfileImageURL: + m.ResetProfileImageURL() + return nil + case siteconfig.FieldIcpNumber: + m.ResetIcpNumber() + return nil + case siteconfig.FieldPoliceNumber: + m.ResetPoliceNumber() + return nil + case siteconfig.FieldPageTitle: + m.ResetPageTitle() + return nil + case siteconfig.FieldFavicon: + m.ResetFavicon() + return nil + case siteconfig.FieldUmamiScript: + m.ResetUmamiScript() + return nil + case siteconfig.FieldUmamiWebsiteID: + m.ResetUmamiWebsiteID() + return nil + case siteconfig.FieldIconLibrary: + m.ResetIconLibrary() + return nil + case siteconfig.FieldFontLibrary: + m.ResetFontLibrary() + return nil + } + return fmt.Errorf("unknown SiteConfig field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *SiteConfigMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *SiteConfigMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *SiteConfigMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *SiteConfigMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *SiteConfigMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *SiteConfigMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *SiteConfigMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown SiteConfig 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 *SiteConfigMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown SiteConfig edge %s", name) +} + +// UserMutation represents an operation that mutates the User nodes in the graph. +type UserMutation struct { + config + op Op + typ string + id *int + username *string + password *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*User, error) + predicates []predicate.User +} + +var _ ent.Mutation = (*UserMutation)(nil) + +// userOption allows management of the mutation configuration using functional options. +type userOption func(*UserMutation) + +// newUserMutation creates new mutation for the User entity. +func newUserMutation(c config, op Op, opts ...userOption) *UserMutation { + m := &UserMutation{ + config: c, + op: op, + typ: TypeUser, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withUserID sets the ID field of the mutation. +func withUserID(id int) userOption { + return func(m *UserMutation) { + var ( + err error + once sync.Once + value *User + ) + m.oldValue = func(ctx context.Context) (*User, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().User.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withUser sets the old User of the mutation. +func withUser(node *User) userOption { + return func(m *UserMutation) { + m.oldValue = func(context.Context) (*User, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m UserMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m UserMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of User entities. +func (m *UserMutation) SetID(id int) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *UserMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *UserMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().User.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetUsername sets the "username" field. +func (m *UserMutation) SetUsername(s string) { + m.username = &s +} + +// Username returns the value of the "username" field in the mutation. +func (m *UserMutation) Username() (r string, exists bool) { + v := m.username + if v == nil { + return + } + return *v, true +} + +// OldUsername returns the old "username" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldUsername(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUsername is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUsername requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUsername: %w", err) + } + return oldValue.Username, nil +} + +// ResetUsername resets all changes to the "username" field. +func (m *UserMutation) ResetUsername() { + m.username = nil +} + +// SetPassword sets the "password" field. +func (m *UserMutation) SetPassword(s string) { + m.password = &s +} + +// Password returns the value of the "password" field in the mutation. +func (m *UserMutation) Password() (r string, exists bool) { + v := m.password + if v == nil { + return + } + return *v, true +} + +// OldPassword returns the old "password" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldPassword(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPassword is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPassword requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPassword: %w", err) + } + return oldValue.Password, nil +} + +// ResetPassword resets all changes to the "password" field. +func (m *UserMutation) ResetPassword() { + m.password = nil +} + +// Where appends a list predicates to the UserMutation builder. +func (m *UserMutation) Where(ps ...predicate.User) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the UserMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *UserMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.User, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *UserMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *UserMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (User). +func (m *UserMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *UserMutation) Fields() []string { + fields := make([]string, 0, 2) + if m.username != nil { + fields = append(fields, user.FieldUsername) + } + if m.password != nil { + fields = append(fields, user.FieldPassword) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *UserMutation) Field(name string) (ent.Value, bool) { + switch name { + case user.FieldUsername: + return m.Username() + case user.FieldPassword: + return m.Password() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *UserMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case user.FieldUsername: + return m.OldUsername(ctx) + case user.FieldPassword: + return m.OldPassword(ctx) + } + return nil, fmt.Errorf("unknown User field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *UserMutation) SetField(name string, value ent.Value) error { + switch name { + case user.FieldUsername: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUsername(v) + return nil + case user.FieldPassword: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPassword(v) + return nil + } + return fmt.Errorf("unknown User field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *UserMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *UserMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *UserMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown User numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *UserMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *UserMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *UserMutation) ClearField(name string) error { + return fmt.Errorf("unknown User nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *UserMutation) ResetField(name string) error { + switch name { + case user.FieldUsername: + m.ResetUsername() + return nil + case user.FieldPassword: + m.ResetPassword() + return nil + } + return fmt.Errorf("unknown User field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *UserMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + 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 { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *UserMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *UserMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *UserMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *UserMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *UserMutation) ClearEdge(name string) error { + 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 { + return fmt.Errorf("unknown User edge %s", name) +} + +// VisitMutation represents an operation that mutates the Visit nodes in the graph. +type VisitMutation struct { + config + op Op + typ string + id *int + _path *string + ip *string + user_agent *string + referer *string + visit_time *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Visit, error) + predicates []predicate.Visit +} + +var _ ent.Mutation = (*VisitMutation)(nil) + +// visitOption allows management of the mutation configuration using functional options. +type visitOption func(*VisitMutation) + +// newVisitMutation creates new mutation for the Visit entity. +func newVisitMutation(c config, op Op, opts ...visitOption) *VisitMutation { + m := &VisitMutation{ + config: c, + op: op, + typ: TypeVisit, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withVisitID sets the ID field of the mutation. +func withVisitID(id int) visitOption { + return func(m *VisitMutation) { + var ( + err error + once sync.Once + value *Visit + ) + m.oldValue = func(ctx context.Context) (*Visit, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Visit.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withVisit sets the old Visit of the mutation. +func withVisit(node *Visit) visitOption { + return func(m *VisitMutation) { + m.oldValue = func(context.Context) (*Visit, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m VisitMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m VisitMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of Visit entities. +func (m *VisitMutation) SetID(id int) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *VisitMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *VisitMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Visit.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetPath sets the "path" field. +func (m *VisitMutation) SetPath(s string) { + m._path = &s +} + +// Path returns the value of the "path" field in the mutation. +func (m *VisitMutation) Path() (r string, exists bool) { + v := m._path + if v == nil { + return + } + return *v, true +} + +// OldPath returns the old "path" field's value of the Visit entity. +// If the Visit object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *VisitMutation) OldPath(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPath is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPath requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPath: %w", err) + } + return oldValue.Path, nil +} + +// ResetPath resets all changes to the "path" field. +func (m *VisitMutation) ResetPath() { + m._path = nil +} + +// SetIP sets the "ip" field. +func (m *VisitMutation) SetIP(s string) { + m.ip = &s +} + +// IP returns the value of the "ip" field in the mutation. +func (m *VisitMutation) IP() (r string, exists bool) { + v := m.ip + if v == nil { + return + } + return *v, true +} + +// OldIP returns the old "ip" field's value of the Visit entity. +// If the Visit object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *VisitMutation) OldIP(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldIP is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldIP requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldIP: %w", err) + } + return oldValue.IP, nil +} + +// ResetIP resets all changes to the "ip" field. +func (m *VisitMutation) ResetIP() { + m.ip = nil +} + +// SetUserAgent sets the "user_agent" field. +func (m *VisitMutation) SetUserAgent(s string) { + m.user_agent = &s +} + +// UserAgent returns the value of the "user_agent" field in the mutation. +func (m *VisitMutation) UserAgent() (r string, exists bool) { + v := m.user_agent + if v == nil { + return + } + return *v, true +} + +// OldUserAgent returns the old "user_agent" field's value of the Visit entity. +// If the Visit object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *VisitMutation) OldUserAgent(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserAgent is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserAgent requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserAgent: %w", err) + } + return oldValue.UserAgent, nil +} + +// ClearUserAgent clears the value of the "user_agent" field. +func (m *VisitMutation) ClearUserAgent() { + m.user_agent = nil + m.clearedFields[visit.FieldUserAgent] = struct{}{} +} + +// UserAgentCleared returns if the "user_agent" field was cleared in this mutation. +func (m *VisitMutation) UserAgentCleared() bool { + _, ok := m.clearedFields[visit.FieldUserAgent] + return ok +} + +// ResetUserAgent resets all changes to the "user_agent" field. +func (m *VisitMutation) ResetUserAgent() { + m.user_agent = nil + delete(m.clearedFields, visit.FieldUserAgent) +} + +// SetReferer sets the "referer" field. +func (m *VisitMutation) SetReferer(s string) { + m.referer = &s +} + +// Referer returns the value of the "referer" field in the mutation. +func (m *VisitMutation) Referer() (r string, exists bool) { + v := m.referer + if v == nil { + return + } + return *v, true +} + +// OldReferer returns the old "referer" field's value of the Visit entity. +// If the Visit object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *VisitMutation) OldReferer(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldReferer is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldReferer requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldReferer: %w", err) + } + return oldValue.Referer, nil +} + +// ClearReferer clears the value of the "referer" field. +func (m *VisitMutation) ClearReferer() { + m.referer = nil + m.clearedFields[visit.FieldReferer] = struct{}{} +} + +// RefererCleared returns if the "referer" field was cleared in this mutation. +func (m *VisitMutation) RefererCleared() bool { + _, ok := m.clearedFields[visit.FieldReferer] + return ok +} + +// ResetReferer resets all changes to the "referer" field. +func (m *VisitMutation) ResetReferer() { + m.referer = nil + delete(m.clearedFields, visit.FieldReferer) +} + +// SetVisitTime sets the "visit_time" field. +func (m *VisitMutation) SetVisitTime(t time.Time) { + m.visit_time = &t +} + +// VisitTime returns the value of the "visit_time" field in the mutation. +func (m *VisitMutation) VisitTime() (r time.Time, exists bool) { + v := m.visit_time + if v == nil { + return + } + return *v, true +} + +// OldVisitTime returns the old "visit_time" field's value of the Visit entity. +// If the Visit object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *VisitMutation) OldVisitTime(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldVisitTime is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldVisitTime requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldVisitTime: %w", err) + } + return oldValue.VisitTime, nil +} + +// ResetVisitTime resets all changes to the "visit_time" field. +func (m *VisitMutation) ResetVisitTime() { + m.visit_time = nil +} + +// Where appends a list predicates to the VisitMutation builder. +func (m *VisitMutation) Where(ps ...predicate.Visit) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the VisitMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *VisitMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Visit, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *VisitMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *VisitMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Visit). +func (m *VisitMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *VisitMutation) Fields() []string { + fields := make([]string, 0, 5) + if m._path != nil { + fields = append(fields, visit.FieldPath) + } + if m.ip != nil { + fields = append(fields, visit.FieldIP) + } + if m.user_agent != nil { + fields = append(fields, visit.FieldUserAgent) + } + if m.referer != nil { + fields = append(fields, visit.FieldReferer) + } + if m.visit_time != nil { + fields = append(fields, visit.FieldVisitTime) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *VisitMutation) Field(name string) (ent.Value, bool) { + switch name { + case visit.FieldPath: + return m.Path() + case visit.FieldIP: + return m.IP() + case visit.FieldUserAgent: + return m.UserAgent() + case visit.FieldReferer: + return m.Referer() + case visit.FieldVisitTime: + return m.VisitTime() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *VisitMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case visit.FieldPath: + return m.OldPath(ctx) + case visit.FieldIP: + return m.OldIP(ctx) + case visit.FieldUserAgent: + return m.OldUserAgent(ctx) + case visit.FieldReferer: + return m.OldReferer(ctx) + case visit.FieldVisitTime: + return m.OldVisitTime(ctx) + } + return nil, fmt.Errorf("unknown Visit field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *VisitMutation) SetField(name string, value ent.Value) error { + switch name { + case visit.FieldPath: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPath(v) + return nil + case visit.FieldIP: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIP(v) + return nil + case visit.FieldUserAgent: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserAgent(v) + return nil + case visit.FieldReferer: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetReferer(v) + return nil + case visit.FieldVisitTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetVisitTime(v) + return nil + } + return fmt.Errorf("unknown Visit field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *VisitMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *VisitMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *VisitMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Visit numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *VisitMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(visit.FieldUserAgent) { + fields = append(fields, visit.FieldUserAgent) + } + if m.FieldCleared(visit.FieldReferer) { + fields = append(fields, visit.FieldReferer) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *VisitMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *VisitMutation) ClearField(name string) error { + switch name { + case visit.FieldUserAgent: + m.ClearUserAgent() + return nil + case visit.FieldReferer: + m.ClearReferer() + return nil + } + return fmt.Errorf("unknown Visit nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *VisitMutation) ResetField(name string) error { + switch name { + case visit.FieldPath: + m.ResetPath() + return nil + case visit.FieldIP: + m.ResetIP() + return nil + case visit.FieldUserAgent: + m.ResetUserAgent() + return nil + case visit.FieldReferer: + m.ResetReferer() + return nil + case visit.FieldVisitTime: + m.ResetVisitTime() + return nil + } + return fmt.Errorf("unknown Visit field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *VisitMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *VisitMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *VisitMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *VisitMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *VisitMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *VisitMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *VisitMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Visit 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 *VisitMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Visit edge %s", name) +} diff --git a/internal/ent/predicate/predicate.go b/internal/ent/predicate/predicate.go new file mode 100644 index 0000000..99b6019 --- /dev/null +++ b/internal/ent/predicate/predicate.go @@ -0,0 +1,25 @@ +// Code generated by ent, DO NOT EDIT. + +package predicate + +import ( + "entgo.io/ent/dialect/sql" +) + +// Contact is the predicate function for contact builders. +type Contact func(*sql.Selector) + +// LoginHistory is the predicate function for loginhistory builders. +type LoginHistory func(*sql.Selector) + +// Site is the predicate function for site builders. +type Site func(*sql.Selector) + +// SiteConfig is the predicate function for siteconfig builders. +type SiteConfig func(*sql.Selector) + +// User is the predicate function for user builders. +type User func(*sql.Selector) + +// Visit is the predicate function for visit builders. +type Visit func(*sql.Selector) diff --git a/internal/ent/runtime.go b/internal/ent/runtime.go new file mode 100644 index 0000000..3a98059 --- /dev/null +++ b/internal/ent/runtime.go @@ -0,0 +1,53 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "home-vue-go/internal/ent/contact" + "home-vue-go/internal/ent/loginhistory" + "home-vue-go/internal/ent/schema" + "home-vue-go/internal/ent/site" + "home-vue-go/internal/ent/siteconfig" + "home-vue-go/internal/ent/visit" + "time" +) + +// The init function reads all schema descriptors with runtime code +// (default values, validators, hooks and policies) and stitches it +// to their package variables. +func init() { + contactFields := schema.Contact{}.Fields() + _ = contactFields + // contactDescSortOrder is the schema descriptor for sort_order field. + contactDescSortOrder := contactFields[6].Descriptor() + // contact.DefaultSortOrder holds the default value on creation for the sort_order field. + contact.DefaultSortOrder = contactDescSortOrder.Default.(int) + loginhistoryFields := schema.LoginHistory{}.Fields() + _ = loginhistoryFields + // loginhistoryDescLoginTime is the schema descriptor for login_time field. + loginhistoryDescLoginTime := loginhistoryFields[5].Descriptor() + // loginhistory.DefaultLoginTime holds the default value on creation for the login_time field. + loginhistory.DefaultLoginTime = loginhistoryDescLoginTime.Default.(func() time.Time) + // loginhistoryDescSuccess is the schema descriptor for success field. + loginhistoryDescSuccess := loginhistoryFields[6].Descriptor() + // loginhistory.DefaultSuccess holds the default value on creation for the success field. + loginhistory.DefaultSuccess = loginhistoryDescSuccess.Default.(bool) + siteFields := schema.Site{}.Fields() + _ = siteFields + // siteDescSortOrder is the schema descriptor for sort_order field. + siteDescSortOrder := siteFields[4].Descriptor() + // site.DefaultSortOrder holds the default value on creation for the sort_order field. + site.DefaultSortOrder = siteDescSortOrder.Default.(int) + siteconfigFields := schema.SiteConfig{}.Fields() + _ = siteconfigFields + // siteconfigDescID is the schema descriptor for id field. + siteconfigDescID := siteconfigFields[0].Descriptor() + // siteconfig.DefaultID holds the default value on creation for the id field. + siteconfig.DefaultID = siteconfigDescID.Default.(int) + visitFields := schema.Visit{}.Fields() + _ = visitFields + // visitDescVisitTime is the schema descriptor for visit_time field. + visitDescVisitTime := visitFields[5].Descriptor() + // visit.DefaultVisitTime holds the default value on creation for the visit_time field. + visit.DefaultVisitTime = visitDescVisitTime.Default.(func() time.Time) +} diff --git a/internal/ent/runtime/runtime.go b/internal/ent/runtime/runtime.go new file mode 100644 index 0000000..8c147fe --- /dev/null +++ b/internal/ent/runtime/runtime.go @@ -0,0 +1,10 @@ +// Code generated by ent, DO NOT EDIT. + +package runtime + +// The schema-stitching logic is generated in home-vue-go/internal/ent/runtime.go + +const ( + Version = "v0.14.5" // Version of ent codegen. + Sum = "h1:Rj2WOYJtCkWyFo6a+5wB3EfBRP0rnx1fMk6gGA0UUe4=" // Sum of ent codegen. +) diff --git a/internal/ent/schema/contact.go b/internal/ent/schema/contact.go new file mode 100644 index 0000000..667bef0 --- /dev/null +++ b/internal/ent/schema/contact.go @@ -0,0 +1,27 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/schema/field" +) + +// Contact 联系方式实体 +type Contact struct { + ent.Schema +} + +func (Contact) Fields() []ent.Field { + return []ent.Field{ + field.Int("id"), + field.String("type").Comment("联系方式类型(Email, Github, 支付宝, 微信等)"), + field.String("icon").Comment("图标类名"), + field.String("url").Optional().Comment("链接URL(mailto:或https://)"), + field.String("qr_code").Optional().Comment("二维码图片URL或路径"), + field.String("hover_color").Optional().Comment("悬停颜色"), + field.Int("sort_order").Default(0).Comment("排序顺序"), + } +} + +func (Contact) Edges() []ent.Edge { + return nil +} diff --git a/internal/ent/schema/login_history.go b/internal/ent/schema/login_history.go new file mode 100644 index 0000000..e062834 --- /dev/null +++ b/internal/ent/schema/login_history.go @@ -0,0 +1,28 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/schema/field" + "time" +) + +// LoginHistory 登录历史记录实体 +type LoginHistory struct { + ent.Schema +} + +func (LoginHistory) Fields() []ent.Field { + return []ent.Field{ + field.Int("id"), + field.String("username").Comment("用户名"), + field.String("ip").Comment("登录IP地址"), + field.String("location").Optional().Comment("IP地理位置"), + field.String("user_agent").Optional().Comment("用户代理"), + field.Time("login_time").Default(time.Now).Comment("登录时间"), + field.Bool("success").Default(true).Comment("登录是否成功"), + } +} + +func (LoginHistory) Edges() []ent.Edge { + return nil +} diff --git a/internal/ent/schema/site.go b/internal/ent/schema/site.go new file mode 100644 index 0000000..921da69 --- /dev/null +++ b/internal/ent/schema/site.go @@ -0,0 +1,25 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/schema/field" +) + +// Site 站点实体 +type Site struct { + ent.Schema +} + +func (Site) Fields() []ent.Field { + return []ent.Field{ + field.Int("id"), + field.String("name").Comment("站点名称"), + field.String("url").Comment("站点URL"), + field.String("icon").Comment("站点图标类名"), + field.Int("sort_order").Default(0).Comment("排序顺序"), + } +} + +func (Site) Edges() []ent.Edge { + return nil +} diff --git a/internal/ent/schema/site_config.go b/internal/ent/schema/site_config.go new file mode 100644 index 0000000..8b09f55 --- /dev/null +++ b/internal/ent/schema/site_config.go @@ -0,0 +1,37 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/schema/field" +) + +// SiteConfig 站点配置实体(单例) +type SiteConfig struct { + ent.Schema +} + +func (SiteConfig) Fields() []ent.Field { + return []ent.Field{ + field.Int("id").Default(1), + field.String("site_name").Comment("站点名称"), + field.String("site_url").Comment("站点URL"), + field.String("site_icon").Comment("站点图标"), + field.String("site_description").Comment("站点描述"), + field.String("site_keywords").Comment("站点关键词"), + field.String("user_name").Comment("用户名"), + field.String("profile_image_url").Optional().Comment("头像URL"), + field.String("icp_number").Optional().Comment("ICP备案号"), + field.String("police_number").Optional().Comment("公安备案号"), + // 新增字段:对应.env文件中的配置 + field.String("page_title").Optional().Comment("网页标题"), + field.String("favicon").Optional().Comment("网页图标路径"), + field.String("umami_script").Optional().Comment("Umami统计脚本地址"), + field.String("umami_website_id").Optional().Comment("Umami统计网站ID"), + field.String("icon_library").Optional().Comment("图标库CDN地址"), + field.String("font_library").Optional().Comment("字体库CDN地址"), + } +} + +func (SiteConfig) Edges() []ent.Edge { + return nil +} diff --git a/internal/ent/schema/user.go b/internal/ent/schema/user.go new file mode 100644 index 0000000..2ed7806 --- /dev/null +++ b/internal/ent/schema/user.go @@ -0,0 +1,23 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/schema/field" +) + +// User 用户实体(用于JWT认证) +type User struct { + ent.Schema +} + +func (User) Fields() []ent.Field { + return []ent.Field{ + field.Int("id"), + field.String("username").Unique().Comment("用户名"), + field.String("password").Comment("密码(bcrypt哈希)"), + } +} + +func (User) Edges() []ent.Edge { + return nil +} diff --git a/internal/ent/schema/visit.go b/internal/ent/schema/visit.go new file mode 100644 index 0000000..853bf8c --- /dev/null +++ b/internal/ent/schema/visit.go @@ -0,0 +1,27 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/schema/field" + "time" +) + +// Visit 访问记录实体 +type Visit struct { + ent.Schema +} + +func (Visit) Fields() []ent.Field { + return []ent.Field{ + field.Int("id"), + field.String("path").Comment("访问路径"), + field.String("ip").Comment("访问IP"), + field.String("user_agent").Optional().Comment("用户代理"), + field.String("referer").Optional().Comment("来源页面"), + field.Time("visit_time").Default(time.Now).Comment("访问时间"), + } +} + +func (Visit) Edges() []ent.Edge { + return nil +} diff --git a/internal/ent/site.go b/internal/ent/site.go new file mode 100644 index 0000000..f00e764 --- /dev/null +++ b/internal/ent/site.go @@ -0,0 +1,136 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "home-vue-go/internal/ent/site" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// Site is the model entity for the Site schema. +type Site struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // 站点名称 + Name string `json:"name,omitempty"` + // 站点URL + URL string `json:"url,omitempty"` + // 站点图标类名 + Icon string `json:"icon,omitempty"` + // 排序顺序 + SortOrder int `json:"sort_order,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Site) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case site.FieldID, site.FieldSortOrder: + values[i] = new(sql.NullInt64) + case site.FieldName, site.FieldURL, site.FieldIcon: + values[i] = new(sql.NullString) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Site fields. +func (_m *Site) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case site.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int(value.Int64) + case site.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case site.FieldURL: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field url", values[i]) + } else if value.Valid { + _m.URL = value.String + } + case site.FieldIcon: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field icon", values[i]) + } else if value.Valid { + _m.Icon = value.String + } + case site.FieldSortOrder: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field sort_order", values[i]) + } else if value.Valid { + _m.SortOrder = int(value.Int64) + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Site. +// This includes values selected through modifiers, order, etc. +func (_m *Site) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this Site. +// Note that you need to call Site.Unwrap() before calling this method if this Site +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Site) Update() *SiteUpdateOne { + return NewSiteClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Site entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *Site) Unwrap() *Site { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: Site is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Site) String() string { + var builder strings.Builder + builder.WriteString("Site(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + builder.WriteString("url=") + builder.WriteString(_m.URL) + builder.WriteString(", ") + builder.WriteString("icon=") + builder.WriteString(_m.Icon) + builder.WriteString(", ") + builder.WriteString("sort_order=") + builder.WriteString(fmt.Sprintf("%v", _m.SortOrder)) + builder.WriteByte(')') + return builder.String() +} + +// Sites is a parsable slice of Site. +type Sites []*Site diff --git a/internal/ent/site/site.go b/internal/ent/site/site.go new file mode 100644 index 0000000..d57c716 --- /dev/null +++ b/internal/ent/site/site.go @@ -0,0 +1,76 @@ +// Code generated by ent, DO NOT EDIT. + +package site + +import ( + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the site type in the database. + Label = "site" + // 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" + // FieldURL holds the string denoting the url field in the database. + FieldURL = "url" + // FieldIcon holds the string denoting the icon field in the database. + FieldIcon = "icon" + // FieldSortOrder holds the string denoting the sort_order field in the database. + FieldSortOrder = "sort_order" + // Table holds the table name of the site in the database. + Table = "sites" +) + +// Columns holds all SQL columns for site fields. +var Columns = []string{ + FieldID, + FieldName, + FieldURL, + FieldIcon, + FieldSortOrder, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultSortOrder holds the default value on creation for the "sort_order" field. + DefaultSortOrder int +) + +// OrderOption defines the ordering options for the Site 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() +} + +// ByURL orders the results by the url field. +func ByURL(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldURL, opts...).ToFunc() +} + +// ByIcon orders the results by the icon field. +func ByIcon(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIcon, opts...).ToFunc() +} + +// BySortOrder orders the results by the sort_order field. +func BySortOrder(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSortOrder, opts...).ToFunc() +} diff --git a/internal/ent/site/where.go b/internal/ent/site/where.go new file mode 100644 index 0000000..054a1ae --- /dev/null +++ b/internal/ent/site/where.go @@ -0,0 +1,324 @@ +// Code generated by ent, DO NOT EDIT. + +package site + +import ( + "home-vue-go/internal/ent/predicate" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.Site { + return predicate.Site(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.Site { + return predicate.Site(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.Site { + return predicate.Site(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.Site { + return predicate.Site(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.Site { + return predicate.Site(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.Site { + return predicate.Site(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.Site { + return predicate.Site(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.Site { + return predicate.Site(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.Site { + return predicate.Site(sql.FieldLTE(FieldID, id)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.Site { + return predicate.Site(sql.FieldEQ(FieldName, v)) +} + +// URL applies equality check predicate on the "url" field. It's identical to URLEQ. +func URL(v string) predicate.Site { + return predicate.Site(sql.FieldEQ(FieldURL, v)) +} + +// Icon applies equality check predicate on the "icon" field. It's identical to IconEQ. +func Icon(v string) predicate.Site { + return predicate.Site(sql.FieldEQ(FieldIcon, v)) +} + +// SortOrder applies equality check predicate on the "sort_order" field. It's identical to SortOrderEQ. +func SortOrder(v int) predicate.Site { + return predicate.Site(sql.FieldEQ(FieldSortOrder, v)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.Site { + return predicate.Site(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.Site { + return predicate.Site(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.Site { + return predicate.Site(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.Site { + return predicate.Site(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.Site { + return predicate.Site(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.Site { + return predicate.Site(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.Site { + return predicate.Site(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.Site { + return predicate.Site(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.Site { + return predicate.Site(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.Site { + return predicate.Site(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.Site { + return predicate.Site(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.Site { + return predicate.Site(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.Site { + return predicate.Site(sql.FieldContainsFold(FieldName, v)) +} + +// URLEQ applies the EQ predicate on the "url" field. +func URLEQ(v string) predicate.Site { + return predicate.Site(sql.FieldEQ(FieldURL, v)) +} + +// URLNEQ applies the NEQ predicate on the "url" field. +func URLNEQ(v string) predicate.Site { + return predicate.Site(sql.FieldNEQ(FieldURL, v)) +} + +// URLIn applies the In predicate on the "url" field. +func URLIn(vs ...string) predicate.Site { + return predicate.Site(sql.FieldIn(FieldURL, vs...)) +} + +// URLNotIn applies the NotIn predicate on the "url" field. +func URLNotIn(vs ...string) predicate.Site { + return predicate.Site(sql.FieldNotIn(FieldURL, vs...)) +} + +// URLGT applies the GT predicate on the "url" field. +func URLGT(v string) predicate.Site { + return predicate.Site(sql.FieldGT(FieldURL, v)) +} + +// URLGTE applies the GTE predicate on the "url" field. +func URLGTE(v string) predicate.Site { + return predicate.Site(sql.FieldGTE(FieldURL, v)) +} + +// URLLT applies the LT predicate on the "url" field. +func URLLT(v string) predicate.Site { + return predicate.Site(sql.FieldLT(FieldURL, v)) +} + +// URLLTE applies the LTE predicate on the "url" field. +func URLLTE(v string) predicate.Site { + return predicate.Site(sql.FieldLTE(FieldURL, v)) +} + +// URLContains applies the Contains predicate on the "url" field. +func URLContains(v string) predicate.Site { + return predicate.Site(sql.FieldContains(FieldURL, v)) +} + +// URLHasPrefix applies the HasPrefix predicate on the "url" field. +func URLHasPrefix(v string) predicate.Site { + return predicate.Site(sql.FieldHasPrefix(FieldURL, v)) +} + +// URLHasSuffix applies the HasSuffix predicate on the "url" field. +func URLHasSuffix(v string) predicate.Site { + return predicate.Site(sql.FieldHasSuffix(FieldURL, v)) +} + +// URLEqualFold applies the EqualFold predicate on the "url" field. +func URLEqualFold(v string) predicate.Site { + return predicate.Site(sql.FieldEqualFold(FieldURL, v)) +} + +// URLContainsFold applies the ContainsFold predicate on the "url" field. +func URLContainsFold(v string) predicate.Site { + return predicate.Site(sql.FieldContainsFold(FieldURL, v)) +} + +// IconEQ applies the EQ predicate on the "icon" field. +func IconEQ(v string) predicate.Site { + return predicate.Site(sql.FieldEQ(FieldIcon, v)) +} + +// IconNEQ applies the NEQ predicate on the "icon" field. +func IconNEQ(v string) predicate.Site { + return predicate.Site(sql.FieldNEQ(FieldIcon, v)) +} + +// IconIn applies the In predicate on the "icon" field. +func IconIn(vs ...string) predicate.Site { + return predicate.Site(sql.FieldIn(FieldIcon, vs...)) +} + +// IconNotIn applies the NotIn predicate on the "icon" field. +func IconNotIn(vs ...string) predicate.Site { + return predicate.Site(sql.FieldNotIn(FieldIcon, vs...)) +} + +// IconGT applies the GT predicate on the "icon" field. +func IconGT(v string) predicate.Site { + return predicate.Site(sql.FieldGT(FieldIcon, v)) +} + +// IconGTE applies the GTE predicate on the "icon" field. +func IconGTE(v string) predicate.Site { + return predicate.Site(sql.FieldGTE(FieldIcon, v)) +} + +// IconLT applies the LT predicate on the "icon" field. +func IconLT(v string) predicate.Site { + return predicate.Site(sql.FieldLT(FieldIcon, v)) +} + +// IconLTE applies the LTE predicate on the "icon" field. +func IconLTE(v string) predicate.Site { + return predicate.Site(sql.FieldLTE(FieldIcon, v)) +} + +// IconContains applies the Contains predicate on the "icon" field. +func IconContains(v string) predicate.Site { + return predicate.Site(sql.FieldContains(FieldIcon, v)) +} + +// IconHasPrefix applies the HasPrefix predicate on the "icon" field. +func IconHasPrefix(v string) predicate.Site { + return predicate.Site(sql.FieldHasPrefix(FieldIcon, v)) +} + +// IconHasSuffix applies the HasSuffix predicate on the "icon" field. +func IconHasSuffix(v string) predicate.Site { + return predicate.Site(sql.FieldHasSuffix(FieldIcon, v)) +} + +// IconEqualFold applies the EqualFold predicate on the "icon" field. +func IconEqualFold(v string) predicate.Site { + return predicate.Site(sql.FieldEqualFold(FieldIcon, v)) +} + +// IconContainsFold applies the ContainsFold predicate on the "icon" field. +func IconContainsFold(v string) predicate.Site { + return predicate.Site(sql.FieldContainsFold(FieldIcon, v)) +} + +// SortOrderEQ applies the EQ predicate on the "sort_order" field. +func SortOrderEQ(v int) predicate.Site { + return predicate.Site(sql.FieldEQ(FieldSortOrder, v)) +} + +// SortOrderNEQ applies the NEQ predicate on the "sort_order" field. +func SortOrderNEQ(v int) predicate.Site { + return predicate.Site(sql.FieldNEQ(FieldSortOrder, v)) +} + +// SortOrderIn applies the In predicate on the "sort_order" field. +func SortOrderIn(vs ...int) predicate.Site { + return predicate.Site(sql.FieldIn(FieldSortOrder, vs...)) +} + +// SortOrderNotIn applies the NotIn predicate on the "sort_order" field. +func SortOrderNotIn(vs ...int) predicate.Site { + return predicate.Site(sql.FieldNotIn(FieldSortOrder, vs...)) +} + +// SortOrderGT applies the GT predicate on the "sort_order" field. +func SortOrderGT(v int) predicate.Site { + return predicate.Site(sql.FieldGT(FieldSortOrder, v)) +} + +// SortOrderGTE applies the GTE predicate on the "sort_order" field. +func SortOrderGTE(v int) predicate.Site { + return predicate.Site(sql.FieldGTE(FieldSortOrder, v)) +} + +// SortOrderLT applies the LT predicate on the "sort_order" field. +func SortOrderLT(v int) predicate.Site { + return predicate.Site(sql.FieldLT(FieldSortOrder, v)) +} + +// SortOrderLTE applies the LTE predicate on the "sort_order" field. +func SortOrderLTE(v int) predicate.Site { + return predicate.Site(sql.FieldLTE(FieldSortOrder, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Site) predicate.Site { + return predicate.Site(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Site) predicate.Site { + return predicate.Site(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Site) predicate.Site { + return predicate.Site(sql.NotPredicates(p)) +} diff --git a/internal/ent/site_create.go b/internal/ent/site_create.go new file mode 100644 index 0000000..3c91ff3 --- /dev/null +++ b/internal/ent/site_create.go @@ -0,0 +1,252 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "home-vue-go/internal/ent/site" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// SiteCreate is the builder for creating a Site entity. +type SiteCreate struct { + config + mutation *SiteMutation + hooks []Hook +} + +// SetName sets the "name" field. +func (_c *SiteCreate) SetName(v string) *SiteCreate { + _c.mutation.SetName(v) + return _c +} + +// SetURL sets the "url" field. +func (_c *SiteCreate) SetURL(v string) *SiteCreate { + _c.mutation.SetURL(v) + return _c +} + +// SetIcon sets the "icon" field. +func (_c *SiteCreate) SetIcon(v string) *SiteCreate { + _c.mutation.SetIcon(v) + return _c +} + +// SetSortOrder sets the "sort_order" field. +func (_c *SiteCreate) SetSortOrder(v int) *SiteCreate { + _c.mutation.SetSortOrder(v) + return _c +} + +// SetNillableSortOrder sets the "sort_order" field if the given value is not nil. +func (_c *SiteCreate) SetNillableSortOrder(v *int) *SiteCreate { + if v != nil { + _c.SetSortOrder(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *SiteCreate) SetID(v int) *SiteCreate { + _c.mutation.SetID(v) + return _c +} + +// Mutation returns the SiteMutation object of the builder. +func (_c *SiteCreate) Mutation() *SiteMutation { + return _c.mutation +} + +// Save creates the Site in the database. +func (_c *SiteCreate) Save(ctx context.Context) (*Site, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *SiteCreate) SaveX(ctx context.Context) *Site { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *SiteCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *SiteCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *SiteCreate) defaults() { + if _, ok := _c.mutation.SortOrder(); !ok { + v := site.DefaultSortOrder + _c.mutation.SetSortOrder(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *SiteCreate) check() error { + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Site.name"`)} + } + if _, ok := _c.mutation.URL(); !ok { + return &ValidationError{Name: "url", err: errors.New(`ent: missing required field "Site.url"`)} + } + if _, ok := _c.mutation.Icon(); !ok { + return &ValidationError{Name: "icon", err: errors.New(`ent: missing required field "Site.icon"`)} + } + if _, ok := _c.mutation.SortOrder(); !ok { + return &ValidationError{Name: "sort_order", err: errors.New(`ent: missing required field "Site.sort_order"`)} + } + return nil +} + +func (_c *SiteCreate) sqlSave(ctx context.Context) (*Site, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != _node.ID { + id := _spec.ID.Value.(int64) + _node.ID = int(id) + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *SiteCreate) createSpec() (*Site, *sqlgraph.CreateSpec) { + var ( + _node = &Site{config: _c.config} + _spec = sqlgraph.NewCreateSpec(site.Table, sqlgraph.NewFieldSpec(site.FieldID, field.TypeInt)) + ) + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(site.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.URL(); ok { + _spec.SetField(site.FieldURL, field.TypeString, value) + _node.URL = value + } + if value, ok := _c.mutation.Icon(); ok { + _spec.SetField(site.FieldIcon, field.TypeString, value) + _node.Icon = value + } + if value, ok := _c.mutation.SortOrder(); ok { + _spec.SetField(site.FieldSortOrder, field.TypeInt, value) + _node.SortOrder = value + } + return _node, _spec +} + +// SiteCreateBulk is the builder for creating many Site entities in bulk. +type SiteCreateBulk struct { + config + err error + builders []*SiteCreate +} + +// Save creates the Site entities in the database. +func (_c *SiteCreateBulk) Save(ctx context.Context) ([]*Site, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Site, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*SiteMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil && nodes[i].ID == 0 { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *SiteCreateBulk) SaveX(ctx context.Context) []*Site { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *SiteCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *SiteCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/ent/site_delete.go b/internal/ent/site_delete.go new file mode 100644 index 0000000..96cd9c3 --- /dev/null +++ b/internal/ent/site_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "home-vue-go/internal/ent/predicate" + "home-vue-go/internal/ent/site" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// SiteDelete is the builder for deleting a Site entity. +type SiteDelete struct { + config + hooks []Hook + mutation *SiteMutation +} + +// Where appends a list predicates to the SiteDelete builder. +func (_d *SiteDelete) Where(ps ...predicate.Site) *SiteDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *SiteDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *SiteDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *SiteDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(site.Table, sqlgraph.NewFieldSpec(site.FieldID, field.TypeInt)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// SiteDeleteOne is the builder for deleting a single Site entity. +type SiteDeleteOne struct { + _d *SiteDelete +} + +// Where appends a list predicates to the SiteDelete builder. +func (_d *SiteDeleteOne) Where(ps ...predicate.Site) *SiteDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *SiteDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{site.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *SiteDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/ent/site_query.go b/internal/ent/site_query.go new file mode 100644 index 0000000..b1bbf77 --- /dev/null +++ b/internal/ent/site_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "home-vue-go/internal/ent/predicate" + "home-vue-go/internal/ent/site" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// SiteQuery is the builder for querying Site entities. +type SiteQuery struct { + config + ctx *QueryContext + order []site.OrderOption + inters []Interceptor + predicates []predicate.Site + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the SiteQuery builder. +func (_q *SiteQuery) Where(ps ...predicate.Site) *SiteQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *SiteQuery) Limit(limit int) *SiteQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *SiteQuery) Offset(offset int) *SiteQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *SiteQuery) Unique(unique bool) *SiteQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *SiteQuery) Order(o ...site.OrderOption) *SiteQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first Site entity from the query. +// Returns a *NotFoundError when no Site was found. +func (_q *SiteQuery) First(ctx context.Context) (*Site, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{site.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *SiteQuery) FirstX(ctx context.Context) *Site { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Site ID from the query. +// Returns a *NotFoundError when no Site ID was found. +func (_q *SiteQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{site.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *SiteQuery) FirstIDX(ctx context.Context) int { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Site entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Site entity is found. +// Returns a *NotFoundError when no Site entities are found. +func (_q *SiteQuery) Only(ctx context.Context) (*Site, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{site.Label} + default: + return nil, &NotSingularError{site.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *SiteQuery) OnlyX(ctx context.Context) *Site { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Site ID in the query. +// Returns a *NotSingularError when more than one Site ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *SiteQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{site.Label} + default: + err = &NotSingularError{site.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *SiteQuery) OnlyIDX(ctx context.Context) int { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Sites. +func (_q *SiteQuery) All(ctx context.Context) ([]*Site, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Site, *SiteQuery]() + return withInterceptors[[]*Site](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *SiteQuery) AllX(ctx context.Context) []*Site { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Site IDs. +func (_q *SiteQuery) IDs(ctx context.Context) (ids []int, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(site.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *SiteQuery) IDsX(ctx context.Context) []int { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *SiteQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*SiteQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *SiteQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *SiteQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *SiteQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the SiteQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *SiteQuery) Clone() *SiteQuery { + if _q == nil { + return nil + } + return &SiteQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]site.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Site{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Site.Query(). +// GroupBy(site.FieldName). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *SiteQuery) GroupBy(field string, fields ...string) *SiteGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &SiteGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = site.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// } +// +// client.Site.Query(). +// Select(site.FieldName). +// Scan(ctx, &v) +func (_q *SiteQuery) Select(fields ...string) *SiteSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &SiteSelect{SiteQuery: _q} + sbuild.label = site.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a SiteSelect configured with the given aggregations. +func (_q *SiteQuery) Aggregate(fns ...AggregateFunc) *SiteSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *SiteQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !site.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *SiteQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Site, error) { + var ( + nodes = []*Site{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Site).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Site{config: _q.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (_q *SiteQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *SiteQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(site.Table, site.Columns, sqlgraph.NewFieldSpec(site.FieldID, field.TypeInt)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, site.FieldID) + for i := range fields { + if fields[i] != site.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *SiteQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(site.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = site.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// SiteGroupBy is the group-by builder for Site entities. +type SiteGroupBy struct { + selector + build *SiteQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *SiteGroupBy) Aggregate(fns ...AggregateFunc) *SiteGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *SiteGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*SiteQuery, *SiteGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *SiteGroupBy) sqlScan(ctx context.Context, root *SiteQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// SiteSelect is the builder for selecting fields of Site entities. +type SiteSelect struct { + *SiteQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *SiteSelect) Aggregate(fns ...AggregateFunc) *SiteSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *SiteSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*SiteQuery, *SiteSelect](ctx, _s.SiteQuery, _s, _s.inters, v) +} + +func (_s *SiteSelect) sqlScan(ctx context.Context, root *SiteQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/internal/ent/site_update.go b/internal/ent/site_update.go new file mode 100644 index 0000000..694a9fd --- /dev/null +++ b/internal/ent/site_update.go @@ -0,0 +1,331 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "home-vue-go/internal/ent/predicate" + "home-vue-go/internal/ent/site" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// SiteUpdate is the builder for updating Site entities. +type SiteUpdate struct { + config + hooks []Hook + mutation *SiteMutation +} + +// Where appends a list predicates to the SiteUpdate builder. +func (_u *SiteUpdate) Where(ps ...predicate.Site) *SiteUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetName sets the "name" field. +func (_u *SiteUpdate) SetName(v string) *SiteUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *SiteUpdate) SetNillableName(v *string) *SiteUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetURL sets the "url" field. +func (_u *SiteUpdate) SetURL(v string) *SiteUpdate { + _u.mutation.SetURL(v) + return _u +} + +// SetNillableURL sets the "url" field if the given value is not nil. +func (_u *SiteUpdate) SetNillableURL(v *string) *SiteUpdate { + if v != nil { + _u.SetURL(*v) + } + return _u +} + +// SetIcon sets the "icon" field. +func (_u *SiteUpdate) SetIcon(v string) *SiteUpdate { + _u.mutation.SetIcon(v) + return _u +} + +// SetNillableIcon sets the "icon" field if the given value is not nil. +func (_u *SiteUpdate) SetNillableIcon(v *string) *SiteUpdate { + if v != nil { + _u.SetIcon(*v) + } + return _u +} + +// SetSortOrder sets the "sort_order" field. +func (_u *SiteUpdate) SetSortOrder(v int) *SiteUpdate { + _u.mutation.ResetSortOrder() + _u.mutation.SetSortOrder(v) + return _u +} + +// SetNillableSortOrder sets the "sort_order" field if the given value is not nil. +func (_u *SiteUpdate) SetNillableSortOrder(v *int) *SiteUpdate { + if v != nil { + _u.SetSortOrder(*v) + } + return _u +} + +// AddSortOrder adds value to the "sort_order" field. +func (_u *SiteUpdate) AddSortOrder(v int) *SiteUpdate { + _u.mutation.AddSortOrder(v) + return _u +} + +// Mutation returns the SiteMutation object of the builder. +func (_u *SiteUpdate) Mutation() *SiteMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *SiteUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *SiteUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *SiteUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *SiteUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *SiteUpdate) sqlSave(ctx context.Context) (_node int, err error) { + _spec := sqlgraph.NewUpdateSpec(site.Table, site.Columns, sqlgraph.NewFieldSpec(site.FieldID, field.TypeInt)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(site.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.URL(); ok { + _spec.SetField(site.FieldURL, field.TypeString, value) + } + if value, ok := _u.mutation.Icon(); ok { + _spec.SetField(site.FieldIcon, field.TypeString, value) + } + if value, ok := _u.mutation.SortOrder(); ok { + _spec.SetField(site.FieldSortOrder, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedSortOrder(); ok { + _spec.AddField(site.FieldSortOrder, field.TypeInt, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{site.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// SiteUpdateOne is the builder for updating a single Site entity. +type SiteUpdateOne struct { + config + fields []string + hooks []Hook + mutation *SiteMutation +} + +// SetName sets the "name" field. +func (_u *SiteUpdateOne) SetName(v string) *SiteUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *SiteUpdateOne) SetNillableName(v *string) *SiteUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetURL sets the "url" field. +func (_u *SiteUpdateOne) SetURL(v string) *SiteUpdateOne { + _u.mutation.SetURL(v) + return _u +} + +// SetNillableURL sets the "url" field if the given value is not nil. +func (_u *SiteUpdateOne) SetNillableURL(v *string) *SiteUpdateOne { + if v != nil { + _u.SetURL(*v) + } + return _u +} + +// SetIcon sets the "icon" field. +func (_u *SiteUpdateOne) SetIcon(v string) *SiteUpdateOne { + _u.mutation.SetIcon(v) + return _u +} + +// SetNillableIcon sets the "icon" field if the given value is not nil. +func (_u *SiteUpdateOne) SetNillableIcon(v *string) *SiteUpdateOne { + if v != nil { + _u.SetIcon(*v) + } + return _u +} + +// SetSortOrder sets the "sort_order" field. +func (_u *SiteUpdateOne) SetSortOrder(v int) *SiteUpdateOne { + _u.mutation.ResetSortOrder() + _u.mutation.SetSortOrder(v) + return _u +} + +// SetNillableSortOrder sets the "sort_order" field if the given value is not nil. +func (_u *SiteUpdateOne) SetNillableSortOrder(v *int) *SiteUpdateOne { + if v != nil { + _u.SetSortOrder(*v) + } + return _u +} + +// AddSortOrder adds value to the "sort_order" field. +func (_u *SiteUpdateOne) AddSortOrder(v int) *SiteUpdateOne { + _u.mutation.AddSortOrder(v) + return _u +} + +// Mutation returns the SiteMutation object of the builder. +func (_u *SiteUpdateOne) Mutation() *SiteMutation { + return _u.mutation +} + +// Where appends a list predicates to the SiteUpdate builder. +func (_u *SiteUpdateOne) Where(ps ...predicate.Site) *SiteUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *SiteUpdateOne) Select(field string, fields ...string) *SiteUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Site entity. +func (_u *SiteUpdateOne) Save(ctx context.Context) (*Site, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *SiteUpdateOne) SaveX(ctx context.Context) *Site { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *SiteUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *SiteUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *SiteUpdateOne) sqlSave(ctx context.Context) (_node *Site, err error) { + _spec := sqlgraph.NewUpdateSpec(site.Table, site.Columns, sqlgraph.NewFieldSpec(site.FieldID, field.TypeInt)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Site.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, site.FieldID) + for _, f := range fields { + if !site.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != site.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(site.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.URL(); ok { + _spec.SetField(site.FieldURL, field.TypeString, value) + } + if value, ok := _u.mutation.Icon(); ok { + _spec.SetField(site.FieldIcon, field.TypeString, value) + } + if value, ok := _u.mutation.SortOrder(); ok { + _spec.SetField(site.FieldSortOrder, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedSortOrder(); ok { + _spec.AddField(site.FieldSortOrder, field.TypeInt, value) + } + _node = &Site{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{site.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/internal/ent/siteconfig.go b/internal/ent/siteconfig.go new file mode 100644 index 0000000..1b576de --- /dev/null +++ b/internal/ent/siteconfig.go @@ -0,0 +1,257 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "home-vue-go/internal/ent/siteconfig" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// SiteConfig is the model entity for the SiteConfig schema. +type SiteConfig struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // 站点名称 + SiteName string `json:"site_name,omitempty"` + // 站点URL + SiteURL string `json:"site_url,omitempty"` + // 站点图标 + SiteIcon string `json:"site_icon,omitempty"` + // 站点描述 + SiteDescription string `json:"site_description,omitempty"` + // 站点关键词 + SiteKeywords string `json:"site_keywords,omitempty"` + // 用户名 + UserName string `json:"user_name,omitempty"` + // 头像URL + ProfileImageURL string `json:"profile_image_url,omitempty"` + // ICP备案号 + IcpNumber string `json:"icp_number,omitempty"` + // 公安备案号 + PoliceNumber string `json:"police_number,omitempty"` + // 网页标题 + PageTitle string `json:"page_title,omitempty"` + // 网页图标路径 + Favicon string `json:"favicon,omitempty"` + // Umami统计脚本地址 + UmamiScript string `json:"umami_script,omitempty"` + // Umami统计网站ID + UmamiWebsiteID string `json:"umami_website_id,omitempty"` + // 图标库CDN地址 + IconLibrary string `json:"icon_library,omitempty"` + // 字体库CDN地址 + FontLibrary string `json:"font_library,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*SiteConfig) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case siteconfig.FieldID: + values[i] = new(sql.NullInt64) + case siteconfig.FieldSiteName, siteconfig.FieldSiteURL, siteconfig.FieldSiteIcon, siteconfig.FieldSiteDescription, siteconfig.FieldSiteKeywords, siteconfig.FieldUserName, siteconfig.FieldProfileImageURL, siteconfig.FieldIcpNumber, siteconfig.FieldPoliceNumber, siteconfig.FieldPageTitle, siteconfig.FieldFavicon, siteconfig.FieldUmamiScript, siteconfig.FieldUmamiWebsiteID, siteconfig.FieldIconLibrary, siteconfig.FieldFontLibrary: + values[i] = new(sql.NullString) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the SiteConfig fields. +func (_m *SiteConfig) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case siteconfig.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int(value.Int64) + case siteconfig.FieldSiteName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field site_name", values[i]) + } else if value.Valid { + _m.SiteName = value.String + } + case siteconfig.FieldSiteURL: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field site_url", values[i]) + } else if value.Valid { + _m.SiteURL = value.String + } + case siteconfig.FieldSiteIcon: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field site_icon", values[i]) + } else if value.Valid { + _m.SiteIcon = value.String + } + case siteconfig.FieldSiteDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field site_description", values[i]) + } else if value.Valid { + _m.SiteDescription = value.String + } + case siteconfig.FieldSiteKeywords: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field site_keywords", values[i]) + } else if value.Valid { + _m.SiteKeywords = value.String + } + case siteconfig.FieldUserName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field user_name", values[i]) + } else if value.Valid { + _m.UserName = value.String + } + case siteconfig.FieldProfileImageURL: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field profile_image_url", values[i]) + } else if value.Valid { + _m.ProfileImageURL = value.String + } + case siteconfig.FieldIcpNumber: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field icp_number", values[i]) + } else if value.Valid { + _m.IcpNumber = value.String + } + case siteconfig.FieldPoliceNumber: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field police_number", values[i]) + } else if value.Valid { + _m.PoliceNumber = value.String + } + case siteconfig.FieldPageTitle: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field page_title", values[i]) + } else if value.Valid { + _m.PageTitle = value.String + } + case siteconfig.FieldFavicon: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field favicon", values[i]) + } else if value.Valid { + _m.Favicon = value.String + } + case siteconfig.FieldUmamiScript: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field umami_script", values[i]) + } else if value.Valid { + _m.UmamiScript = value.String + } + case siteconfig.FieldUmamiWebsiteID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field umami_website_id", values[i]) + } else if value.Valid { + _m.UmamiWebsiteID = value.String + } + case siteconfig.FieldIconLibrary: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field icon_library", values[i]) + } else if value.Valid { + _m.IconLibrary = value.String + } + case siteconfig.FieldFontLibrary: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field font_library", values[i]) + } else if value.Valid { + _m.FontLibrary = value.String + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the SiteConfig. +// This includes values selected through modifiers, order, etc. +func (_m *SiteConfig) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this SiteConfig. +// Note that you need to call SiteConfig.Unwrap() before calling this method if this SiteConfig +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *SiteConfig) Update() *SiteConfigUpdateOne { + return NewSiteConfigClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the SiteConfig entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *SiteConfig) Unwrap() *SiteConfig { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: SiteConfig is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *SiteConfig) String() string { + var builder strings.Builder + builder.WriteString("SiteConfig(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("site_name=") + builder.WriteString(_m.SiteName) + builder.WriteString(", ") + builder.WriteString("site_url=") + builder.WriteString(_m.SiteURL) + builder.WriteString(", ") + builder.WriteString("site_icon=") + builder.WriteString(_m.SiteIcon) + builder.WriteString(", ") + builder.WriteString("site_description=") + builder.WriteString(_m.SiteDescription) + builder.WriteString(", ") + builder.WriteString("site_keywords=") + builder.WriteString(_m.SiteKeywords) + builder.WriteString(", ") + builder.WriteString("user_name=") + builder.WriteString(_m.UserName) + builder.WriteString(", ") + builder.WriteString("profile_image_url=") + builder.WriteString(_m.ProfileImageURL) + builder.WriteString(", ") + builder.WriteString("icp_number=") + builder.WriteString(_m.IcpNumber) + builder.WriteString(", ") + builder.WriteString("police_number=") + builder.WriteString(_m.PoliceNumber) + builder.WriteString(", ") + builder.WriteString("page_title=") + builder.WriteString(_m.PageTitle) + builder.WriteString(", ") + builder.WriteString("favicon=") + builder.WriteString(_m.Favicon) + builder.WriteString(", ") + builder.WriteString("umami_script=") + builder.WriteString(_m.UmamiScript) + builder.WriteString(", ") + builder.WriteString("umami_website_id=") + builder.WriteString(_m.UmamiWebsiteID) + builder.WriteString(", ") + builder.WriteString("icon_library=") + builder.WriteString(_m.IconLibrary) + builder.WriteString(", ") + builder.WriteString("font_library=") + builder.WriteString(_m.FontLibrary) + builder.WriteByte(')') + return builder.String() +} + +// SiteConfigs is a parsable slice of SiteConfig. +type SiteConfigs []*SiteConfig diff --git a/internal/ent/siteconfig/siteconfig.go b/internal/ent/siteconfig/siteconfig.go new file mode 100644 index 0000000..79992fa --- /dev/null +++ b/internal/ent/siteconfig/siteconfig.go @@ -0,0 +1,164 @@ +// Code generated by ent, DO NOT EDIT. + +package siteconfig + +import ( + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the siteconfig type in the database. + Label = "site_config" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldSiteName holds the string denoting the site_name field in the database. + FieldSiteName = "site_name" + // FieldSiteURL holds the string denoting the site_url field in the database. + FieldSiteURL = "site_url" + // FieldSiteIcon holds the string denoting the site_icon field in the database. + FieldSiteIcon = "site_icon" + // FieldSiteDescription holds the string denoting the site_description field in the database. + FieldSiteDescription = "site_description" + // FieldSiteKeywords holds the string denoting the site_keywords field in the database. + FieldSiteKeywords = "site_keywords" + // FieldUserName holds the string denoting the user_name field in the database. + FieldUserName = "user_name" + // FieldProfileImageURL holds the string denoting the profile_image_url field in the database. + FieldProfileImageURL = "profile_image_url" + // FieldIcpNumber holds the string denoting the icp_number field in the database. + FieldIcpNumber = "icp_number" + // FieldPoliceNumber holds the string denoting the police_number field in the database. + FieldPoliceNumber = "police_number" + // FieldPageTitle holds the string denoting the page_title field in the database. + FieldPageTitle = "page_title" + // FieldFavicon holds the string denoting the favicon field in the database. + FieldFavicon = "favicon" + // FieldUmamiScript holds the string denoting the umami_script field in the database. + FieldUmamiScript = "umami_script" + // FieldUmamiWebsiteID holds the string denoting the umami_website_id field in the database. + FieldUmamiWebsiteID = "umami_website_id" + // FieldIconLibrary holds the string denoting the icon_library field in the database. + FieldIconLibrary = "icon_library" + // FieldFontLibrary holds the string denoting the font_library field in the database. + FieldFontLibrary = "font_library" + // Table holds the table name of the siteconfig in the database. + Table = "site_configs" +) + +// Columns holds all SQL columns for siteconfig fields. +var Columns = []string{ + FieldID, + FieldSiteName, + FieldSiteURL, + FieldSiteIcon, + FieldSiteDescription, + FieldSiteKeywords, + FieldUserName, + FieldProfileImageURL, + FieldIcpNumber, + FieldPoliceNumber, + FieldPageTitle, + FieldFavicon, + FieldUmamiScript, + FieldUmamiWebsiteID, + FieldIconLibrary, + FieldFontLibrary, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultID holds the default value on creation for the "id" field. + DefaultID int +) + +// OrderOption defines the ordering options for the SiteConfig 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() +} + +// BySiteName orders the results by the site_name field. +func BySiteName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSiteName, opts...).ToFunc() +} + +// BySiteURL orders the results by the site_url field. +func BySiteURL(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSiteURL, opts...).ToFunc() +} + +// BySiteIcon orders the results by the site_icon field. +func BySiteIcon(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSiteIcon, opts...).ToFunc() +} + +// BySiteDescription orders the results by the site_description field. +func BySiteDescription(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSiteDescription, opts...).ToFunc() +} + +// BySiteKeywords orders the results by the site_keywords field. +func BySiteKeywords(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSiteKeywords, opts...).ToFunc() +} + +// ByUserName orders the results by the user_name field. +func ByUserName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUserName, opts...).ToFunc() +} + +// ByProfileImageURL orders the results by the profile_image_url field. +func ByProfileImageURL(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldProfileImageURL, opts...).ToFunc() +} + +// ByIcpNumber orders the results by the icp_number field. +func ByIcpNumber(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIcpNumber, opts...).ToFunc() +} + +// ByPoliceNumber orders the results by the police_number field. +func ByPoliceNumber(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPoliceNumber, opts...).ToFunc() +} + +// ByPageTitle orders the results by the page_title field. +func ByPageTitle(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPageTitle, opts...).ToFunc() +} + +// ByFavicon orders the results by the favicon field. +func ByFavicon(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFavicon, opts...).ToFunc() +} + +// ByUmamiScript orders the results by the umami_script field. +func ByUmamiScript(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUmamiScript, opts...).ToFunc() +} + +// ByUmamiWebsiteID orders the results by the umami_website_id field. +func ByUmamiWebsiteID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUmamiWebsiteID, opts...).ToFunc() +} + +// ByIconLibrary orders the results by the icon_library field. +func ByIconLibrary(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIconLibrary, opts...).ToFunc() +} + +// ByFontLibrary orders the results by the font_library field. +func ByFontLibrary(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFontLibrary, opts...).ToFunc() +} diff --git a/internal/ent/siteconfig/where.go b/internal/ent/siteconfig/where.go new file mode 100644 index 0000000..e6b597c --- /dev/null +++ b/internal/ent/siteconfig/where.go @@ -0,0 +1,1209 @@ +// Code generated by ent, DO NOT EDIT. + +package siteconfig + +import ( + "home-vue-go/internal/ent/predicate" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLTE(FieldID, id)) +} + +// SiteName applies equality check predicate on the "site_name" field. It's identical to SiteNameEQ. +func SiteName(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldSiteName, v)) +} + +// SiteURL applies equality check predicate on the "site_url" field. It's identical to SiteURLEQ. +func SiteURL(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldSiteURL, v)) +} + +// SiteIcon applies equality check predicate on the "site_icon" field. It's identical to SiteIconEQ. +func SiteIcon(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldSiteIcon, v)) +} + +// SiteDescription applies equality check predicate on the "site_description" field. It's identical to SiteDescriptionEQ. +func SiteDescription(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldSiteDescription, v)) +} + +// SiteKeywords applies equality check predicate on the "site_keywords" field. It's identical to SiteKeywordsEQ. +func SiteKeywords(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldSiteKeywords, v)) +} + +// UserName applies equality check predicate on the "user_name" field. It's identical to UserNameEQ. +func UserName(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldUserName, v)) +} + +// ProfileImageURL applies equality check predicate on the "profile_image_url" field. It's identical to ProfileImageURLEQ. +func ProfileImageURL(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldProfileImageURL, v)) +} + +// IcpNumber applies equality check predicate on the "icp_number" field. It's identical to IcpNumberEQ. +func IcpNumber(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldIcpNumber, v)) +} + +// PoliceNumber applies equality check predicate on the "police_number" field. It's identical to PoliceNumberEQ. +func PoliceNumber(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldPoliceNumber, v)) +} + +// PageTitle applies equality check predicate on the "page_title" field. It's identical to PageTitleEQ. +func PageTitle(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldPageTitle, v)) +} + +// Favicon applies equality check predicate on the "favicon" field. It's identical to FaviconEQ. +func Favicon(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldFavicon, v)) +} + +// UmamiScript applies equality check predicate on the "umami_script" field. It's identical to UmamiScriptEQ. +func UmamiScript(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldUmamiScript, v)) +} + +// UmamiWebsiteID applies equality check predicate on the "umami_website_id" field. It's identical to UmamiWebsiteIDEQ. +func UmamiWebsiteID(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldUmamiWebsiteID, v)) +} + +// IconLibrary applies equality check predicate on the "icon_library" field. It's identical to IconLibraryEQ. +func IconLibrary(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldIconLibrary, v)) +} + +// FontLibrary applies equality check predicate on the "font_library" field. It's identical to FontLibraryEQ. +func FontLibrary(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldFontLibrary, v)) +} + +// SiteNameEQ applies the EQ predicate on the "site_name" field. +func SiteNameEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldSiteName, v)) +} + +// SiteNameNEQ applies the NEQ predicate on the "site_name" field. +func SiteNameNEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNEQ(FieldSiteName, v)) +} + +// SiteNameIn applies the In predicate on the "site_name" field. +func SiteNameIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIn(FieldSiteName, vs...)) +} + +// SiteNameNotIn applies the NotIn predicate on the "site_name" field. +func SiteNameNotIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotIn(FieldSiteName, vs...)) +} + +// SiteNameGT applies the GT predicate on the "site_name" field. +func SiteNameGT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGT(FieldSiteName, v)) +} + +// SiteNameGTE applies the GTE predicate on the "site_name" field. +func SiteNameGTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGTE(FieldSiteName, v)) +} + +// SiteNameLT applies the LT predicate on the "site_name" field. +func SiteNameLT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLT(FieldSiteName, v)) +} + +// SiteNameLTE applies the LTE predicate on the "site_name" field. +func SiteNameLTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLTE(FieldSiteName, v)) +} + +// SiteNameContains applies the Contains predicate on the "site_name" field. +func SiteNameContains(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContains(FieldSiteName, v)) +} + +// SiteNameHasPrefix applies the HasPrefix predicate on the "site_name" field. +func SiteNameHasPrefix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasPrefix(FieldSiteName, v)) +} + +// SiteNameHasSuffix applies the HasSuffix predicate on the "site_name" field. +func SiteNameHasSuffix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasSuffix(FieldSiteName, v)) +} + +// SiteNameEqualFold applies the EqualFold predicate on the "site_name" field. +func SiteNameEqualFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEqualFold(FieldSiteName, v)) +} + +// SiteNameContainsFold applies the ContainsFold predicate on the "site_name" field. +func SiteNameContainsFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContainsFold(FieldSiteName, v)) +} + +// SiteURLEQ applies the EQ predicate on the "site_url" field. +func SiteURLEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldSiteURL, v)) +} + +// SiteURLNEQ applies the NEQ predicate on the "site_url" field. +func SiteURLNEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNEQ(FieldSiteURL, v)) +} + +// SiteURLIn applies the In predicate on the "site_url" field. +func SiteURLIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIn(FieldSiteURL, vs...)) +} + +// SiteURLNotIn applies the NotIn predicate on the "site_url" field. +func SiteURLNotIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotIn(FieldSiteURL, vs...)) +} + +// SiteURLGT applies the GT predicate on the "site_url" field. +func SiteURLGT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGT(FieldSiteURL, v)) +} + +// SiteURLGTE applies the GTE predicate on the "site_url" field. +func SiteURLGTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGTE(FieldSiteURL, v)) +} + +// SiteURLLT applies the LT predicate on the "site_url" field. +func SiteURLLT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLT(FieldSiteURL, v)) +} + +// SiteURLLTE applies the LTE predicate on the "site_url" field. +func SiteURLLTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLTE(FieldSiteURL, v)) +} + +// SiteURLContains applies the Contains predicate on the "site_url" field. +func SiteURLContains(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContains(FieldSiteURL, v)) +} + +// SiteURLHasPrefix applies the HasPrefix predicate on the "site_url" field. +func SiteURLHasPrefix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasPrefix(FieldSiteURL, v)) +} + +// SiteURLHasSuffix applies the HasSuffix predicate on the "site_url" field. +func SiteURLHasSuffix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasSuffix(FieldSiteURL, v)) +} + +// SiteURLEqualFold applies the EqualFold predicate on the "site_url" field. +func SiteURLEqualFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEqualFold(FieldSiteURL, v)) +} + +// SiteURLContainsFold applies the ContainsFold predicate on the "site_url" field. +func SiteURLContainsFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContainsFold(FieldSiteURL, v)) +} + +// SiteIconEQ applies the EQ predicate on the "site_icon" field. +func SiteIconEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldSiteIcon, v)) +} + +// SiteIconNEQ applies the NEQ predicate on the "site_icon" field. +func SiteIconNEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNEQ(FieldSiteIcon, v)) +} + +// SiteIconIn applies the In predicate on the "site_icon" field. +func SiteIconIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIn(FieldSiteIcon, vs...)) +} + +// SiteIconNotIn applies the NotIn predicate on the "site_icon" field. +func SiteIconNotIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotIn(FieldSiteIcon, vs...)) +} + +// SiteIconGT applies the GT predicate on the "site_icon" field. +func SiteIconGT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGT(FieldSiteIcon, v)) +} + +// SiteIconGTE applies the GTE predicate on the "site_icon" field. +func SiteIconGTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGTE(FieldSiteIcon, v)) +} + +// SiteIconLT applies the LT predicate on the "site_icon" field. +func SiteIconLT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLT(FieldSiteIcon, v)) +} + +// SiteIconLTE applies the LTE predicate on the "site_icon" field. +func SiteIconLTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLTE(FieldSiteIcon, v)) +} + +// SiteIconContains applies the Contains predicate on the "site_icon" field. +func SiteIconContains(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContains(FieldSiteIcon, v)) +} + +// SiteIconHasPrefix applies the HasPrefix predicate on the "site_icon" field. +func SiteIconHasPrefix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasPrefix(FieldSiteIcon, v)) +} + +// SiteIconHasSuffix applies the HasSuffix predicate on the "site_icon" field. +func SiteIconHasSuffix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasSuffix(FieldSiteIcon, v)) +} + +// SiteIconEqualFold applies the EqualFold predicate on the "site_icon" field. +func SiteIconEqualFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEqualFold(FieldSiteIcon, v)) +} + +// SiteIconContainsFold applies the ContainsFold predicate on the "site_icon" field. +func SiteIconContainsFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContainsFold(FieldSiteIcon, v)) +} + +// SiteDescriptionEQ applies the EQ predicate on the "site_description" field. +func SiteDescriptionEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldSiteDescription, v)) +} + +// SiteDescriptionNEQ applies the NEQ predicate on the "site_description" field. +func SiteDescriptionNEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNEQ(FieldSiteDescription, v)) +} + +// SiteDescriptionIn applies the In predicate on the "site_description" field. +func SiteDescriptionIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIn(FieldSiteDescription, vs...)) +} + +// SiteDescriptionNotIn applies the NotIn predicate on the "site_description" field. +func SiteDescriptionNotIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotIn(FieldSiteDescription, vs...)) +} + +// SiteDescriptionGT applies the GT predicate on the "site_description" field. +func SiteDescriptionGT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGT(FieldSiteDescription, v)) +} + +// SiteDescriptionGTE applies the GTE predicate on the "site_description" field. +func SiteDescriptionGTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGTE(FieldSiteDescription, v)) +} + +// SiteDescriptionLT applies the LT predicate on the "site_description" field. +func SiteDescriptionLT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLT(FieldSiteDescription, v)) +} + +// SiteDescriptionLTE applies the LTE predicate on the "site_description" field. +func SiteDescriptionLTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLTE(FieldSiteDescription, v)) +} + +// SiteDescriptionContains applies the Contains predicate on the "site_description" field. +func SiteDescriptionContains(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContains(FieldSiteDescription, v)) +} + +// SiteDescriptionHasPrefix applies the HasPrefix predicate on the "site_description" field. +func SiteDescriptionHasPrefix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasPrefix(FieldSiteDescription, v)) +} + +// SiteDescriptionHasSuffix applies the HasSuffix predicate on the "site_description" field. +func SiteDescriptionHasSuffix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasSuffix(FieldSiteDescription, v)) +} + +// SiteDescriptionEqualFold applies the EqualFold predicate on the "site_description" field. +func SiteDescriptionEqualFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEqualFold(FieldSiteDescription, v)) +} + +// SiteDescriptionContainsFold applies the ContainsFold predicate on the "site_description" field. +func SiteDescriptionContainsFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContainsFold(FieldSiteDescription, v)) +} + +// SiteKeywordsEQ applies the EQ predicate on the "site_keywords" field. +func SiteKeywordsEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldSiteKeywords, v)) +} + +// SiteKeywordsNEQ applies the NEQ predicate on the "site_keywords" field. +func SiteKeywordsNEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNEQ(FieldSiteKeywords, v)) +} + +// SiteKeywordsIn applies the In predicate on the "site_keywords" field. +func SiteKeywordsIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIn(FieldSiteKeywords, vs...)) +} + +// SiteKeywordsNotIn applies the NotIn predicate on the "site_keywords" field. +func SiteKeywordsNotIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotIn(FieldSiteKeywords, vs...)) +} + +// SiteKeywordsGT applies the GT predicate on the "site_keywords" field. +func SiteKeywordsGT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGT(FieldSiteKeywords, v)) +} + +// SiteKeywordsGTE applies the GTE predicate on the "site_keywords" field. +func SiteKeywordsGTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGTE(FieldSiteKeywords, v)) +} + +// SiteKeywordsLT applies the LT predicate on the "site_keywords" field. +func SiteKeywordsLT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLT(FieldSiteKeywords, v)) +} + +// SiteKeywordsLTE applies the LTE predicate on the "site_keywords" field. +func SiteKeywordsLTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLTE(FieldSiteKeywords, v)) +} + +// SiteKeywordsContains applies the Contains predicate on the "site_keywords" field. +func SiteKeywordsContains(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContains(FieldSiteKeywords, v)) +} + +// SiteKeywordsHasPrefix applies the HasPrefix predicate on the "site_keywords" field. +func SiteKeywordsHasPrefix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasPrefix(FieldSiteKeywords, v)) +} + +// SiteKeywordsHasSuffix applies the HasSuffix predicate on the "site_keywords" field. +func SiteKeywordsHasSuffix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasSuffix(FieldSiteKeywords, v)) +} + +// SiteKeywordsEqualFold applies the EqualFold predicate on the "site_keywords" field. +func SiteKeywordsEqualFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEqualFold(FieldSiteKeywords, v)) +} + +// SiteKeywordsContainsFold applies the ContainsFold predicate on the "site_keywords" field. +func SiteKeywordsContainsFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContainsFold(FieldSiteKeywords, v)) +} + +// UserNameEQ applies the EQ predicate on the "user_name" field. +func UserNameEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldUserName, v)) +} + +// UserNameNEQ applies the NEQ predicate on the "user_name" field. +func UserNameNEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNEQ(FieldUserName, v)) +} + +// UserNameIn applies the In predicate on the "user_name" field. +func UserNameIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIn(FieldUserName, vs...)) +} + +// UserNameNotIn applies the NotIn predicate on the "user_name" field. +func UserNameNotIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotIn(FieldUserName, vs...)) +} + +// UserNameGT applies the GT predicate on the "user_name" field. +func UserNameGT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGT(FieldUserName, v)) +} + +// UserNameGTE applies the GTE predicate on the "user_name" field. +func UserNameGTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGTE(FieldUserName, v)) +} + +// UserNameLT applies the LT predicate on the "user_name" field. +func UserNameLT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLT(FieldUserName, v)) +} + +// UserNameLTE applies the LTE predicate on the "user_name" field. +func UserNameLTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLTE(FieldUserName, v)) +} + +// UserNameContains applies the Contains predicate on the "user_name" field. +func UserNameContains(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContains(FieldUserName, v)) +} + +// UserNameHasPrefix applies the HasPrefix predicate on the "user_name" field. +func UserNameHasPrefix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasPrefix(FieldUserName, v)) +} + +// UserNameHasSuffix applies the HasSuffix predicate on the "user_name" field. +func UserNameHasSuffix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasSuffix(FieldUserName, v)) +} + +// UserNameEqualFold applies the EqualFold predicate on the "user_name" field. +func UserNameEqualFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEqualFold(FieldUserName, v)) +} + +// UserNameContainsFold applies the ContainsFold predicate on the "user_name" field. +func UserNameContainsFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContainsFold(FieldUserName, v)) +} + +// ProfileImageURLEQ applies the EQ predicate on the "profile_image_url" field. +func ProfileImageURLEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldProfileImageURL, v)) +} + +// ProfileImageURLNEQ applies the NEQ predicate on the "profile_image_url" field. +func ProfileImageURLNEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNEQ(FieldProfileImageURL, v)) +} + +// ProfileImageURLIn applies the In predicate on the "profile_image_url" field. +func ProfileImageURLIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIn(FieldProfileImageURL, vs...)) +} + +// ProfileImageURLNotIn applies the NotIn predicate on the "profile_image_url" field. +func ProfileImageURLNotIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotIn(FieldProfileImageURL, vs...)) +} + +// ProfileImageURLGT applies the GT predicate on the "profile_image_url" field. +func ProfileImageURLGT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGT(FieldProfileImageURL, v)) +} + +// ProfileImageURLGTE applies the GTE predicate on the "profile_image_url" field. +func ProfileImageURLGTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGTE(FieldProfileImageURL, v)) +} + +// ProfileImageURLLT applies the LT predicate on the "profile_image_url" field. +func ProfileImageURLLT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLT(FieldProfileImageURL, v)) +} + +// ProfileImageURLLTE applies the LTE predicate on the "profile_image_url" field. +func ProfileImageURLLTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLTE(FieldProfileImageURL, v)) +} + +// ProfileImageURLContains applies the Contains predicate on the "profile_image_url" field. +func ProfileImageURLContains(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContains(FieldProfileImageURL, v)) +} + +// ProfileImageURLHasPrefix applies the HasPrefix predicate on the "profile_image_url" field. +func ProfileImageURLHasPrefix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasPrefix(FieldProfileImageURL, v)) +} + +// ProfileImageURLHasSuffix applies the HasSuffix predicate on the "profile_image_url" field. +func ProfileImageURLHasSuffix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasSuffix(FieldProfileImageURL, v)) +} + +// ProfileImageURLIsNil applies the IsNil predicate on the "profile_image_url" field. +func ProfileImageURLIsNil() predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIsNull(FieldProfileImageURL)) +} + +// ProfileImageURLNotNil applies the NotNil predicate on the "profile_image_url" field. +func ProfileImageURLNotNil() predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotNull(FieldProfileImageURL)) +} + +// ProfileImageURLEqualFold applies the EqualFold predicate on the "profile_image_url" field. +func ProfileImageURLEqualFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEqualFold(FieldProfileImageURL, v)) +} + +// ProfileImageURLContainsFold applies the ContainsFold predicate on the "profile_image_url" field. +func ProfileImageURLContainsFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContainsFold(FieldProfileImageURL, v)) +} + +// IcpNumberEQ applies the EQ predicate on the "icp_number" field. +func IcpNumberEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldIcpNumber, v)) +} + +// IcpNumberNEQ applies the NEQ predicate on the "icp_number" field. +func IcpNumberNEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNEQ(FieldIcpNumber, v)) +} + +// IcpNumberIn applies the In predicate on the "icp_number" field. +func IcpNumberIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIn(FieldIcpNumber, vs...)) +} + +// IcpNumberNotIn applies the NotIn predicate on the "icp_number" field. +func IcpNumberNotIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotIn(FieldIcpNumber, vs...)) +} + +// IcpNumberGT applies the GT predicate on the "icp_number" field. +func IcpNumberGT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGT(FieldIcpNumber, v)) +} + +// IcpNumberGTE applies the GTE predicate on the "icp_number" field. +func IcpNumberGTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGTE(FieldIcpNumber, v)) +} + +// IcpNumberLT applies the LT predicate on the "icp_number" field. +func IcpNumberLT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLT(FieldIcpNumber, v)) +} + +// IcpNumberLTE applies the LTE predicate on the "icp_number" field. +func IcpNumberLTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLTE(FieldIcpNumber, v)) +} + +// IcpNumberContains applies the Contains predicate on the "icp_number" field. +func IcpNumberContains(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContains(FieldIcpNumber, v)) +} + +// IcpNumberHasPrefix applies the HasPrefix predicate on the "icp_number" field. +func IcpNumberHasPrefix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasPrefix(FieldIcpNumber, v)) +} + +// IcpNumberHasSuffix applies the HasSuffix predicate on the "icp_number" field. +func IcpNumberHasSuffix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasSuffix(FieldIcpNumber, v)) +} + +// IcpNumberIsNil applies the IsNil predicate on the "icp_number" field. +func IcpNumberIsNil() predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIsNull(FieldIcpNumber)) +} + +// IcpNumberNotNil applies the NotNil predicate on the "icp_number" field. +func IcpNumberNotNil() predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotNull(FieldIcpNumber)) +} + +// IcpNumberEqualFold applies the EqualFold predicate on the "icp_number" field. +func IcpNumberEqualFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEqualFold(FieldIcpNumber, v)) +} + +// IcpNumberContainsFold applies the ContainsFold predicate on the "icp_number" field. +func IcpNumberContainsFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContainsFold(FieldIcpNumber, v)) +} + +// PoliceNumberEQ applies the EQ predicate on the "police_number" field. +func PoliceNumberEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldPoliceNumber, v)) +} + +// PoliceNumberNEQ applies the NEQ predicate on the "police_number" field. +func PoliceNumberNEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNEQ(FieldPoliceNumber, v)) +} + +// PoliceNumberIn applies the In predicate on the "police_number" field. +func PoliceNumberIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIn(FieldPoliceNumber, vs...)) +} + +// PoliceNumberNotIn applies the NotIn predicate on the "police_number" field. +func PoliceNumberNotIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotIn(FieldPoliceNumber, vs...)) +} + +// PoliceNumberGT applies the GT predicate on the "police_number" field. +func PoliceNumberGT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGT(FieldPoliceNumber, v)) +} + +// PoliceNumberGTE applies the GTE predicate on the "police_number" field. +func PoliceNumberGTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGTE(FieldPoliceNumber, v)) +} + +// PoliceNumberLT applies the LT predicate on the "police_number" field. +func PoliceNumberLT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLT(FieldPoliceNumber, v)) +} + +// PoliceNumberLTE applies the LTE predicate on the "police_number" field. +func PoliceNumberLTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLTE(FieldPoliceNumber, v)) +} + +// PoliceNumberContains applies the Contains predicate on the "police_number" field. +func PoliceNumberContains(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContains(FieldPoliceNumber, v)) +} + +// PoliceNumberHasPrefix applies the HasPrefix predicate on the "police_number" field. +func PoliceNumberHasPrefix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasPrefix(FieldPoliceNumber, v)) +} + +// PoliceNumberHasSuffix applies the HasSuffix predicate on the "police_number" field. +func PoliceNumberHasSuffix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasSuffix(FieldPoliceNumber, v)) +} + +// PoliceNumberIsNil applies the IsNil predicate on the "police_number" field. +func PoliceNumberIsNil() predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIsNull(FieldPoliceNumber)) +} + +// PoliceNumberNotNil applies the NotNil predicate on the "police_number" field. +func PoliceNumberNotNil() predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotNull(FieldPoliceNumber)) +} + +// PoliceNumberEqualFold applies the EqualFold predicate on the "police_number" field. +func PoliceNumberEqualFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEqualFold(FieldPoliceNumber, v)) +} + +// PoliceNumberContainsFold applies the ContainsFold predicate on the "police_number" field. +func PoliceNumberContainsFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContainsFold(FieldPoliceNumber, v)) +} + +// PageTitleEQ applies the EQ predicate on the "page_title" field. +func PageTitleEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldPageTitle, v)) +} + +// PageTitleNEQ applies the NEQ predicate on the "page_title" field. +func PageTitleNEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNEQ(FieldPageTitle, v)) +} + +// PageTitleIn applies the In predicate on the "page_title" field. +func PageTitleIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIn(FieldPageTitle, vs...)) +} + +// PageTitleNotIn applies the NotIn predicate on the "page_title" field. +func PageTitleNotIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotIn(FieldPageTitle, vs...)) +} + +// PageTitleGT applies the GT predicate on the "page_title" field. +func PageTitleGT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGT(FieldPageTitle, v)) +} + +// PageTitleGTE applies the GTE predicate on the "page_title" field. +func PageTitleGTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGTE(FieldPageTitle, v)) +} + +// PageTitleLT applies the LT predicate on the "page_title" field. +func PageTitleLT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLT(FieldPageTitle, v)) +} + +// PageTitleLTE applies the LTE predicate on the "page_title" field. +func PageTitleLTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLTE(FieldPageTitle, v)) +} + +// PageTitleContains applies the Contains predicate on the "page_title" field. +func PageTitleContains(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContains(FieldPageTitle, v)) +} + +// PageTitleHasPrefix applies the HasPrefix predicate on the "page_title" field. +func PageTitleHasPrefix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasPrefix(FieldPageTitle, v)) +} + +// PageTitleHasSuffix applies the HasSuffix predicate on the "page_title" field. +func PageTitleHasSuffix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasSuffix(FieldPageTitle, v)) +} + +// PageTitleIsNil applies the IsNil predicate on the "page_title" field. +func PageTitleIsNil() predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIsNull(FieldPageTitle)) +} + +// PageTitleNotNil applies the NotNil predicate on the "page_title" field. +func PageTitleNotNil() predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotNull(FieldPageTitle)) +} + +// PageTitleEqualFold applies the EqualFold predicate on the "page_title" field. +func PageTitleEqualFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEqualFold(FieldPageTitle, v)) +} + +// PageTitleContainsFold applies the ContainsFold predicate on the "page_title" field. +func PageTitleContainsFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContainsFold(FieldPageTitle, v)) +} + +// FaviconEQ applies the EQ predicate on the "favicon" field. +func FaviconEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldFavicon, v)) +} + +// FaviconNEQ applies the NEQ predicate on the "favicon" field. +func FaviconNEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNEQ(FieldFavicon, v)) +} + +// FaviconIn applies the In predicate on the "favicon" field. +func FaviconIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIn(FieldFavicon, vs...)) +} + +// FaviconNotIn applies the NotIn predicate on the "favicon" field. +func FaviconNotIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotIn(FieldFavicon, vs...)) +} + +// FaviconGT applies the GT predicate on the "favicon" field. +func FaviconGT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGT(FieldFavicon, v)) +} + +// FaviconGTE applies the GTE predicate on the "favicon" field. +func FaviconGTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGTE(FieldFavicon, v)) +} + +// FaviconLT applies the LT predicate on the "favicon" field. +func FaviconLT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLT(FieldFavicon, v)) +} + +// FaviconLTE applies the LTE predicate on the "favicon" field. +func FaviconLTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLTE(FieldFavicon, v)) +} + +// FaviconContains applies the Contains predicate on the "favicon" field. +func FaviconContains(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContains(FieldFavicon, v)) +} + +// FaviconHasPrefix applies the HasPrefix predicate on the "favicon" field. +func FaviconHasPrefix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasPrefix(FieldFavicon, v)) +} + +// FaviconHasSuffix applies the HasSuffix predicate on the "favicon" field. +func FaviconHasSuffix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasSuffix(FieldFavicon, v)) +} + +// FaviconIsNil applies the IsNil predicate on the "favicon" field. +func FaviconIsNil() predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIsNull(FieldFavicon)) +} + +// FaviconNotNil applies the NotNil predicate on the "favicon" field. +func FaviconNotNil() predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotNull(FieldFavicon)) +} + +// FaviconEqualFold applies the EqualFold predicate on the "favicon" field. +func FaviconEqualFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEqualFold(FieldFavicon, v)) +} + +// FaviconContainsFold applies the ContainsFold predicate on the "favicon" field. +func FaviconContainsFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContainsFold(FieldFavicon, v)) +} + +// UmamiScriptEQ applies the EQ predicate on the "umami_script" field. +func UmamiScriptEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldUmamiScript, v)) +} + +// UmamiScriptNEQ applies the NEQ predicate on the "umami_script" field. +func UmamiScriptNEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNEQ(FieldUmamiScript, v)) +} + +// UmamiScriptIn applies the In predicate on the "umami_script" field. +func UmamiScriptIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIn(FieldUmamiScript, vs...)) +} + +// UmamiScriptNotIn applies the NotIn predicate on the "umami_script" field. +func UmamiScriptNotIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotIn(FieldUmamiScript, vs...)) +} + +// UmamiScriptGT applies the GT predicate on the "umami_script" field. +func UmamiScriptGT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGT(FieldUmamiScript, v)) +} + +// UmamiScriptGTE applies the GTE predicate on the "umami_script" field. +func UmamiScriptGTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGTE(FieldUmamiScript, v)) +} + +// UmamiScriptLT applies the LT predicate on the "umami_script" field. +func UmamiScriptLT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLT(FieldUmamiScript, v)) +} + +// UmamiScriptLTE applies the LTE predicate on the "umami_script" field. +func UmamiScriptLTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLTE(FieldUmamiScript, v)) +} + +// UmamiScriptContains applies the Contains predicate on the "umami_script" field. +func UmamiScriptContains(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContains(FieldUmamiScript, v)) +} + +// UmamiScriptHasPrefix applies the HasPrefix predicate on the "umami_script" field. +func UmamiScriptHasPrefix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasPrefix(FieldUmamiScript, v)) +} + +// UmamiScriptHasSuffix applies the HasSuffix predicate on the "umami_script" field. +func UmamiScriptHasSuffix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasSuffix(FieldUmamiScript, v)) +} + +// UmamiScriptIsNil applies the IsNil predicate on the "umami_script" field. +func UmamiScriptIsNil() predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIsNull(FieldUmamiScript)) +} + +// UmamiScriptNotNil applies the NotNil predicate on the "umami_script" field. +func UmamiScriptNotNil() predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotNull(FieldUmamiScript)) +} + +// UmamiScriptEqualFold applies the EqualFold predicate on the "umami_script" field. +func UmamiScriptEqualFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEqualFold(FieldUmamiScript, v)) +} + +// UmamiScriptContainsFold applies the ContainsFold predicate on the "umami_script" field. +func UmamiScriptContainsFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContainsFold(FieldUmamiScript, v)) +} + +// UmamiWebsiteIDEQ applies the EQ predicate on the "umami_website_id" field. +func UmamiWebsiteIDEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldUmamiWebsiteID, v)) +} + +// UmamiWebsiteIDNEQ applies the NEQ predicate on the "umami_website_id" field. +func UmamiWebsiteIDNEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNEQ(FieldUmamiWebsiteID, v)) +} + +// UmamiWebsiteIDIn applies the In predicate on the "umami_website_id" field. +func UmamiWebsiteIDIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIn(FieldUmamiWebsiteID, vs...)) +} + +// UmamiWebsiteIDNotIn applies the NotIn predicate on the "umami_website_id" field. +func UmamiWebsiteIDNotIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotIn(FieldUmamiWebsiteID, vs...)) +} + +// UmamiWebsiteIDGT applies the GT predicate on the "umami_website_id" field. +func UmamiWebsiteIDGT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGT(FieldUmamiWebsiteID, v)) +} + +// UmamiWebsiteIDGTE applies the GTE predicate on the "umami_website_id" field. +func UmamiWebsiteIDGTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGTE(FieldUmamiWebsiteID, v)) +} + +// UmamiWebsiteIDLT applies the LT predicate on the "umami_website_id" field. +func UmamiWebsiteIDLT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLT(FieldUmamiWebsiteID, v)) +} + +// UmamiWebsiteIDLTE applies the LTE predicate on the "umami_website_id" field. +func UmamiWebsiteIDLTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLTE(FieldUmamiWebsiteID, v)) +} + +// UmamiWebsiteIDContains applies the Contains predicate on the "umami_website_id" field. +func UmamiWebsiteIDContains(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContains(FieldUmamiWebsiteID, v)) +} + +// UmamiWebsiteIDHasPrefix applies the HasPrefix predicate on the "umami_website_id" field. +func UmamiWebsiteIDHasPrefix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasPrefix(FieldUmamiWebsiteID, v)) +} + +// UmamiWebsiteIDHasSuffix applies the HasSuffix predicate on the "umami_website_id" field. +func UmamiWebsiteIDHasSuffix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasSuffix(FieldUmamiWebsiteID, v)) +} + +// UmamiWebsiteIDIsNil applies the IsNil predicate on the "umami_website_id" field. +func UmamiWebsiteIDIsNil() predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIsNull(FieldUmamiWebsiteID)) +} + +// UmamiWebsiteIDNotNil applies the NotNil predicate on the "umami_website_id" field. +func UmamiWebsiteIDNotNil() predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotNull(FieldUmamiWebsiteID)) +} + +// UmamiWebsiteIDEqualFold applies the EqualFold predicate on the "umami_website_id" field. +func UmamiWebsiteIDEqualFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEqualFold(FieldUmamiWebsiteID, v)) +} + +// UmamiWebsiteIDContainsFold applies the ContainsFold predicate on the "umami_website_id" field. +func UmamiWebsiteIDContainsFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContainsFold(FieldUmamiWebsiteID, v)) +} + +// IconLibraryEQ applies the EQ predicate on the "icon_library" field. +func IconLibraryEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldIconLibrary, v)) +} + +// IconLibraryNEQ applies the NEQ predicate on the "icon_library" field. +func IconLibraryNEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNEQ(FieldIconLibrary, v)) +} + +// IconLibraryIn applies the In predicate on the "icon_library" field. +func IconLibraryIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIn(FieldIconLibrary, vs...)) +} + +// IconLibraryNotIn applies the NotIn predicate on the "icon_library" field. +func IconLibraryNotIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotIn(FieldIconLibrary, vs...)) +} + +// IconLibraryGT applies the GT predicate on the "icon_library" field. +func IconLibraryGT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGT(FieldIconLibrary, v)) +} + +// IconLibraryGTE applies the GTE predicate on the "icon_library" field. +func IconLibraryGTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGTE(FieldIconLibrary, v)) +} + +// IconLibraryLT applies the LT predicate on the "icon_library" field. +func IconLibraryLT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLT(FieldIconLibrary, v)) +} + +// IconLibraryLTE applies the LTE predicate on the "icon_library" field. +func IconLibraryLTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLTE(FieldIconLibrary, v)) +} + +// IconLibraryContains applies the Contains predicate on the "icon_library" field. +func IconLibraryContains(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContains(FieldIconLibrary, v)) +} + +// IconLibraryHasPrefix applies the HasPrefix predicate on the "icon_library" field. +func IconLibraryHasPrefix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasPrefix(FieldIconLibrary, v)) +} + +// IconLibraryHasSuffix applies the HasSuffix predicate on the "icon_library" field. +func IconLibraryHasSuffix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasSuffix(FieldIconLibrary, v)) +} + +// IconLibraryIsNil applies the IsNil predicate on the "icon_library" field. +func IconLibraryIsNil() predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIsNull(FieldIconLibrary)) +} + +// IconLibraryNotNil applies the NotNil predicate on the "icon_library" field. +func IconLibraryNotNil() predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotNull(FieldIconLibrary)) +} + +// IconLibraryEqualFold applies the EqualFold predicate on the "icon_library" field. +func IconLibraryEqualFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEqualFold(FieldIconLibrary, v)) +} + +// IconLibraryContainsFold applies the ContainsFold predicate on the "icon_library" field. +func IconLibraryContainsFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContainsFold(FieldIconLibrary, v)) +} + +// FontLibraryEQ applies the EQ predicate on the "font_library" field. +func FontLibraryEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEQ(FieldFontLibrary, v)) +} + +// FontLibraryNEQ applies the NEQ predicate on the "font_library" field. +func FontLibraryNEQ(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNEQ(FieldFontLibrary, v)) +} + +// FontLibraryIn applies the In predicate on the "font_library" field. +func FontLibraryIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIn(FieldFontLibrary, vs...)) +} + +// FontLibraryNotIn applies the NotIn predicate on the "font_library" field. +func FontLibraryNotIn(vs ...string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotIn(FieldFontLibrary, vs...)) +} + +// FontLibraryGT applies the GT predicate on the "font_library" field. +func FontLibraryGT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGT(FieldFontLibrary, v)) +} + +// FontLibraryGTE applies the GTE predicate on the "font_library" field. +func FontLibraryGTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldGTE(FieldFontLibrary, v)) +} + +// FontLibraryLT applies the LT predicate on the "font_library" field. +func FontLibraryLT(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLT(FieldFontLibrary, v)) +} + +// FontLibraryLTE applies the LTE predicate on the "font_library" field. +func FontLibraryLTE(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldLTE(FieldFontLibrary, v)) +} + +// FontLibraryContains applies the Contains predicate on the "font_library" field. +func FontLibraryContains(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContains(FieldFontLibrary, v)) +} + +// FontLibraryHasPrefix applies the HasPrefix predicate on the "font_library" field. +func FontLibraryHasPrefix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasPrefix(FieldFontLibrary, v)) +} + +// FontLibraryHasSuffix applies the HasSuffix predicate on the "font_library" field. +func FontLibraryHasSuffix(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldHasSuffix(FieldFontLibrary, v)) +} + +// FontLibraryIsNil applies the IsNil predicate on the "font_library" field. +func FontLibraryIsNil() predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldIsNull(FieldFontLibrary)) +} + +// FontLibraryNotNil applies the NotNil predicate on the "font_library" field. +func FontLibraryNotNil() predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldNotNull(FieldFontLibrary)) +} + +// FontLibraryEqualFold applies the EqualFold predicate on the "font_library" field. +func FontLibraryEqualFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldEqualFold(FieldFontLibrary, v)) +} + +// FontLibraryContainsFold applies the ContainsFold predicate on the "font_library" field. +func FontLibraryContainsFold(v string) predicate.SiteConfig { + return predicate.SiteConfig(sql.FieldContainsFold(FieldFontLibrary, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.SiteConfig) predicate.SiteConfig { + return predicate.SiteConfig(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.SiteConfig) predicate.SiteConfig { + return predicate.SiteConfig(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.SiteConfig) predicate.SiteConfig { + return predicate.SiteConfig(sql.NotPredicates(p)) +} diff --git a/internal/ent/siteconfig_create.go b/internal/ent/siteconfig_create.go new file mode 100644 index 0000000..725c2bc --- /dev/null +++ b/internal/ent/siteconfig_create.go @@ -0,0 +1,440 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "home-vue-go/internal/ent/siteconfig" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// SiteConfigCreate is the builder for creating a SiteConfig entity. +type SiteConfigCreate struct { + config + mutation *SiteConfigMutation + hooks []Hook +} + +// SetSiteName sets the "site_name" field. +func (_c *SiteConfigCreate) SetSiteName(v string) *SiteConfigCreate { + _c.mutation.SetSiteName(v) + return _c +} + +// SetSiteURL sets the "site_url" field. +func (_c *SiteConfigCreate) SetSiteURL(v string) *SiteConfigCreate { + _c.mutation.SetSiteURL(v) + return _c +} + +// SetSiteIcon sets the "site_icon" field. +func (_c *SiteConfigCreate) SetSiteIcon(v string) *SiteConfigCreate { + _c.mutation.SetSiteIcon(v) + return _c +} + +// SetSiteDescription sets the "site_description" field. +func (_c *SiteConfigCreate) SetSiteDescription(v string) *SiteConfigCreate { + _c.mutation.SetSiteDescription(v) + return _c +} + +// SetSiteKeywords sets the "site_keywords" field. +func (_c *SiteConfigCreate) SetSiteKeywords(v string) *SiteConfigCreate { + _c.mutation.SetSiteKeywords(v) + return _c +} + +// SetUserName sets the "user_name" field. +func (_c *SiteConfigCreate) SetUserName(v string) *SiteConfigCreate { + _c.mutation.SetUserName(v) + return _c +} + +// SetProfileImageURL sets the "profile_image_url" field. +func (_c *SiteConfigCreate) SetProfileImageURL(v string) *SiteConfigCreate { + _c.mutation.SetProfileImageURL(v) + return _c +} + +// SetNillableProfileImageURL sets the "profile_image_url" field if the given value is not nil. +func (_c *SiteConfigCreate) SetNillableProfileImageURL(v *string) *SiteConfigCreate { + if v != nil { + _c.SetProfileImageURL(*v) + } + return _c +} + +// SetIcpNumber sets the "icp_number" field. +func (_c *SiteConfigCreate) SetIcpNumber(v string) *SiteConfigCreate { + _c.mutation.SetIcpNumber(v) + return _c +} + +// SetNillableIcpNumber sets the "icp_number" field if the given value is not nil. +func (_c *SiteConfigCreate) SetNillableIcpNumber(v *string) *SiteConfigCreate { + if v != nil { + _c.SetIcpNumber(*v) + } + return _c +} + +// SetPoliceNumber sets the "police_number" field. +func (_c *SiteConfigCreate) SetPoliceNumber(v string) *SiteConfigCreate { + _c.mutation.SetPoliceNumber(v) + return _c +} + +// SetNillablePoliceNumber sets the "police_number" field if the given value is not nil. +func (_c *SiteConfigCreate) SetNillablePoliceNumber(v *string) *SiteConfigCreate { + if v != nil { + _c.SetPoliceNumber(*v) + } + return _c +} + +// SetPageTitle sets the "page_title" field. +func (_c *SiteConfigCreate) SetPageTitle(v string) *SiteConfigCreate { + _c.mutation.SetPageTitle(v) + return _c +} + +// SetNillablePageTitle sets the "page_title" field if the given value is not nil. +func (_c *SiteConfigCreate) SetNillablePageTitle(v *string) *SiteConfigCreate { + if v != nil { + _c.SetPageTitle(*v) + } + return _c +} + +// SetFavicon sets the "favicon" field. +func (_c *SiteConfigCreate) SetFavicon(v string) *SiteConfigCreate { + _c.mutation.SetFavicon(v) + return _c +} + +// SetNillableFavicon sets the "favicon" field if the given value is not nil. +func (_c *SiteConfigCreate) SetNillableFavicon(v *string) *SiteConfigCreate { + if v != nil { + _c.SetFavicon(*v) + } + return _c +} + +// SetUmamiScript sets the "umami_script" field. +func (_c *SiteConfigCreate) SetUmamiScript(v string) *SiteConfigCreate { + _c.mutation.SetUmamiScript(v) + return _c +} + +// SetNillableUmamiScript sets the "umami_script" field if the given value is not nil. +func (_c *SiteConfigCreate) SetNillableUmamiScript(v *string) *SiteConfigCreate { + if v != nil { + _c.SetUmamiScript(*v) + } + return _c +} + +// SetUmamiWebsiteID sets the "umami_website_id" field. +func (_c *SiteConfigCreate) SetUmamiWebsiteID(v string) *SiteConfigCreate { + _c.mutation.SetUmamiWebsiteID(v) + return _c +} + +// SetNillableUmamiWebsiteID sets the "umami_website_id" field if the given value is not nil. +func (_c *SiteConfigCreate) SetNillableUmamiWebsiteID(v *string) *SiteConfigCreate { + if v != nil { + _c.SetUmamiWebsiteID(*v) + } + return _c +} + +// SetIconLibrary sets the "icon_library" field. +func (_c *SiteConfigCreate) SetIconLibrary(v string) *SiteConfigCreate { + _c.mutation.SetIconLibrary(v) + return _c +} + +// SetNillableIconLibrary sets the "icon_library" field if the given value is not nil. +func (_c *SiteConfigCreate) SetNillableIconLibrary(v *string) *SiteConfigCreate { + if v != nil { + _c.SetIconLibrary(*v) + } + return _c +} + +// SetFontLibrary sets the "font_library" field. +func (_c *SiteConfigCreate) SetFontLibrary(v string) *SiteConfigCreate { + _c.mutation.SetFontLibrary(v) + return _c +} + +// SetNillableFontLibrary sets the "font_library" field if the given value is not nil. +func (_c *SiteConfigCreate) SetNillableFontLibrary(v *string) *SiteConfigCreate { + if v != nil { + _c.SetFontLibrary(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *SiteConfigCreate) SetID(v int) *SiteConfigCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *SiteConfigCreate) SetNillableID(v *int) *SiteConfigCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// Mutation returns the SiteConfigMutation object of the builder. +func (_c *SiteConfigCreate) Mutation() *SiteConfigMutation { + return _c.mutation +} + +// Save creates the SiteConfig in the database. +func (_c *SiteConfigCreate) Save(ctx context.Context) (*SiteConfig, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *SiteConfigCreate) SaveX(ctx context.Context) *SiteConfig { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *SiteConfigCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *SiteConfigCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *SiteConfigCreate) defaults() { + if _, ok := _c.mutation.ID(); !ok { + v := siteconfig.DefaultID + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *SiteConfigCreate) check() error { + if _, ok := _c.mutation.SiteName(); !ok { + return &ValidationError{Name: "site_name", err: errors.New(`ent: missing required field "SiteConfig.site_name"`)} + } + if _, ok := _c.mutation.SiteURL(); !ok { + return &ValidationError{Name: "site_url", err: errors.New(`ent: missing required field "SiteConfig.site_url"`)} + } + if _, ok := _c.mutation.SiteIcon(); !ok { + return &ValidationError{Name: "site_icon", err: errors.New(`ent: missing required field "SiteConfig.site_icon"`)} + } + if _, ok := _c.mutation.SiteDescription(); !ok { + return &ValidationError{Name: "site_description", err: errors.New(`ent: missing required field "SiteConfig.site_description"`)} + } + if _, ok := _c.mutation.SiteKeywords(); !ok { + return &ValidationError{Name: "site_keywords", err: errors.New(`ent: missing required field "SiteConfig.site_keywords"`)} + } + if _, ok := _c.mutation.UserName(); !ok { + return &ValidationError{Name: "user_name", err: errors.New(`ent: missing required field "SiteConfig.user_name"`)} + } + return nil +} + +func (_c *SiteConfigCreate) sqlSave(ctx context.Context) (*SiteConfig, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != _node.ID { + id := _spec.ID.Value.(int64) + _node.ID = int(id) + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *SiteConfigCreate) createSpec() (*SiteConfig, *sqlgraph.CreateSpec) { + var ( + _node = &SiteConfig{config: _c.config} + _spec = sqlgraph.NewCreateSpec(siteconfig.Table, sqlgraph.NewFieldSpec(siteconfig.FieldID, field.TypeInt)) + ) + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.SiteName(); ok { + _spec.SetField(siteconfig.FieldSiteName, field.TypeString, value) + _node.SiteName = value + } + if value, ok := _c.mutation.SiteURL(); ok { + _spec.SetField(siteconfig.FieldSiteURL, field.TypeString, value) + _node.SiteURL = value + } + if value, ok := _c.mutation.SiteIcon(); ok { + _spec.SetField(siteconfig.FieldSiteIcon, field.TypeString, value) + _node.SiteIcon = value + } + if value, ok := _c.mutation.SiteDescription(); ok { + _spec.SetField(siteconfig.FieldSiteDescription, field.TypeString, value) + _node.SiteDescription = value + } + if value, ok := _c.mutation.SiteKeywords(); ok { + _spec.SetField(siteconfig.FieldSiteKeywords, field.TypeString, value) + _node.SiteKeywords = value + } + if value, ok := _c.mutation.UserName(); ok { + _spec.SetField(siteconfig.FieldUserName, field.TypeString, value) + _node.UserName = value + } + if value, ok := _c.mutation.ProfileImageURL(); ok { + _spec.SetField(siteconfig.FieldProfileImageURL, field.TypeString, value) + _node.ProfileImageURL = value + } + if value, ok := _c.mutation.IcpNumber(); ok { + _spec.SetField(siteconfig.FieldIcpNumber, field.TypeString, value) + _node.IcpNumber = value + } + if value, ok := _c.mutation.PoliceNumber(); ok { + _spec.SetField(siteconfig.FieldPoliceNumber, field.TypeString, value) + _node.PoliceNumber = value + } + if value, ok := _c.mutation.PageTitle(); ok { + _spec.SetField(siteconfig.FieldPageTitle, field.TypeString, value) + _node.PageTitle = value + } + if value, ok := _c.mutation.Favicon(); ok { + _spec.SetField(siteconfig.FieldFavicon, field.TypeString, value) + _node.Favicon = value + } + if value, ok := _c.mutation.UmamiScript(); ok { + _spec.SetField(siteconfig.FieldUmamiScript, field.TypeString, value) + _node.UmamiScript = value + } + if value, ok := _c.mutation.UmamiWebsiteID(); ok { + _spec.SetField(siteconfig.FieldUmamiWebsiteID, field.TypeString, value) + _node.UmamiWebsiteID = value + } + if value, ok := _c.mutation.IconLibrary(); ok { + _spec.SetField(siteconfig.FieldIconLibrary, field.TypeString, value) + _node.IconLibrary = value + } + if value, ok := _c.mutation.FontLibrary(); ok { + _spec.SetField(siteconfig.FieldFontLibrary, field.TypeString, value) + _node.FontLibrary = value + } + return _node, _spec +} + +// SiteConfigCreateBulk is the builder for creating many SiteConfig entities in bulk. +type SiteConfigCreateBulk struct { + config + err error + builders []*SiteConfigCreate +} + +// Save creates the SiteConfig entities in the database. +func (_c *SiteConfigCreateBulk) Save(ctx context.Context) ([]*SiteConfig, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*SiteConfig, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*SiteConfigMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil && nodes[i].ID == 0 { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *SiteConfigCreateBulk) SaveX(ctx context.Context) []*SiteConfig { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *SiteConfigCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *SiteConfigCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/ent/siteconfig_delete.go b/internal/ent/siteconfig_delete.go new file mode 100644 index 0000000..8cad175 --- /dev/null +++ b/internal/ent/siteconfig_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "home-vue-go/internal/ent/predicate" + "home-vue-go/internal/ent/siteconfig" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// SiteConfigDelete is the builder for deleting a SiteConfig entity. +type SiteConfigDelete struct { + config + hooks []Hook + mutation *SiteConfigMutation +} + +// Where appends a list predicates to the SiteConfigDelete builder. +func (_d *SiteConfigDelete) Where(ps ...predicate.SiteConfig) *SiteConfigDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *SiteConfigDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *SiteConfigDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *SiteConfigDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(siteconfig.Table, sqlgraph.NewFieldSpec(siteconfig.FieldID, field.TypeInt)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// SiteConfigDeleteOne is the builder for deleting a single SiteConfig entity. +type SiteConfigDeleteOne struct { + _d *SiteConfigDelete +} + +// Where appends a list predicates to the SiteConfigDelete builder. +func (_d *SiteConfigDeleteOne) Where(ps ...predicate.SiteConfig) *SiteConfigDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *SiteConfigDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{siteconfig.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *SiteConfigDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/ent/siteconfig_query.go b/internal/ent/siteconfig_query.go new file mode 100644 index 0000000..6cba511 --- /dev/null +++ b/internal/ent/siteconfig_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "home-vue-go/internal/ent/predicate" + "home-vue-go/internal/ent/siteconfig" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// SiteConfigQuery is the builder for querying SiteConfig entities. +type SiteConfigQuery struct { + config + ctx *QueryContext + order []siteconfig.OrderOption + inters []Interceptor + predicates []predicate.SiteConfig + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the SiteConfigQuery builder. +func (_q *SiteConfigQuery) Where(ps ...predicate.SiteConfig) *SiteConfigQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *SiteConfigQuery) Limit(limit int) *SiteConfigQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *SiteConfigQuery) Offset(offset int) *SiteConfigQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *SiteConfigQuery) Unique(unique bool) *SiteConfigQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *SiteConfigQuery) Order(o ...siteconfig.OrderOption) *SiteConfigQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first SiteConfig entity from the query. +// Returns a *NotFoundError when no SiteConfig was found. +func (_q *SiteConfigQuery) First(ctx context.Context) (*SiteConfig, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{siteconfig.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *SiteConfigQuery) FirstX(ctx context.Context) *SiteConfig { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first SiteConfig ID from the query. +// Returns a *NotFoundError when no SiteConfig ID was found. +func (_q *SiteConfigQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{siteconfig.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *SiteConfigQuery) FirstIDX(ctx context.Context) int { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single SiteConfig entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one SiteConfig entity is found. +// Returns a *NotFoundError when no SiteConfig entities are found. +func (_q *SiteConfigQuery) Only(ctx context.Context) (*SiteConfig, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{siteconfig.Label} + default: + return nil, &NotSingularError{siteconfig.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *SiteConfigQuery) OnlyX(ctx context.Context) *SiteConfig { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only SiteConfig ID in the query. +// Returns a *NotSingularError when more than one SiteConfig ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *SiteConfigQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{siteconfig.Label} + default: + err = &NotSingularError{siteconfig.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *SiteConfigQuery) OnlyIDX(ctx context.Context) int { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of SiteConfigs. +func (_q *SiteConfigQuery) All(ctx context.Context) ([]*SiteConfig, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*SiteConfig, *SiteConfigQuery]() + return withInterceptors[[]*SiteConfig](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *SiteConfigQuery) AllX(ctx context.Context) []*SiteConfig { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of SiteConfig IDs. +func (_q *SiteConfigQuery) IDs(ctx context.Context) (ids []int, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(siteconfig.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *SiteConfigQuery) IDsX(ctx context.Context) []int { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *SiteConfigQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*SiteConfigQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *SiteConfigQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *SiteConfigQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *SiteConfigQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the SiteConfigQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *SiteConfigQuery) Clone() *SiteConfigQuery { + if _q == nil { + return nil + } + return &SiteConfigQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]siteconfig.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.SiteConfig{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// SiteName string `json:"site_name,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.SiteConfig.Query(). +// GroupBy(siteconfig.FieldSiteName). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *SiteConfigQuery) GroupBy(field string, fields ...string) *SiteConfigGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &SiteConfigGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = siteconfig.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// SiteName string `json:"site_name,omitempty"` +// } +// +// client.SiteConfig.Query(). +// Select(siteconfig.FieldSiteName). +// Scan(ctx, &v) +func (_q *SiteConfigQuery) Select(fields ...string) *SiteConfigSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &SiteConfigSelect{SiteConfigQuery: _q} + sbuild.label = siteconfig.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a SiteConfigSelect configured with the given aggregations. +func (_q *SiteConfigQuery) Aggregate(fns ...AggregateFunc) *SiteConfigSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *SiteConfigQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !siteconfig.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *SiteConfigQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*SiteConfig, error) { + var ( + nodes = []*SiteConfig{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*SiteConfig).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &SiteConfig{config: _q.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (_q *SiteConfigQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *SiteConfigQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(siteconfig.Table, siteconfig.Columns, sqlgraph.NewFieldSpec(siteconfig.FieldID, field.TypeInt)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, siteconfig.FieldID) + for i := range fields { + if fields[i] != siteconfig.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *SiteConfigQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(siteconfig.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = siteconfig.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// SiteConfigGroupBy is the group-by builder for SiteConfig entities. +type SiteConfigGroupBy struct { + selector + build *SiteConfigQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *SiteConfigGroupBy) Aggregate(fns ...AggregateFunc) *SiteConfigGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *SiteConfigGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*SiteConfigQuery, *SiteConfigGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *SiteConfigGroupBy) sqlScan(ctx context.Context, root *SiteConfigQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// SiteConfigSelect is the builder for selecting fields of SiteConfig entities. +type SiteConfigSelect struct { + *SiteConfigQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *SiteConfigSelect) Aggregate(fns ...AggregateFunc) *SiteConfigSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *SiteConfigSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*SiteConfigQuery, *SiteConfigSelect](ctx, _s.SiteConfigQuery, _s, _s.inters, v) +} + +func (_s *SiteConfigSelect) sqlScan(ctx context.Context, root *SiteConfigQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/internal/ent/siteconfig_update.go b/internal/ent/siteconfig_update.go new file mode 100644 index 0000000..6340708 --- /dev/null +++ b/internal/ent/siteconfig_update.go @@ -0,0 +1,847 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "home-vue-go/internal/ent/predicate" + "home-vue-go/internal/ent/siteconfig" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// SiteConfigUpdate is the builder for updating SiteConfig entities. +type SiteConfigUpdate struct { + config + hooks []Hook + mutation *SiteConfigMutation +} + +// Where appends a list predicates to the SiteConfigUpdate builder. +func (_u *SiteConfigUpdate) Where(ps ...predicate.SiteConfig) *SiteConfigUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetSiteName sets the "site_name" field. +func (_u *SiteConfigUpdate) SetSiteName(v string) *SiteConfigUpdate { + _u.mutation.SetSiteName(v) + return _u +} + +// SetNillableSiteName sets the "site_name" field if the given value is not nil. +func (_u *SiteConfigUpdate) SetNillableSiteName(v *string) *SiteConfigUpdate { + if v != nil { + _u.SetSiteName(*v) + } + return _u +} + +// SetSiteURL sets the "site_url" field. +func (_u *SiteConfigUpdate) SetSiteURL(v string) *SiteConfigUpdate { + _u.mutation.SetSiteURL(v) + return _u +} + +// SetNillableSiteURL sets the "site_url" field if the given value is not nil. +func (_u *SiteConfigUpdate) SetNillableSiteURL(v *string) *SiteConfigUpdate { + if v != nil { + _u.SetSiteURL(*v) + } + return _u +} + +// SetSiteIcon sets the "site_icon" field. +func (_u *SiteConfigUpdate) SetSiteIcon(v string) *SiteConfigUpdate { + _u.mutation.SetSiteIcon(v) + return _u +} + +// SetNillableSiteIcon sets the "site_icon" field if the given value is not nil. +func (_u *SiteConfigUpdate) SetNillableSiteIcon(v *string) *SiteConfigUpdate { + if v != nil { + _u.SetSiteIcon(*v) + } + return _u +} + +// SetSiteDescription sets the "site_description" field. +func (_u *SiteConfigUpdate) SetSiteDescription(v string) *SiteConfigUpdate { + _u.mutation.SetSiteDescription(v) + return _u +} + +// SetNillableSiteDescription sets the "site_description" field if the given value is not nil. +func (_u *SiteConfigUpdate) SetNillableSiteDescription(v *string) *SiteConfigUpdate { + if v != nil { + _u.SetSiteDescription(*v) + } + return _u +} + +// SetSiteKeywords sets the "site_keywords" field. +func (_u *SiteConfigUpdate) SetSiteKeywords(v string) *SiteConfigUpdate { + _u.mutation.SetSiteKeywords(v) + return _u +} + +// SetNillableSiteKeywords sets the "site_keywords" field if the given value is not nil. +func (_u *SiteConfigUpdate) SetNillableSiteKeywords(v *string) *SiteConfigUpdate { + if v != nil { + _u.SetSiteKeywords(*v) + } + return _u +} + +// SetUserName sets the "user_name" field. +func (_u *SiteConfigUpdate) SetUserName(v string) *SiteConfigUpdate { + _u.mutation.SetUserName(v) + return _u +} + +// SetNillableUserName sets the "user_name" field if the given value is not nil. +func (_u *SiteConfigUpdate) SetNillableUserName(v *string) *SiteConfigUpdate { + if v != nil { + _u.SetUserName(*v) + } + return _u +} + +// SetProfileImageURL sets the "profile_image_url" field. +func (_u *SiteConfigUpdate) SetProfileImageURL(v string) *SiteConfigUpdate { + _u.mutation.SetProfileImageURL(v) + return _u +} + +// SetNillableProfileImageURL sets the "profile_image_url" field if the given value is not nil. +func (_u *SiteConfigUpdate) SetNillableProfileImageURL(v *string) *SiteConfigUpdate { + if v != nil { + _u.SetProfileImageURL(*v) + } + return _u +} + +// ClearProfileImageURL clears the value of the "profile_image_url" field. +func (_u *SiteConfigUpdate) ClearProfileImageURL() *SiteConfigUpdate { + _u.mutation.ClearProfileImageURL() + return _u +} + +// SetIcpNumber sets the "icp_number" field. +func (_u *SiteConfigUpdate) SetIcpNumber(v string) *SiteConfigUpdate { + _u.mutation.SetIcpNumber(v) + return _u +} + +// SetNillableIcpNumber sets the "icp_number" field if the given value is not nil. +func (_u *SiteConfigUpdate) SetNillableIcpNumber(v *string) *SiteConfigUpdate { + if v != nil { + _u.SetIcpNumber(*v) + } + return _u +} + +// ClearIcpNumber clears the value of the "icp_number" field. +func (_u *SiteConfigUpdate) ClearIcpNumber() *SiteConfigUpdate { + _u.mutation.ClearIcpNumber() + return _u +} + +// SetPoliceNumber sets the "police_number" field. +func (_u *SiteConfigUpdate) SetPoliceNumber(v string) *SiteConfigUpdate { + _u.mutation.SetPoliceNumber(v) + return _u +} + +// SetNillablePoliceNumber sets the "police_number" field if the given value is not nil. +func (_u *SiteConfigUpdate) SetNillablePoliceNumber(v *string) *SiteConfigUpdate { + if v != nil { + _u.SetPoliceNumber(*v) + } + return _u +} + +// ClearPoliceNumber clears the value of the "police_number" field. +func (_u *SiteConfigUpdate) ClearPoliceNumber() *SiteConfigUpdate { + _u.mutation.ClearPoliceNumber() + return _u +} + +// SetPageTitle sets the "page_title" field. +func (_u *SiteConfigUpdate) SetPageTitle(v string) *SiteConfigUpdate { + _u.mutation.SetPageTitle(v) + return _u +} + +// SetNillablePageTitle sets the "page_title" field if the given value is not nil. +func (_u *SiteConfigUpdate) SetNillablePageTitle(v *string) *SiteConfigUpdate { + if v != nil { + _u.SetPageTitle(*v) + } + return _u +} + +// ClearPageTitle clears the value of the "page_title" field. +func (_u *SiteConfigUpdate) ClearPageTitle() *SiteConfigUpdate { + _u.mutation.ClearPageTitle() + return _u +} + +// SetFavicon sets the "favicon" field. +func (_u *SiteConfigUpdate) SetFavicon(v string) *SiteConfigUpdate { + _u.mutation.SetFavicon(v) + return _u +} + +// SetNillableFavicon sets the "favicon" field if the given value is not nil. +func (_u *SiteConfigUpdate) SetNillableFavicon(v *string) *SiteConfigUpdate { + if v != nil { + _u.SetFavicon(*v) + } + return _u +} + +// ClearFavicon clears the value of the "favicon" field. +func (_u *SiteConfigUpdate) ClearFavicon() *SiteConfigUpdate { + _u.mutation.ClearFavicon() + return _u +} + +// SetUmamiScript sets the "umami_script" field. +func (_u *SiteConfigUpdate) SetUmamiScript(v string) *SiteConfigUpdate { + _u.mutation.SetUmamiScript(v) + return _u +} + +// SetNillableUmamiScript sets the "umami_script" field if the given value is not nil. +func (_u *SiteConfigUpdate) SetNillableUmamiScript(v *string) *SiteConfigUpdate { + if v != nil { + _u.SetUmamiScript(*v) + } + return _u +} + +// ClearUmamiScript clears the value of the "umami_script" field. +func (_u *SiteConfigUpdate) ClearUmamiScript() *SiteConfigUpdate { + _u.mutation.ClearUmamiScript() + return _u +} + +// SetUmamiWebsiteID sets the "umami_website_id" field. +func (_u *SiteConfigUpdate) SetUmamiWebsiteID(v string) *SiteConfigUpdate { + _u.mutation.SetUmamiWebsiteID(v) + return _u +} + +// SetNillableUmamiWebsiteID sets the "umami_website_id" field if the given value is not nil. +func (_u *SiteConfigUpdate) SetNillableUmamiWebsiteID(v *string) *SiteConfigUpdate { + if v != nil { + _u.SetUmamiWebsiteID(*v) + } + return _u +} + +// ClearUmamiWebsiteID clears the value of the "umami_website_id" field. +func (_u *SiteConfigUpdate) ClearUmamiWebsiteID() *SiteConfigUpdate { + _u.mutation.ClearUmamiWebsiteID() + return _u +} + +// SetIconLibrary sets the "icon_library" field. +func (_u *SiteConfigUpdate) SetIconLibrary(v string) *SiteConfigUpdate { + _u.mutation.SetIconLibrary(v) + return _u +} + +// SetNillableIconLibrary sets the "icon_library" field if the given value is not nil. +func (_u *SiteConfigUpdate) SetNillableIconLibrary(v *string) *SiteConfigUpdate { + if v != nil { + _u.SetIconLibrary(*v) + } + return _u +} + +// ClearIconLibrary clears the value of the "icon_library" field. +func (_u *SiteConfigUpdate) ClearIconLibrary() *SiteConfigUpdate { + _u.mutation.ClearIconLibrary() + return _u +} + +// SetFontLibrary sets the "font_library" field. +func (_u *SiteConfigUpdate) SetFontLibrary(v string) *SiteConfigUpdate { + _u.mutation.SetFontLibrary(v) + return _u +} + +// SetNillableFontLibrary sets the "font_library" field if the given value is not nil. +func (_u *SiteConfigUpdate) SetNillableFontLibrary(v *string) *SiteConfigUpdate { + if v != nil { + _u.SetFontLibrary(*v) + } + return _u +} + +// ClearFontLibrary clears the value of the "font_library" field. +func (_u *SiteConfigUpdate) ClearFontLibrary() *SiteConfigUpdate { + _u.mutation.ClearFontLibrary() + return _u +} + +// Mutation returns the SiteConfigMutation object of the builder. +func (_u *SiteConfigUpdate) Mutation() *SiteConfigMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *SiteConfigUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *SiteConfigUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *SiteConfigUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *SiteConfigUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *SiteConfigUpdate) sqlSave(ctx context.Context) (_node int, err error) { + _spec := sqlgraph.NewUpdateSpec(siteconfig.Table, siteconfig.Columns, sqlgraph.NewFieldSpec(siteconfig.FieldID, field.TypeInt)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.SiteName(); ok { + _spec.SetField(siteconfig.FieldSiteName, field.TypeString, value) + } + if value, ok := _u.mutation.SiteURL(); ok { + _spec.SetField(siteconfig.FieldSiteURL, field.TypeString, value) + } + if value, ok := _u.mutation.SiteIcon(); ok { + _spec.SetField(siteconfig.FieldSiteIcon, field.TypeString, value) + } + if value, ok := _u.mutation.SiteDescription(); ok { + _spec.SetField(siteconfig.FieldSiteDescription, field.TypeString, value) + } + if value, ok := _u.mutation.SiteKeywords(); ok { + _spec.SetField(siteconfig.FieldSiteKeywords, field.TypeString, value) + } + if value, ok := _u.mutation.UserName(); ok { + _spec.SetField(siteconfig.FieldUserName, field.TypeString, value) + } + if value, ok := _u.mutation.ProfileImageURL(); ok { + _spec.SetField(siteconfig.FieldProfileImageURL, field.TypeString, value) + } + if _u.mutation.ProfileImageURLCleared() { + _spec.ClearField(siteconfig.FieldProfileImageURL, field.TypeString) + } + if value, ok := _u.mutation.IcpNumber(); ok { + _spec.SetField(siteconfig.FieldIcpNumber, field.TypeString, value) + } + if _u.mutation.IcpNumberCleared() { + _spec.ClearField(siteconfig.FieldIcpNumber, field.TypeString) + } + if value, ok := _u.mutation.PoliceNumber(); ok { + _spec.SetField(siteconfig.FieldPoliceNumber, field.TypeString, value) + } + if _u.mutation.PoliceNumberCleared() { + _spec.ClearField(siteconfig.FieldPoliceNumber, field.TypeString) + } + if value, ok := _u.mutation.PageTitle(); ok { + _spec.SetField(siteconfig.FieldPageTitle, field.TypeString, value) + } + if _u.mutation.PageTitleCleared() { + _spec.ClearField(siteconfig.FieldPageTitle, field.TypeString) + } + if value, ok := _u.mutation.Favicon(); ok { + _spec.SetField(siteconfig.FieldFavicon, field.TypeString, value) + } + if _u.mutation.FaviconCleared() { + _spec.ClearField(siteconfig.FieldFavicon, field.TypeString) + } + if value, ok := _u.mutation.UmamiScript(); ok { + _spec.SetField(siteconfig.FieldUmamiScript, field.TypeString, value) + } + if _u.mutation.UmamiScriptCleared() { + _spec.ClearField(siteconfig.FieldUmamiScript, field.TypeString) + } + if value, ok := _u.mutation.UmamiWebsiteID(); ok { + _spec.SetField(siteconfig.FieldUmamiWebsiteID, field.TypeString, value) + } + if _u.mutation.UmamiWebsiteIDCleared() { + _spec.ClearField(siteconfig.FieldUmamiWebsiteID, field.TypeString) + } + if value, ok := _u.mutation.IconLibrary(); ok { + _spec.SetField(siteconfig.FieldIconLibrary, field.TypeString, value) + } + if _u.mutation.IconLibraryCleared() { + _spec.ClearField(siteconfig.FieldIconLibrary, field.TypeString) + } + if value, ok := _u.mutation.FontLibrary(); ok { + _spec.SetField(siteconfig.FieldFontLibrary, field.TypeString, value) + } + if _u.mutation.FontLibraryCleared() { + _spec.ClearField(siteconfig.FieldFontLibrary, field.TypeString) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{siteconfig.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// SiteConfigUpdateOne is the builder for updating a single SiteConfig entity. +type SiteConfigUpdateOne struct { + config + fields []string + hooks []Hook + mutation *SiteConfigMutation +} + +// SetSiteName sets the "site_name" field. +func (_u *SiteConfigUpdateOne) SetSiteName(v string) *SiteConfigUpdateOne { + _u.mutation.SetSiteName(v) + return _u +} + +// SetNillableSiteName sets the "site_name" field if the given value is not nil. +func (_u *SiteConfigUpdateOne) SetNillableSiteName(v *string) *SiteConfigUpdateOne { + if v != nil { + _u.SetSiteName(*v) + } + return _u +} + +// SetSiteURL sets the "site_url" field. +func (_u *SiteConfigUpdateOne) SetSiteURL(v string) *SiteConfigUpdateOne { + _u.mutation.SetSiteURL(v) + return _u +} + +// SetNillableSiteURL sets the "site_url" field if the given value is not nil. +func (_u *SiteConfigUpdateOne) SetNillableSiteURL(v *string) *SiteConfigUpdateOne { + if v != nil { + _u.SetSiteURL(*v) + } + return _u +} + +// SetSiteIcon sets the "site_icon" field. +func (_u *SiteConfigUpdateOne) SetSiteIcon(v string) *SiteConfigUpdateOne { + _u.mutation.SetSiteIcon(v) + return _u +} + +// SetNillableSiteIcon sets the "site_icon" field if the given value is not nil. +func (_u *SiteConfigUpdateOne) SetNillableSiteIcon(v *string) *SiteConfigUpdateOne { + if v != nil { + _u.SetSiteIcon(*v) + } + return _u +} + +// SetSiteDescription sets the "site_description" field. +func (_u *SiteConfigUpdateOne) SetSiteDescription(v string) *SiteConfigUpdateOne { + _u.mutation.SetSiteDescription(v) + return _u +} + +// SetNillableSiteDescription sets the "site_description" field if the given value is not nil. +func (_u *SiteConfigUpdateOne) SetNillableSiteDescription(v *string) *SiteConfigUpdateOne { + if v != nil { + _u.SetSiteDescription(*v) + } + return _u +} + +// SetSiteKeywords sets the "site_keywords" field. +func (_u *SiteConfigUpdateOne) SetSiteKeywords(v string) *SiteConfigUpdateOne { + _u.mutation.SetSiteKeywords(v) + return _u +} + +// SetNillableSiteKeywords sets the "site_keywords" field if the given value is not nil. +func (_u *SiteConfigUpdateOne) SetNillableSiteKeywords(v *string) *SiteConfigUpdateOne { + if v != nil { + _u.SetSiteKeywords(*v) + } + return _u +} + +// SetUserName sets the "user_name" field. +func (_u *SiteConfigUpdateOne) SetUserName(v string) *SiteConfigUpdateOne { + _u.mutation.SetUserName(v) + return _u +} + +// SetNillableUserName sets the "user_name" field if the given value is not nil. +func (_u *SiteConfigUpdateOne) SetNillableUserName(v *string) *SiteConfigUpdateOne { + if v != nil { + _u.SetUserName(*v) + } + return _u +} + +// SetProfileImageURL sets the "profile_image_url" field. +func (_u *SiteConfigUpdateOne) SetProfileImageURL(v string) *SiteConfigUpdateOne { + _u.mutation.SetProfileImageURL(v) + return _u +} + +// SetNillableProfileImageURL sets the "profile_image_url" field if the given value is not nil. +func (_u *SiteConfigUpdateOne) SetNillableProfileImageURL(v *string) *SiteConfigUpdateOne { + if v != nil { + _u.SetProfileImageURL(*v) + } + return _u +} + +// ClearProfileImageURL clears the value of the "profile_image_url" field. +func (_u *SiteConfigUpdateOne) ClearProfileImageURL() *SiteConfigUpdateOne { + _u.mutation.ClearProfileImageURL() + return _u +} + +// SetIcpNumber sets the "icp_number" field. +func (_u *SiteConfigUpdateOne) SetIcpNumber(v string) *SiteConfigUpdateOne { + _u.mutation.SetIcpNumber(v) + return _u +} + +// SetNillableIcpNumber sets the "icp_number" field if the given value is not nil. +func (_u *SiteConfigUpdateOne) SetNillableIcpNumber(v *string) *SiteConfigUpdateOne { + if v != nil { + _u.SetIcpNumber(*v) + } + return _u +} + +// ClearIcpNumber clears the value of the "icp_number" field. +func (_u *SiteConfigUpdateOne) ClearIcpNumber() *SiteConfigUpdateOne { + _u.mutation.ClearIcpNumber() + return _u +} + +// SetPoliceNumber sets the "police_number" field. +func (_u *SiteConfigUpdateOne) SetPoliceNumber(v string) *SiteConfigUpdateOne { + _u.mutation.SetPoliceNumber(v) + return _u +} + +// SetNillablePoliceNumber sets the "police_number" field if the given value is not nil. +func (_u *SiteConfigUpdateOne) SetNillablePoliceNumber(v *string) *SiteConfigUpdateOne { + if v != nil { + _u.SetPoliceNumber(*v) + } + return _u +} + +// ClearPoliceNumber clears the value of the "police_number" field. +func (_u *SiteConfigUpdateOne) ClearPoliceNumber() *SiteConfigUpdateOne { + _u.mutation.ClearPoliceNumber() + return _u +} + +// SetPageTitle sets the "page_title" field. +func (_u *SiteConfigUpdateOne) SetPageTitle(v string) *SiteConfigUpdateOne { + _u.mutation.SetPageTitle(v) + return _u +} + +// SetNillablePageTitle sets the "page_title" field if the given value is not nil. +func (_u *SiteConfigUpdateOne) SetNillablePageTitle(v *string) *SiteConfigUpdateOne { + if v != nil { + _u.SetPageTitle(*v) + } + return _u +} + +// ClearPageTitle clears the value of the "page_title" field. +func (_u *SiteConfigUpdateOne) ClearPageTitle() *SiteConfigUpdateOne { + _u.mutation.ClearPageTitle() + return _u +} + +// SetFavicon sets the "favicon" field. +func (_u *SiteConfigUpdateOne) SetFavicon(v string) *SiteConfigUpdateOne { + _u.mutation.SetFavicon(v) + return _u +} + +// SetNillableFavicon sets the "favicon" field if the given value is not nil. +func (_u *SiteConfigUpdateOne) SetNillableFavicon(v *string) *SiteConfigUpdateOne { + if v != nil { + _u.SetFavicon(*v) + } + return _u +} + +// ClearFavicon clears the value of the "favicon" field. +func (_u *SiteConfigUpdateOne) ClearFavicon() *SiteConfigUpdateOne { + _u.mutation.ClearFavicon() + return _u +} + +// SetUmamiScript sets the "umami_script" field. +func (_u *SiteConfigUpdateOne) SetUmamiScript(v string) *SiteConfigUpdateOne { + _u.mutation.SetUmamiScript(v) + return _u +} + +// SetNillableUmamiScript sets the "umami_script" field if the given value is not nil. +func (_u *SiteConfigUpdateOne) SetNillableUmamiScript(v *string) *SiteConfigUpdateOne { + if v != nil { + _u.SetUmamiScript(*v) + } + return _u +} + +// ClearUmamiScript clears the value of the "umami_script" field. +func (_u *SiteConfigUpdateOne) ClearUmamiScript() *SiteConfigUpdateOne { + _u.mutation.ClearUmamiScript() + return _u +} + +// SetUmamiWebsiteID sets the "umami_website_id" field. +func (_u *SiteConfigUpdateOne) SetUmamiWebsiteID(v string) *SiteConfigUpdateOne { + _u.mutation.SetUmamiWebsiteID(v) + return _u +} + +// SetNillableUmamiWebsiteID sets the "umami_website_id" field if the given value is not nil. +func (_u *SiteConfigUpdateOne) SetNillableUmamiWebsiteID(v *string) *SiteConfigUpdateOne { + if v != nil { + _u.SetUmamiWebsiteID(*v) + } + return _u +} + +// ClearUmamiWebsiteID clears the value of the "umami_website_id" field. +func (_u *SiteConfigUpdateOne) ClearUmamiWebsiteID() *SiteConfigUpdateOne { + _u.mutation.ClearUmamiWebsiteID() + return _u +} + +// SetIconLibrary sets the "icon_library" field. +func (_u *SiteConfigUpdateOne) SetIconLibrary(v string) *SiteConfigUpdateOne { + _u.mutation.SetIconLibrary(v) + return _u +} + +// SetNillableIconLibrary sets the "icon_library" field if the given value is not nil. +func (_u *SiteConfigUpdateOne) SetNillableIconLibrary(v *string) *SiteConfigUpdateOne { + if v != nil { + _u.SetIconLibrary(*v) + } + return _u +} + +// ClearIconLibrary clears the value of the "icon_library" field. +func (_u *SiteConfigUpdateOne) ClearIconLibrary() *SiteConfigUpdateOne { + _u.mutation.ClearIconLibrary() + return _u +} + +// SetFontLibrary sets the "font_library" field. +func (_u *SiteConfigUpdateOne) SetFontLibrary(v string) *SiteConfigUpdateOne { + _u.mutation.SetFontLibrary(v) + return _u +} + +// SetNillableFontLibrary sets the "font_library" field if the given value is not nil. +func (_u *SiteConfigUpdateOne) SetNillableFontLibrary(v *string) *SiteConfigUpdateOne { + if v != nil { + _u.SetFontLibrary(*v) + } + return _u +} + +// ClearFontLibrary clears the value of the "font_library" field. +func (_u *SiteConfigUpdateOne) ClearFontLibrary() *SiteConfigUpdateOne { + _u.mutation.ClearFontLibrary() + return _u +} + +// Mutation returns the SiteConfigMutation object of the builder. +func (_u *SiteConfigUpdateOne) Mutation() *SiteConfigMutation { + return _u.mutation +} + +// Where appends a list predicates to the SiteConfigUpdate builder. +func (_u *SiteConfigUpdateOne) Where(ps ...predicate.SiteConfig) *SiteConfigUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *SiteConfigUpdateOne) Select(field string, fields ...string) *SiteConfigUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated SiteConfig entity. +func (_u *SiteConfigUpdateOne) Save(ctx context.Context) (*SiteConfig, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *SiteConfigUpdateOne) SaveX(ctx context.Context) *SiteConfig { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *SiteConfigUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *SiteConfigUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *SiteConfigUpdateOne) sqlSave(ctx context.Context) (_node *SiteConfig, err error) { + _spec := sqlgraph.NewUpdateSpec(siteconfig.Table, siteconfig.Columns, sqlgraph.NewFieldSpec(siteconfig.FieldID, field.TypeInt)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "SiteConfig.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, siteconfig.FieldID) + for _, f := range fields { + if !siteconfig.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != siteconfig.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.SiteName(); ok { + _spec.SetField(siteconfig.FieldSiteName, field.TypeString, value) + } + if value, ok := _u.mutation.SiteURL(); ok { + _spec.SetField(siteconfig.FieldSiteURL, field.TypeString, value) + } + if value, ok := _u.mutation.SiteIcon(); ok { + _spec.SetField(siteconfig.FieldSiteIcon, field.TypeString, value) + } + if value, ok := _u.mutation.SiteDescription(); ok { + _spec.SetField(siteconfig.FieldSiteDescription, field.TypeString, value) + } + if value, ok := _u.mutation.SiteKeywords(); ok { + _spec.SetField(siteconfig.FieldSiteKeywords, field.TypeString, value) + } + if value, ok := _u.mutation.UserName(); ok { + _spec.SetField(siteconfig.FieldUserName, field.TypeString, value) + } + if value, ok := _u.mutation.ProfileImageURL(); ok { + _spec.SetField(siteconfig.FieldProfileImageURL, field.TypeString, value) + } + if _u.mutation.ProfileImageURLCleared() { + _spec.ClearField(siteconfig.FieldProfileImageURL, field.TypeString) + } + if value, ok := _u.mutation.IcpNumber(); ok { + _spec.SetField(siteconfig.FieldIcpNumber, field.TypeString, value) + } + if _u.mutation.IcpNumberCleared() { + _spec.ClearField(siteconfig.FieldIcpNumber, field.TypeString) + } + if value, ok := _u.mutation.PoliceNumber(); ok { + _spec.SetField(siteconfig.FieldPoliceNumber, field.TypeString, value) + } + if _u.mutation.PoliceNumberCleared() { + _spec.ClearField(siteconfig.FieldPoliceNumber, field.TypeString) + } + if value, ok := _u.mutation.PageTitle(); ok { + _spec.SetField(siteconfig.FieldPageTitle, field.TypeString, value) + } + if _u.mutation.PageTitleCleared() { + _spec.ClearField(siteconfig.FieldPageTitle, field.TypeString) + } + if value, ok := _u.mutation.Favicon(); ok { + _spec.SetField(siteconfig.FieldFavicon, field.TypeString, value) + } + if _u.mutation.FaviconCleared() { + _spec.ClearField(siteconfig.FieldFavicon, field.TypeString) + } + if value, ok := _u.mutation.UmamiScript(); ok { + _spec.SetField(siteconfig.FieldUmamiScript, field.TypeString, value) + } + if _u.mutation.UmamiScriptCleared() { + _spec.ClearField(siteconfig.FieldUmamiScript, field.TypeString) + } + if value, ok := _u.mutation.UmamiWebsiteID(); ok { + _spec.SetField(siteconfig.FieldUmamiWebsiteID, field.TypeString, value) + } + if _u.mutation.UmamiWebsiteIDCleared() { + _spec.ClearField(siteconfig.FieldUmamiWebsiteID, field.TypeString) + } + if value, ok := _u.mutation.IconLibrary(); ok { + _spec.SetField(siteconfig.FieldIconLibrary, field.TypeString, value) + } + if _u.mutation.IconLibraryCleared() { + _spec.ClearField(siteconfig.FieldIconLibrary, field.TypeString) + } + if value, ok := _u.mutation.FontLibrary(); ok { + _spec.SetField(siteconfig.FieldFontLibrary, field.TypeString, value) + } + if _u.mutation.FontLibraryCleared() { + _spec.ClearField(siteconfig.FieldFontLibrary, field.TypeString) + } + _node = &SiteConfig{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{siteconfig.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/internal/ent/tx.go b/internal/ent/tx.go new file mode 100644 index 0000000..7b07980 --- /dev/null +++ b/internal/ent/tx.go @@ -0,0 +1,225 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "sync" + + "entgo.io/ent/dialect" +) + +// Tx is a transactional client that is created by calling Client.Tx(). +type Tx struct { + config + // Contact is the client for interacting with the Contact builders. + Contact *ContactClient + // LoginHistory is the client for interacting with the LoginHistory builders. + LoginHistory *LoginHistoryClient + // Site is the client for interacting with the Site builders. + Site *SiteClient + // SiteConfig is the client for interacting with the SiteConfig builders. + SiteConfig *SiteConfigClient + // User is the client for interacting with the User builders. + User *UserClient + // Visit is the client for interacting with the Visit builders. + Visit *VisitClient + + // lazily loaded. + client *Client + clientOnce sync.Once + // ctx lives for the life of the transaction. It is + // the same context used by the underlying connection. + ctx context.Context +} + +type ( + // Committer is the interface that wraps the Commit method. + Committer interface { + Commit(context.Context, *Tx) error + } + + // The CommitFunc type is an adapter to allow the use of ordinary + // function as a Committer. If f is a function with the appropriate + // signature, CommitFunc(f) is a Committer that calls f. + CommitFunc func(context.Context, *Tx) error + + // CommitHook defines the "commit middleware". A function that gets a Committer + // and returns a Committer. For example: + // + // hook := func(next ent.Committer) ent.Committer { + // return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Commit(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + CommitHook func(Committer) Committer +) + +// Commit calls f(ctx, m). +func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Commit commits the transaction. +func (tx *Tx) Commit() error { + txDriver := tx.config.driver.(*txDriver) + var fn Committer = CommitFunc(func(context.Context, *Tx) error { + return txDriver.tx.Commit() + }) + txDriver.mu.Lock() + hooks := append([]CommitHook(nil), txDriver.onCommit...) + txDriver.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Commit(tx.ctx, tx) +} + +// OnCommit adds a hook to call on commit. +func (tx *Tx) OnCommit(f CommitHook) { + txDriver := tx.config.driver.(*txDriver) + txDriver.mu.Lock() + txDriver.onCommit = append(txDriver.onCommit, f) + txDriver.mu.Unlock() +} + +type ( + // Rollbacker is the interface that wraps the Rollback method. + Rollbacker interface { + Rollback(context.Context, *Tx) error + } + + // The RollbackFunc type is an adapter to allow the use of ordinary + // function as a Rollbacker. If f is a function with the appropriate + // signature, RollbackFunc(f) is a Rollbacker that calls f. + RollbackFunc func(context.Context, *Tx) error + + // RollbackHook defines the "rollback middleware". A function that gets a Rollbacker + // and returns a Rollbacker. For example: + // + // hook := func(next ent.Rollbacker) ent.Rollbacker { + // return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Rollback(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + RollbackHook func(Rollbacker) Rollbacker +) + +// Rollback calls f(ctx, m). +func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Rollback rollbacks the transaction. +func (tx *Tx) Rollback() error { + txDriver := tx.config.driver.(*txDriver) + var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error { + return txDriver.tx.Rollback() + }) + txDriver.mu.Lock() + hooks := append([]RollbackHook(nil), txDriver.onRollback...) + txDriver.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Rollback(tx.ctx, tx) +} + +// OnRollback adds a hook to call on rollback. +func (tx *Tx) OnRollback(f RollbackHook) { + txDriver := tx.config.driver.(*txDriver) + txDriver.mu.Lock() + txDriver.onRollback = append(txDriver.onRollback, f) + txDriver.mu.Unlock() +} + +// Client returns a Client that binds to current transaction. +func (tx *Tx) Client() *Client { + tx.clientOnce.Do(func() { + tx.client = &Client{config: tx.config} + tx.client.init() + }) + return tx.client +} + +func (tx *Tx) init() { + tx.Contact = NewContactClient(tx.config) + tx.LoginHistory = NewLoginHistoryClient(tx.config) + tx.Site = NewSiteClient(tx.config) + tx.SiteConfig = NewSiteConfigClient(tx.config) + tx.User = NewUserClient(tx.config) + tx.Visit = NewVisitClient(tx.config) +} + +// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation. +// The idea is to support transactions without adding any extra code to the builders. +// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance. +// Commit and Rollback are nop for the internal builders and the user must call one +// of them in order to commit or rollback the transaction. +// +// If a closed transaction is embedded in one of the generated entities, and the entity +// applies a query, for example: Contact.QueryXXX(), the query will be executed +// through the driver which created this transaction. +// +// Note that txDriver is not goroutine safe. +type txDriver struct { + // the driver we started the transaction from. + drv dialect.Driver + // tx is the underlying transaction. + tx dialect.Tx + // completion hooks. + mu sync.Mutex + onCommit []CommitHook + onRollback []RollbackHook +} + +// newTx creates a new transactional driver. +func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) { + tx, err := drv.Tx(ctx) + if err != nil { + return nil, err + } + return &txDriver{tx: tx, drv: drv}, nil +} + +// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls +// from the internal builders. Should be called only by the internal builders. +func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil } + +// Dialect returns the dialect of the driver we started the transaction from. +func (tx *txDriver) Dialect() string { return tx.drv.Dialect() } + +// Close is a nop close. +func (*txDriver) Close() error { return nil } + +// Commit is a nop commit for the internal builders. +// User must call `Tx.Commit` in order to commit the transaction. +func (*txDriver) Commit() error { return nil } + +// Rollback is a nop rollback for the internal builders. +// User must call `Tx.Rollback` in order to rollback the transaction. +func (*txDriver) Rollback() error { return nil } + +// Exec calls tx.Exec. +func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error { + return tx.tx.Exec(ctx, query, args, v) +} + +// Query calls tx.Query. +func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error { + return tx.tx.Query(ctx, query, args, v) +} + +var _ dialect.Driver = (*txDriver)(nil) diff --git a/internal/ent/user.go b/internal/ent/user.go new file mode 100644 index 0000000..3155856 --- /dev/null +++ b/internal/ent/user.go @@ -0,0 +1,114 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "home-vue-go/internal/ent/user" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// User is the model entity for the User schema. +type User struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // 用户名 + Username string `json:"username,omitempty"` + // 密码(bcrypt哈希) + Password string `json:"password,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*User) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case user.FieldID: + values[i] = new(sql.NullInt64) + case user.FieldUsername, user.FieldPassword: + values[i] = new(sql.NullString) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the User fields. +func (_m *User) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case user.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int(value.Int64) + case user.FieldUsername: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field username", values[i]) + } else if value.Valid { + _m.Username = value.String + } + case user.FieldPassword: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field password", values[i]) + } else if value.Valid { + _m.Password = value.String + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the User. +// This includes values selected through modifiers, order, etc. +func (_m *User) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this User. +// Note that you need to call User.Unwrap() before calling this method if this User +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *User) Update() *UserUpdateOne { + return NewUserClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the User entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *User) Unwrap() *User { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: User is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *User) String() string { + var builder strings.Builder + builder.WriteString("User(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("username=") + builder.WriteString(_m.Username) + builder.WriteString(", ") + builder.WriteString("password=") + builder.WriteString(_m.Password) + builder.WriteByte(')') + return builder.String() +} + +// Users is a parsable slice of User. +type Users []*User diff --git a/internal/ent/user/user.go b/internal/ent/user/user.go new file mode 100644 index 0000000..027dec1 --- /dev/null +++ b/internal/ent/user/user.go @@ -0,0 +1,55 @@ +// Code generated by ent, DO NOT EDIT. + +package user + +import ( + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the user type in the database. + Label = "user" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldUsername holds the string denoting the username field in the database. + FieldUsername = "username" + // FieldPassword holds the string denoting the password field in the database. + FieldPassword = "password" + // Table holds the table name of the user in the database. + Table = "users" +) + +// Columns holds all SQL columns for user fields. +var Columns = []string{ + FieldID, + FieldUsername, + FieldPassword, +} + +// 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 User queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByUsername orders the results by the username field. +func ByUsername(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUsername, opts...).ToFunc() +} + +// ByPassword orders the results by the password field. +func ByPassword(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPassword, opts...).ToFunc() +} diff --git a/internal/ent/user/where.go b/internal/ent/user/where.go new file mode 100644 index 0000000..e06919b --- /dev/null +++ b/internal/ent/user/where.go @@ -0,0 +1,209 @@ +// Code generated by ent, DO NOT EDIT. + +package user + +import ( + "home-vue-go/internal/ent/predicate" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.User { + return predicate.User(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.User { + return predicate.User(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.User { + return predicate.User(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.User { + return predicate.User(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.User { + return predicate.User(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.User { + return predicate.User(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.User { + return predicate.User(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.User { + return predicate.User(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.User { + return predicate.User(sql.FieldLTE(FieldID, id)) +} + +// Username applies equality check predicate on the "username" field. It's identical to UsernameEQ. +func Username(v string) predicate.User { + return predicate.User(sql.FieldEQ(FieldUsername, v)) +} + +// Password applies equality check predicate on the "password" field. It's identical to PasswordEQ. +func Password(v string) predicate.User { + return predicate.User(sql.FieldEQ(FieldPassword, v)) +} + +// UsernameEQ applies the EQ predicate on the "username" field. +func UsernameEQ(v string) predicate.User { + return predicate.User(sql.FieldEQ(FieldUsername, v)) +} + +// UsernameNEQ applies the NEQ predicate on the "username" field. +func UsernameNEQ(v string) predicate.User { + return predicate.User(sql.FieldNEQ(FieldUsername, v)) +} + +// UsernameIn applies the In predicate on the "username" field. +func UsernameIn(vs ...string) predicate.User { + return predicate.User(sql.FieldIn(FieldUsername, vs...)) +} + +// UsernameNotIn applies the NotIn predicate on the "username" field. +func UsernameNotIn(vs ...string) predicate.User { + return predicate.User(sql.FieldNotIn(FieldUsername, vs...)) +} + +// UsernameGT applies the GT predicate on the "username" field. +func UsernameGT(v string) predicate.User { + return predicate.User(sql.FieldGT(FieldUsername, v)) +} + +// UsernameGTE applies the GTE predicate on the "username" field. +func UsernameGTE(v string) predicate.User { + return predicate.User(sql.FieldGTE(FieldUsername, v)) +} + +// UsernameLT applies the LT predicate on the "username" field. +func UsernameLT(v string) predicate.User { + return predicate.User(sql.FieldLT(FieldUsername, v)) +} + +// UsernameLTE applies the LTE predicate on the "username" field. +func UsernameLTE(v string) predicate.User { + return predicate.User(sql.FieldLTE(FieldUsername, v)) +} + +// UsernameContains applies the Contains predicate on the "username" field. +func UsernameContains(v string) predicate.User { + return predicate.User(sql.FieldContains(FieldUsername, v)) +} + +// UsernameHasPrefix applies the HasPrefix predicate on the "username" field. +func UsernameHasPrefix(v string) predicate.User { + return predicate.User(sql.FieldHasPrefix(FieldUsername, v)) +} + +// UsernameHasSuffix applies the HasSuffix predicate on the "username" field. +func UsernameHasSuffix(v string) predicate.User { + return predicate.User(sql.FieldHasSuffix(FieldUsername, v)) +} + +// UsernameEqualFold applies the EqualFold predicate on the "username" field. +func UsernameEqualFold(v string) predicate.User { + return predicate.User(sql.FieldEqualFold(FieldUsername, v)) +} + +// UsernameContainsFold applies the ContainsFold predicate on the "username" field. +func UsernameContainsFold(v string) predicate.User { + return predicate.User(sql.FieldContainsFold(FieldUsername, v)) +} + +// PasswordEQ applies the EQ predicate on the "password" field. +func PasswordEQ(v string) predicate.User { + return predicate.User(sql.FieldEQ(FieldPassword, v)) +} + +// PasswordNEQ applies the NEQ predicate on the "password" field. +func PasswordNEQ(v string) predicate.User { + return predicate.User(sql.FieldNEQ(FieldPassword, v)) +} + +// PasswordIn applies the In predicate on the "password" field. +func PasswordIn(vs ...string) predicate.User { + return predicate.User(sql.FieldIn(FieldPassword, vs...)) +} + +// PasswordNotIn applies the NotIn predicate on the "password" field. +func PasswordNotIn(vs ...string) predicate.User { + return predicate.User(sql.FieldNotIn(FieldPassword, vs...)) +} + +// PasswordGT applies the GT predicate on the "password" field. +func PasswordGT(v string) predicate.User { + return predicate.User(sql.FieldGT(FieldPassword, v)) +} + +// PasswordGTE applies the GTE predicate on the "password" field. +func PasswordGTE(v string) predicate.User { + return predicate.User(sql.FieldGTE(FieldPassword, v)) +} + +// PasswordLT applies the LT predicate on the "password" field. +func PasswordLT(v string) predicate.User { + return predicate.User(sql.FieldLT(FieldPassword, v)) +} + +// PasswordLTE applies the LTE predicate on the "password" field. +func PasswordLTE(v string) predicate.User { + return predicate.User(sql.FieldLTE(FieldPassword, v)) +} + +// PasswordContains applies the Contains predicate on the "password" field. +func PasswordContains(v string) predicate.User { + return predicate.User(sql.FieldContains(FieldPassword, v)) +} + +// PasswordHasPrefix applies the HasPrefix predicate on the "password" field. +func PasswordHasPrefix(v string) predicate.User { + return predicate.User(sql.FieldHasPrefix(FieldPassword, v)) +} + +// PasswordHasSuffix applies the HasSuffix predicate on the "password" field. +func PasswordHasSuffix(v string) predicate.User { + return predicate.User(sql.FieldHasSuffix(FieldPassword, v)) +} + +// PasswordEqualFold applies the EqualFold predicate on the "password" field. +func PasswordEqualFold(v string) predicate.User { + return predicate.User(sql.FieldEqualFold(FieldPassword, v)) +} + +// PasswordContainsFold applies the ContainsFold predicate on the "password" field. +func PasswordContainsFold(v string) predicate.User { + return predicate.User(sql.FieldContainsFold(FieldPassword, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.User) predicate.User { + return predicate.User(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.User) predicate.User { + return predicate.User(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.User) predicate.User { + return predicate.User(sql.NotPredicates(p)) +} diff --git a/internal/ent/user_create.go b/internal/ent/user_create.go new file mode 100644 index 0000000..31c2bf2 --- /dev/null +++ b/internal/ent/user_create.go @@ -0,0 +1,208 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "home-vue-go/internal/ent/user" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// UserCreate is the builder for creating a User entity. +type UserCreate struct { + config + mutation *UserMutation + hooks []Hook +} + +// SetUsername sets the "username" field. +func (_c *UserCreate) SetUsername(v string) *UserCreate { + _c.mutation.SetUsername(v) + return _c +} + +// SetPassword sets the "password" field. +func (_c *UserCreate) SetPassword(v string) *UserCreate { + _c.mutation.SetPassword(v) + return _c +} + +// SetID sets the "id" field. +func (_c *UserCreate) SetID(v int) *UserCreate { + _c.mutation.SetID(v) + return _c +} + +// Mutation returns the UserMutation object of the builder. +func (_c *UserCreate) Mutation() *UserMutation { + return _c.mutation +} + +// Save creates the User in the database. +func (_c *UserCreate) Save(ctx context.Context) (*User, error) { + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *UserCreate) SaveX(ctx context.Context) *User { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *UserCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *UserCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *UserCreate) check() error { + if _, ok := _c.mutation.Username(); !ok { + return &ValidationError{Name: "username", err: errors.New(`ent: missing required field "User.username"`)} + } + if _, ok := _c.mutation.Password(); !ok { + return &ValidationError{Name: "password", err: errors.New(`ent: missing required field "User.password"`)} + } + return nil +} + +func (_c *UserCreate) sqlSave(ctx context.Context) (*User, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != _node.ID { + id := _spec.ID.Value.(int64) + _node.ID = int(id) + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { + var ( + _node = &User{config: _c.config} + _spec = sqlgraph.NewCreateSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) + ) + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.Username(); ok { + _spec.SetField(user.FieldUsername, field.TypeString, value) + _node.Username = value + } + if value, ok := _c.mutation.Password(); ok { + _spec.SetField(user.FieldPassword, field.TypeString, value) + _node.Password = value + } + return _node, _spec +} + +// UserCreateBulk is the builder for creating many User entities in bulk. +type UserCreateBulk struct { + config + err error + builders []*UserCreate +} + +// Save creates the User entities in the database. +func (_c *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*User, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil && nodes[i].ID == 0 { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *UserCreateBulk) SaveX(ctx context.Context) []*User { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *UserCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *UserCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/ent/user_delete.go b/internal/ent/user_delete.go new file mode 100644 index 0000000..f89f340 --- /dev/null +++ b/internal/ent/user_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "home-vue-go/internal/ent/predicate" + "home-vue-go/internal/ent/user" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// UserDelete is the builder for deleting a User entity. +type UserDelete struct { + config + hooks []Hook + mutation *UserMutation +} + +// Where appends a list predicates to the UserDelete builder. +func (_d *UserDelete) Where(ps ...predicate.User) *UserDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *UserDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *UserDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *UserDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// UserDeleteOne is the builder for deleting a single User entity. +type UserDeleteOne struct { + _d *UserDelete +} + +// Where appends a list predicates to the UserDelete builder. +func (_d *UserDeleteOne) Where(ps ...predicate.User) *UserDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *UserDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{user.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *UserDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/ent/user_query.go b/internal/ent/user_query.go new file mode 100644 index 0000000..30fd3f2 --- /dev/null +++ b/internal/ent/user_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "home-vue-go/internal/ent/predicate" + "home-vue-go/internal/ent/user" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// UserQuery is the builder for querying User entities. +type UserQuery struct { + config + ctx *QueryContext + order []user.OrderOption + inters []Interceptor + predicates []predicate.User + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the UserQuery builder. +func (_q *UserQuery) Where(ps ...predicate.User) *UserQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *UserQuery) Limit(limit int) *UserQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *UserQuery) Offset(offset int) *UserQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *UserQuery) Unique(unique bool) *UserQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *UserQuery) Order(o ...user.OrderOption) *UserQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first User entity from the query. +// Returns a *NotFoundError when no User was found. +func (_q *UserQuery) First(ctx context.Context) (*User, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{user.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *UserQuery) FirstX(ctx context.Context) *User { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first User ID from the query. +// Returns a *NotFoundError when no User ID was found. +func (_q *UserQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{user.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *UserQuery) FirstIDX(ctx context.Context) int { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single User entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one User entity is found. +// Returns a *NotFoundError when no User entities are found. +func (_q *UserQuery) Only(ctx context.Context) (*User, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{user.Label} + default: + return nil, &NotSingularError{user.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *UserQuery) OnlyX(ctx context.Context) *User { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only User ID in the query. +// Returns a *NotSingularError when more than one User ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *UserQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{user.Label} + default: + err = &NotSingularError{user.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *UserQuery) OnlyIDX(ctx context.Context) int { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Users. +func (_q *UserQuery) All(ctx context.Context) ([]*User, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*User, *UserQuery]() + return withInterceptors[[]*User](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *UserQuery) AllX(ctx context.Context) []*User { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of User IDs. +func (_q *UserQuery) IDs(ctx context.Context) (ids []int, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(user.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *UserQuery) IDsX(ctx context.Context) []int { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *UserQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*UserQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *UserQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *UserQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *UserQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the UserQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *UserQuery) Clone() *UserQuery { + if _q == nil { + return nil + } + return &UserQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]user.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.User{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Username string `json:"username,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.User.Query(). +// GroupBy(user.FieldUsername). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *UserQuery) GroupBy(field string, fields ...string) *UserGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &UserGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = user.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// Username string `json:"username,omitempty"` +// } +// +// client.User.Query(). +// Select(user.FieldUsername). +// Scan(ctx, &v) +func (_q *UserQuery) Select(fields ...string) *UserSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &UserSelect{UserQuery: _q} + sbuild.label = user.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a UserSelect configured with the given aggregations. +func (_q *UserQuery) Aggregate(fns ...AggregateFunc) *UserSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *UserQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !user.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, error) { + var ( + nodes = []*User{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*User).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &User{config: _q.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (_q *UserQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *UserQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, user.FieldID) + for i := range fields { + if fields[i] != user.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *UserQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(user.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = user.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// UserGroupBy is the group-by builder for User entities. +type UserGroupBy struct { + selector + build *UserQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *UserGroupBy) Aggregate(fns ...AggregateFunc) *UserGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *UserGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*UserQuery, *UserGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *UserGroupBy) sqlScan(ctx context.Context, root *UserQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// UserSelect is the builder for selecting fields of User entities. +type UserSelect struct { + *UserQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *UserSelect) Aggregate(fns ...AggregateFunc) *UserSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *UserSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*UserQuery, *UserSelect](ctx, _s.UserQuery, _s, _s.inters, v) +} + +func (_s *UserSelect) sqlScan(ctx context.Context, root *UserQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/internal/ent/user_update.go b/internal/ent/user_update.go new file mode 100644 index 0000000..fed4503 --- /dev/null +++ b/internal/ent/user_update.go @@ -0,0 +1,243 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "home-vue-go/internal/ent/predicate" + "home-vue-go/internal/ent/user" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// UserUpdate is the builder for updating User entities. +type UserUpdate struct { + config + hooks []Hook + mutation *UserMutation +} + +// Where appends a list predicates to the UserUpdate builder. +func (_u *UserUpdate) Where(ps ...predicate.User) *UserUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUsername sets the "username" field. +func (_u *UserUpdate) SetUsername(v string) *UserUpdate { + _u.mutation.SetUsername(v) + return _u +} + +// SetNillableUsername sets the "username" field if the given value is not nil. +func (_u *UserUpdate) SetNillableUsername(v *string) *UserUpdate { + if v != nil { + _u.SetUsername(*v) + } + return _u +} + +// SetPassword sets the "password" field. +func (_u *UserUpdate) SetPassword(v string) *UserUpdate { + _u.mutation.SetPassword(v) + return _u +} + +// SetNillablePassword sets the "password" field if the given value is not nil. +func (_u *UserUpdate) SetNillablePassword(v *string) *UserUpdate { + if v != nil { + _u.SetPassword(*v) + } + return _u +} + +// Mutation returns the UserMutation object of the builder. +func (_u *UserUpdate) Mutation() *UserMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *UserUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *UserUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *UserUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *UserUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *UserUpdate) sqlSave(ctx context.Context) (_node int, err error) { + _spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Username(); ok { + _spec.SetField(user.FieldUsername, field.TypeString, value) + } + if value, ok := _u.mutation.Password(); ok { + _spec.SetField(user.FieldPassword, field.TypeString, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{user.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// UserUpdateOne is the builder for updating a single User entity. +type UserUpdateOne struct { + config + fields []string + hooks []Hook + mutation *UserMutation +} + +// SetUsername sets the "username" field. +func (_u *UserUpdateOne) SetUsername(v string) *UserUpdateOne { + _u.mutation.SetUsername(v) + return _u +} + +// SetNillableUsername sets the "username" field if the given value is not nil. +func (_u *UserUpdateOne) SetNillableUsername(v *string) *UserUpdateOne { + if v != nil { + _u.SetUsername(*v) + } + return _u +} + +// SetPassword sets the "password" field. +func (_u *UserUpdateOne) SetPassword(v string) *UserUpdateOne { + _u.mutation.SetPassword(v) + return _u +} + +// SetNillablePassword sets the "password" field if the given value is not nil. +func (_u *UserUpdateOne) SetNillablePassword(v *string) *UserUpdateOne { + if v != nil { + _u.SetPassword(*v) + } + return _u +} + +// Mutation returns the UserMutation object of the builder. +func (_u *UserUpdateOne) Mutation() *UserMutation { + return _u.mutation +} + +// Where appends a list predicates to the UserUpdate builder. +func (_u *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *UserUpdateOne) Select(field string, fields ...string) *UserUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated User entity. +func (_u *UserUpdateOne) Save(ctx context.Context) (*User, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *UserUpdateOne) SaveX(ctx context.Context) *User { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *UserUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *UserUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) { + _spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "User.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, user.FieldID) + for _, f := range fields { + if !user.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != user.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Username(); ok { + _spec.SetField(user.FieldUsername, field.TypeString, value) + } + if value, ok := _u.mutation.Password(); ok { + _spec.SetField(user.FieldPassword, field.TypeString, value) + } + _node = &User{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{user.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/internal/ent/visit.go b/internal/ent/visit.go new file mode 100644 index 0000000..bb6ddff --- /dev/null +++ b/internal/ent/visit.go @@ -0,0 +1,150 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "home-vue-go/internal/ent/visit" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// Visit is the model entity for the Visit schema. +type Visit struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // 访问路径 + Path string `json:"path,omitempty"` + // 访问IP + IP string `json:"ip,omitempty"` + // 用户代理 + UserAgent string `json:"user_agent,omitempty"` + // 来源页面 + Referer string `json:"referer,omitempty"` + // 访问时间 + VisitTime time.Time `json:"visit_time,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Visit) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case visit.FieldID: + values[i] = new(sql.NullInt64) + case visit.FieldPath, visit.FieldIP, visit.FieldUserAgent, visit.FieldReferer: + values[i] = new(sql.NullString) + case visit.FieldVisitTime: + values[i] = new(sql.NullTime) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Visit fields. +func (_m *Visit) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case visit.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int(value.Int64) + case visit.FieldPath: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field path", values[i]) + } else if value.Valid { + _m.Path = value.String + } + case visit.FieldIP: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field ip", values[i]) + } else if value.Valid { + _m.IP = value.String + } + case visit.FieldUserAgent: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field user_agent", values[i]) + } else if value.Valid { + _m.UserAgent = value.String + } + case visit.FieldReferer: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field referer", values[i]) + } else if value.Valid { + _m.Referer = value.String + } + case visit.FieldVisitTime: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field visit_time", values[i]) + } else if value.Valid { + _m.VisitTime = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Visit. +// This includes values selected through modifiers, order, etc. +func (_m *Visit) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this Visit. +// Note that you need to call Visit.Unwrap() before calling this method if this Visit +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Visit) Update() *VisitUpdateOne { + return NewVisitClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Visit entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *Visit) Unwrap() *Visit { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: Visit is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Visit) String() string { + var builder strings.Builder + builder.WriteString("Visit(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("path=") + builder.WriteString(_m.Path) + builder.WriteString(", ") + builder.WriteString("ip=") + builder.WriteString(_m.IP) + builder.WriteString(", ") + builder.WriteString("user_agent=") + builder.WriteString(_m.UserAgent) + builder.WriteString(", ") + builder.WriteString("referer=") + builder.WriteString(_m.Referer) + builder.WriteString(", ") + builder.WriteString("visit_time=") + builder.WriteString(_m.VisitTime.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// Visits is a parsable slice of Visit. +type Visits []*Visit diff --git a/internal/ent/visit/visit.go b/internal/ent/visit/visit.go new file mode 100644 index 0000000..3f3cf66 --- /dev/null +++ b/internal/ent/visit/visit.go @@ -0,0 +1,86 @@ +// Code generated by ent, DO NOT EDIT. + +package visit + +import ( + "time" + + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the visit type in the database. + Label = "visit" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldPath holds the string denoting the path field in the database. + FieldPath = "path" + // FieldIP holds the string denoting the ip field in the database. + FieldIP = "ip" + // FieldUserAgent holds the string denoting the user_agent field in the database. + FieldUserAgent = "user_agent" + // FieldReferer holds the string denoting the referer field in the database. + FieldReferer = "referer" + // FieldVisitTime holds the string denoting the visit_time field in the database. + FieldVisitTime = "visit_time" + // Table holds the table name of the visit in the database. + Table = "visits" +) + +// Columns holds all SQL columns for visit fields. +var Columns = []string{ + FieldID, + FieldPath, + FieldIP, + FieldUserAgent, + FieldReferer, + FieldVisitTime, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultVisitTime holds the default value on creation for the "visit_time" field. + DefaultVisitTime func() time.Time +) + +// OrderOption defines the ordering options for the Visit 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() +} + +// ByPath orders the results by the path field. +func ByPath(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPath, opts...).ToFunc() +} + +// ByIP orders the results by the ip field. +func ByIP(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIP, opts...).ToFunc() +} + +// ByUserAgent orders the results by the user_agent field. +func ByUserAgent(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUserAgent, opts...).ToFunc() +} + +// ByReferer orders the results by the referer field. +func ByReferer(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldReferer, opts...).ToFunc() +} + +// ByVisitTime orders the results by the visit_time field. +func ByVisitTime(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldVisitTime, opts...).ToFunc() +} diff --git a/internal/ent/visit/where.go b/internal/ent/visit/where.go new file mode 100644 index 0000000..fa19eb2 --- /dev/null +++ b/internal/ent/visit/where.go @@ -0,0 +1,415 @@ +// Code generated by ent, DO NOT EDIT. + +package visit + +import ( + "home-vue-go/internal/ent/predicate" + "time" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.Visit { + return predicate.Visit(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.Visit { + return predicate.Visit(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.Visit { + return predicate.Visit(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.Visit { + return predicate.Visit(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.Visit { + return predicate.Visit(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.Visit { + return predicate.Visit(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.Visit { + return predicate.Visit(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.Visit { + return predicate.Visit(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.Visit { + return predicate.Visit(sql.FieldLTE(FieldID, id)) +} + +// Path applies equality check predicate on the "path" field. It's identical to PathEQ. +func Path(v string) predicate.Visit { + return predicate.Visit(sql.FieldEQ(FieldPath, v)) +} + +// IP applies equality check predicate on the "ip" field. It's identical to IPEQ. +func IP(v string) predicate.Visit { + return predicate.Visit(sql.FieldEQ(FieldIP, v)) +} + +// UserAgent applies equality check predicate on the "user_agent" field. It's identical to UserAgentEQ. +func UserAgent(v string) predicate.Visit { + return predicate.Visit(sql.FieldEQ(FieldUserAgent, v)) +} + +// Referer applies equality check predicate on the "referer" field. It's identical to RefererEQ. +func Referer(v string) predicate.Visit { + return predicate.Visit(sql.FieldEQ(FieldReferer, v)) +} + +// VisitTime applies equality check predicate on the "visit_time" field. It's identical to VisitTimeEQ. +func VisitTime(v time.Time) predicate.Visit { + return predicate.Visit(sql.FieldEQ(FieldVisitTime, v)) +} + +// PathEQ applies the EQ predicate on the "path" field. +func PathEQ(v string) predicate.Visit { + return predicate.Visit(sql.FieldEQ(FieldPath, v)) +} + +// PathNEQ applies the NEQ predicate on the "path" field. +func PathNEQ(v string) predicate.Visit { + return predicate.Visit(sql.FieldNEQ(FieldPath, v)) +} + +// PathIn applies the In predicate on the "path" field. +func PathIn(vs ...string) predicate.Visit { + return predicate.Visit(sql.FieldIn(FieldPath, vs...)) +} + +// PathNotIn applies the NotIn predicate on the "path" field. +func PathNotIn(vs ...string) predicate.Visit { + return predicate.Visit(sql.FieldNotIn(FieldPath, vs...)) +} + +// PathGT applies the GT predicate on the "path" field. +func PathGT(v string) predicate.Visit { + return predicate.Visit(sql.FieldGT(FieldPath, v)) +} + +// PathGTE applies the GTE predicate on the "path" field. +func PathGTE(v string) predicate.Visit { + return predicate.Visit(sql.FieldGTE(FieldPath, v)) +} + +// PathLT applies the LT predicate on the "path" field. +func PathLT(v string) predicate.Visit { + return predicate.Visit(sql.FieldLT(FieldPath, v)) +} + +// PathLTE applies the LTE predicate on the "path" field. +func PathLTE(v string) predicate.Visit { + return predicate.Visit(sql.FieldLTE(FieldPath, v)) +} + +// PathContains applies the Contains predicate on the "path" field. +func PathContains(v string) predicate.Visit { + return predicate.Visit(sql.FieldContains(FieldPath, v)) +} + +// PathHasPrefix applies the HasPrefix predicate on the "path" field. +func PathHasPrefix(v string) predicate.Visit { + return predicate.Visit(sql.FieldHasPrefix(FieldPath, v)) +} + +// PathHasSuffix applies the HasSuffix predicate on the "path" field. +func PathHasSuffix(v string) predicate.Visit { + return predicate.Visit(sql.FieldHasSuffix(FieldPath, v)) +} + +// PathEqualFold applies the EqualFold predicate on the "path" field. +func PathEqualFold(v string) predicate.Visit { + return predicate.Visit(sql.FieldEqualFold(FieldPath, v)) +} + +// PathContainsFold applies the ContainsFold predicate on the "path" field. +func PathContainsFold(v string) predicate.Visit { + return predicate.Visit(sql.FieldContainsFold(FieldPath, v)) +} + +// IPEQ applies the EQ predicate on the "ip" field. +func IPEQ(v string) predicate.Visit { + return predicate.Visit(sql.FieldEQ(FieldIP, v)) +} + +// IPNEQ applies the NEQ predicate on the "ip" field. +func IPNEQ(v string) predicate.Visit { + return predicate.Visit(sql.FieldNEQ(FieldIP, v)) +} + +// IPIn applies the In predicate on the "ip" field. +func IPIn(vs ...string) predicate.Visit { + return predicate.Visit(sql.FieldIn(FieldIP, vs...)) +} + +// IPNotIn applies the NotIn predicate on the "ip" field. +func IPNotIn(vs ...string) predicate.Visit { + return predicate.Visit(sql.FieldNotIn(FieldIP, vs...)) +} + +// IPGT applies the GT predicate on the "ip" field. +func IPGT(v string) predicate.Visit { + return predicate.Visit(sql.FieldGT(FieldIP, v)) +} + +// IPGTE applies the GTE predicate on the "ip" field. +func IPGTE(v string) predicate.Visit { + return predicate.Visit(sql.FieldGTE(FieldIP, v)) +} + +// IPLT applies the LT predicate on the "ip" field. +func IPLT(v string) predicate.Visit { + return predicate.Visit(sql.FieldLT(FieldIP, v)) +} + +// IPLTE applies the LTE predicate on the "ip" field. +func IPLTE(v string) predicate.Visit { + return predicate.Visit(sql.FieldLTE(FieldIP, v)) +} + +// IPContains applies the Contains predicate on the "ip" field. +func IPContains(v string) predicate.Visit { + return predicate.Visit(sql.FieldContains(FieldIP, v)) +} + +// IPHasPrefix applies the HasPrefix predicate on the "ip" field. +func IPHasPrefix(v string) predicate.Visit { + return predicate.Visit(sql.FieldHasPrefix(FieldIP, v)) +} + +// IPHasSuffix applies the HasSuffix predicate on the "ip" field. +func IPHasSuffix(v string) predicate.Visit { + return predicate.Visit(sql.FieldHasSuffix(FieldIP, v)) +} + +// IPEqualFold applies the EqualFold predicate on the "ip" field. +func IPEqualFold(v string) predicate.Visit { + return predicate.Visit(sql.FieldEqualFold(FieldIP, v)) +} + +// IPContainsFold applies the ContainsFold predicate on the "ip" field. +func IPContainsFold(v string) predicate.Visit { + return predicate.Visit(sql.FieldContainsFold(FieldIP, v)) +} + +// UserAgentEQ applies the EQ predicate on the "user_agent" field. +func UserAgentEQ(v string) predicate.Visit { + return predicate.Visit(sql.FieldEQ(FieldUserAgent, v)) +} + +// UserAgentNEQ applies the NEQ predicate on the "user_agent" field. +func UserAgentNEQ(v string) predicate.Visit { + return predicate.Visit(sql.FieldNEQ(FieldUserAgent, v)) +} + +// UserAgentIn applies the In predicate on the "user_agent" field. +func UserAgentIn(vs ...string) predicate.Visit { + return predicate.Visit(sql.FieldIn(FieldUserAgent, vs...)) +} + +// UserAgentNotIn applies the NotIn predicate on the "user_agent" field. +func UserAgentNotIn(vs ...string) predicate.Visit { + return predicate.Visit(sql.FieldNotIn(FieldUserAgent, vs...)) +} + +// UserAgentGT applies the GT predicate on the "user_agent" field. +func UserAgentGT(v string) predicate.Visit { + return predicate.Visit(sql.FieldGT(FieldUserAgent, v)) +} + +// UserAgentGTE applies the GTE predicate on the "user_agent" field. +func UserAgentGTE(v string) predicate.Visit { + return predicate.Visit(sql.FieldGTE(FieldUserAgent, v)) +} + +// UserAgentLT applies the LT predicate on the "user_agent" field. +func UserAgentLT(v string) predicate.Visit { + return predicate.Visit(sql.FieldLT(FieldUserAgent, v)) +} + +// UserAgentLTE applies the LTE predicate on the "user_agent" field. +func UserAgentLTE(v string) predicate.Visit { + return predicate.Visit(sql.FieldLTE(FieldUserAgent, v)) +} + +// UserAgentContains applies the Contains predicate on the "user_agent" field. +func UserAgentContains(v string) predicate.Visit { + return predicate.Visit(sql.FieldContains(FieldUserAgent, v)) +} + +// UserAgentHasPrefix applies the HasPrefix predicate on the "user_agent" field. +func UserAgentHasPrefix(v string) predicate.Visit { + return predicate.Visit(sql.FieldHasPrefix(FieldUserAgent, v)) +} + +// UserAgentHasSuffix applies the HasSuffix predicate on the "user_agent" field. +func UserAgentHasSuffix(v string) predicate.Visit { + return predicate.Visit(sql.FieldHasSuffix(FieldUserAgent, v)) +} + +// UserAgentIsNil applies the IsNil predicate on the "user_agent" field. +func UserAgentIsNil() predicate.Visit { + return predicate.Visit(sql.FieldIsNull(FieldUserAgent)) +} + +// UserAgentNotNil applies the NotNil predicate on the "user_agent" field. +func UserAgentNotNil() predicate.Visit { + return predicate.Visit(sql.FieldNotNull(FieldUserAgent)) +} + +// UserAgentEqualFold applies the EqualFold predicate on the "user_agent" field. +func UserAgentEqualFold(v string) predicate.Visit { + return predicate.Visit(sql.FieldEqualFold(FieldUserAgent, v)) +} + +// UserAgentContainsFold applies the ContainsFold predicate on the "user_agent" field. +func UserAgentContainsFold(v string) predicate.Visit { + return predicate.Visit(sql.FieldContainsFold(FieldUserAgent, v)) +} + +// RefererEQ applies the EQ predicate on the "referer" field. +func RefererEQ(v string) predicate.Visit { + return predicate.Visit(sql.FieldEQ(FieldReferer, v)) +} + +// RefererNEQ applies the NEQ predicate on the "referer" field. +func RefererNEQ(v string) predicate.Visit { + return predicate.Visit(sql.FieldNEQ(FieldReferer, v)) +} + +// RefererIn applies the In predicate on the "referer" field. +func RefererIn(vs ...string) predicate.Visit { + return predicate.Visit(sql.FieldIn(FieldReferer, vs...)) +} + +// RefererNotIn applies the NotIn predicate on the "referer" field. +func RefererNotIn(vs ...string) predicate.Visit { + return predicate.Visit(sql.FieldNotIn(FieldReferer, vs...)) +} + +// RefererGT applies the GT predicate on the "referer" field. +func RefererGT(v string) predicate.Visit { + return predicate.Visit(sql.FieldGT(FieldReferer, v)) +} + +// RefererGTE applies the GTE predicate on the "referer" field. +func RefererGTE(v string) predicate.Visit { + return predicate.Visit(sql.FieldGTE(FieldReferer, v)) +} + +// RefererLT applies the LT predicate on the "referer" field. +func RefererLT(v string) predicate.Visit { + return predicate.Visit(sql.FieldLT(FieldReferer, v)) +} + +// RefererLTE applies the LTE predicate on the "referer" field. +func RefererLTE(v string) predicate.Visit { + return predicate.Visit(sql.FieldLTE(FieldReferer, v)) +} + +// RefererContains applies the Contains predicate on the "referer" field. +func RefererContains(v string) predicate.Visit { + return predicate.Visit(sql.FieldContains(FieldReferer, v)) +} + +// RefererHasPrefix applies the HasPrefix predicate on the "referer" field. +func RefererHasPrefix(v string) predicate.Visit { + return predicate.Visit(sql.FieldHasPrefix(FieldReferer, v)) +} + +// RefererHasSuffix applies the HasSuffix predicate on the "referer" field. +func RefererHasSuffix(v string) predicate.Visit { + return predicate.Visit(sql.FieldHasSuffix(FieldReferer, v)) +} + +// RefererIsNil applies the IsNil predicate on the "referer" field. +func RefererIsNil() predicate.Visit { + return predicate.Visit(sql.FieldIsNull(FieldReferer)) +} + +// RefererNotNil applies the NotNil predicate on the "referer" field. +func RefererNotNil() predicate.Visit { + return predicate.Visit(sql.FieldNotNull(FieldReferer)) +} + +// RefererEqualFold applies the EqualFold predicate on the "referer" field. +func RefererEqualFold(v string) predicate.Visit { + return predicate.Visit(sql.FieldEqualFold(FieldReferer, v)) +} + +// RefererContainsFold applies the ContainsFold predicate on the "referer" field. +func RefererContainsFold(v string) predicate.Visit { + return predicate.Visit(sql.FieldContainsFold(FieldReferer, v)) +} + +// VisitTimeEQ applies the EQ predicate on the "visit_time" field. +func VisitTimeEQ(v time.Time) predicate.Visit { + return predicate.Visit(sql.FieldEQ(FieldVisitTime, v)) +} + +// VisitTimeNEQ applies the NEQ predicate on the "visit_time" field. +func VisitTimeNEQ(v time.Time) predicate.Visit { + return predicate.Visit(sql.FieldNEQ(FieldVisitTime, v)) +} + +// VisitTimeIn applies the In predicate on the "visit_time" field. +func VisitTimeIn(vs ...time.Time) predicate.Visit { + return predicate.Visit(sql.FieldIn(FieldVisitTime, vs...)) +} + +// VisitTimeNotIn applies the NotIn predicate on the "visit_time" field. +func VisitTimeNotIn(vs ...time.Time) predicate.Visit { + return predicate.Visit(sql.FieldNotIn(FieldVisitTime, vs...)) +} + +// VisitTimeGT applies the GT predicate on the "visit_time" field. +func VisitTimeGT(v time.Time) predicate.Visit { + return predicate.Visit(sql.FieldGT(FieldVisitTime, v)) +} + +// VisitTimeGTE applies the GTE predicate on the "visit_time" field. +func VisitTimeGTE(v time.Time) predicate.Visit { + return predicate.Visit(sql.FieldGTE(FieldVisitTime, v)) +} + +// VisitTimeLT applies the LT predicate on the "visit_time" field. +func VisitTimeLT(v time.Time) predicate.Visit { + return predicate.Visit(sql.FieldLT(FieldVisitTime, v)) +} + +// VisitTimeLTE applies the LTE predicate on the "visit_time" field. +func VisitTimeLTE(v time.Time) predicate.Visit { + return predicate.Visit(sql.FieldLTE(FieldVisitTime, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Visit) predicate.Visit { + return predicate.Visit(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Visit) predicate.Visit { + return predicate.Visit(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Visit) predicate.Visit { + return predicate.Visit(sql.NotPredicates(p)) +} diff --git a/internal/ent/visit_create.go b/internal/ent/visit_create.go new file mode 100644 index 0000000..fa84f76 --- /dev/null +++ b/internal/ent/visit_create.go @@ -0,0 +1,276 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "home-vue-go/internal/ent/visit" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// VisitCreate is the builder for creating a Visit entity. +type VisitCreate struct { + config + mutation *VisitMutation + hooks []Hook +} + +// SetPath sets the "path" field. +func (_c *VisitCreate) SetPath(v string) *VisitCreate { + _c.mutation.SetPath(v) + return _c +} + +// SetIP sets the "ip" field. +func (_c *VisitCreate) SetIP(v string) *VisitCreate { + _c.mutation.SetIP(v) + return _c +} + +// SetUserAgent sets the "user_agent" field. +func (_c *VisitCreate) SetUserAgent(v string) *VisitCreate { + _c.mutation.SetUserAgent(v) + return _c +} + +// SetNillableUserAgent sets the "user_agent" field if the given value is not nil. +func (_c *VisitCreate) SetNillableUserAgent(v *string) *VisitCreate { + if v != nil { + _c.SetUserAgent(*v) + } + return _c +} + +// SetReferer sets the "referer" field. +func (_c *VisitCreate) SetReferer(v string) *VisitCreate { + _c.mutation.SetReferer(v) + return _c +} + +// SetNillableReferer sets the "referer" field if the given value is not nil. +func (_c *VisitCreate) SetNillableReferer(v *string) *VisitCreate { + if v != nil { + _c.SetReferer(*v) + } + return _c +} + +// SetVisitTime sets the "visit_time" field. +func (_c *VisitCreate) SetVisitTime(v time.Time) *VisitCreate { + _c.mutation.SetVisitTime(v) + return _c +} + +// SetNillableVisitTime sets the "visit_time" field if the given value is not nil. +func (_c *VisitCreate) SetNillableVisitTime(v *time.Time) *VisitCreate { + if v != nil { + _c.SetVisitTime(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *VisitCreate) SetID(v int) *VisitCreate { + _c.mutation.SetID(v) + return _c +} + +// Mutation returns the VisitMutation object of the builder. +func (_c *VisitCreate) Mutation() *VisitMutation { + return _c.mutation +} + +// Save creates the Visit in the database. +func (_c *VisitCreate) Save(ctx context.Context) (*Visit, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *VisitCreate) SaveX(ctx context.Context) *Visit { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *VisitCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *VisitCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *VisitCreate) defaults() { + if _, ok := _c.mutation.VisitTime(); !ok { + v := visit.DefaultVisitTime() + _c.mutation.SetVisitTime(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *VisitCreate) check() error { + if _, ok := _c.mutation.Path(); !ok { + return &ValidationError{Name: "path", err: errors.New(`ent: missing required field "Visit.path"`)} + } + if _, ok := _c.mutation.IP(); !ok { + return &ValidationError{Name: "ip", err: errors.New(`ent: missing required field "Visit.ip"`)} + } + if _, ok := _c.mutation.VisitTime(); !ok { + return &ValidationError{Name: "visit_time", err: errors.New(`ent: missing required field "Visit.visit_time"`)} + } + return nil +} + +func (_c *VisitCreate) sqlSave(ctx context.Context) (*Visit, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != _node.ID { + id := _spec.ID.Value.(int64) + _node.ID = int(id) + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *VisitCreate) createSpec() (*Visit, *sqlgraph.CreateSpec) { + var ( + _node = &Visit{config: _c.config} + _spec = sqlgraph.NewCreateSpec(visit.Table, sqlgraph.NewFieldSpec(visit.FieldID, field.TypeInt)) + ) + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.Path(); ok { + _spec.SetField(visit.FieldPath, field.TypeString, value) + _node.Path = value + } + if value, ok := _c.mutation.IP(); ok { + _spec.SetField(visit.FieldIP, field.TypeString, value) + _node.IP = value + } + if value, ok := _c.mutation.UserAgent(); ok { + _spec.SetField(visit.FieldUserAgent, field.TypeString, value) + _node.UserAgent = value + } + if value, ok := _c.mutation.Referer(); ok { + _spec.SetField(visit.FieldReferer, field.TypeString, value) + _node.Referer = value + } + if value, ok := _c.mutation.VisitTime(); ok { + _spec.SetField(visit.FieldVisitTime, field.TypeTime, value) + _node.VisitTime = value + } + return _node, _spec +} + +// VisitCreateBulk is the builder for creating many Visit entities in bulk. +type VisitCreateBulk struct { + config + err error + builders []*VisitCreate +} + +// Save creates the Visit entities in the database. +func (_c *VisitCreateBulk) Save(ctx context.Context) ([]*Visit, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Visit, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*VisitMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil && nodes[i].ID == 0 { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *VisitCreateBulk) SaveX(ctx context.Context) []*Visit { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *VisitCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *VisitCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/ent/visit_delete.go b/internal/ent/visit_delete.go new file mode 100644 index 0000000..0873f2e --- /dev/null +++ b/internal/ent/visit_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "home-vue-go/internal/ent/predicate" + "home-vue-go/internal/ent/visit" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// VisitDelete is the builder for deleting a Visit entity. +type VisitDelete struct { + config + hooks []Hook + mutation *VisitMutation +} + +// Where appends a list predicates to the VisitDelete builder. +func (_d *VisitDelete) Where(ps ...predicate.Visit) *VisitDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *VisitDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *VisitDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *VisitDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(visit.Table, sqlgraph.NewFieldSpec(visit.FieldID, field.TypeInt)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// VisitDeleteOne is the builder for deleting a single Visit entity. +type VisitDeleteOne struct { + _d *VisitDelete +} + +// Where appends a list predicates to the VisitDelete builder. +func (_d *VisitDeleteOne) Where(ps ...predicate.Visit) *VisitDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *VisitDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{visit.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *VisitDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/ent/visit_query.go b/internal/ent/visit_query.go new file mode 100644 index 0000000..fdbf721 --- /dev/null +++ b/internal/ent/visit_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "home-vue-go/internal/ent/predicate" + "home-vue-go/internal/ent/visit" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// VisitQuery is the builder for querying Visit entities. +type VisitQuery struct { + config + ctx *QueryContext + order []visit.OrderOption + inters []Interceptor + predicates []predicate.Visit + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the VisitQuery builder. +func (_q *VisitQuery) Where(ps ...predicate.Visit) *VisitQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *VisitQuery) Limit(limit int) *VisitQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *VisitQuery) Offset(offset int) *VisitQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *VisitQuery) Unique(unique bool) *VisitQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *VisitQuery) Order(o ...visit.OrderOption) *VisitQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first Visit entity from the query. +// Returns a *NotFoundError when no Visit was found. +func (_q *VisitQuery) First(ctx context.Context) (*Visit, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{visit.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *VisitQuery) FirstX(ctx context.Context) *Visit { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Visit ID from the query. +// Returns a *NotFoundError when no Visit ID was found. +func (_q *VisitQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{visit.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *VisitQuery) FirstIDX(ctx context.Context) int { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Visit entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Visit entity is found. +// Returns a *NotFoundError when no Visit entities are found. +func (_q *VisitQuery) Only(ctx context.Context) (*Visit, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{visit.Label} + default: + return nil, &NotSingularError{visit.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *VisitQuery) OnlyX(ctx context.Context) *Visit { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Visit ID in the query. +// Returns a *NotSingularError when more than one Visit ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *VisitQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{visit.Label} + default: + err = &NotSingularError{visit.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *VisitQuery) OnlyIDX(ctx context.Context) int { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Visits. +func (_q *VisitQuery) All(ctx context.Context) ([]*Visit, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Visit, *VisitQuery]() + return withInterceptors[[]*Visit](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *VisitQuery) AllX(ctx context.Context) []*Visit { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Visit IDs. +func (_q *VisitQuery) IDs(ctx context.Context) (ids []int, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(visit.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *VisitQuery) IDsX(ctx context.Context) []int { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *VisitQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*VisitQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *VisitQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *VisitQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *VisitQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the VisitQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *VisitQuery) Clone() *VisitQuery { + if _q == nil { + return nil + } + return &VisitQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]visit.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Visit{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Path string `json:"path,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Visit.Query(). +// GroupBy(visit.FieldPath). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *VisitQuery) GroupBy(field string, fields ...string) *VisitGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &VisitGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = visit.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// Path string `json:"path,omitempty"` +// } +// +// client.Visit.Query(). +// Select(visit.FieldPath). +// Scan(ctx, &v) +func (_q *VisitQuery) Select(fields ...string) *VisitSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &VisitSelect{VisitQuery: _q} + sbuild.label = visit.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a VisitSelect configured with the given aggregations. +func (_q *VisitQuery) Aggregate(fns ...AggregateFunc) *VisitSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *VisitQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !visit.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *VisitQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Visit, error) { + var ( + nodes = []*Visit{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Visit).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Visit{config: _q.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (_q *VisitQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *VisitQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(visit.Table, visit.Columns, sqlgraph.NewFieldSpec(visit.FieldID, field.TypeInt)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, visit.FieldID) + for i := range fields { + if fields[i] != visit.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *VisitQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(visit.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = visit.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// VisitGroupBy is the group-by builder for Visit entities. +type VisitGroupBy struct { + selector + build *VisitQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *VisitGroupBy) Aggregate(fns ...AggregateFunc) *VisitGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *VisitGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*VisitQuery, *VisitGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *VisitGroupBy) sqlScan(ctx context.Context, root *VisitQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// VisitSelect is the builder for selecting fields of Visit entities. +type VisitSelect struct { + *VisitQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *VisitSelect) Aggregate(fns ...AggregateFunc) *VisitSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *VisitSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*VisitQuery, *VisitSelect](ctx, _s.VisitQuery, _s, _s.inters, v) +} + +func (_s *VisitSelect) sqlScan(ctx context.Context, root *VisitQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/internal/ent/visit_update.go b/internal/ent/visit_update.go new file mode 100644 index 0000000..ab0a4d4 --- /dev/null +++ b/internal/ent/visit_update.go @@ -0,0 +1,382 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "home-vue-go/internal/ent/predicate" + "home-vue-go/internal/ent/visit" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// VisitUpdate is the builder for updating Visit entities. +type VisitUpdate struct { + config + hooks []Hook + mutation *VisitMutation +} + +// Where appends a list predicates to the VisitUpdate builder. +func (_u *VisitUpdate) Where(ps ...predicate.Visit) *VisitUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetPath sets the "path" field. +func (_u *VisitUpdate) SetPath(v string) *VisitUpdate { + _u.mutation.SetPath(v) + return _u +} + +// SetNillablePath sets the "path" field if the given value is not nil. +func (_u *VisitUpdate) SetNillablePath(v *string) *VisitUpdate { + if v != nil { + _u.SetPath(*v) + } + return _u +} + +// SetIP sets the "ip" field. +func (_u *VisitUpdate) SetIP(v string) *VisitUpdate { + _u.mutation.SetIP(v) + return _u +} + +// SetNillableIP sets the "ip" field if the given value is not nil. +func (_u *VisitUpdate) SetNillableIP(v *string) *VisitUpdate { + if v != nil { + _u.SetIP(*v) + } + return _u +} + +// SetUserAgent sets the "user_agent" field. +func (_u *VisitUpdate) SetUserAgent(v string) *VisitUpdate { + _u.mutation.SetUserAgent(v) + return _u +} + +// SetNillableUserAgent sets the "user_agent" field if the given value is not nil. +func (_u *VisitUpdate) SetNillableUserAgent(v *string) *VisitUpdate { + if v != nil { + _u.SetUserAgent(*v) + } + return _u +} + +// ClearUserAgent clears the value of the "user_agent" field. +func (_u *VisitUpdate) ClearUserAgent() *VisitUpdate { + _u.mutation.ClearUserAgent() + return _u +} + +// SetReferer sets the "referer" field. +func (_u *VisitUpdate) SetReferer(v string) *VisitUpdate { + _u.mutation.SetReferer(v) + return _u +} + +// SetNillableReferer sets the "referer" field if the given value is not nil. +func (_u *VisitUpdate) SetNillableReferer(v *string) *VisitUpdate { + if v != nil { + _u.SetReferer(*v) + } + return _u +} + +// ClearReferer clears the value of the "referer" field. +func (_u *VisitUpdate) ClearReferer() *VisitUpdate { + _u.mutation.ClearReferer() + return _u +} + +// SetVisitTime sets the "visit_time" field. +func (_u *VisitUpdate) SetVisitTime(v time.Time) *VisitUpdate { + _u.mutation.SetVisitTime(v) + return _u +} + +// SetNillableVisitTime sets the "visit_time" field if the given value is not nil. +func (_u *VisitUpdate) SetNillableVisitTime(v *time.Time) *VisitUpdate { + if v != nil { + _u.SetVisitTime(*v) + } + return _u +} + +// Mutation returns the VisitMutation object of the builder. +func (_u *VisitUpdate) Mutation() *VisitMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *VisitUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *VisitUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *VisitUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *VisitUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *VisitUpdate) sqlSave(ctx context.Context) (_node int, err error) { + _spec := sqlgraph.NewUpdateSpec(visit.Table, visit.Columns, sqlgraph.NewFieldSpec(visit.FieldID, field.TypeInt)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Path(); ok { + _spec.SetField(visit.FieldPath, field.TypeString, value) + } + if value, ok := _u.mutation.IP(); ok { + _spec.SetField(visit.FieldIP, field.TypeString, value) + } + if value, ok := _u.mutation.UserAgent(); ok { + _spec.SetField(visit.FieldUserAgent, field.TypeString, value) + } + if _u.mutation.UserAgentCleared() { + _spec.ClearField(visit.FieldUserAgent, field.TypeString) + } + if value, ok := _u.mutation.Referer(); ok { + _spec.SetField(visit.FieldReferer, field.TypeString, value) + } + if _u.mutation.RefererCleared() { + _spec.ClearField(visit.FieldReferer, field.TypeString) + } + if value, ok := _u.mutation.VisitTime(); ok { + _spec.SetField(visit.FieldVisitTime, field.TypeTime, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{visit.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// VisitUpdateOne is the builder for updating a single Visit entity. +type VisitUpdateOne struct { + config + fields []string + hooks []Hook + mutation *VisitMutation +} + +// SetPath sets the "path" field. +func (_u *VisitUpdateOne) SetPath(v string) *VisitUpdateOne { + _u.mutation.SetPath(v) + return _u +} + +// SetNillablePath sets the "path" field if the given value is not nil. +func (_u *VisitUpdateOne) SetNillablePath(v *string) *VisitUpdateOne { + if v != nil { + _u.SetPath(*v) + } + return _u +} + +// SetIP sets the "ip" field. +func (_u *VisitUpdateOne) SetIP(v string) *VisitUpdateOne { + _u.mutation.SetIP(v) + return _u +} + +// SetNillableIP sets the "ip" field if the given value is not nil. +func (_u *VisitUpdateOne) SetNillableIP(v *string) *VisitUpdateOne { + if v != nil { + _u.SetIP(*v) + } + return _u +} + +// SetUserAgent sets the "user_agent" field. +func (_u *VisitUpdateOne) SetUserAgent(v string) *VisitUpdateOne { + _u.mutation.SetUserAgent(v) + return _u +} + +// SetNillableUserAgent sets the "user_agent" field if the given value is not nil. +func (_u *VisitUpdateOne) SetNillableUserAgent(v *string) *VisitUpdateOne { + if v != nil { + _u.SetUserAgent(*v) + } + return _u +} + +// ClearUserAgent clears the value of the "user_agent" field. +func (_u *VisitUpdateOne) ClearUserAgent() *VisitUpdateOne { + _u.mutation.ClearUserAgent() + return _u +} + +// SetReferer sets the "referer" field. +func (_u *VisitUpdateOne) SetReferer(v string) *VisitUpdateOne { + _u.mutation.SetReferer(v) + return _u +} + +// SetNillableReferer sets the "referer" field if the given value is not nil. +func (_u *VisitUpdateOne) SetNillableReferer(v *string) *VisitUpdateOne { + if v != nil { + _u.SetReferer(*v) + } + return _u +} + +// ClearReferer clears the value of the "referer" field. +func (_u *VisitUpdateOne) ClearReferer() *VisitUpdateOne { + _u.mutation.ClearReferer() + return _u +} + +// SetVisitTime sets the "visit_time" field. +func (_u *VisitUpdateOne) SetVisitTime(v time.Time) *VisitUpdateOne { + _u.mutation.SetVisitTime(v) + return _u +} + +// SetNillableVisitTime sets the "visit_time" field if the given value is not nil. +func (_u *VisitUpdateOne) SetNillableVisitTime(v *time.Time) *VisitUpdateOne { + if v != nil { + _u.SetVisitTime(*v) + } + return _u +} + +// Mutation returns the VisitMutation object of the builder. +func (_u *VisitUpdateOne) Mutation() *VisitMutation { + return _u.mutation +} + +// Where appends a list predicates to the VisitUpdate builder. +func (_u *VisitUpdateOne) Where(ps ...predicate.Visit) *VisitUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *VisitUpdateOne) Select(field string, fields ...string) *VisitUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Visit entity. +func (_u *VisitUpdateOne) Save(ctx context.Context) (*Visit, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *VisitUpdateOne) SaveX(ctx context.Context) *Visit { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *VisitUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *VisitUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *VisitUpdateOne) sqlSave(ctx context.Context) (_node *Visit, err error) { + _spec := sqlgraph.NewUpdateSpec(visit.Table, visit.Columns, sqlgraph.NewFieldSpec(visit.FieldID, field.TypeInt)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Visit.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, visit.FieldID) + for _, f := range fields { + if !visit.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != visit.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Path(); ok { + _spec.SetField(visit.FieldPath, field.TypeString, value) + } + if value, ok := _u.mutation.IP(); ok { + _spec.SetField(visit.FieldIP, field.TypeString, value) + } + if value, ok := _u.mutation.UserAgent(); ok { + _spec.SetField(visit.FieldUserAgent, field.TypeString, value) + } + if _u.mutation.UserAgentCleared() { + _spec.ClearField(visit.FieldUserAgent, field.TypeString) + } + if value, ok := _u.mutation.Referer(); ok { + _spec.SetField(visit.FieldReferer, field.TypeString, value) + } + if _u.mutation.RefererCleared() { + _spec.ClearField(visit.FieldReferer, field.TypeString) + } + if value, ok := _u.mutation.VisitTime(); ok { + _spec.SetField(visit.FieldVisitTime, field.TypeTime, value) + } + _node = &Visit{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{visit.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +}