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

514 lines
10 KiB

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