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

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