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

717 lines
15 KiB

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