数据库操作
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.

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