From fc259ba2746f4c912550986feb1e9324de070716 Mon Sep 17 00:00:00 2001 From: Siyi Guo Date: Fri, 3 Feb 2023 12:52:14 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0category=E7=9A=84=E6=A8=A1?= =?UTF-8?q?=E6=9D=BF=E4=BB=A5=E5=8F=8A=E7=9B=B8=E5=85=B3=E7=9A=84sql?= =?UTF-8?q?=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/jbxh/apis/category.go | 192 ++++++++++++++++++++ app/jbxh/models/category.go | 31 ++++ app/jbxh/router/category.go | 27 +++ app/jbxh/router/int_router.go | 36 ++++ app/jbxh/router/router.go | 42 +++++ app/jbxh/service/category.go | 109 ++++++++++++ app/jbxh/service/dto/category.go | 105 +++++++++++ cmd/api/jbxh.go | 8 + config/jbxy/sql.sql | 78 +++++++++ config/jbxy/sqlite.sql | 83 +++++++++ mysql2sqlite.sh | 289 +++++++++++++++++++++++++++++++ 11 files changed, 1000 insertions(+) create mode 100644 app/jbxh/apis/category.go create mode 100644 app/jbxh/models/category.go create mode 100644 app/jbxh/router/category.go create mode 100644 app/jbxh/router/int_router.go create mode 100644 app/jbxh/router/router.go create mode 100644 app/jbxh/service/category.go create mode 100644 app/jbxh/service/dto/category.go create mode 100644 cmd/api/jbxh.go create mode 100644 config/jbxy/sql.sql create mode 100644 config/jbxy/sqlite.sql create mode 100755 mysql2sqlite.sh diff --git a/app/jbxh/apis/category.go b/app/jbxh/apis/category.go new file mode 100644 index 0000000..eb2dec8 --- /dev/null +++ b/app/jbxh/apis/category.go @@ -0,0 +1,192 @@ +package apis + +import ( + "fmt" + + "github.com/gin-gonic/gin" + "github.com/gin-gonic/gin/binding" + "github.com/go-admin-team/go-admin-core/sdk/api" + "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user" + _ "github.com/go-admin-team/go-admin-core/sdk/pkg/response" + + "go-admin/app/jbxh/models" + "go-admin/app/jbxh/service" + "go-admin/app/jbxh/service/dto" + "go-admin/common/actions" +) + +type Category struct { + api.Api +} + +// GetPage 获取分类列表 +// @Summary 获取分类列表 +// @Description 获取分类列表 +// @Tags 分类 +// @Param pageSize query int false "页条数" +// @Param pageIndex query int false "页码" +// @Success 200 {object} response.Response{data=response.Page{list=[]models.Category}} "{"code": 200, "data": [...]}" +// @Router /api/v1/category [get] +// @Security Bearer +func (e Category) GetPage(c *gin.Context) { + req := dto.CategoryGetPageReq{} + s := service.Category{} + err := e.MakeContext(c). + MakeOrm(). + Bind(&req, binding.Form). + MakeService(&s.Service). + Errors + if err != nil { + e.Logger.Error(err) + e.Error(500, err, err.Error()) + return + } + + p := actions.GetPermissionFromContext(c) + list := make([]models.Category, 0) + var count int64 + + err = s.GetPage(&req, p, &list, &count) + if err != nil { + e.Error(500, err, fmt.Sprintf("获取分类失败,\r\n失败信息 %s", err.Error())) + return + } + + e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功") +} + +// Get 获取分类 +// @Summary 获取分类 +// @Description 获取分类 +// @Tags 分类 +// @Param id path int false "id" +// @Success 200 {object} response.Response{data=models.Category} "{"code": 200, "data": [...]}" +// @Router /api/v1/category/{id} [get] +// @Security Bearer +func (e Category) Get(c *gin.Context) { + req := dto.CategoryGetReq{} + s := service.Category{} + err := e.MakeContext(c). + MakeOrm(). + Bind(&req). + MakeService(&s.Service). + Errors + if err != nil { + e.Logger.Error(err) + e.Error(500, err, err.Error()) + return + } + var object models.Category + + p := actions.GetPermissionFromContext(c) + err = s.Get(&req, p, &object) + if err != nil { + e.Error(500, err, fmt.Sprintf("获取分类失败,\r\n失败信息 %s", err.Error())) + return + } + + e.OK(object, "查询成功") +} + +// Insert 创建分类 +// @Summary 创建分类 +// @Description 创建分类 +// @Tags 分类 +// @Accept application/json +// @Product application/json +// @Param data body dto.CategoryInsertReq true "data" +// @Success 200 {object} response.Response "{"code": 200, "message": "添加成功"}" +// @Router /api/v1/category [post] +// @Security Bearer +func (e Category) Insert(c *gin.Context) { + req := dto.CategoryInsertReq{} + s := service.Category{} + err := e.MakeContext(c). + MakeOrm(). + Bind(&req). + MakeService(&s.Service). + Errors + if err != nil { + e.Logger.Error(err) + e.Error(500, err, err.Error()) + return + } + // 设置创建人 + req.SetCreateBy(user.GetUserId(c)) + + err = s.Insert(&req) + if err != nil { + e.Error(500, err, fmt.Sprintf("创建分类失败,\r\n失败信息 %s", err.Error())) + return + } + + e.OK(req.GetId(), "创建成功") +} + +// Update 修改分类 +// @Summary 修改分类 +// @Description 修改分类 +// @Tags 分类 +// @Accept application/json +// @Product application/json +// @Param id path int true "id" +// @Param data body dto.CategoryUpdateReq true "body" +// @Success 200 {object} response.Response "{"code": 200, "message": "修改成功"}" +// @Router /api/v1/category/{id} [put] +// @Security Bearer +func (e Category) Update(c *gin.Context) { + req := dto.CategoryUpdateReq{} + s := service.Category{} + err := e.MakeContext(c). + MakeOrm(). + Bind(&req). + MakeService(&s.Service). + Errors + if err != nil { + e.Logger.Error(err) + e.Error(500, err, err.Error()) + return + } + req.SetUpdateBy(user.GetUserId(c)) + p := actions.GetPermissionFromContext(c) + + err = s.Update(&req, p) + if err != nil { + e.Error(500, err, fmt.Sprintf("修改分类失败,\r\n失败信息 %s", err.Error())) + return + } + e.OK(req.GetId(), "修改成功") +} + +// Delete 删除分类 +// @Summary 删除分类 +// @Description 删除分类 +// @Tags 分类 +// @Param data body dto.CategoryDeleteReq true "body" +// @Success 200 {object} response.Response "{"code": 200, "message": "删除成功"}" +// @Router /api/v1/category [delete] +// @Security Bearer +func (e Category) Delete(c *gin.Context) { + s := service.Category{} + req := dto.CategoryDeleteReq{} + err := e.MakeContext(c). + MakeOrm(). + Bind(&req). + MakeService(&s.Service). + Errors + if err != nil { + e.Logger.Error(err) + e.Error(500, err, err.Error()) + return + } + + // req.SetUpdateBy(user.GetUserId(c)) + p := actions.GetPermissionFromContext(c) + + err = s.Remove(&req, p) + if err != nil { + e.Error(500, err, fmt.Sprintf("删除分类失败,\r\n失败信息 %s", err.Error())) + return + } + e.OK(req.GetId(), "删除成功") +} diff --git a/app/jbxh/models/category.go b/app/jbxh/models/category.go new file mode 100644 index 0000000..bf8b3bb --- /dev/null +++ b/app/jbxh/models/category.go @@ -0,0 +1,31 @@ +package models + +import ( + "go-admin/common/models" +) + +type Category struct { + models.Model + + Title string `json:"title" gorm:"type:varchar(127);comment:标题"` + Slug string `json:"slug" gorm:"type:varchar(127);comment:id"` + Desc string `json:"desc" gorm:"type:varchar(127);comment:描述"` + Parent string `json:"parent" gorm:"type:bigint;comment:父"` + Order string `json:"order" gorm:"type:bigint;comment:排序"` + Status string `json:"status" gorm:"type:int;comment:状态"` + models.ModelTime + models.ControlBy +} + +func (Category) TableName() string { + return "category" +} + +func (e *Category) Generate() models.ActiveRecord { + o := *e + return &o +} + +func (e *Category) GetId() interface{} { + return e.Id +} diff --git a/app/jbxh/router/category.go b/app/jbxh/router/category.go new file mode 100644 index 0000000..c85b66a --- /dev/null +++ b/app/jbxh/router/category.go @@ -0,0 +1,27 @@ +package router + +import ( + "github.com/gin-gonic/gin" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" + + "go-admin/app/jbxh/apis" + "go-admin/common/actions" + "go-admin/common/middleware" +) + +func init() { + routerCheckRole = append(routerCheckRole, registerCategoryRouter) +} + +// registerCategoryRouter +func registerCategoryRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) { + api := apis.Category{} + r := v1.Group("/category").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()) + { + r.GET("", actions.PermissionAction(), api.GetPage) + r.GET("/:id", actions.PermissionAction(), api.Get) + r.POST("", api.Insert) + r.PUT("/:id", actions.PermissionAction(), api.Update) + r.DELETE("", api.Delete) + } +} diff --git a/app/jbxh/router/int_router.go b/app/jbxh/router/int_router.go new file mode 100644 index 0000000..ab65faa --- /dev/null +++ b/app/jbxh/router/int_router.go @@ -0,0 +1,36 @@ +package router + +import ( + //"github.com/go-admin-team/go-admin-core/sdk/pkg" + "os" + + "github.com/gin-gonic/gin" + log "github.com/go-admin-team/go-admin-core/logger" + "github.com/go-admin-team/go-admin-core/sdk" + common "go-admin/common/middleware" +) + +// InitRouter 路由初始化,不要怀疑,这里用到了 +func InitRouter() { + var r *gin.Engine + h := sdk.Runtime.GetEngine() + if h == nil { + log.Fatal("not found engine...") + os.Exit(-1) + } + switch h.(type) { + case *gin.Engine: + r = h.(*gin.Engine) + default: + log.Fatal("not support other engine") + os.Exit(-1) + } + + authMiddleware, err := common.AuthInit() + if err != nil { + log.Fatalf("JWT Init Error, %s", err.Error()) + } + + // 注册业务路由 + initRouter(r, authMiddleware) +} diff --git a/app/jbxh/router/router.go b/app/jbxh/router/router.go new file mode 100644 index 0000000..8c893a2 --- /dev/null +++ b/app/jbxh/router/router.go @@ -0,0 +1,42 @@ +package router + +import ( + "github.com/gin-gonic/gin" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" +) + +var ( + routerNoCheckRole = make([]func(*gin.RouterGroup), 0) + routerCheckRole = make([]func(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware), 0) +) + +// initRouter 路由示例 +func initRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) *gin.Engine { + + // 无需认证的路由 + noCheckRoleRouter(r) + // 需要认证的路由 + checkRoleRouter(r, authMiddleware) + + return r +} + +// noCheckRoleRouter 无需认证的路由示例 +func noCheckRoleRouter(r *gin.Engine) { + // 可根据业务需求来设置接口版本 + v1 := r.Group("/api/v1") + + for _, f := range routerNoCheckRole { + f(v1) + } +} + +// checkRoleRouter 需要认证的路由示例 +func checkRoleRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) { + // 可根据业务需求来设置接口版本 + v1 := r.Group("/api/v1") + + for _, f := range routerCheckRole { + f(v1, authMiddleware) + } +} diff --git a/app/jbxh/service/category.go b/app/jbxh/service/category.go new file mode 100644 index 0000000..fb280c0 --- /dev/null +++ b/app/jbxh/service/category.go @@ -0,0 +1,109 @@ +package service + +import ( + "errors" + + "github.com/go-admin-team/go-admin-core/sdk/service" + "gorm.io/gorm" + + "go-admin/app/jbxh/models" + "go-admin/app/jbxh/service/dto" + "go-admin/common/actions" + cDto "go-admin/common/dto" +) + +type Category struct { + service.Service +} + +// GetPage 获取Category列表 +func (e *Category) GetPage(c *dto.CategoryGetPageReq, p *actions.DataPermission, list *[]models.Category, count *int64) error { + var err error + var data models.Category + + err = e.Orm.Model(&data). + Scopes( + cDto.MakeCondition(c.GetNeedSearch()), + cDto.Paginate(c.GetPageSize(), c.GetPageIndex()), + actions.Permission(data.TableName(), p), + ). + Find(list).Limit(-1).Offset(-1). + Count(count).Error + if err != nil { + e.Log.Errorf("CategoryService GetPage error:%s \r\n", err) + return err + } + return nil +} + +// Get 获取Category对象 +func (e *Category) Get(d *dto.CategoryGetReq, p *actions.DataPermission, model *models.Category) error { + var data models.Category + + err := e.Orm.Model(&data). + Scopes( + actions.Permission(data.TableName(), p), + ). + First(model, d.GetId()).Error + if err != nil && errors.Is(err, gorm.ErrRecordNotFound) { + err = errors.New("查看对象不存在或无权查看") + e.Log.Errorf("Service GetCategory error:%s \r\n", err) + return err + } + if err != nil { + e.Log.Errorf("db error:%s", err) + return err + } + return nil +} + +// Insert 创建Category对象 +func (e *Category) Insert(c *dto.CategoryInsertReq) error { + var err error + var data models.Category + c.Generate(&data) + err = e.Orm.Create(&data).Error + if err != nil { + e.Log.Errorf("CategoryService Insert error:%s \r\n", err) + return err + } + return nil +} + +// Update 修改Category对象 +func (e *Category) Update(c *dto.CategoryUpdateReq, p *actions.DataPermission) error { + var err error + var data = models.Category{} + e.Orm.Scopes( + actions.Permission(data.TableName(), p), + ).First(&data, c.GetId()) + c.Generate(&data) + + db := e.Orm.Save(&data) + if err = db.Error; err != nil { + e.Log.Errorf("CategoryService Save error:%s \r\n", err) + return err + } + if db.RowsAffected == 0 { + return errors.New("无权更新该数据") + } + return nil +} + +// Remove 删除Category +func (e *Category) Remove(d *dto.CategoryDeleteReq, p *actions.DataPermission) error { + var data models.Category + + db := e.Orm.Model(&data). + Scopes( + actions.Permission(data.TableName(), p), + ).Delete(&data, d.GetId()) + if err := db.Error; err != nil { + e.Log.Errorf("Service RemoveCategory error:%s \r\n", err) + return err + } + if db.RowsAffected == 0 { + return errors.New("无权删除该数据") + } + return nil +} diff --git a/app/jbxh/service/dto/category.go b/app/jbxh/service/dto/category.go new file mode 100644 index 0000000..50fcbd0 --- /dev/null +++ b/app/jbxh/service/dto/category.go @@ -0,0 +1,105 @@ +package dto + +import ( + "go-admin/app/jbxh/models" + "go-admin/common/dto" + common "go-admin/common/models" +) + +type CategoryGetPageReq struct { + dto.Pagination `search:"-"` + CategoryOrder +} + +type CategoryOrder struct { + Id string `form:"idOrder" search:"type:order;column:id;table:category"` + Title string `form:"titleOrder" search:"type:order;column:title;table:category"` + Slug string `form:"slugOrder" search:"type:order;column:slug;table:category"` + Desc string `form:"descOrder" search:"type:order;column:desc;table:category"` + Parent string `form:"parentOrder" search:"type:order;column:parent;table:category"` + Order string `form:"orderOrder" search:"type:order;column:order;table:category"` + Status string `form:"statusOrder" search:"type:order;column:status;table:category"` + CreateBy string `form:"createByOrder" search:"type:order;column:create_by;table:category"` + UpdateBy string `form:"updateByOrder" search:"type:order;column:update_by;table:category"` + CreatedAt string `form:"createdAtOrder" search:"type:order;column:created_at;table:category"` + UpdatedAt string `form:"updatedAtOrder" search:"type:order;column:updated_at;table:category"` + DeletedAt string `form:"deletedAtOrder" search:"type:order;column:deleted_at;table:category"` +} + +func (m *CategoryGetPageReq) GetNeedSearch() interface{} { + return *m +} + +type CategoryInsertReq struct { + Id int `json:"-" comment:"编码"` // 编码 + Title string `json:"title" comment:"标题"` + Slug string `json:"slug" comment:"id"` + Desc string `json:"desc" comment:"描述"` + Parent string `json:"parent" comment:"父"` + Order string `json:"order" comment:"排序"` + Status string `json:"status" comment:"状态"` + common.ControlBy +} + +func (s *CategoryInsertReq) Generate(model *models.Category) { + if s.Id == 0 { + model.Model = common.Model{Id: s.Id} + } + model.Title = s.Title + model.Slug = s.Slug + model.Desc = s.Desc + model.Parent = s.Parent + model.Order = s.Order + model.Status = s.Status + model.CreateBy = s.CreateBy // 添加这而,需要记录是被谁创建的 +} + +func (s *CategoryInsertReq) GetId() interface{} { + return s.Id +} + +type CategoryUpdateReq struct { + Id int `uri:"id" comment:"编码"` // 编码 + Title string `json:"title" comment:"标题"` + Slug string `json:"slug" comment:"id"` + Desc string `json:"desc" comment:"描述"` + Parent string `json:"parent" comment:"父"` + Order string `json:"order" comment:"排序"` + Status string `json:"status" comment:"状态"` + common.ControlBy +} + +func (s *CategoryUpdateReq) Generate(model *models.Category) { + if s.Id == 0 { + model.Model = common.Model{Id: s.Id} + } + model.Title = s.Title + model.Slug = s.Slug + model.Desc = s.Desc + model.Parent = s.Parent + model.Order = s.Order + model.Status = s.Status + model.UpdateBy = s.UpdateBy // 添加这而,需要记录是被谁更新的 +} + +func (s *CategoryUpdateReq) GetId() interface{} { + return s.Id +} + +// CategoryGetReq 功能获取请求参数 +type CategoryGetReq struct { + Id int `uri:"id"` +} + +func (s *CategoryGetReq) GetId() interface{} { + return s.Id +} + +// CategoryDeleteReq 功能删除请求参数 +type CategoryDeleteReq struct { + Ids []int `json:"ids"` +} + +func (s *CategoryDeleteReq) GetId() interface{} { + return s.Ids +} diff --git a/cmd/api/jbxh.go b/cmd/api/jbxh.go new file mode 100644 index 0000000..835fc5b --- /dev/null +++ b/cmd/api/jbxh.go @@ -0,0 +1,8 @@ +package api + +import "go-admin/app/jbxh/router" + +func init() { + //注册路由 fixme 其他应用的路由,在本目录新建文件放在init方法 + AppRouters = append(AppRouters, router.InitRouter) +} diff --git a/config/jbxy/sql.sql b/config/jbxy/sql.sql new file mode 100644 index 0000000..b0a6eda --- /dev/null +++ b/config/jbxy/sql.sql @@ -0,0 +1,78 @@ +drop table `article`; +create table `article` +( + `id` bigint unsigned NOT NULL AUTO_INCREMENT comment '编码', + `title` varchar(1023) DEFAULT NULL comment '标题', + `author` varchar(127) DEFAULT NULL comment '作者', + `content` longtext DEFAULT NULL comment '内容', + `status` int(1) DEFAULT NULL comment '状态', + `order` int DEFAULT 0 comment '排序', + `create_by` bigint unsigned DEFAULT NULL, + `update_by` bigint unsigned DEFAULT NULL, + `publish_at` datetime NULL DEFAULT NULL comment '发布时间', + `created_at` datetime not null default current_timestamp comment '创建时间', + `updated_at` datetime not null default current_timestamp on update current_timestamp comment '更新时间', + `deleted_at` datetime NULL DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE = InnoDB + AUTO_INCREMENT = 1 + DEFAULT CHARSET = utf8mb4 + COLLATE = utf8mb4_general_ci comment ='文章'; + +drop table `category`; +create TABLE `category` +( + `id` bigint unsigned not null auto_increment comment '编码', + `title` varchar(127) default null comment '标题', + `slug` varchar(127) not null comment 'id', + `desc` varchar(127) null comment '描述', + `parent` bigint default 0 comment '父', + `order` bigint default 0 comment '排序', + `status` int(1) default NULL comment '状态', + `create_by` bigint unsigned DEFAULT NULL, + `update_by` bigint unsigned DEFAULT NULL, + `created_at` datetime not null default current_timestamp comment '创建时间', + `updated_at` datetime not null default current_timestamp on update current_timestamp comment '更新时间', + `deleted_at` datetime NULL DEFAULT NULL, + PRIMARY KEY (`id`), + unique (`slug`) +) ENGINE = InnoDB + AUTO_INCREMENT = 1 + DEFAULT CHARSET = utf8mb4 + COLLATE = utf8mb4_general_ci comment ='分类'; + +insert into category values (1, '网站首页', 'wzsy', '网站首页-分类', 0, 0, 0, 0, 0, current_timestamp, current_timestamp, null); + +insert into category values (2, '协会概况', 'xhgk', '协会概况-分类', 0, 0, 0, 0, 0, current_timestamp, current_timestamp, null); +insert into category values (3, '协会简介', 'xhjj', '协会简介-分类', 2, 0, 0, 0, 0, current_timestamp, current_timestamp, null); +insert into category values (4, '规章制度', 'gzzd', '规章制度-分类', 2, 0, 0, 0, 0, current_timestamp, current_timestamp, null); +insert into category values (5, '协会领导', 'xhld', '协会领导-分类', 2, 0, 0, 0, 0, current_timestamp, current_timestamp, null); +insert into category values (6, '发展历程', 'fzlc', '发展历程-分类', 2, 0, 0, 0, 0, current_timestamp, current_timestamp, null); +insert into category values (7, '联系我们', 'lxwm', '联系我们-分类', 2, 0, 0, 0, 0, current_timestamp, current_timestamp, null); + +insert into category values (8, '重点资讯', 'zdzx', '重点资讯-分类', 0, 0, 0, 0, 0, current_timestamp, current_timestamp, null); +insert into category values (9, '新闻资讯', 'xwzx', '新闻资讯-分类', 8, 0, 0, 0, 0, current_timestamp, current_timestamp, null); +insert into category values (10, '通知公告', 'tzgg', '通知公告-分类', 8, 0, 0, 0, 0, current_timestamp, current_timestamp, null); +insert into category values (11, '行业动态', 'hydt', '行业动态-分类', 8, 0, 0, 0, 0, current_timestamp, current_timestamp, null); +insert into category values (12, '品牌活动', 'pphd', '品牌活动-分类', 8, 0, 0, 0, 0, current_timestamp, current_timestamp, null); +insert into category values (13, '学习专栏', 'xxzl', '学习专栏-分类', 8, 0, 0, 0, 0, current_timestamp, current_timestamp, null); + +insert into category values (14, '分支机构', 'fzjg', '分支机构-分类', 0, 0, 0, 0, 0, current_timestamp, current_timestamp, null); +insert into category values (15, '乡村振兴与共同富裕委员会', 'xczxygtfywyh', '乡村振兴与共同富裕委员会-分类', 14, 0, 0, 0, 0, current_timestamp, current_timestamp, null); +insert into category values (16, '文化艺术委员会', 'whyswyh', '文化艺术委员会-分类', 14, 0, 0, 0, 0, current_timestamp, current_timestamp, null); +insert into category values (17, '旅游委员会', 'lywyh', '旅游委员会-分类', 14, 0, 0, 0, 0, current_timestamp, current_timestamp, null); +insert into category values (18, '科技委员会', 'kjwyh', '科技委员会-分类', 14, 0, 0, 0, 0, current_timestamp, current_timestamp, null); +insert into category values (19, '海外联谊委员会', 'hwlywyh', '海外联谊委员会-分类', 14, 0, 0, 0, 0, current_timestamp, current_timestamp, null); +insert into category values (20, '中华民族城建委员会', 'zhmzcjwyh', '中华民族城建委员会-分类', 14, 0, 0, 0, 0, current_timestamp, current_timestamp, null); +insert into category values (21, '基金管理委员会', 'jjglwyh', '基金管理委员会-分类', 14, 0, 0, 0, 0, current_timestamp, current_timestamp, null); +insert into category values (22, '专家委员会', 'zjwyh', '专家委员会-分类', 14, 0, 0, 0, 0, current_timestamp, current_timestamp, null); +insert into category values (23, '中华传统医药委员会', 'zhctyywyh', '中华传统医药委员会-分类', 14, 0, 0, 0, 0, current_timestamp, current_timestamp, null); + +insert into category values (24, '主题活动', 'tthd', '主题活动-分类', 0, 0, 0, 0, 0, current_timestamp, current_timestamp, null); +insert into category values (25, '会员代表大会', 'hydbdh', '会员代表大会-分类', 24, 0, 0, 0, 0, current_timestamp, current_timestamp, null); +insert into category values (26, '理事会工作会议', 'lshgzhy', '理事会工作会议-分类', 24, 0, 0, 0, 0, current_timestamp, current_timestamp, null); +insert into category values (27, '青少年交流专题', 'qsnjlzt', '青少年交流专题-分类', 24, 0, 0, 0, 0, current_timestamp, current_timestamp, null); +insert into category values (28, '互嵌式发展专题', 'hqsfzzt', '互嵌式发展专题-分类', 24, 0, 0, 0, 0, current_timestamp, current_timestamp, null); +insert into category values (29, '旅游振兴专题', 'lyzxzt', '旅游振兴专题-分类', 24, 0, 0, 0, 0, current_timestamp, current_timestamp, null); + +insert into category values (30, '会员天地', 'hytd', '会员天地-分类', 0, 0, 0, 0, 0, current_timestamp, current_timestamp, null); diff --git a/config/jbxy/sqlite.sql b/config/jbxy/sqlite.sql new file mode 100644 index 0000000..4db7747 --- /dev/null +++ b/config/jbxy/sqlite.sql @@ -0,0 +1,83 @@ +-- import to SQLite by running: sqlite3.exe db.sqlite3 -init sqlite.sql + +PRAGMA journal_mode = MEMORY; +PRAGMA synchronous = OFF; +PRAGMA foreign_keys = OFF; +PRAGMA ignore_check_constraints = OFF; +PRAGMA auto_vacuum = NONE; +PRAGMA secure_delete = OFF; +BEGIN TRANSACTION; + + +create table `xh_article` +( + `id` bigint NOT NULL , + `title` TEXT DEFAULT NULL , + `author` TEXT DEFAULT NULL , + `content` TEXT DEFAULT NULL , + `status` INTEGER DEFAULT NULL , + `order` int DEFAULT 0 , + `create_by` bigint DEFAULT NULL, + `update_by` bigint DEFAULT NULL, + `publish_at` datetime NULL DEFAULT NULL , + `created_at` datetime not null default current_timestamp , + `updated_at` datetime not null , + `deleted_at` datetime NULL DEFAULT NULL, + PRIMARY KEY (`id`) +); + +create TABLE `xh_category` +( + `id` bigint not null , + `title` TEXT default null , + `slug` TEXT not null , + `desc` TEXT null , + `parent` bigint default 0 , + `order` bigint default 0 , + `status` INTEGER default NULL , + `created_at` datetime not null default current_timestamp , + `updated_at` datetime not null , + PRIMARY KEY (`id`), + unique (`slug`) +); + +insert into `xh_category` values (1, '网站首页', 'wzsy', '网站首页-分类', 0, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (2, '协会概况', 'xhgk', '协会概况-分类', 0, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (3, '协会简介', 'xhjj', '协会简介-分类', 2, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (4, '规章制度', 'gzzd', '规章制度-分类', 2, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (5, '协会领导', 'xhld', '协会领导-分类', 2, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (6, '发展历程', 'fzlc', '发展历程-分类', 2, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (7, '联系我们', 'lxwm', '联系我们-分类', 2, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (8, '重点资讯', 'zdzx', '重点资讯-分类', 0, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (9, '新闻资讯', 'xwzx', '新闻资讯-分类', 8, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (10, '通知公告', 'tzgg', '通知公告-分类', 8, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (11, '行业动态', 'hydt', '行业动态-分类', 8, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (12, '品牌活动', 'pphd', '品牌活动-分类', 8, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (13, '学习专栏', 'xxzl', '学习专栏-分类', 8, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (14, '分支机构', 'fzjg', '分支机构-分类', 0, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (15, '乡村振兴与共同富裕委员会', 'xczxygtfywyh', '乡村振兴与共同富裕委员会-分类', 15, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (16, '文化艺术委员会', 'whyswyh', '文化艺术委员会-分类', 15, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (17, '旅游委员会', 'lywyh', '旅游委员会-分类', 15, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (18, '科技委员会', 'kjwyh', '科技委员会-分类', 15, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (19, '海外联谊委员会', 'hwlywyh', '海外联谊委员会-分类', 15, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (20, '中华民族城建委员会', 'zhmzcjwyh', '中华民族城建委员会-分类', 15, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (21, '基金管理委员会', 'jjglwyh', '基金管理委员会-分类', 15, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (22, '专家委员会', 'zjwyh', '专家委员会-分类', 15, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (23, '中华传统医药委员会', 'zhctyywyh', '中华传统医药委员会-分类', 15, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (24, '主题活动', 'tthd', '主题活动-分类', 0, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (25, '会员代表大会', 'hydbdh', '会员代表大会-分类', 24, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (26, '理事会工作会议', 'lshgzhy', '理事会工作会议-分类', 24, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (27, '青少年交流专题', 'qsnjlzt', '青少年交流专题-分类', 24, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (28, '互嵌式发展专题', 'hqsfzzt', '互嵌式发展专题-分类', 24, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (29, '旅游振兴专题', 'lyzxzt', '旅游振兴专题-分类', 24, 0, 0, current_timestamp, current_timestamp); +insert into `xh_category` values (30, '会员天地', 'hytd', '会员天地-分类', 0, 0, 0, current_timestamp, current_timestamp); + + + + + +COMMIT; +PRAGMA ignore_check_constraints = ON; +PRAGMA foreign_keys = ON; +PRAGMA journal_mode = WAL; +PRAGMA synchronous = NORMAL; diff --git a/mysql2sqlite.sh b/mysql2sqlite.sh new file mode 100755 index 0000000..2a3e374 --- /dev/null +++ b/mysql2sqlite.sh @@ -0,0 +1,289 @@ +#!/usr/bin/awk -f + +# Authors: @esperlu, @artemyk, @gkuenning, @dumblob + +# FIXME detect empty input file and issue a warning + +function printerr( s ){ print s | "cat >&2" } + +BEGIN { + if( ARGC != 2 ){ + printerr( \ + "USAGE:\n"\ + " mysql2sqlite dump_mysql.sql > dump_sqlite3.sql\n" \ + " OR\n" \ + " mysql2sqlite dump_mysql.sql | sqlite3 sqlite.db\n" \ + "\n" \ + "NOTES:\n" \ + " Dash in filename is not supported, because dash (-) means stdin." ) + no_END = 1 + exit 1 + } + + # Find INT_MAX supported by both this AWK (usually an ISO C signed int) + # and SQlite. + # On non-8bit-based architectures, the additional bits are safely ignored. + + # 8bit (lower precision should not exist) + s="127" + # "63" + 0 avoids potential parser misbehavior + if( (s + 0) "" == s ){ INT_MAX_HALF = "63" + 0 } + # 16bit + s="32767" + if( (s + 0) "" == s ){ INT_MAX_HALF = "16383" + 0 } + # 32bit + s="2147483647" + if( (s + 0) "" == s ){ INT_MAX_HALF = "1073741823" + 0 } + # 64bit (as INTEGER in SQlite3) + s="9223372036854775807" + if( (s + 0) "" == s ){ INT_MAX_HALF = "4611686018427387904" + 0 } +# # 128bit +# s="170141183460469231731687303715884105728" +# if( (s + 0) "" == s ){ INT_MAX_HALF = "85070591730234615865843651857942052864" + 0 } +# # 256bit +# s="57896044618658097711785492504343953926634992332820282019728792003956564819968" +# if( (s + 0) "" == s ){ INT_MAX_HALF = "28948022309329048855892746252171976963317496166410141009864396001978282409984" + 0 } +# # 512bit +# s="6703903964971298549787012499102923063739682910296196688861780721860882015036773488400937149083451713845015929093243025426876941405973284973216824503042048" +# if( (s + 0) "" == s ){ INT_MAX_HALF = "3351951982485649274893506249551461531869841455148098344430890360930441007518386744200468574541725856922507964546621512713438470702986642486608412251521024" + 0 } +# # 1024bit +# s="89884656743115795386465259539451236680898848947115328636715040578866337902750481566354238661203768010560056939935696678829394884407208311246423715319737062188883946712432742638151109800623047059726541476042502884419075341171231440736956555270413618581675255342293149119973622969239858152417678164812112068608" +# if( (s + 0) "" == s ){ INT_MAX_HALF = "44942328371557897693232629769725618340449424473557664318357520289433168951375240783177119330601884005280028469967848339414697442203604155623211857659868531094441973356216371319075554900311523529863270738021251442209537670585615720368478277635206809290837627671146574559986811484619929076208839082406056034304" + 0 } +# # higher precision probably not needed + + FS=",$" + print "PRAGMA synchronous = OFF;" + print "PRAGMA journal_mode = MEMORY;" + print "BEGIN TRANSACTION;" +} + +# historically 3 spaces separate non-argument local variables +function bit_to_int( str_bit, powtwo, i, res, bit, overflow ){ + powtwo = 1 + overflow = 0 + # 011101 = 1*2^0 + 0*2^1 + 1*2^2 ... + for( i = length( str_bit ); i > 0; --i ){ + bit = substr( str_bit, i, 1 ) + if( overflow || ( bit == 1 && res > INT_MAX_HALF ) ){ + printerr( \ + NR ": WARN Bit field overflow, number truncated (LSBs saved, MSBs ignored)." ) + break + } + res = res + bit * powtwo + # no warning here as it might be the last iteration + if( powtwo > INT_MAX_HALF ){ overflow = 1; continue } + powtwo = powtwo * 2 + } + return res +} + +# CREATE TRIGGER statements have funny commenting. Remember we are in trigger. +/^\/\*.*(CREATE.*TRIGGER|create.*trigger)/ { + gsub( /^.*(TRIGGER|trigger)/, "CREATE TRIGGER" ) + print + inTrigger = 1 + next +} +# The end of CREATE TRIGGER has a stray comment terminator +/(END|end) \*\/;;/ { gsub( /\*\//, "" ); print; inTrigger = 0; next } +# The rest of triggers just get passed through +inTrigger != 0 { print; next } + +# CREATE VIEW looks like a TABLE in comments +/^\/\*.*(CREATE.*TABLE|create.*table)/ { + inView = 1 + next +} +# end of CREATE VIEW +/^(\).*(ENGINE|engine).*\*\/;)/ { + inView = 0 + next +} +# content of CREATE VIEW +inView != 0 { next } + +# skip comments +/^\/\*/ { next } + +# skip PARTITION statements +/^ *[(]?(PARTITION|partition) +[^ ]+/ { next } + +# print all INSERT lines +( /^ *\(/ && /\) *[,;] *$/ ) || /^(INSERT|insert|REPLACE|replace)/ { + prev = "" + + # first replace \\ by \_ that mysqldump never generates to deal with + # sequnces like \\n that should be translated into \n, not \. + # After we convert all escapes we replace \_ by backslashes. + gsub( /\\\\/, "\\_" ) + + # single quotes are escaped by another single quote + gsub( /\\'/, "''" ) + gsub( /\\n/, "\n" ) + gsub( /\\r/, "\r" ) + gsub( /\\"/, "\"" ) + gsub( /\\\032/, "\032" ) # substitute char + + gsub( /\\_/, "\\" ) + + # sqlite3 is limited to 16 significant digits of precision + while( match( $0, /0x[0-9a-fA-F]{17}/ ) ){ + hexIssue = 1 + sub( /0x[0-9a-fA-F]+/, substr( $0, RSTART, RLENGTH-1 ), $0 ) + } + if( hexIssue ){ + printerr( \ + NR ": WARN Hex number trimmed (length longer than 16 chars)." ) + hexIssue = 0 + } + print + next +} + +# CREATE DATABASE is not supported +/^(CREATE DATABASE|create database)/ { next } + +# print the CREATE line as is and capture the table name +/^(CREATE|create)/ { + if( $0 ~ /IF NOT EXISTS|if not exists/ || $0 ~ /TEMPORARY|temporary/ ){ + caseIssue = 1 + printerr( \ + NR ": WARN Potential case sensitivity issues with table/column naming\n" \ + " (see INFO at the end)." ) + } + if( match( $0, /`[^`]+/ ) ){ + tableName = substr( $0, RSTART+1, RLENGTH-1 ) + } + aInc = 0 + prev = "" + firstInTable = 1 + print + next +} + +# Replace `FULLTEXT KEY` (probably other `XXXXX KEY`) +/^ (FULLTEXT KEY|fulltext key)/ { gsub( /[A-Za-z ]+(KEY|key)/, " KEY" ) } + +# Get rid of field lengths in KEY lines +/ (PRIMARY |primary )?(KEY|key)/ { gsub( /\([0-9]+\)/, "" ) } + +aInc == 1 && /PRIMARY KEY|primary key/ { next } + +# Replace COLLATE xxx_xxxx_xx statements with COLLATE BINARY +/ (COLLATE|collate) [a-z0-9_]*/ { gsub( /(COLLATE|collate) [a-z0-9_]*/, "COLLATE BINARY" ) } + +# Print all fields definition lines except the `KEY` lines. +/^ / && !/^( (KEY|key)|\);)/ { + if( match( $0, /[^"`]AUTO_INCREMENT|auto_increment[^"`]/) ){ + aInc = 1 + gsub( /AUTO_INCREMENT|auto_increment/, "PRIMARY KEY AUTOINCREMENT" ) + } + gsub( /(UNIQUE KEY|unique key) (`.*`|".*") /, "UNIQUE " ) + gsub( /(CHARACTER SET|character set) [^ ]+[ ,]/, "" ) + # FIXME + # CREATE TRIGGER [UpdateLastTime] + # AFTER UPDATE + # ON Package + # FOR EACH ROW + # BEGIN + # UPDATE Package SET LastUpdate = CURRENT_TIMESTAMP WHERE ActionId = old.ActionId; + # END + gsub( /(ON|on) (UPDATE|update) (CURRENT_TIMESTAMP|current_timestamp)(\(\))?/, "" ) + gsub( /(DEFAULT|default) (CURRENT_TIMESTAMP|current_timestamp)(\(\))?/, "DEFAULT current_timestamp") + gsub( /(COLLATE|collate) [^ ]+ /, "" ) + gsub( /(ENUM|enum)[^)]+\)/, "text " ) + gsub( /(SET|set)\([^)]+\)/, "text " ) + gsub( /UNSIGNED|unsigned/, "" ) + gsub( /_utf8mb3/, "" ) + gsub( /` [^ ]*(INT|int|BIT|bit)[^ ]*/, "` integer" ) + gsub( /" [^ ]*(INT|int|BIT|bit)[^ ]*/, "\" integer" ) + ere_bit_field = "[bB]'[10]+'" + if( match($0, ere_bit_field) ){ + sub( ere_bit_field, bit_to_int( substr( $0, RSTART +2, RLENGTH -2 -1 ) ) ) + } + + # remove USING BTREE and other suffixes for USING, for example: "UNIQUE KEY + # `hostname_domain` (`hostname`,`domain`) USING BTREE," + gsub( / USING [^, ]+/, "" ) + + # field comments are not supported + gsub( / (COMMENT|comment).+$/, "" ) + # Get commas off end of line + gsub( /,.?$/, "" ) + if( prev ){ + if( firstInTable ){ + print prev + firstInTable = 0 + } + else { + print "," prev + } + } + else { + # FIXME check if this is correct in all cases + if( match( $1, + /(CONSTRAINT|constraint) ["].*["] (FOREIGN KEY|foreign key)/ ) ){ + print "," + } + } + prev = $1 +} + +/ ENGINE| engine/ { + if( prev ){ + if( firstInTable ){ + print prev + firstInTable = 0 + } + else { + print "," prev + } + } + prev="" + print ");" + next +} +# `KEY` lines are extracted from the `CREATE` block and stored in array for later print +# in a separate `CREATE KEY` command. The index name is prefixed by the table name to +# avoid a sqlite error for duplicate index name. +/^( (KEY|key)|\);)/ { + if( prev ){ + if( firstInTable ){ + print prev + firstInTable = 0 + } + else { + print "," prev + } + } + prev = "" + if( $0 == ");" ){ + print + } + else { + if( match( $0, /`[^`]+/ ) ){ + indexName = substr( $0, RSTART+1, RLENGTH-1 ) + } + if( match( $0, /\([^()]+/ ) ){ + indexKey = substr( $0, RSTART+1, RLENGTH-1 ) + } + # idx_ prefix to avoid name clashes (they really happen!) + key[tableName] = key[tableName] "CREATE INDEX \"idx_" \ + tableName "_" indexName "\" ON \"" tableName "\" (" indexKey ");\n" + } +} + +END { + if( no_END ){ exit 1} + # print all KEY creation lines. + for( table in key ){ printf key[table] } + + print "END TRANSACTION;" + + if( caseIssue ){ + printerr( \ + "INFO Pure sqlite identifiers are case insensitive (even if quoted\n" \ + " or if ASCII) and doesnt cross-check TABLE and TEMPORARY TABLE\n" \ + " identifiers. Thus expect errors like \"table T has no column named F\".") + } +}