database.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. package database
  2. import (
  3. "git.sxidc.com/go-framework/baize/framework/core/infrastructure/database/operations"
  4. "git.sxidc.com/go-framework/baize/framework/core/infrastructure/database/sql"
  5. "git.sxidc.com/go-framework/baize/framework/core/tag/sql/sql_mapping"
  6. "git.sxidc.com/go-tools/utils/reflectutils"
  7. "git.sxidc.com/go-tools/utils/strutils"
  8. "github.com/pkg/errors"
  9. "reflect"
  10. "strings"
  11. "time"
  12. )
  13. // Executor 数据库基础设施接口
  14. type Executor interface {
  15. // ExecuteRawSql SQL执行接口
  16. // 参数:
  17. // - sql: SQL语句,可以使用预编译,需要填充的值用?占位
  18. // - values: 预编译填充值
  19. // 返回值:
  20. // - SQL执行结果
  21. // - 错误
  22. ExecuteRawSql(sql string, args ...any) ([]sql.Result, error)
  23. // ExecuteRawSqlTemplate SQL模板执行接口
  24. // 参数:
  25. // - sql: SQL语句模板,可以使用预编译,需要填充的值用?占位,可以使用Go模板构造SQL语句
  26. // - template: 渲染SQL语句模板的模板参数
  27. // - values: 预编译填充值
  28. // 返回值:
  29. // - SQL执行结果
  30. // - 错误
  31. ExecuteRawSqlTemplate(sql string, template map[string]any, args ...any) ([]sql.Result, error)
  32. }
  33. const (
  34. createdTimeFieldName = "CreatedTime"
  35. lastUpdatedTimeFieldName = "LastUpdatedTime"
  36. )
  37. // Transaction 执行事务
  38. // 参数:
  39. // - executor: 数据库基础设施接口
  40. // - txFunc: 事务函数
  41. // 返回值:
  42. // - 错误
  43. func Transaction(executor Executor, txFunc func(tx Executor) error) (err error) {
  44. if executor == nil {
  45. return nil
  46. }
  47. if txFunc == nil {
  48. return nil
  49. }
  50. switch e := executor.(type) {
  51. case *operations.Operations:
  52. tx := e.BeginTransaction()
  53. defer func() {
  54. if r := recover(); r != nil {
  55. tx.RollbackTransaction()
  56. err = errors.Errorf("panic: %v", r)
  57. }
  58. }()
  59. err = txFunc(tx)
  60. if err != nil {
  61. tx.RollbackTransaction()
  62. return err
  63. }
  64. tx.CommitTransaction()
  65. default:
  66. return nil
  67. }
  68. return nil
  69. }
  70. // InsertEntity 通过结构插入数据
  71. // 参数:
  72. // - executor: 数据库基础设施接口
  73. // - tableName: 表名
  74. // - es: 结构或结构slice(批量插入),结构字段需要使用sqlmapping标注
  75. // 返回值:
  76. // - 错误
  77. func InsertEntity(executor Executor, tableName string, es any) error {
  78. if executor == nil {
  79. return errors.New("没有传递执行器")
  80. }
  81. if strutils.IsStringEmpty(tableName) {
  82. return errors.New("没有传递表名")
  83. }
  84. if es == nil {
  85. return nil
  86. }
  87. entityType := reflect.TypeOf(es)
  88. entityElemType := reflectutils.PointerTypeElem(entityType)
  89. if entityElemType.Kind() == reflect.Struct {
  90. return insertEntitySingle(executor, tableName, es)
  91. } else if entityElemType.Kind() == reflect.Slice {
  92. return insertEntityBatch(executor, tableName, es)
  93. } else {
  94. return errors.New("实体可以是结构,结构指针,结构Slice,结构指针的Slice或Slice的指针")
  95. }
  96. }
  97. func insertEntitySingle(executor Executor, tableName string, e any) error {
  98. fields, err := sql_mapping.DefaultUsage(e)
  99. if err != nil {
  100. return err
  101. }
  102. executeParams := sql.InsertExecuteParams{
  103. TableName: tableName,
  104. TableRow: formInsertTableRow(fields, time.Now().Local()),
  105. }
  106. executeParamsMap, err := executeParams.Map()
  107. if err != nil {
  108. return err
  109. }
  110. _, err = executor.ExecuteRawSqlTemplate(sql.InsertTpl, executeParamsMap, executeParams.TableRow.Values()...)
  111. if err != nil {
  112. if strings.Contains(err.Error(), "SQLSTATE 23505") {
  113. return ErrDBRecordHasExist
  114. }
  115. return err
  116. }
  117. return nil
  118. }
  119. func insertEntityBatch(executor Executor, tableName string, es any) error {
  120. now := time.Now().Local()
  121. tableRowBatch := make([]sql.TableRow, 0)
  122. entitiesValue := reflectutils.PointerValueElem(reflect.ValueOf(es))
  123. for i := 0; i < entitiesValue.Len(); i++ {
  124. entityValue := entitiesValue.Index(i)
  125. if !entityValue.IsValid() || entityValue.IsZero() {
  126. continue
  127. }
  128. e := entityValue.Interface()
  129. entityType := reflect.TypeOf(e)
  130. if !reflectutils.IsTypeStructOrStructPointer(entityType) {
  131. return errors.New("实体参数不是结构或结构指针")
  132. }
  133. fields, err := sql_mapping.DefaultUsage(e)
  134. if err != nil {
  135. return err
  136. }
  137. tableRowBatch = append(tableRowBatch, *formInsertTableRow(fields, now))
  138. }
  139. executeParams := sql.InsertBatchExecuteParams{
  140. TableName: tableName,
  141. TableRowBatch: tableRowBatch,
  142. }
  143. executeParamsMap, err := executeParams.Map()
  144. if err != nil {
  145. return err
  146. }
  147. values := make([]any, 0)
  148. for _, tableRow := range executeParams.TableRowBatch {
  149. values = append(values, tableRow.Values()...)
  150. }
  151. _, err = executor.ExecuteRawSqlTemplate(sql.InsertTpl, executeParamsMap, values...)
  152. if err != nil {
  153. if strings.Contains(err.Error(), "SQLSTATE 23505") {
  154. return ErrDBRecordHasExist
  155. }
  156. return err
  157. }
  158. return nil
  159. }
  160. func formInsertTableRow(fields []sql_mapping.Field, createTime time.Time) *sql.TableRow {
  161. tableRow := sql.NewTableRow()
  162. for _, field := range fields {
  163. fieldValue := reflect.ValueOf(field.Value)
  164. if (field.FieldName == createdTimeFieldName || field.FieldName == lastUpdatedTimeFieldName) &&
  165. reflectutils.IsValueTime(fieldValue) && fieldValue.IsZero() {
  166. field.Value = createTime
  167. }
  168. tableRow.Add(field.ColumnName, field.Value)
  169. }
  170. return tableRow
  171. }
  172. // DeleteEntity 通过结构删除数据
  173. // 参数:
  174. // - executor: 数据库基础设施接口
  175. // - tableName: 表名
  176. // - e: 结构,结构字段需要使用sqlmapping标注
  177. // 返回值:
  178. // - 错误
  179. func DeleteEntity(executor Executor, tableName string, e any) error {
  180. if executor == nil {
  181. return errors.New("没有传递执行器")
  182. }
  183. if strutils.IsStringEmpty(tableName) {
  184. return errors.New("没有传递表名")
  185. }
  186. if e == nil {
  187. return nil
  188. }
  189. entityType := reflect.TypeOf(e)
  190. if !reflectutils.IsTypeStructOrStructPointer(entityType) {
  191. return errors.New("实体参数不是结构或结构指针")
  192. }
  193. fields, err := sql_mapping.DefaultUsage(e)
  194. if err != nil {
  195. return err
  196. }
  197. conditions := sql.NewConditions()
  198. for _, field := range fields {
  199. // 不是键,字段跳过
  200. if !field.IsKey {
  201. continue
  202. }
  203. conditions.Equal(field.ColumnName, field.Value)
  204. }
  205. executeParams := sql.DeleteExecuteParams{
  206. TableName: tableName,
  207. Conditions: conditions,
  208. }
  209. executeParamsMap, err := executeParams.Map()
  210. if err != nil {
  211. return err
  212. }
  213. _, err = executor.ExecuteRawSqlTemplate(sql.DeleteTpl, executeParamsMap, executeParams.Conditions.Args()...)
  214. if err != nil {
  215. return err
  216. }
  217. return nil
  218. }
  219. // UpdateEntity 通过结构更新数据
  220. // 参数:
  221. // - executor: 数据库基础设施接口
  222. // - tableName: 表名
  223. // - e: 结构,结构字段需要使用sqlmapping标注
  224. // 返回值:
  225. // - 错误
  226. func UpdateEntity(executor Executor, tableName string, e any) error {
  227. if executor == nil {
  228. return errors.New("没有传递执行器")
  229. }
  230. if strutils.IsStringEmpty(tableName) {
  231. return errors.New("没有传递表名")
  232. }
  233. if e == nil {
  234. return nil
  235. }
  236. entityType := reflect.TypeOf(e)
  237. if !reflectutils.IsTypeStructOrStructPointer(entityType) {
  238. return errors.New("实体参数不是结构或结构指针")
  239. }
  240. fields, err := sql_mapping.DefaultUsage(e)
  241. if err != nil {
  242. return err
  243. }
  244. now := time.Now().Local()
  245. tableRow := sql.NewTableRow()
  246. conditions := sql.NewConditions()
  247. for _, field := range fields {
  248. // 不是键字段
  249. // 不是更新时间字段
  250. // 不更新的字段或者字段为零值且不能清空,跳过
  251. if !field.IsKey && field.FieldName != lastUpdatedTimeFieldName &&
  252. (!field.CanUpdate || (reflect.ValueOf(field.Value).IsZero() && !field.CanUpdateClear)) {
  253. continue
  254. }
  255. fieldValue := reflect.ValueOf(field.Value)
  256. if field.FieldName == lastUpdatedTimeFieldName &&
  257. reflectutils.IsValueTime(fieldValue) && fieldValue.IsZero() {
  258. field.Value = now
  259. }
  260. if field.IsKey {
  261. conditions.Equal(field.ColumnName, field.Value)
  262. } else {
  263. if reflect.ValueOf(field.Value).IsZero() && !field.CanUpdateClear {
  264. continue
  265. }
  266. tableRow.Add(field.ColumnName, field.Value)
  267. }
  268. }
  269. executeParams := sql.UpdateExecuteParams{
  270. TableName: tableName,
  271. TableRow: tableRow,
  272. Conditions: conditions,
  273. }
  274. executeParamsMap, err := executeParams.Map()
  275. if err != nil {
  276. return err
  277. }
  278. args := make([]any, 0)
  279. args = append(args, executeParams.TableRow.Values()...)
  280. args = append(args, executeParams.Conditions.Args()...)
  281. _, err = executor.ExecuteRawSqlTemplate(sql.UpdateTpl, executeParamsMap, args...)
  282. if err != nil {
  283. return err
  284. }
  285. return nil
  286. }
  287. // Insert 插入数据
  288. // 参数:
  289. // - executor: 数据库基础设施接口
  290. // - executeParams: 插入数据参数
  291. // 返回值:
  292. // - 错误
  293. func Insert(executor Executor, executeParams *sql.InsertExecuteParams) error {
  294. if executor == nil {
  295. return errors.New("没有传递执行器")
  296. }
  297. if executeParams == nil {
  298. return errors.New("没有传递执行参数")
  299. }
  300. executeParamsMap, err := executeParams.Map()
  301. if err != nil {
  302. return err
  303. }
  304. _, err = executor.ExecuteRawSqlTemplate(sql.InsertTpl, executeParamsMap, executeParams.TableRow.Values()...)
  305. if err != nil {
  306. return err
  307. }
  308. return nil
  309. }
  310. // InsertBatch 批量插入数据
  311. // 参数:
  312. // - executor: 数据库基础设施接口
  313. // - executeParams: 批量插入数据参数
  314. // 返回值:
  315. // - 错误
  316. func InsertBatch(executor Executor, executeParams *sql.InsertBatchExecuteParams) error {
  317. if executor == nil {
  318. return errors.New("没有传递执行器")
  319. }
  320. if executeParams == nil {
  321. return errors.New("没有传递执行参数")
  322. }
  323. executeParamsMap, err := executeParams.Map()
  324. if err != nil {
  325. return err
  326. }
  327. values := make([]any, 0)
  328. for _, tableRow := range executeParams.TableRowBatch {
  329. values = append(values, tableRow.Values()...)
  330. }
  331. _, err = executor.ExecuteRawSqlTemplate(sql.InsertTpl, executeParamsMap, values...)
  332. if err != nil {
  333. return err
  334. }
  335. return nil
  336. }
  337. // Delete 删除数据
  338. // 参数:
  339. // - executor: 数据库基础设施接口
  340. // - executeParams: 删除数据参数
  341. // 返回值:
  342. // - 错误
  343. func Delete(executor Executor, executeParams *sql.DeleteExecuteParams) error {
  344. if executor == nil {
  345. return errors.New("没有传递执行器")
  346. }
  347. if executeParams == nil {
  348. return errors.New("没有传递执行参数")
  349. }
  350. executeParamsMap, err := executeParams.Map()
  351. if err != nil {
  352. return err
  353. }
  354. _, err = executor.ExecuteRawSqlTemplate(sql.DeleteTpl, executeParamsMap, executeParams.Conditions.Args()...)
  355. if err != nil {
  356. return err
  357. }
  358. return nil
  359. }
  360. // Update 更新数据
  361. // 参数:
  362. // - executor: 数据库基础设施接口
  363. // - executeParams: 更新数据参数
  364. // 返回值:
  365. // - 错误
  366. func Update(executor Executor, executeParams *sql.UpdateExecuteParams) error {
  367. if executor == nil {
  368. return errors.New("没有传递执行器")
  369. }
  370. if executeParams == nil {
  371. return errors.New("没有传递执行参数")
  372. }
  373. if executeParams.Conditions == nil {
  374. executeParams.Conditions = sql.NewConditions()
  375. }
  376. executeParamsMap, err := executeParams.Map()
  377. if err != nil {
  378. return err
  379. }
  380. args := make([]any, 0)
  381. args = append(args, executeParams.TableRow.Values()...)
  382. args = append(args, executeParams.Conditions.Args()...)
  383. _, err = executor.ExecuteRawSqlTemplate(sql.UpdateTpl, executeParamsMap, args...)
  384. if err != nil {
  385. return err
  386. }
  387. return nil
  388. }
  389. // Query 查询数据
  390. // 参数:
  391. // - executor: 数据库基础设施接口
  392. // - executeParams: 查询数据参数
  393. // 返回值:
  394. // - 查询结果
  395. // - 总数
  396. // - 错误
  397. func Query(executor Executor, executeParams *sql.QueryExecuteParams) ([]sql.Result, int64, error) {
  398. if executor == nil {
  399. return nil, 0, errors.New("没有传递执行器")
  400. }
  401. if executeParams == nil {
  402. return nil, 0, errors.New("没有传递执行参数")
  403. }
  404. if executeParams.Conditions == nil {
  405. executeParams.Conditions = sql.NewConditions()
  406. }
  407. queryExecuteParamsMap, err := executeParams.Map()
  408. if err != nil {
  409. return nil, 0, err
  410. }
  411. countExecuteParams := sql.CountExecuteParams{
  412. TableName: executeParams.TableName,
  413. Conditions: executeParams.Conditions,
  414. }
  415. countExecuteParamsMap, err := countExecuteParams.Map()
  416. if err != nil {
  417. return nil, 0, err
  418. }
  419. tableRows, err := executor.ExecuteRawSqlTemplate(sql.QueryTpl, queryExecuteParamsMap, executeParams.Conditions.Args()...)
  420. if err != nil {
  421. return nil, 0, err
  422. }
  423. countTableRow, err := executor.ExecuteRawSqlTemplate(sql.CountTpl, countExecuteParamsMap, countExecuteParams.Conditions.Args()...)
  424. if err != nil {
  425. return nil, 0, err
  426. }
  427. results := make([]sql.Result, len(tableRows))
  428. for i, row := range tableRows {
  429. results[i] = row
  430. }
  431. totalCount, err := reflectutils.ToInt64(countTableRow[0]["count"])
  432. if err != nil {
  433. return nil, 0, err
  434. }
  435. return results, totalCount, nil
  436. }
  437. // QueryOne 查询单条数据
  438. // 参数:
  439. // - executor: 数据库基础设施接口
  440. // - executeParams: 查询单条数据参数
  441. // 返回值:
  442. // - 查询结果
  443. // - 错误
  444. func QueryOne(executor Executor, executeParams *sql.QueryOneExecuteParams) (sql.Result, error) {
  445. if executor == nil {
  446. return nil, errors.New("没有传递执行器")
  447. }
  448. if executeParams == nil {
  449. return nil, errors.New("没有传递执行参数")
  450. }
  451. if executeParams.Conditions == nil {
  452. executeParams.Conditions = sql.NewConditions()
  453. }
  454. executeParamsMap, err := executeParams.Map()
  455. if err != nil {
  456. return nil, err
  457. }
  458. tableRows, err := executor.ExecuteRawSqlTemplate(sql.QueryTpl, executeParamsMap, executeParams.Conditions.Args()...)
  459. if err != nil {
  460. return nil, err
  461. }
  462. if tableRows == nil || len(tableRows) == 0 {
  463. return nil, ErrDBRecordNotExist
  464. }
  465. return tableRows[0], nil
  466. }
  467. // Count 数据计数
  468. // 参数:
  469. // - executor: 数据库基础设施接口
  470. // - executeParams: 数据计数参数
  471. // 返回值:
  472. // - 数量
  473. // - 错误
  474. func Count(executor Executor, executeParams *sql.CountExecuteParams) (int64, error) {
  475. if executor == nil {
  476. return 0, errors.New("没有传递执行器")
  477. }
  478. if executeParams == nil {
  479. return 0, errors.New("没有传递执行参数")
  480. }
  481. if executeParams.Conditions == nil {
  482. executeParams.Conditions = sql.NewConditions()
  483. }
  484. executeParamsMap, err := executeParams.Map()
  485. if err != nil {
  486. return 0, err
  487. }
  488. tableRows, err := executor.ExecuteRawSqlTemplate(sql.CountTpl, executeParamsMap, executeParams.Conditions.Args()...)
  489. if err != nil {
  490. return 0, err
  491. }
  492. count, err := reflectutils.ToInt64(tableRows[0]["count"])
  493. if err != nil {
  494. return 0, err
  495. }
  496. return count, nil
  497. }
  498. // CheckExist 数据存在性检查
  499. // 参数:
  500. // - executor: 数据库基础设施接口
  501. // - executeParams: 数据存在性检查参数
  502. // 返回值:
  503. // - 是否存在
  504. // - 错误
  505. func CheckExist(executor Executor, executeParams *sql.CheckExistExecuteParams) (bool, error) {
  506. if executor == nil {
  507. return false, errors.New("没有传递执行器")
  508. }
  509. if executeParams == nil {
  510. return false, errors.New("没有传递执行参数")
  511. }
  512. if executeParams.Conditions == nil {
  513. executeParams.Conditions = sql.NewConditions()
  514. }
  515. executeParamsMap, err := executeParams.Map()
  516. if err != nil {
  517. return false, err
  518. }
  519. tableRows, err := executor.ExecuteRawSqlTemplate(sql.CountTpl, executeParamsMap, executeParams.Conditions.Args()...)
  520. if err != nil {
  521. return false, err
  522. }
  523. count, err := reflectutils.ToInt64(tableRows[0]["count"])
  524. if err != nil {
  525. return false, err
  526. }
  527. return count > 0, nil
  528. }
  529. // CheckHasOnlyOne 数据唯一性检查
  530. // 参数:
  531. // - executor: 数据库基础设施接口
  532. // - executeParams: 数据唯一性检查参数
  533. // 返回值:
  534. // - 是否唯一
  535. // - 错误
  536. func CheckHasOnlyOne(executor Executor, executeParams *sql.CheckHasOnlyOneExecuteParams) (bool, error) {
  537. if executor == nil {
  538. return false, errors.New("没有传递执行器")
  539. }
  540. if executeParams == nil {
  541. return false, errors.New("没有传递执行参数")
  542. }
  543. if executeParams.Conditions == nil {
  544. executeParams.Conditions = sql.NewConditions()
  545. }
  546. executeParamsMap, err := executeParams.Map()
  547. if err != nil {
  548. return false, err
  549. }
  550. tableRows, err := executor.ExecuteRawSqlTemplate(sql.CountTpl, executeParamsMap, executeParams.Conditions.Args()...)
  551. if err != nil {
  552. return false, err
  553. }
  554. count, err := reflectutils.ToInt64(tableRows[0]["count"])
  555. if err != nil {
  556. return false, err
  557. }
  558. return count == 1, nil
  559. }
  560. // ExecuteRawSql SQL执行接口
  561. // 参数:
  562. // - executor: 数据库基础设施接口
  563. // - sql: SQL语句,可以使用预编译,需要填充的值用?占位
  564. // - args: 预编译填充值
  565. // 返回值:
  566. // - SQL执行结果
  567. // - 错误
  568. func ExecuteRawSql(executor Executor, sql string, args ...any) ([]sql.Result, error) {
  569. return ExecuteRawSqlTemplate(executor, sql, nil, args...)
  570. }
  571. // ExecuteRawSqlTemplate SQL模板执行接口
  572. // 参数:
  573. // - executor: 数据库基础设施接口
  574. // - sql: SQL语句模板,可以使用预编译,需要填充的值用?占位,可以使用Go模板构造SQL语句
  575. // - template: 渲染SQL语句模板的模板参数
  576. // - args: 预编译填充值
  577. // 返回值:
  578. // - SQL执行结果
  579. // - 错误
  580. func ExecuteRawSqlTemplate(executor Executor, sql string, executeParams map[string]any, args ...any) ([]sql.Result, error) {
  581. if executor == nil {
  582. return nil, errors.New("没有传递执行器")
  583. }
  584. if strutils.IsStringEmpty(sql) {
  585. return nil, errors.New("没有sql")
  586. }
  587. tableRows, err := executor.ExecuteRawSqlTemplate(sql, executeParams, args...)
  588. if err != nil {
  589. return nil, err
  590. }
  591. return tableRows, nil
  592. }