sql-hint.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://codemirror.net/LICENSE
  3. (function(mod) {
  4. if (typeof exports == "object" && typeof module == "object") // CommonJS
  5. mod(require("../../lib/codemirror"), require("../../mode/sql/sql"));
  6. else if (typeof define == "function" && define.amd) // AMD
  7. define(["../../lib/codemirror", "../../mode/sql/sql"], mod);
  8. else // Plain browser env
  9. mod(CodeMirror);
  10. })(function(CodeMirror) {
  11. "use strict";
  12. var tables;
  13. var defaultTable;
  14. var keywords;
  15. var CONS = {
  16. QUERY_DIV: ";",
  17. ALIAS_KEYWORD: "AS"
  18. };
  19. var Pos = CodeMirror.Pos;
  20. function getKeywords(editor) {
  21. var mode = editor.doc.modeOption;
  22. if (mode === "sql") mode = "text/x-sql";
  23. return CodeMirror.resolveMode(mode).keywords;
  24. }
  25. function getText(item) {
  26. return typeof item == "string" ? item : item.text;
  27. }
  28. function getItem(list, item) {
  29. if (!list.slice) return list[item];
  30. for (var i = list.length - 1; i >= 0; i--) if (getText(list[i]) == item)
  31. return list[i];
  32. }
  33. function shallowClone(object) {
  34. var result = {};
  35. for (var key in object) if (object.hasOwnProperty(key))
  36. result[key] = object[key];
  37. return result;
  38. }
  39. function match(string, word) {
  40. var len = string.length;
  41. var sub = getText(word).substr(0, len);
  42. return string.toUpperCase() === sub.toUpperCase();
  43. }
  44. function addMatches(result, search, wordlist, formatter) {
  45. for (var word in wordlist) {
  46. if (!wordlist.hasOwnProperty(word)) continue;
  47. if (Array.isArray(wordlist)) {
  48. word = wordlist[word];
  49. }
  50. if (match(search, word)) {
  51. result.push(formatter(word));
  52. }
  53. }
  54. }
  55. function cleanName(name) {
  56. // Get rid name from backticks(`) and preceding dot(.)
  57. if (name.charAt(0) == ".") {
  58. name = name.substr(1);
  59. }
  60. return name.replace(/`/g, "");
  61. }
  62. function insertBackticks(name) {
  63. var nameParts = getText(name).split(".");
  64. for (var i = 0; i < nameParts.length; i++)
  65. nameParts[i] = "`" + nameParts[i] + "`";
  66. var escaped = nameParts.join(".");
  67. if (typeof name == "string") return escaped;
  68. name = shallowClone(name);
  69. name.text = escaped;
  70. return name;
  71. }
  72. function nameCompletion(cur, token, result, editor) {
  73. // Try to complete table, colunm names and return start position of completion
  74. var useBacktick = false;
  75. var nameParts = [];
  76. var start = token.start;
  77. var cont = true;
  78. while (cont) {
  79. cont = (token.string.charAt(0) == ".");
  80. useBacktick = useBacktick || (token.string.charAt(0) == "`");
  81. start = token.start;
  82. nameParts.unshift(cleanName(token.string));
  83. token = editor.getTokenAt(Pos(cur.line, token.start));
  84. if (token.string == ".") {
  85. cont = true;
  86. token = editor.getTokenAt(Pos(cur.line, token.start));
  87. }
  88. }
  89. // Try to complete table names
  90. var string = nameParts.join(".");
  91. addMatches(result, string, tables, function(w) {
  92. return useBacktick ? insertBackticks(w) : w;
  93. });
  94. // Try to complete columns from defaultTable
  95. addMatches(result, string, defaultTable, function(w) {
  96. return useBacktick ? insertBackticks(w) : w;
  97. });
  98. // Try to complete columns
  99. string = nameParts.pop();
  100. var table = nameParts.join(".");
  101. // Check if table is available. If not, find table by Alias
  102. if (!getItem(tables, table))
  103. table = findTableByAlias(table, editor);
  104. var columns = getItem(tables, table);
  105. if (columns && Array.isArray(tables) && columns.columns)
  106. columns = columns.columns;
  107. if (columns) {
  108. addMatches(result, string, columns, function(w) {
  109. if (typeof w == "string") {
  110. w = table + "." + w;
  111. } else {
  112. w = shallowClone(w);
  113. w.text = table + "." + w.text;
  114. }
  115. return useBacktick ? insertBackticks(w) : w;
  116. });
  117. }
  118. return start;
  119. }
  120. function eachWord(lineText, f) {
  121. if (!lineText) return;
  122. var excepted = /[,;]/g;
  123. var words = lineText.split(" ");
  124. for (var i = 0; i < words.length; i++) {
  125. f(words[i]?words[i].replace(excepted, '') : '');
  126. }
  127. }
  128. function convertCurToNumber(cur) {
  129. // max characters of a line is 999,999.
  130. return cur.line + cur.ch / Math.pow(10, 6);
  131. }
  132. function convertNumberToCur(num) {
  133. return Pos(Math.floor(num), +num.toString().split('.').pop());
  134. }
  135. function findTableByAlias(alias, editor) {
  136. var doc = editor.doc;
  137. var fullQuery = doc.getValue();
  138. var aliasUpperCase = alias.toUpperCase();
  139. var previousWord = "";
  140. var table = "";
  141. var separator = [];
  142. var validRange = {
  143. start: Pos(0, 0),
  144. end: Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).length)
  145. };
  146. //add separator
  147. var indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV);
  148. while(indexOfSeparator != -1) {
  149. separator.push(doc.posFromIndex(indexOfSeparator));
  150. indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV, indexOfSeparator+1);
  151. }
  152. separator.unshift(Pos(0, 0));
  153. separator.push(Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).text.length));
  154. //find valid range
  155. var prevItem = 0;
  156. var current = convertCurToNumber(editor.getCursor());
  157. for (var i=0; i< separator.length; i++) {
  158. var _v = convertCurToNumber(separator[i]);
  159. if (current > prevItem && current <= _v) {
  160. validRange = { start: convertNumberToCur(prevItem), end: convertNumberToCur(_v) };
  161. break;
  162. }
  163. prevItem = _v;
  164. }
  165. var query = doc.getRange(validRange.start, validRange.end, false);
  166. for (var i = 0; i < query.length; i++) {
  167. var lineText = query[i];
  168. eachWord(lineText, function(word) {
  169. var wordUpperCase = word.toUpperCase();
  170. if (wordUpperCase === aliasUpperCase && getItem(tables, previousWord))
  171. table = previousWord;
  172. if (wordUpperCase !== CONS.ALIAS_KEYWORD)
  173. previousWord = word;
  174. });
  175. if (table) break;
  176. }
  177. return table;
  178. }
  179. CodeMirror.registerHelper("hint", "sql", function(editor, options) {
  180. tables = (options && options.tables) || {};
  181. var defaultTableName = options && options.defaultTable;
  182. defaultTable = (defaultTableName && getItem(tables, defaultTableName)) || [];
  183. keywords = keywords || getKeywords(editor);
  184. var cur = editor.getCursor();
  185. var result = [];
  186. var token = editor.getTokenAt(cur), start, end, search;
  187. if (token.end > cur.ch) {
  188. token.end = cur.ch;
  189. token.string = token.string.slice(0, cur.ch - token.start);
  190. }
  191. if (token.string.match(/^[.`\w@]\w*$/)) {
  192. search = token.string;
  193. start = token.start;
  194. end = token.end;
  195. } else {
  196. start = end = cur.ch;
  197. search = "";
  198. }
  199. if (search.charAt(0) == "." || search.charAt(0) == "`") {
  200. start = nameCompletion(cur, token, result, editor);
  201. } else {
  202. addMatches(result, search, tables, function(w) {return w;});
  203. addMatches(result, search, defaultTable, function(w) {return w;});
  204. addMatches(result, search, keywords, function(w) {return w.toUpperCase();});
  205. }
  206. return {list: result, from: Pos(cur.line, start), to: Pos(cur.line, end)};
  207. });
  208. });