sql_builder.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. 'use strict';
  2. /**
  3. * sql语句构建器
  4. *
  5. * @author CaiAoLin
  6. * @date 2017/10/11
  7. * @version
  8. */
  9. class SqlBuilder {
  10. /**
  11. * 构造函数
  12. *
  13. * @return {void}
  14. */
  15. constructor() {
  16. this.resetCondition();
  17. }
  18. /**
  19. * 设置andWhere数据
  20. *
  21. * @param {String} field - where中的字段名称
  22. * @param {Object} data - where中的value部分
  23. * @return {void}
  24. */
  25. setAndWhere(field, data) {
  26. if (Object.keys(data).length <= 0) {
  27. return;
  28. }
  29. this.andWhere.push({ field, data });
  30. }
  31. /**
  32. * 设置新的orWhere数据
  33. *
  34. * @param {String} field - where中的字段名称
  35. * @param {Object} data - where中的value部分
  36. * @return {void}
  37. */
  38. setNewOrWhere(data) {
  39. if (Object.keys(data).length <= 0) {
  40. return;
  41. }
  42. this.newOrWhere.push(data);
  43. }
  44. /**
  45. * 更新字段设置
  46. *
  47. * @param {String} field - set的字段
  48. * @param {Object} data - set中的字段
  49. * @return {void}
  50. */
  51. setUpdateData(field, data) {
  52. if (Object.keys(data).length <= 0) {
  53. return;
  54. }
  55. this.setData.push({ field, data });
  56. }
  57. /**
  58. * 重置条件
  59. *
  60. * @return {void}
  61. */
  62. resetCondition() {
  63. this.andWhere = [];
  64. this.orWhere = [];
  65. this.newOrWhere = [];
  66. this.columns = [];
  67. this.limit = -1;
  68. this.offset = -1;
  69. this.orderBy = [];
  70. this.setData = [];
  71. this.sql = '';
  72. this.sqlParam = [];
  73. this.type = 'select';
  74. }
  75. /**
  76. * 类型设置
  77. *
  78. * @param {String} tableName - 表名
  79. * @return {void}
  80. */
  81. _typeBuild(tableName) {
  82. switch (this.type) {
  83. case 'select':
  84. this.sql = this.columns.length === 0 ? 'SELECT * FROM ??' : 'SELECT ?? FROM ??';
  85. this.sqlParam = this.columns.length === 0 ? [tableName] : [this.columns, tableName];
  86. break;
  87. case 'update':
  88. this.sql = 'UPDATE ?? SET ';
  89. this.sqlParam = [tableName];
  90. break;
  91. case 'delete':
  92. this.sql = 'DELETE FROM ??';
  93. this.sqlParam = [tableName];
  94. break;
  95. default:
  96. break;
  97. }
  98. }
  99. /**
  100. * 设置update数据
  101. *
  102. * @return {void}
  103. */
  104. _setDataBuild() {
  105. if (this.setData.length <= 0) {
  106. return;
  107. }
  108. const setDataArr = [];
  109. for (const set of this.setData) {
  110. if (set.data.literal) {
  111. const values = set.data.value instanceof Array ? set.data.value : [set.data.value];
  112. setDataArr.push(' ?? = ' + set.data.literal + '(' + values.join(',') + ')');
  113. this.sqlParam.push(set.field);
  114. } else {
  115. const tmp = set.data.selfOperate !== undefined ?
  116. ' ?? = IF(IsNull(??), 0, ??) ' + set.data.selfOperate + ' ' + set.data.value : ' ?? = ' + set.data.value;
  117. setDataArr.push(tmp);
  118. // 如果是自身操作则压多一次字段进数组
  119. if (set.data.selfOperate !== undefined) {
  120. this.sqlParam.push(set.field);
  121. this.sqlParam.push(set.field);
  122. }
  123. this.sqlParam.push(set.field);
  124. }
  125. }
  126. const setString = setDataArr.join(',');
  127. this.sql += setString;
  128. }
  129. /**
  130. * andWhere设置
  131. *
  132. * @return {void}
  133. */
  134. _andWhereBuild() {
  135. if (this.andWhere.length <= 0) {
  136. return;
  137. }
  138. const whereArr = [];
  139. for (const where of this.andWhere) {
  140. if (where.data.operate === 'in') {
  141. // in操作
  142. const valueLength = where.data.value instanceof Array ? where.data.value.length : 1;
  143. // 生成参数集
  144. const inArr = [];
  145. for (let i = 0; i < valueLength; i++) {
  146. inArr.push('?');
  147. }
  148. const inData = inArr.join(',');
  149. whereArr.push(' ?? IN (' + inData + ')');
  150. this.sqlParam.push(where.field);
  151. // 赋值参数
  152. this.sqlParam.push.apply(this.sqlParam, where.data.value);
  153. } else if (where.data.operate === 'find_in_set') {
  154. whereArr.push(' find_in_set (' + where.data.value + ', ?? )');
  155. this.sqlParam.push(where.field);
  156. } else {
  157. // 普通操作
  158. whereArr.push(' ?? ' + where.data.operate + ' ' + where.data.value);
  159. this.sqlParam.push(where.field);
  160. }
  161. }
  162. const whereString = whereArr.join(' AND ');
  163. this.sql += this.sql.indexOf('WHERE') > 0 ? whereString : ' WHERE ' + whereString;
  164. }
  165. /**
  166. * orWhere设置
  167. *
  168. * @return {void}
  169. */
  170. _orWhereBuild() {
  171. if (this.orWhere.length <= 0) {
  172. return;
  173. }
  174. const whereArr = [];
  175. for (const where in this.orWhere) {
  176. whereArr.push(' ?? ' + where.data.operate + ' ' + where.data.value);
  177. this.sqlParam.push(where.field);
  178. }
  179. const whereString = whereArr.join(' OR ');
  180. // 如果前面已经有设置过WHERE则不需要再重复添加
  181. this.sql += this.sql.indexOf('WHERE') > 0 ? whereString : ' WHERE ' + whereString;
  182. }
  183. /**
  184. * orWhere设置-旧的不好用,独立写了一个包含括号的or兼容,传对象数组,
  185. * 例:
  186. * [{ field: 'office_share', value: managerSession.office, operate: 'find_in_set'},
  187. * {field: 'office',value: managerSession.office,operate: '='},......]
  188. *
  189. * @return {void}
  190. */
  191. _newOrWhereBuild() {
  192. if (this.newOrWhere.length <= 0) {
  193. return;
  194. }
  195. const whereArr = [];
  196. for (const oneOw in this.newOrWhere) {
  197. for (const where of this.newOrWhere[oneOw]) {
  198. if (where.operate === 'in') {
  199. // in操作
  200. const valueLength = where.value instanceof Array ? where.value.length : 1;
  201. // 生成参数集
  202. const inArr = [];
  203. for (let i = 0; i < valueLength; i++) {
  204. inArr.push('?');
  205. }
  206. const inData = inArr.join(',');
  207. whereArr.push(' ?? IN (' + inData + ')');
  208. this.sqlParam.push(where.field);
  209. // 赋值参数
  210. this.sqlParam.push.apply(this.sqlParam, where.value);
  211. } else if (where.operate === 'find_in_set') {
  212. whereArr.push(' find_in_set (' + where.value + ', ?? )');
  213. this.sqlParam.push(where.field);
  214. } else {
  215. // 普通操作
  216. whereArr.push(' ?? ' + where.operate + ' ' + where.value);
  217. this.sqlParam.push(where.field);
  218. }
  219. }
  220. let whereString = whereArr.join(' OR ');
  221. whereString = '(' + whereString + ')';
  222. // 如果前面已经有设置过WHERE则不需要再重复添加
  223. this.sql += this.sql.indexOf('WHERE') > 0 ? ' AND ' + whereString : ' WHERE ' + whereString;
  224. }
  225. }
  226. /**
  227. * limit设置
  228. *
  229. * @return {void}
  230. */
  231. _limitBuild() {
  232. if (typeof this.limit !== 'number' || this.limit <= 0) {
  233. return;
  234. }
  235. this.offset = parseInt(this.offset);
  236. this.offset = isNaN(this.offset) || this.offset < 0 ? 0 : this.offset;
  237. const limitString = this.offset >= 0 ? this.offset + ',' + this.limit : this.limit;
  238. this.sql += ' LIMIT ' + limitString;
  239. }
  240. /**
  241. * orderby 设置
  242. *
  243. * @return {void}
  244. */
  245. _orderByBuild() {
  246. if (this.orderBy.length <= 0) {
  247. return;
  248. }
  249. const orderArr = [];
  250. for (const index in this.orderBy) {
  251. if (!this.orderBy[index]) continue;
  252. orderArr.push(' ?? ' + this.orderBy[index][1]);
  253. this.sqlParam.push(this.orderBy[index][0]);
  254. }
  255. const orderByString = orderArr.join(',');
  256. this.sql += ' ORDER BY ' + orderByString;
  257. }
  258. /**
  259. * 构建sql
  260. *
  261. * @param {String} tableName - 表名
  262. * @param {String} type - 类型
  263. * @return {Array} - 返回数组,第一个元素为sql语句,第二个元素为sql中问号部分的param
  264. */
  265. build(tableName, type = 'select') {
  266. this.type = type;
  267. this._typeBuild(tableName);
  268. if (this.sql === '') {
  269. throw '类型错误';
  270. }
  271. this._setDataBuild();
  272. this._andWhereBuild();
  273. this._orWhereBuild();
  274. this._newOrWhereBuild();
  275. this._orderByBuild();
  276. this._limitBuild();
  277. const sql = this.sql;
  278. const sqlParam = this.sqlParam;
  279. // 重置数据
  280. this.resetCondition();
  281. return [sql, sqlParam];
  282. }
  283. /**
  284. * 构建sql
  285. *
  286. * @param {String} tableName - 表名
  287. * @param {String} type - 类型
  288. * @return {Array} - 返回数组,第一个元素为sql语句,第二个元素为sql中问号部分的param
  289. */
  290. buildCount(tableName, type = 'select') {
  291. this.type = type;
  292. this._typeBuild(tableName);
  293. if (this.sql === '') {
  294. throw '类型错误';
  295. }
  296. this._setDataBuild();
  297. this._andWhereBuild();
  298. this._orWhereBuild();
  299. this._newOrWhereBuild();
  300. const sql = this.sql;
  301. const sqlParam = this.sqlParam;
  302. // 重置数据
  303. // this.resetCondition();
  304. return [sql, sqlParam];
  305. }
  306. }
  307. module.exports = SqlBuilder;