数据库操作
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

692 lines
14 KiB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
  1. package dbquery
  2. /**
  3. * 事务操作
  4. */
  5. import (
  6. "database/sql"
  7. "errors"
  8. "log"
  9. "strconv"
  10. "strings"
  11. "git.tetele.net/tgo/helper"
  12. )
  13. type TxQuery struct {
  14. dbname string
  15. table string
  16. alias string
  17. title string
  18. where []string
  19. where_or []string
  20. join [][]string //[["tablea as a","a.id=b.id","left"]]
  21. data []string
  22. value []interface{}
  23. save_data []map[string]interface{} //批量操作的数据[["title":"a","num":1,],["title":"a","num":1,]]
  24. upd_field []string // 批量更新时需要更新的字段,为空时按除id外的字段进行更新
  25. orderby string
  26. groupby string
  27. having string
  28. page int
  29. page_size int
  30. stmt *sql.Stmt
  31. conn *sql.DB
  32. tx *sql.Tx
  33. debug bool
  34. }
  35. func NewTxQuery(t ...string) *TxQuery {
  36. var conn_type *sql.DB = DB
  37. if len(t) > 0 {
  38. switch t[0] {
  39. case "mysql":
  40. conn_type = DB
  41. case "mssql": //sql server
  42. conn_type = MSDB_CONN
  43. }
  44. }
  45. tx, err := conn_type.Begin()
  46. if err != nil {
  47. log.Println("start tx begin error", err)
  48. }
  49. return &TxQuery{
  50. conn: conn_type,
  51. tx: tx,
  52. }
  53. }
  54. func (this *TxQuery) Conn(conn *sql.DB) *TxQuery {
  55. this.conn = conn
  56. return this
  57. }
  58. func (this *TxQuery) Db(dbname string) *TxQuery {
  59. this.dbname = dbname
  60. return this
  61. }
  62. func (this *TxQuery) Table(tablename string) *TxQuery {
  63. this.table = tablename
  64. return this
  65. }
  66. func (this *TxQuery) Alias(tablename string) *TxQuery {
  67. this.alias = tablename
  68. return this
  69. }
  70. func (this *TxQuery) Title(title string) *TxQuery {
  71. this.title = title
  72. return this
  73. }
  74. func (this *TxQuery) Page(page int) *TxQuery {
  75. this.page = page
  76. return this
  77. }
  78. func (this *TxQuery) PageSize(page_num int) *TxQuery {
  79. this.page_size = page_num
  80. return this
  81. }
  82. func (this *TxQuery) Orderby(orderby string) *TxQuery {
  83. this.orderby = orderby
  84. return this
  85. }
  86. func (this *TxQuery) Groupby(groupby string) *TxQuery {
  87. this.groupby = groupby
  88. return this
  89. }
  90. func (this *TxQuery) Having(having string) *TxQuery {
  91. this.having = having
  92. return this
  93. }
  94. func (this *TxQuery) Where(where string) *TxQuery {
  95. this.where = append(this.where, where)
  96. return this
  97. }
  98. func (this *TxQuery) Wheres(wheres []string) *TxQuery {
  99. if len(wheres) > 0 {
  100. this.where = append(this.where, wheres...)
  101. }
  102. return this
  103. }
  104. func (this *TxQuery) WhereOr(where string) *TxQuery {
  105. this.where_or = append(this.where_or, where)
  106. return this
  107. }
  108. func (this *TxQuery) Value(value interface{}) *TxQuery {
  109. this.value = append(this.value, value)
  110. return this
  111. }
  112. func (this *TxQuery) SaveData(value map[string]interface{}) *TxQuery {
  113. this.save_data = append(this.save_data, value)
  114. return this
  115. }
  116. func (this *TxQuery) SaveDatas(value []map[string]interface{}) *TxQuery {
  117. this.save_data = append(this.save_data, value...)
  118. return this
  119. }
  120. func (this *TxQuery) UpdField(value string) *TxQuery {
  121. this.upd_field = append(this.upd_field, value)
  122. return this
  123. }
  124. func (this *TxQuery) UpdFields(value []string) *TxQuery {
  125. this.upd_field = append(this.upd_field, value...)
  126. return this
  127. }
  128. func (this *TxQuery) Values(values []interface{}) *TxQuery {
  129. this.value = append(this.value, values...)
  130. return this
  131. }
  132. func (this *TxQuery) Join(join []string) *TxQuery {
  133. this.join = append(this.join, join)
  134. return this
  135. }
  136. func (this *TxQuery) Data(data string) *TxQuery {
  137. this.data = append(this.data, data)
  138. return this
  139. }
  140. func (this *TxQuery) Datas(datas []string) *TxQuery {
  141. this.data = append(this.data, datas...)
  142. return this
  143. }
  144. func (this *TxQuery) Debug(debug bool) *TxQuery {
  145. this.debug = debug
  146. return this
  147. }
  148. /*
  149. * 清理上次查询
  150. */
  151. func (this *TxQuery) Clean() *TxQuery {
  152. this.title = ""
  153. this.where = this.where[0:0]
  154. this.where_or = this.where_or[0:0]
  155. this.join = this.join[0:0]
  156. this.data = this.data[0:0]
  157. this.value = this.value[0:0]
  158. this.orderby = ""
  159. this.groupby = ""
  160. this.page = 0
  161. this.page_size = 0
  162. this.save_data = this.save_data[0:0]
  163. this.upd_field = this.upd_field[0:0]
  164. this.having = ""
  165. return this
  166. }
  167. //构造子查询
  168. func (this *TxQuery) BuildSelectSql() (map[string]interface{}, error) {
  169. if this.dbname == "" && this.table == "" {
  170. return nil, errors.New("参数错误,没有数据表")
  171. }
  172. var table = ""
  173. if strings.Contains(this.table, "select ") {
  174. table = this.table
  175. } else {
  176. table = getTableName(this.dbname, this.table)
  177. }
  178. var sql, title string
  179. if this.title != "" {
  180. title = this.title
  181. } else {
  182. title = "*"
  183. }
  184. sql = helper.StringJoin("select ", title)
  185. if this.alias != "" {
  186. table = helper.StringJoin(table, " as ", this.alias)
  187. }
  188. sql = helper.StringJoin(sql, " from ", table)
  189. if len(this.join) > 0 {
  190. for _, joinitem := range this.join {
  191. if len(joinitem) < 2 {
  192. continue
  193. }
  194. if len(joinitem) == 3 {
  195. sql = helper.StringJoin(sql, " ", joinitem[2], " join ", getTableName(this.dbname, joinitem[0]), " on ", joinitem[1])
  196. } else { //默认左连接
  197. sql = helper.StringJoin(sql, " left join ", getTableName(this.dbname, joinitem[0]), " on ", joinitem[1])
  198. }
  199. }
  200. }
  201. if len(this.where) > 0 || len(this.where_or) > 0 {
  202. sql = helper.StringJoin(sql, " where ")
  203. }
  204. if len(this.where) > 0 {
  205. sql = helper.StringJoin(sql, " (", strings.Join(this.where, " and "), " ) ")
  206. }
  207. if len(this.where_or) > 0 {
  208. if len(this.where) > 0 {
  209. sql = helper.StringJoin(sql, " or ", strings.Join(this.where_or, " or "))
  210. } else {
  211. sql = helper.StringJoin(sql, strings.Join(this.where_or, " or "))
  212. }
  213. }
  214. if this.groupby != "" {
  215. sql = helper.StringJoin(sql, " group by ", this.groupby)
  216. }
  217. if this.having != "" {
  218. sql = helper.StringJoin(sql, " having ", this.having)
  219. }
  220. if this.orderby != "" {
  221. sql = helper.StringJoin(sql, " order by ", this.orderby)
  222. }
  223. if this.page > 0 || this.page_size > 0 {
  224. if this.page < 1 {
  225. this.page = 1
  226. }
  227. if this.page_size < 1 {
  228. this.page_size = 10
  229. }
  230. from := strconv.Itoa((this.page - 1) * this.page_size)
  231. offset := strconv.Itoa(this.page_size)
  232. if from != "" && offset != "" {
  233. sql = helper.StringJoin(sql, " limit ", from, " , ", offset)
  234. }
  235. }
  236. if this.debug {
  237. log.Println("query sql:", sql, this.value)
  238. }
  239. condition_len := 0 //所有条件数
  240. for _, ch2 := range sql {
  241. if string(ch2) == "?" {
  242. condition_len++
  243. }
  244. }
  245. if condition_len != len(this.value) {
  246. return nil, errors.New("参数错误,条件值错误")
  247. }
  248. return map[string]interface{}{
  249. "sql": sql,
  250. "value": this.value,
  251. }, nil
  252. }
  253. // 拼查询sql
  254. func (this *TxQuery) QueryStmt() error {
  255. res := map[string]interface{}{}
  256. res, err = this.BuildSelectSql()
  257. if err != nil {
  258. return err
  259. }
  260. sql := helper.ToStr(res["sql"])
  261. stmt, err = this.tx.Prepare(sql + " FOR UPDATE")
  262. if err != nil {
  263. return err
  264. }
  265. this.stmt = stmt
  266. return nil
  267. }
  268. // 拼更新sql
  269. func (this *TxQuery) UpdateStmt() error {
  270. if this.dbname == "" && this.table == "" {
  271. return errors.New("参数错误,没有数据表")
  272. }
  273. if len(this.where) < 1 {
  274. return errors.New("参数错误,缺少条件")
  275. }
  276. dbName := getTableName(this.dbname, this.table)
  277. var sql string
  278. sql = helper.StringJoin("update ", dbName, " set ", strings.Join(this.data, " , "))
  279. sql = helper.StringJoin(sql, " where ", strings.Join(this.where, " and "))
  280. if this.debug {
  281. log.Println("update sql:", sql, this.value)
  282. }
  283. condition_len := 0 //所有条件数
  284. for _, ch2 := range sql {
  285. if string(ch2) == "?" {
  286. condition_len++
  287. }
  288. }
  289. if condition_len != len(this.value) {
  290. return errors.New("参数错误,条件值错误")
  291. }
  292. stmt, err = this.tx.Prepare(sql)
  293. if err != nil {
  294. return err
  295. }
  296. this.stmt = stmt
  297. return nil
  298. }
  299. // 拼批量存在更新不存在插入sql
  300. func (this *TxQuery) UpdateAllStmt() error {
  301. if this.dbname == "" && this.table == "" {
  302. return errors.New("参数错误,没有数据表")
  303. }
  304. dbName := getTableName(this.dbname, this.table)
  305. var sql string
  306. var dataSql = []string{}
  307. var valSql = []string{}
  308. var updSql = []string{}
  309. var updFieldLen = len(this.upd_field)
  310. if len(this.save_data) > 0 {
  311. this.data = []string{}
  312. this.value = []interface{}{}
  313. for i, datum := range this.save_data {
  314. if i == 0 {
  315. for k, _ := range datum {
  316. this.data = append(this.data, k)
  317. dataSql = append(dataSql, "?")
  318. if updFieldLen == 0 && k != "id" {
  319. updSql = append(updSql, k+"=values("+k+")")
  320. }
  321. }
  322. if updFieldLen > 0 {
  323. for _, k := range this.upd_field {
  324. updSql = append(updSql, k+"=values("+k+")")
  325. }
  326. }
  327. }
  328. for _, k := range this.data {
  329. this.value = append(this.value, datum[k])
  330. }
  331. valSql = append(valSql, "("+strings.Join(dataSql, " , ")+")")
  332. }
  333. } else {
  334. for _, datum := range this.data {
  335. dataSql = append(dataSql, "?")
  336. if updFieldLen == 0 && datum != "id" {
  337. updSql = append(updSql, datum+"=values("+datum+")")
  338. }
  339. }
  340. if updFieldLen > 0 {
  341. for _, k := range this.upd_field {
  342. updSql = append(updSql, k+"=values("+k+")")
  343. }
  344. }
  345. valSql = append(valSql, "("+strings.Join(dataSql, " , ")+")")
  346. }
  347. if len(this.data) == 0 {
  348. return errors.New("参数错误,没有数据表")
  349. }
  350. if len(this.value) == 0 {
  351. return errors.New("参数错误,条件值错误")
  352. }
  353. setText := " values "
  354. if len(valSql) > 1 {
  355. setText = " value "
  356. }
  357. sql = helper.StringJoin("insert into ", dbName, " (", strings.Join(this.data, " , "), ")", setText, strings.Join(valSql, ","))
  358. if len(this.value) == 0 {
  359. return errors.New("参数错误,条件值错误")
  360. }
  361. if this.debug {
  362. log.Println("insert on duplicate key update sql:", sql, this.value)
  363. }
  364. stmt, err = this.tx.Prepare(sql)
  365. if err != nil {
  366. return err
  367. }
  368. this.stmt = stmt
  369. return nil
  370. }
  371. // 拼插入sql
  372. func (this *TxQuery) CreateStmt() error {
  373. if this.dbname == "" && this.table == "" {
  374. return errors.New("参数错误,没有数据表")
  375. }
  376. dbName := getTableName(this.dbname, this.table)
  377. var sql string
  378. sql = helper.StringJoin("insert into ", dbName, " set ", strings.Join(this.data, " , "))
  379. if this.debug {
  380. log.Println("insert sql:", sql, this.value)
  381. }
  382. condition_len := 0 //所有条件数
  383. for _, ch2 := range sql {
  384. if string(ch2) == "?" {
  385. condition_len++
  386. }
  387. }
  388. if condition_len != len(this.value) {
  389. return errors.New("参数错误,条件值错误")
  390. }
  391. stmt, err = this.tx.Prepare(sql)
  392. if err != nil {
  393. return err
  394. }
  395. this.stmt = stmt
  396. return nil
  397. }
  398. // 拼批量插入sql
  399. func (this *TxQuery) CreateAllStmt() error {
  400. if this.dbname == "" && this.table == "" {
  401. return errors.New("参数错误,没有数据表")
  402. }
  403. dbName := getTableName(this.dbname, this.table)
  404. var sql string
  405. var dataSql = []string{}
  406. var valSql = []string{}
  407. if len(this.save_data) > 0 {
  408. this.data = []string{}
  409. this.value = []interface{}{}
  410. for i, datum := range this.save_data {
  411. if i == 0 {
  412. for k, _ := range datum {
  413. this.data = append(this.data, k)
  414. dataSql = append(dataSql, "?")
  415. }
  416. }
  417. for _, k := range this.data {
  418. this.value = append(this.value, datum[k])
  419. }
  420. valSql = append(valSql, "("+strings.Join(dataSql, " , ")+")")
  421. }
  422. } else {
  423. for i := 0; i < len(this.data); i++ {
  424. dataSql = append(dataSql, "?")
  425. }
  426. valSql = append(valSql, "("+strings.Join(dataSql, " , ")+")")
  427. }
  428. if len(this.data) == 0 {
  429. return errors.New("参数错误,没有数据表")
  430. }
  431. if len(this.value) == 0 {
  432. return errors.New("参数错误,条件值错误")
  433. }
  434. setText := " values "
  435. if len(valSql) > 1 {
  436. setText = " value "
  437. }
  438. sql = helper.StringJoin("insert into ", dbName, " (", strings.Join(this.data, " , "), ")", setText, strings.Join(valSql, ","))
  439. if len(this.value) == 0 {
  440. return errors.New("参数错误,条件值错误")
  441. }
  442. if this.debug {
  443. log.Println("insert sql:", sql, this.value)
  444. }
  445. stmt, err = this.tx.Prepare(sql)
  446. if err != nil {
  447. return err
  448. }
  449. this.stmt = stmt
  450. return nil
  451. }
  452. // 拼删除sql
  453. func (this *TxQuery) DeleteStmt() error {
  454. if this.dbname == "" && this.table == "" {
  455. return errors.New("参数错误,没有数据表")
  456. }
  457. if len(this.where) < 1 {
  458. return errors.New("参数错误,缺少条件")
  459. }
  460. dbName := getTableName(this.dbname, this.table)
  461. var sql string
  462. sql = helper.StringJoin("delete from ", dbName, " where ", strings.Join(this.where, " and "))
  463. if this.page_size > 0 {
  464. sql = helper.StringJoin(sql, " limit ", strconv.Itoa(this.page_size))
  465. }
  466. if this.debug {
  467. log.Println("delete sql:", sql, this.value)
  468. }
  469. condition_len := 0 //所有条件数
  470. for _, ch2 := range sql {
  471. if string(ch2) == "?" {
  472. condition_len++
  473. }
  474. }
  475. if condition_len != len(this.value) {
  476. return errors.New("参数错误,条件值错误")
  477. }
  478. stmt, err = this.tx.Prepare(sql)
  479. if err != nil {
  480. return err
  481. }
  482. this.stmt = stmt
  483. return nil
  484. }
  485. /**
  486. * 执行查询列表
  487. * return list error
  488. */
  489. func (this *TxQuery) Select() ([]map[string]string, error) {
  490. err := this.QueryStmt()
  491. if err != nil {
  492. return []map[string]string{}, err
  493. }
  494. if this.stmt == nil {
  495. return []map[string]string{}, errors.New("缺少必要参数")
  496. }
  497. return StmtForQueryList(this.stmt, this.value)
  498. }
  499. /**
  500. * 执行查询一条数据
  501. * return row error
  502. */
  503. func (this *TxQuery) Find() (map[string]string, error) {
  504. this.page = 1
  505. this.page_size = 1
  506. err := this.QueryStmt()
  507. if err != nil {
  508. return map[string]string{}, err
  509. }
  510. if this.stmt == nil {
  511. return nil, errors.New("缺少必要参数")
  512. }
  513. return StmtForQueryRow(this.stmt, this.value)
  514. }
  515. /**
  516. * 执行更新
  517. * return is_updated error
  518. */
  519. func (this *TxQuery) Update() (int64, error) {
  520. err := this.UpdateStmt()
  521. if err != nil {
  522. return 0, err
  523. }
  524. return StmtForUpdateExec(this.stmt, this.value)
  525. }
  526. //批量更新
  527. func (this *TxQuery) UpdateAll() (int64, error) {
  528. err := this.UpdateAllStmt()
  529. if err != nil {
  530. return 0, err
  531. }
  532. return StmtForUpdateExec(this.stmt, this.value)
  533. }
  534. /**
  535. * 执行删除
  536. * return is_delete error
  537. */
  538. func (this *TxQuery) Delete() (int64, error) {
  539. err := this.DeleteStmt()
  540. if err != nil {
  541. return 0, err
  542. }
  543. return StmtForUpdateExec(this.stmt, this.value)
  544. }
  545. /**
  546. * 执行写入
  547. * return is_insert error
  548. */
  549. func (this *TxQuery) Create() (int64, error) {
  550. err := this.CreateStmt()
  551. if err != nil {
  552. return 0, err
  553. }
  554. return StmtForInsertExec(this.stmt, this.value)
  555. }
  556. /**
  557. * 执行批量写入
  558. * return is_insert error
  559. */
  560. func (this *TxQuery) CreateAll() (int64, error) {
  561. err := this.CreateAllStmt()
  562. if err != nil {
  563. return 0, err
  564. }
  565. return StmtForInsertExec(this.stmt, this.value)
  566. }
  567. /**
  568. * 提交
  569. */
  570. func (this *TxQuery) Commit() error {
  571. return this.tx.Commit()
  572. }
  573. /**
  574. * 回滚
  575. */
  576. func (this *TxQuery) Rollback() error {
  577. return this.tx.Rollback()
  578. }