table.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. package gen_service
  2. import (
  3. "gfast/app/model/admin/gen_table"
  4. "gfast/app/model/admin/gen_table_column"
  5. "strings"
  6. "github.com/gogf/gf/database/gdb"
  7. "github.com/gogf/gf/encoding/gjson"
  8. "github.com/gogf/gf/errors/gerror"
  9. "github.com/gogf/gf/frame/g"
  10. "github.com/gogf/gf/os/gtime"
  11. "github.com/gogf/gf/text/gregex"
  12. "github.com/gogf/gf/text/gstr"
  13. "github.com/gogf/gf/util/gconv"
  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 = "datetime"
  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. if strings.HasPrefix(tableName, str) {
  301. tableName = strings.Replace(tableName, str, "", 1) //注意,只替换一次
  302. }
  303. }
  304. }
  305. return tableName
  306. }
  307. //获取业务名
  308. func GetBusinessName(tableName string) string {
  309. lastIndex := strings.LastIndex(tableName, "_")
  310. nameLength := len(tableName)
  311. businessName := tableName[lastIndex+1 : nameLength]
  312. return businessName
  313. }
  314. //根据table_id查询表列数据
  315. func SelectGenTableColumnListByTableId(tableId int64) ([]*gen_table_column.Entity, error) {
  316. return gen_table_column.SelectGenTableColumnListByTableId(tableId)
  317. }
  318. func GetTableInfoByTableId(tableId int64) (info *gen_table.Entity, err error) {
  319. return gen_table.GetInfoById(tableId)
  320. }
  321. //修改表和列信息
  322. func SaveEdit(req *gen_table.EditReq) (err error) {
  323. if req == nil {
  324. err = gerror.New("参数错误")
  325. return
  326. }
  327. table, err := gen_table.FindOne("table_id=?", req.TableId)
  328. if err != nil || table == nil {
  329. err = gerror.New("数据不存在")
  330. return
  331. }
  332. if req.TableName != "" {
  333. table.TableName = req.TableName
  334. }
  335. if req.TableComment != "" {
  336. table.TableComment = req.TableComment
  337. }
  338. if req.BusinessName != "" {
  339. table.BusinessName = req.BusinessName
  340. }
  341. if req.ClassName != "" {
  342. table.ClassName = req.ClassName
  343. }
  344. if req.FunctionAuthor != "" {
  345. table.FunctionAuthor = req.FunctionAuthor
  346. }
  347. if req.FunctionName != "" {
  348. table.FunctionName = req.FunctionName
  349. }
  350. if req.ModuleName != "" {
  351. table.ModuleName = req.ModuleName
  352. }
  353. if req.PackageName != "" {
  354. table.PackageName = req.PackageName
  355. }
  356. if req.Remark != "" {
  357. table.Remark = req.Remark
  358. }
  359. if req.TplCategory != "" {
  360. table.TplCategory = req.TplCategory
  361. }
  362. if req.Params != "" {
  363. table.Options = req.Params
  364. }
  365. table.UpdateTime = gtime.Now()
  366. table.UpdateBy = req.UserName
  367. if req.TplCategory == "tree" {
  368. //树表设置options
  369. options := g.Map{
  370. "tree_code": req.TreeCode,
  371. "tree_parent_code": req.TreeParentCode,
  372. "tree_name": req.TreeName,
  373. }
  374. table.Options = gconv.String(options)
  375. } else {
  376. table.Options = ""
  377. }
  378. var tx *gdb.TX
  379. tx, err = g.DB().Begin()
  380. if err != nil {
  381. return
  382. }
  383. _, err = tx.Table(gen_table.Table).Save(table)
  384. if err != nil {
  385. tx.Rollback()
  386. return err
  387. }
  388. //保存列数据
  389. if req.Columns != "" {
  390. var j *gjson.Json
  391. if j, err = gjson.DecodeToJson([]byte(req.Columns)); err != nil {
  392. tx.Rollback()
  393. return
  394. } else {
  395. var columnList []gen_table_column.Entity
  396. err = j.ToStructs(&columnList)
  397. if err == nil && columnList != nil && len(columnList) > 0 {
  398. for _, column := range columnList {
  399. if column.ColumnId > 0 {
  400. tmp, _ := gen_table_column.FindOne("column_id=?", column.ColumnId)
  401. if tmp != nil {
  402. tmp.ColumnComment = column.ColumnComment
  403. tmp.GoType = column.GoType
  404. tmp.HtmlType = column.HtmlType
  405. tmp.QueryType = column.QueryType
  406. tmp.GoField = column.GoField
  407. tmp.DictType = column.DictType
  408. tmp.IsInsert = column.IsInsert
  409. tmp.IsEdit = column.IsEdit
  410. tmp.IsList = column.IsList
  411. tmp.IsQuery = column.IsQuery
  412. _, err = tx.Table(gen_table_column.Table).Save(tmp)
  413. if err != nil {
  414. tx.Rollback()
  415. return
  416. }
  417. }
  418. }
  419. }
  420. }
  421. }
  422. }
  423. tx.Commit()
  424. return
  425. }
  426. //删除表格
  427. func Delete(ids []int) error {
  428. tx, err := g.DB().Begin()
  429. if err != nil {
  430. g.Log().Error(err)
  431. return gerror.New("开启删除事务出错")
  432. }
  433. _, err = tx.Table(gen_table.Table).Where(gen_table.Columns.TableId+" in(?)", ids).Delete()
  434. if err != nil {
  435. g.Log().Error(err)
  436. tx.Rollback()
  437. return gerror.New("删除表格数据失败")
  438. }
  439. _, err = tx.Table(gen_table_column.Table).Where(gen_table_column.Columns.TableId+" in(?)", ids).Delete()
  440. if err != nil {
  441. g.Log().Error(err)
  442. tx.Rollback()
  443. return gerror.New("删除表格字段数据失败")
  444. }
  445. tx.Commit()
  446. return nil
  447. }
  448. func SelectRecordById(tableId int64) (entity *gen_table.EntityExtend, err error) {
  449. entity, err = gen_table.SelectRecordById(tableId)
  450. return
  451. }
  452. //设置主键列信息
  453. func SetPkColumn(table *gen_table.EntityExtend, columns []*gen_table_column.Entity) {
  454. for _, column := range columns {
  455. if column.IsPk == "1" {
  456. table.PkColumn = column
  457. break
  458. }
  459. }
  460. if table.PkColumn == nil {
  461. table.PkColumn = columns[0]
  462. }
  463. }