table.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. package gen_service
  2. import (
  3. "gfast/app/model/admin/gen_table"
  4. "gfast/app/model/admin/gen_table_column"
  5. "github.com/gogf/gf/database/gdb"
  6. "github.com/gogf/gf/encoding/gjson"
  7. "github.com/gogf/gf/errors/gerror"
  8. "github.com/gogf/gf/frame/g"
  9. "github.com/gogf/gf/os/gtime"
  10. "github.com/gogf/gf/text/gregex"
  11. "github.com/gogf/gf/text/gstr"
  12. "github.com/gogf/gf/util/gconv"
  13. "strings"
  14. )
  15. //根据条件分页查询数据
  16. func SelectDbTableList(param *gen_table.SelectPageReq) (total int, list []*gen_table.Entity, err error) {
  17. return gen_table.SelectDbTableList(param)
  18. }
  19. //根据条件分页查询数据
  20. func SelectListByPage(param *gen_table.SelectPageReq) (total int, list []*gen_table.Entity, err error) {
  21. return gen_table.SelectListByPage(param)
  22. }
  23. //查询据库列表
  24. func SelectDbTableListByNames(tableNames []string) ([]*gen_table.Entity, error) {
  25. return gen_table.SelectDbTableListByNames(tableNames)
  26. }
  27. //导入表结构
  28. func ImportGenTable(tableList []*gen_table.Entity, operName string) error {
  29. if tableList != nil && operName != "" {
  30. tx, err := g.DB().Begin()
  31. if err != nil {
  32. return err
  33. }
  34. for _, table := range tableList {
  35. tableName := table.TableName
  36. InitTable(table, operName)
  37. result, err := tx.Table(gen_table.Table).Insert(table)
  38. if err != nil {
  39. return err
  40. }
  41. tmpid, err := result.LastInsertId()
  42. if err != nil || tmpid <= 0 {
  43. tx.Rollback()
  44. return gerror.New("保存数据失败")
  45. }
  46. table.TableId = tmpid
  47. // 保存列信息
  48. genTableColumns, err := gen_table_column.SelectDbTableColumnsByName(tableName)
  49. if err != nil || len(genTableColumns) <= 0 {
  50. tx.Rollback()
  51. return gerror.New("获取列数据失败")
  52. }
  53. for _, column := range genTableColumns {
  54. InitColumnField(column, table)
  55. _, err = tx.Table("gen_table_column").Insert(column)
  56. if err != nil {
  57. tx.Rollback()
  58. return gerror.New("保存列数据失败")
  59. }
  60. }
  61. }
  62. return tx.Commit()
  63. } else {
  64. return gerror.New("参数错误")
  65. }
  66. }
  67. //获取数据库类型字段
  68. func GetDbType(columnType string) string {
  69. if strings.Index(columnType, "(") > 0 {
  70. return columnType[0:strings.Index(columnType, "(")]
  71. } else {
  72. return columnType
  73. }
  74. }
  75. //将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld
  76. func ConvertToCamelCase(name string) string {
  77. if name == "" {
  78. return ""
  79. } else if !strings.Contains(name, "_") {
  80. // 不含下划线,仅将首字母大写
  81. return strings.ToUpper(name[0:1]) + name[1:len(name)]
  82. }
  83. var result string = ""
  84. camels := strings.Split(name, "_")
  85. for index := range camels {
  86. if camels[index] == "" {
  87. continue
  88. }
  89. camel := camels[index]
  90. result = result + strings.ToUpper(camel[0:1]) + strings.ToLower(camel[1:len(camel)])
  91. }
  92. return result
  93. }
  94. ////将下划线大写方式命名的字符串转换为驼峰式,首字母小写。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->helloWorld
  95. func ConvertToCamelCase1(name string) string {
  96. if name == "" {
  97. return ""
  98. } else if !strings.Contains(name, "_") {
  99. // 不含下划线,原值返回
  100. return name
  101. }
  102. var result string = ""
  103. camels := strings.Split(name, "_")
  104. for index := range camels {
  105. if camels[index] == "" {
  106. continue
  107. }
  108. camel := camels[index]
  109. if result == "" {
  110. result = strings.ToLower(camel[0:1]) + strings.ToLower(camel[1:len(camel)])
  111. } else {
  112. result = result + strings.ToUpper(camel[0:1]) + strings.ToLower(camel[1:len(camel)])
  113. }
  114. }
  115. return result
  116. }
  117. //获取字段长度
  118. func GetColumnLength(columnType string) int {
  119. start := strings.Index(columnType, "(")
  120. end := strings.Index(columnType, ")")
  121. result := ""
  122. if start >= 0 && end >= 0 {
  123. result = columnType[start+1 : end-1]
  124. }
  125. return gconv.Int(result)
  126. }
  127. //初始化列属性字段
  128. func InitColumnField(column *gen_table_column.Entity, table *gen_table.Entity) {
  129. dataType := GetDbType(column.ColumnType)
  130. columnName := column.ColumnName
  131. column.TableId = table.TableId
  132. column.CreateBy = table.CreateBy
  133. column.CreateTime = gtime.Now()
  134. column.UpdateTime = column.CreateTime
  135. //设置字段名
  136. column.GoField = ConvertToCamelCase(columnName)
  137. column.HtmlField = ConvertToCamelCase1(columnName)
  138. if gen_table_column.IsStringObject(dataType) {
  139. //字段为字符串类型
  140. column.GoType = "string"
  141. columnLength := GetColumnLength(column.ColumnType)
  142. if columnLength >= 500 {
  143. column.HtmlType = "textarea"
  144. } else {
  145. column.HtmlType = "input"
  146. }
  147. } else if gen_table_column.IsTimeObject(dataType) {
  148. //字段为时间类型
  149. column.GoType = "Time"
  150. column.HtmlType = "datatime"
  151. } else if gen_table_column.IsNumberObject(dataType) {
  152. //字段为数字类型
  153. column.HtmlType = "input"
  154. t, _ := gregex.ReplaceString(`\(.+\)`, "", column.ColumnType)
  155. t = gstr.Split(gstr.Trim(t), " ")[0]
  156. t = gstr.ToLower(t)
  157. // 如果是浮点型
  158. switch t {
  159. case "float", "double", "decimal":
  160. column.GoType = "float64"
  161. case "bit", "int", "tinyint", "small_int", "smallint", "medium_int", "mediumint":
  162. if gstr.ContainsI(column.ColumnType, "unsigned") {
  163. column.GoType = "uint"
  164. } else {
  165. column.GoType = "int"
  166. }
  167. case "big_int", "bigint":
  168. if gstr.ContainsI(column.ColumnType, "unsigned") {
  169. column.GoType = "uint64"
  170. } else {
  171. column.GoType = "int64"
  172. }
  173. }
  174. }
  175. //新增字段
  176. if columnName == "create_by" || columnName == "create_time" || columnName == "update_by" || columnName == "update_time" {
  177. column.IsRequired = "0"
  178. column.IsInsert = "0"
  179. } else {
  180. column.IsRequired = "0"
  181. column.IsInsert = "1"
  182. if strings.Index(columnName, "name") >= 0 || strings.Index(columnName, "status") >= 0 {
  183. column.IsRequired = "1"
  184. }
  185. }
  186. // 编辑字段
  187. if gen_table_column.IsNotEdit(columnName) {
  188. if column.IsPk == "1" {
  189. column.IsEdit = "0"
  190. } else {
  191. column.IsEdit = "1"
  192. }
  193. } else {
  194. column.IsEdit = "0"
  195. }
  196. // 列表字段
  197. if gen_table_column.IsNotList(columnName) {
  198. column.IsList = "1"
  199. } else {
  200. column.IsList = "0"
  201. }
  202. // 查询字段
  203. if gen_table_column.IsNotQuery(columnName) {
  204. column.IsQuery = "1"
  205. } else {
  206. column.IsQuery = "0"
  207. }
  208. // 查询字段类型
  209. if CheckNameColumn(columnName) {
  210. column.QueryType = "LIKE"
  211. } else {
  212. column.QueryType = "EQ"
  213. }
  214. // 状态字段设置单选框
  215. if CheckStatusColumn(columnName) {
  216. column.HtmlType = "radio"
  217. } else if CheckTypeColumn(columnName) || CheckSexColumn(columnName) {
  218. // 类型&性别字段设置下拉框
  219. column.HtmlType = "select"
  220. }
  221. }
  222. //检查字段名后3位是否是sex
  223. func CheckSexColumn(columnName string) bool {
  224. if len(columnName) >= 3 {
  225. end := len(columnName)
  226. start := end - 3
  227. if start <= 0 {
  228. start = 0
  229. }
  230. if columnName[start:end] == "sex" {
  231. return true
  232. }
  233. }
  234. return false
  235. }
  236. //检查字段名后4位是否是type
  237. func CheckTypeColumn(columnName string) bool {
  238. if len(columnName) >= 4 {
  239. end := len(columnName)
  240. start := end - 4
  241. if start <= 0 {
  242. start = 0
  243. }
  244. if columnName[start:end] == "type" {
  245. return true
  246. }
  247. }
  248. return false
  249. }
  250. //检查字段名后6位是否是status
  251. func CheckStatusColumn(columnName string) bool {
  252. if len(columnName) >= 6 {
  253. end := len(columnName)
  254. start := end - 6
  255. if start <= 0 {
  256. start = 0
  257. }
  258. tmp := columnName[start:end]
  259. if tmp == "status" {
  260. return true
  261. }
  262. }
  263. return false
  264. }
  265. //检查字段名后4位是否是name
  266. func CheckNameColumn(columnName string) bool {
  267. if len(columnName) >= 4 {
  268. end := len(columnName)
  269. start := end - 4
  270. if start <= 0 {
  271. start = 0
  272. }
  273. tmp := columnName[start:end]
  274. if tmp == "name" {
  275. return true
  276. }
  277. }
  278. return false
  279. }
  280. //初始化表信息
  281. func InitTable(table *gen_table.Entity, operName string) {
  282. table.ClassName = ConvertClassName(table.TableName)
  283. table.PackageName = g.Cfg().GetString("gen.packageName")
  284. table.ModuleName = g.Cfg().GetString("gen.moduleName")
  285. table.BusinessName = GetBusinessName(table.TableName)
  286. table.FunctionName = strings.ReplaceAll(table.TableComment, "表", "")
  287. table.FunctionAuthor = g.Cfg().GetString("gen.author")
  288. table.CreateBy = operName
  289. table.TplCategory = "crud"
  290. table.CreateTime = gtime.Now()
  291. table.UpdateTime = table.CreateTime
  292. }
  293. //表名转换成类名
  294. func ConvertClassName(tableName string) string {
  295. autoRemovePre := g.Cfg().GetBool("gen.autoRemovePre")
  296. tablePrefix := g.Cfg().GetString("gen.tablePrefix")
  297. if autoRemovePre && tablePrefix != "" {
  298. searchList := strings.Split(tablePrefix, ",")
  299. for _, str := range searchList {
  300. tableName = strings.ReplaceAll(tableName, str, "")
  301. }
  302. }
  303. return tableName
  304. }
  305. //获取业务名
  306. func GetBusinessName(tableName string) string {
  307. lastIndex := strings.LastIndex(tableName, "_")
  308. nameLength := len(tableName)
  309. businessName := tableName[lastIndex+1 : nameLength]
  310. return businessName
  311. }
  312. //根据table_id查询表列数据
  313. func SelectGenTableColumnListByTableId(tableId int64) ([]*gen_table_column.Entity, error) {
  314. return gen_table_column.SelectGenTableColumnListByTableId(tableId)
  315. }
  316. func GetTableInfoByTableId(tableId int64) (info *gen_table.Entity, err error) {
  317. return gen_table.GetInfoById(tableId)
  318. }
  319. //修改表和列信息
  320. func SaveEdit(req *gen_table.EditReq) (err error) {
  321. if req == nil {
  322. err = gerror.New("参数错误")
  323. return
  324. }
  325. table, err := gen_table.FindOne("table_id=?", req.TableId)
  326. if err != nil || table == nil {
  327. err = gerror.New("数据不存在")
  328. return
  329. }
  330. if req.TableName != "" {
  331. table.TableName = req.TableName
  332. }
  333. if req.TableComment != "" {
  334. table.TableComment = req.TableComment
  335. }
  336. if req.BusinessName != "" {
  337. table.BusinessName = req.BusinessName
  338. }
  339. if req.ClassName != "" {
  340. table.ClassName = req.ClassName
  341. }
  342. if req.FunctionAuthor != "" {
  343. table.FunctionAuthor = req.FunctionAuthor
  344. }
  345. if req.FunctionName != "" {
  346. table.FunctionName = req.FunctionName
  347. }
  348. if req.ModuleName != "" {
  349. table.ModuleName = req.ModuleName
  350. }
  351. if req.PackageName != "" {
  352. table.PackageName = req.PackageName
  353. }
  354. if req.Remark != "" {
  355. table.Remark = req.Remark
  356. }
  357. if req.TplCategory != "" {
  358. table.TplCategory = req.TplCategory
  359. }
  360. if req.Params != "" {
  361. table.Options = req.Params
  362. }
  363. table.UpdateTime = gtime.Now()
  364. table.UpdateBy = req.UserName
  365. if req.TplCategory == "tree" {
  366. //树表设置options
  367. options := g.Map{
  368. "tree_code": req.TreeCode,
  369. "tree_parent_code": req.TreeParentCode,
  370. "tree_name": req.TreeName,
  371. }
  372. table.Options = gconv.String(options)
  373. } else {
  374. table.Options = ""
  375. }
  376. var tx *gdb.TX
  377. tx, err = g.DB().Begin()
  378. if err != nil {
  379. return
  380. }
  381. _, err = tx.Table(gen_table.Table).Save(table)
  382. if err != nil {
  383. tx.Rollback()
  384. return err
  385. }
  386. //保存列数据
  387. if req.Columns != "" {
  388. var j *gjson.Json
  389. if j, err = gjson.DecodeToJson([]byte(req.Columns)); err != nil {
  390. tx.Rollback()
  391. return
  392. } else {
  393. var columnList []gen_table_column.Entity
  394. err = j.ToStructs(&columnList)
  395. if err == nil && columnList != nil && len(columnList) > 0 {
  396. for _, column := range columnList {
  397. if column.ColumnId > 0 {
  398. tmp, _ := gen_table_column.FindOne("column_id=?", column.ColumnId)
  399. if tmp != nil {
  400. tmp.ColumnComment = column.ColumnComment
  401. tmp.GoType = column.GoType
  402. tmp.HtmlType = column.HtmlType
  403. tmp.QueryType = column.QueryType
  404. tmp.GoField = column.GoField
  405. tmp.DictType = column.DictType
  406. tmp.IsInsert = column.IsInsert
  407. tmp.IsEdit = column.IsEdit
  408. tmp.IsList = column.IsList
  409. tmp.IsQuery = column.IsQuery
  410. _, err = tx.Table(gen_table_column.Table).Save(tmp)
  411. if err != nil {
  412. tx.Rollback()
  413. return
  414. }
  415. }
  416. }
  417. }
  418. }
  419. }
  420. }
  421. tx.Commit()
  422. return
  423. }
  424. //删除表格
  425. func Delete(ids []int) error {
  426. tx, err := g.DB().Begin()
  427. if err != nil {
  428. g.Log().Error(err)
  429. return gerror.New("开启删除事务出错")
  430. }
  431. _, err = tx.Table(gen_table.Table).Where(gen_table.Columns.TableId+" in(?)", ids).Delete()
  432. if err != nil {
  433. g.Log().Error(err)
  434. tx.Rollback()
  435. return gerror.New("删除表格数据失败")
  436. }
  437. _, err = tx.Table(gen_table_column.Table).Where(gen_table_column.Columns.TableId+" in(?)", ids).Delete()
  438. if err != nil {
  439. g.Log().Error(err)
  440. tx.Rollback()
  441. return gerror.New("删除表格字段数据失败")
  442. }
  443. tx.Commit()
  444. return nil
  445. }
  446. func SelectRecordById(tableId int64) (entity *gen_table.EntityExtend, err error) {
  447. entity, err = gen_table.SelectRecordById(tableId)
  448. return
  449. }
  450. //设置主键列信息
  451. func SetPkColumn(table *gen_table.EntityExtend, columns []*gen_table_column.Entity) {
  452. for _, column := range columns {
  453. if column.IsPk == "1" {
  454. table.PkColumn = column
  455. break
  456. }
  457. }
  458. if table.PkColumn == nil {
  459. table.PkColumn = columns[0]
  460. }
  461. }