database.go 17 KB

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