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

488 lines
9.3 KiB

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