database.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  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. if field.FieldName != createdTimeFieldName && field.FieldName != lastUpdatedTimeFieldName &&
  169. reflectutils.IsValueTime(fieldValue) && fieldValue.IsZero() {
  170. field.Value = nil
  171. }
  172. tableRow.Add(field.ColumnName, field.Value)
  173. }
  174. return tableRow
  175. }
  176. // DeleteEntity 通过结构删除数据
  177. // 参数:
  178. // - executor: 数据库基础设施接口
  179. // - tableName: 表名
  180. // - e: 结构,结构字段需要使用sqlmapping标注
  181. // 返回值:
  182. // - 错误
  183. func DeleteEntity(executor Executor, tableName string, e any) error {
  184. if executor == nil {
  185. return errors.New("没有传递执行器")
  186. }
  187. if strutils.IsStringEmpty(tableName) {
  188. return errors.New("没有传递表名")
  189. }
  190. if e == nil {
  191. return nil
  192. }
  193. entityType := reflect.TypeOf(e)
  194. if !reflectutils.IsTypeStructOrStructPointer(entityType) {
  195. return errors.New("实体参数不是结构或结构指针")
  196. }
  197. fields, err := sql_mapping.DefaultUsage(e)
  198. if err != nil {
  199. return err
  200. }
  201. conditions := sql.NewConditions()
  202. for _, field := range fields {
  203. // 不是键,字段跳过
  204. if !field.IsKey {
  205. continue
  206. }
  207. conditions.Equal(field.ColumnName, field.Value)
  208. }
  209. executeParams := sql.DeleteExecuteParams{
  210. TableName: tableName,
  211. Conditions: conditions,
  212. }
  213. executeParamsMap, err := executeParams.Map()
  214. if err != nil {
  215. return err
  216. }
  217. _, err = executor.ExecuteRawSqlTemplate(sql.DeleteTpl, executeParamsMap, executeParams.Conditions.Args()...)
  218. if err != nil {
  219. return err
  220. }
  221. return nil
  222. }
  223. // UpdateEntity 通过结构更新数据
  224. // 参数:
  225. // - executor: 数据库基础设施接口
  226. // - tableName: 表名
  227. // - e: 结构,结构字段需要使用sqlmapping标注
  228. // 返回值:
  229. // - 错误
  230. func UpdateEntity(executor Executor, tableName string, e any) error {
  231. if executor == nil {
  232. return errors.New("没有传递执行器")
  233. }
  234. if strutils.IsStringEmpty(tableName) {
  235. return errors.New("没有传递表名")
  236. }
  237. if e == nil {
  238. return nil
  239. }
  240. entityType := reflect.TypeOf(e)
  241. if !reflectutils.IsTypeStructOrStructPointer(entityType) {
  242. return errors.New("实体参数不是结构或结构指针")
  243. }
  244. fields, err := sql_mapping.DefaultUsage(e)
  245. if err != nil {
  246. return err
  247. }
  248. now := time.Now().Local()
  249. tableRow := sql.NewTableRow()
  250. conditions := sql.NewConditions()
  251. for _, field := range fields {
  252. // 不是键字段
  253. // 不是更新时间字段
  254. // 不更新的字段或者字段为零值且不能清空,跳过
  255. if !field.IsKey && field.FieldName != lastUpdatedTimeFieldName &&
  256. (!field.CanUpdate || (reflect.ValueOf(field.Value).IsZero() && !field.CanUpdateClear)) {
  257. continue
  258. }
  259. fieldValue := reflect.ValueOf(field.Value)
  260. if field.FieldName == lastUpdatedTimeFieldName &&
  261. reflectutils.IsValueTime(fieldValue) && fieldValue.IsZero() {
  262. field.Value = now
  263. }
  264. if field.FieldName != lastUpdatedTimeFieldName &&
  265. reflectutils.IsValueTime(fieldValue) && fieldValue.IsZero() {
  266. field.Value = nil
  267. }
  268. if field.IsKey {
  269. conditions.Equal(field.ColumnName, field.Value)
  270. } else {
  271. if (field.Value == nil || reflect.ValueOf(field.Value).IsZero()) && !field.CanUpdateClear {
  272. continue
  273. }
  274. tableRow.Add(field.ColumnName, field.Value)
  275. }
  276. }
  277. executeParams := sql.UpdateExecuteParams{
  278. TableName: tableName,
  279. TableRow: tableRow,
  280. Conditions: conditions,
  281. }
  282. executeParamsMap, err := executeParams.Map()
  283. if err != nil {
  284. return err
  285. }
  286. args := make([]any, 0)
  287. args = append(args, executeParams.TableRow.Values()...)
  288. args = append(args, executeParams.Conditions.Args()...)
  289. _, err = executor.ExecuteRawSqlTemplate(sql.UpdateTpl, executeParamsMap, args...)
  290. if err != nil {
  291. return err
  292. }
  293. return nil
  294. }
  295. // Insert 插入数据
  296. // 参数:
  297. // - executor: 数据库基础设施接口
  298. // - executeParams: 插入数据参数
  299. // 返回值:
  300. // - 错误
  301. func Insert(executor Executor, executeParams *sql.InsertExecuteParams) error {
  302. if executor == nil {
  303. return errors.New("没有传递执行器")
  304. }
  305. if executeParams == nil {
  306. return errors.New("没有传递执行参数")
  307. }
  308. executeParamsMap, err := executeParams.Map()
  309. if err != nil {
  310. return err
  311. }
  312. _, err = executor.ExecuteRawSqlTemplate(sql.InsertTpl, executeParamsMap, executeParams.TableRow.Values()...)
  313. if err != nil {
  314. return err
  315. }
  316. return nil
  317. }
  318. // InsertBatch 批量插入数据
  319. // 参数:
  320. // - executor: 数据库基础设施接口
  321. // - executeParams: 批量插入数据参数
  322. // 返回值:
  323. // - 错误
  324. func InsertBatch(executor Executor, executeParams *sql.InsertBatchExecuteParams) error {
  325. if executor == nil {
  326. return errors.New("没有传递执行器")
  327. }
  328. if executeParams == nil {
  329. return errors.New("没有传递执行参数")
  330. }
  331. executeParamsMap, err := executeParams.Map()
  332. if err != nil {
  333. return err
  334. }
  335. values := make([]any, 0)
  336. for _, tableRow := range executeParams.TableRowBatch {
  337. values = append(values, tableRow.Values()...)
  338. }
  339. _, err = executor.ExecuteRawSqlTemplate(sql.InsertTpl, executeParamsMap, values...)
  340. if err != nil {
  341. return err
  342. }
  343. return nil
  344. }
  345. // Delete 删除数据
  346. // 参数:
  347. // - executor: 数据库基础设施接口
  348. // - executeParams: 删除数据参数
  349. // 返回值:
  350. // - 错误
  351. func Delete(executor Executor, executeParams *sql.DeleteExecuteParams) error {
  352. if executor == nil {
  353. return errors.New("没有传递执行器")
  354. }
  355. if executeParams == nil {
  356. return errors.New("没有传递执行参数")
  357. }
  358. executeParamsMap, err := executeParams.Map()
  359. if err != nil {
  360. return err
  361. }
  362. _, err = executor.ExecuteRawSqlTemplate(sql.DeleteTpl, executeParamsMap, executeParams.Conditions.Args()...)
  363. if err != nil {
  364. return err
  365. }
  366. return nil
  367. }
  368. // Update 更新数据
  369. // 参数:
  370. // - executor: 数据库基础设施接口
  371. // - executeParams: 更新数据参数
  372. // 返回值:
  373. // - 错误
  374. func Update(executor Executor, executeParams *sql.UpdateExecuteParams) error {
  375. if executor == nil {
  376. return errors.New("没有传递执行器")
  377. }
  378. if executeParams == nil {
  379. return errors.New("没有传递执行参数")
  380. }
  381. if executeParams.Conditions == nil {
  382. executeParams.Conditions = sql.NewConditions()
  383. }
  384. executeParamsMap, err := executeParams.Map()
  385. if err != nil {
  386. return err
  387. }
  388. args := make([]any, 0)
  389. args = append(args, executeParams.TableRow.Values()...)
  390. args = append(args, executeParams.Conditions.Args()...)
  391. _, err = executor.ExecuteRawSqlTemplate(sql.UpdateTpl, executeParamsMap, args...)
  392. if err != nil {
  393. return err
  394. }
  395. return nil
  396. }
  397. // Query 查询数据
  398. // 参数:
  399. // - executor: 数据库基础设施接口
  400. // - executeParams: 查询数据参数
  401. // 返回值:
  402. // - 查询结果
  403. // - 总数
  404. // - 错误
  405. func Query(executor Executor, executeParams *sql.QueryExecuteParams) ([]sql.Result, int64, error) {
  406. if executor == nil {
  407. return nil, 0, errors.New("没有传递执行器")
  408. }
  409. if executeParams == nil {
  410. return nil, 0, errors.New("没有传递执行参数")
  411. }
  412. if executeParams.Conditions == nil {
  413. executeParams.Conditions = sql.NewConditions()
  414. }
  415. queryExecuteParamsMap, err := executeParams.Map()
  416. if err != nil {
  417. return nil, 0, err
  418. }
  419. countExecuteParams := sql.CountExecuteParams{
  420. TableName: executeParams.TableName,
  421. Conditions: executeParams.Conditions,
  422. }
  423. countExecuteParamsMap, err := countExecuteParams.Map()
  424. if err != nil {
  425. return nil, 0, err
  426. }
  427. tableRows, err := executor.ExecuteRawSqlTemplate(sql.QueryTpl, queryExecuteParamsMap, executeParams.Conditions.Args()...)
  428. if err != nil {
  429. return nil, 0, err
  430. }
  431. countTableRow, err := executor.ExecuteRawSqlTemplate(sql.CountTpl, countExecuteParamsMap, countExecuteParams.Conditions.Args()...)
  432. if err != nil {
  433. return nil, 0, err
  434. }
  435. results := make([]sql.Result, len(tableRows))
  436. for i, row := range tableRows {
  437. results[i] = row
  438. }
  439. totalCount, err := reflectutils.ToInt64(countTableRow[0]["count"])
  440. if err != nil {
  441. return nil, 0, err
  442. }
  443. return results, totalCount, nil
  444. }
  445. // QueryOne 查询单条数据
  446. // 参数:
  447. // - executor: 数据库基础设施接口
  448. // - executeParams: 查询单条数据参数
  449. // 返回值:
  450. // - 查询结果
  451. // - 错误
  452. func QueryOne(executor Executor, executeParams *sql.QueryOneExecuteParams) (sql.Result, error) {
  453. if executor == nil {
  454. return nil, errors.New("没有传递执行器")
  455. }
  456. if executeParams == nil {
  457. return nil, errors.New("没有传递执行参数")
  458. }
  459. if executeParams.Conditions == nil {
  460. executeParams.Conditions = sql.NewConditions()
  461. }
  462. executeParamsMap, err := executeParams.Map()
  463. if err != nil {
  464. return nil, err
  465. }
  466. tableRows, err := executor.ExecuteRawSqlTemplate(sql.QueryTpl, executeParamsMap, executeParams.Conditions.Args()...)
  467. if err != nil {
  468. return nil, err
  469. }
  470. if tableRows == nil || len(tableRows) == 0 {
  471. return nil, ErrDBRecordNotExist
  472. }
  473. return tableRows[0], nil
  474. }
  475. // Count 数据计数
  476. // 参数:
  477. // - executor: 数据库基础设施接口
  478. // - executeParams: 数据计数参数
  479. // 返回值:
  480. // - 数量
  481. // - 错误
  482. func Count(executor Executor, executeParams *sql.CountExecuteParams) (int64, error) {
  483. if executor == nil {
  484. return 0, errors.New("没有传递执行器")
  485. }
  486. if executeParams == nil {
  487. return 0, errors.New("没有传递执行参数")
  488. }
  489. if executeParams.Conditions == nil {
  490. executeParams.Conditions = sql.NewConditions()
  491. }
  492. executeParamsMap, err := executeParams.Map()
  493. if err != nil {
  494. return 0, err
  495. }
  496. tableRows, err := executor.ExecuteRawSqlTemplate(sql.CountTpl, executeParamsMap, executeParams.Conditions.Args()...)
  497. if err != nil {
  498. return 0, err
  499. }
  500. count, err := reflectutils.ToInt64(tableRows[0]["count"])
  501. if err != nil {
  502. return 0, err
  503. }
  504. return count, nil
  505. }
  506. // CheckExist 数据存在性检查
  507. // 参数:
  508. // - executor: 数据库基础设施接口
  509. // - executeParams: 数据存在性检查参数
  510. // 返回值:
  511. // - 是否存在
  512. // - 错误
  513. func CheckExist(executor Executor, executeParams *sql.CheckExistExecuteParams) (bool, error) {
  514. if executor == nil {
  515. return false, errors.New("没有传递执行器")
  516. }
  517. if executeParams == nil {
  518. return false, errors.New("没有传递执行参数")
  519. }
  520. if executeParams.Conditions == nil {
  521. executeParams.Conditions = sql.NewConditions()
  522. }
  523. executeParamsMap, err := executeParams.Map()
  524. if err != nil {
  525. return false, err
  526. }
  527. tableRows, err := executor.ExecuteRawSqlTemplate(sql.CountTpl, executeParamsMap, executeParams.Conditions.Args()...)
  528. if err != nil {
  529. return false, err
  530. }
  531. count, err := reflectutils.ToInt64(tableRows[0]["count"])
  532. if err != nil {
  533. return false, err
  534. }
  535. return count > 0, nil
  536. }
  537. // CheckHasOnlyOne 数据唯一性检查
  538. // 参数:
  539. // - executor: 数据库基础设施接口
  540. // - executeParams: 数据唯一性检查参数
  541. // 返回值:
  542. // - 是否唯一
  543. // - 错误
  544. func CheckHasOnlyOne(executor Executor, executeParams *sql.CheckHasOnlyOneExecuteParams) (bool, error) {
  545. if executor == nil {
  546. return false, errors.New("没有传递执行器")
  547. }
  548. if executeParams == nil {
  549. return false, errors.New("没有传递执行参数")
  550. }
  551. if executeParams.Conditions == nil {
  552. executeParams.Conditions = sql.NewConditions()
  553. }
  554. executeParamsMap, err := executeParams.Map()
  555. if err != nil {
  556. return false, err
  557. }
  558. tableRows, err := executor.ExecuteRawSqlTemplate(sql.CountTpl, executeParamsMap, executeParams.Conditions.Args()...)
  559. if err != nil {
  560. return false, err
  561. }
  562. count, err := reflectutils.ToInt64(tableRows[0]["count"])
  563. if err != nil {
  564. return false, err
  565. }
  566. return count == 1, nil
  567. }
  568. // ExecuteRawSql SQL执行接口
  569. // 参数:
  570. // - executor: 数据库基础设施接口
  571. // - sql: SQL语句,可以使用预编译,需要填充的值用?占位
  572. // - args: 预编译填充值
  573. // 返回值:
  574. // - SQL执行结果
  575. // - 错误
  576. func ExecuteRawSql(executor Executor, sql string, args ...any) ([]sql.Result, error) {
  577. return ExecuteRawSqlTemplate(executor, sql, nil, args...)
  578. }
  579. // ExecuteRawSqlTemplate SQL模板执行接口
  580. // 参数:
  581. // - executor: 数据库基础设施接口
  582. // - sql: SQL语句模板,可以使用预编译,需要填充的值用?占位,可以使用Go模板构造SQL语句
  583. // - template: 渲染SQL语句模板的模板参数
  584. // - args: 预编译填充值
  585. // 返回值:
  586. // - SQL执行结果
  587. // - 错误
  588. func ExecuteRawSqlTemplate(executor Executor, sql string, executeParams map[string]any, args ...any) ([]sql.Result, error) {
  589. if executor == nil {
  590. return nil, errors.New("没有传递执行器")
  591. }
  592. if strutils.IsStringEmpty(sql) {
  593. return nil, errors.New("没有sql")
  594. }
  595. tableRows, err := executor.ExecuteRawSqlTemplate(sql, executeParams, args...)
  596. if err != nil {
  597. return nil, err
  598. }
  599. return tableRows, nil
  600. }