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.

305 lines
9.4KB

  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://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 identifierQuote;
  16. var CONS = {
  17. QUERY_DIV: ";",
  18. ALIAS_KEYWORD: "AS"
  19. };
  20. var Pos = CodeMirror.Pos, cmpPos = CodeMirror.cmpPos;
  21. function isArray(val) { return Object.prototype.toString.call(val) == "[object Array]" }
  22. function getKeywords(editor) {
  23. var mode = editor.doc.modeOption;
  24. if (mode === "sql") mode = "text/x-sql";
  25. return CodeMirror.resolveMode(mode).keywords;
  26. }
  27. function getIdentifierQuote(editor) {
  28. var mode = editor.doc.modeOption;
  29. if (mode === "sql") mode = "text/x-sql";
  30. return CodeMirror.resolveMode(mode).identifierQuote || "`";
  31. }
  32. function getText(item) {
  33. return typeof item == "string" ? item : item.text;
  34. }
  35. function wrapTable(name, value) {
  36. if (isArray(value)) value = {columns: value}
  37. if (!value.text) value.text = name
  38. return value
  39. }
  40. function parseTables(input) {
  41. var result = {}
  42. if (isArray(input)) {
  43. for (var i = input.length - 1; i >= 0; i--) {
  44. var item = input[i]
  45. result[getText(item).toUpperCase()] = wrapTable(getText(item), item)
  46. }
  47. } else if (input) {
  48. for (var name in input)
  49. result[name.toUpperCase()] = wrapTable(name, input[name])
  50. }
  51. return result
  52. }
  53. function getTable(name) {
  54. return tables[name.toUpperCase()]
  55. }
  56. function shallowClone(object) {
  57. var result = {};
  58. for (var key in object) if (object.hasOwnProperty(key))
  59. result[key] = object[key];
  60. return result;
  61. }
  62. function match(string, word) {
  63. var len = string.length;
  64. var sub = getText(word).substr(0, len);
  65. return string.toUpperCase() === sub.toUpperCase();
  66. }
  67. function addMatches(result, search, wordlist, formatter) {
  68. if (isArray(wordlist)) {
  69. for (var i = 0; i < wordlist.length; i++)
  70. if (match(search, wordlist[i])) result.push(formatter(wordlist[i]))
  71. } else {
  72. for (var word in wordlist) if (wordlist.hasOwnProperty(word)) {
  73. var val = wordlist[word]
  74. if (!val || val === true)
  75. val = word
  76. else
  77. val = val.displayText ? {text: val.text, displayText: val.displayText} : val.text
  78. if (match(search, val)) result.push(formatter(val))
  79. }
  80. }
  81. }
  82. function cleanName(name) {
  83. // Get rid name from identifierQuote and preceding dot(.)
  84. if (name.charAt(0) == ".") {
  85. name = name.substr(1);
  86. }
  87. // replace duplicated identifierQuotes with single identifierQuotes
  88. // and remove single identifierQuotes
  89. var nameParts = name.split(identifierQuote+identifierQuote);
  90. for (var i = 0; i < nameParts.length; i++)
  91. nameParts[i] = nameParts[i].replace(new RegExp(identifierQuote,"g"), "");
  92. return nameParts.join(identifierQuote);
  93. }
  94. function insertIdentifierQuotes(name) {
  95. var nameParts = getText(name).split(".");
  96. for (var i = 0; i < nameParts.length; i++)
  97. nameParts[i] = identifierQuote +
  98. // duplicate identifierQuotes
  99. nameParts[i].replace(new RegExp(identifierQuote,"g"), identifierQuote+identifierQuote) +
  100. identifierQuote;
  101. var escaped = nameParts.join(".");
  102. if (typeof name == "string") return escaped;
  103. name = shallowClone(name);
  104. name.text = escaped;
  105. return name;
  106. }
  107. function nameCompletion(cur, token, result, editor) {
  108. // Try to complete table, column names and return start position of completion
  109. var useIdentifierQuotes = false;
  110. var nameParts = [];
  111. var start = token.start;
  112. var cont = true;
  113. while (cont) {
  114. cont = (token.string.charAt(0) == ".");
  115. useIdentifierQuotes = useIdentifierQuotes || (token.string.charAt(0) == identifierQuote);
  116. start = token.start;
  117. nameParts.unshift(cleanName(token.string));
  118. token = editor.getTokenAt(Pos(cur.line, token.start));
  119. if (token.string == ".") {
  120. cont = true;
  121. token = editor.getTokenAt(Pos(cur.line, token.start));
  122. }
  123. }
  124. // Try to complete table names
  125. var string = nameParts.join(".");
  126. addMatches(result, string, tables, function(w) {
  127. return useIdentifierQuotes ? insertIdentifierQuotes(w) : w;
  128. });
  129. // Try to complete columns from defaultTable
  130. addMatches(result, string, defaultTable, function(w) {
  131. return useIdentifierQuotes ? insertIdentifierQuotes(w) : w;
  132. });
  133. // Try to complete columns
  134. string = nameParts.pop();
  135. var table = nameParts.join(".");
  136. var alias = false;
  137. var aliasTable = table;
  138. // Check if table is available. If not, find table by Alias
  139. if (!getTable(table)) {
  140. var oldTable = table;
  141. table = findTableByAlias(table, editor);
  142. if (table !== oldTable) alias = true;
  143. }
  144. var columns = getTable(table);
  145. if (columns && columns.columns)
  146. columns = columns.columns;
  147. if (columns) {
  148. addMatches(result, string, columns, function(w) {
  149. var tableInsert = table;
  150. if (alias == true) tableInsert = aliasTable;
  151. if (typeof w == "string") {
  152. w = tableInsert + "." + w;
  153. } else {
  154. w = shallowClone(w);
  155. w.text = tableInsert + "." + w.text;
  156. }
  157. return useIdentifierQuotes ? insertIdentifierQuotes(w) : w;
  158. });
  159. }
  160. return start;
  161. }
  162. function eachWord(lineText, f) {
  163. var words = lineText.split(/\s+/)
  164. for (var i = 0; i < words.length; i++)
  165. if (words[i]) f(words[i].replace(/[`,;]/g, ''))
  166. }
  167. function findTableByAlias(alias, editor) {
  168. var doc = editor.doc;
  169. var fullQuery = doc.getValue();
  170. var aliasUpperCase = alias.toUpperCase();
  171. var previousWord = "";
  172. var table = "";
  173. var separator = [];
  174. var validRange = {
  175. start: Pos(0, 0),
  176. end: Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).length)
  177. };
  178. //add separator
  179. var indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV);
  180. while(indexOfSeparator != -1) {
  181. separator.push(doc.posFromIndex(indexOfSeparator));
  182. indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV, indexOfSeparator+1);
  183. }
  184. separator.unshift(Pos(0, 0));
  185. separator.push(Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).text.length));
  186. //find valid range
  187. var prevItem = null;
  188. var current = editor.getCursor()
  189. for (var i = 0; i < separator.length; i++) {
  190. if ((prevItem == null || cmpPos(current, prevItem) > 0) && cmpPos(current, separator[i]) <= 0) {
  191. validRange = {start: prevItem, end: separator[i]};
  192. break;
  193. }
  194. prevItem = separator[i];
  195. }
  196. if (validRange.start) {
  197. var query = doc.getRange(validRange.start, validRange.end, false);
  198. for (var i = 0; i < query.length; i++) {
  199. var lineText = query[i];
  200. eachWord(lineText, function(word) {
  201. var wordUpperCase = word.toUpperCase();
  202. if (wordUpperCase === aliasUpperCase && getTable(previousWord))
  203. table = previousWord;
  204. if (wordUpperCase !== CONS.ALIAS_KEYWORD)
  205. previousWord = word;
  206. });
  207. if (table) break;
  208. }
  209. }
  210. return table;
  211. }
  212. CodeMirror.registerHelper("hint", "sql", function(editor, options) {
  213. tables = parseTables(options && options.tables)
  214. var defaultTableName = options && options.defaultTable;
  215. var disableKeywords = options && options.disableKeywords;
  216. defaultTable = defaultTableName && getTable(defaultTableName);
  217. keywords = getKeywords(editor);
  218. identifierQuote = getIdentifierQuote(editor);
  219. if (defaultTableName && !defaultTable)
  220. defaultTable = findTableByAlias(defaultTableName, editor);
  221. defaultTable = defaultTable || [];
  222. if (defaultTable.columns)
  223. defaultTable = defaultTable.columns;
  224. var cur = editor.getCursor();
  225. var result = [];
  226. var token = editor.getTokenAt(cur), start, end, search;
  227. if (token.end > cur.ch) {
  228. token.end = cur.ch;
  229. token.string = token.string.slice(0, cur.ch - token.start);
  230. }
  231. if (token.string.match(/^[.`"'\w@][\w$#]*$/g)) {
  232. search = token.string;
  233. start = token.start;
  234. end = token.end;
  235. } else {
  236. start = end = cur.ch;
  237. search = "";
  238. }
  239. if (search.charAt(0) == "." || search.charAt(0) == identifierQuote) {
  240. start = nameCompletion(cur, token, result, editor);
  241. } else {
  242. var objectOrClass = function(w, className) {
  243. if (typeof w === "object") {
  244. w.className = className;
  245. } else {
  246. w = { text: w, className: className };
  247. }
  248. return w;
  249. };
  250. addMatches(result, search, defaultTable, function(w) {
  251. return objectOrClass(w, "CodeMirror-hint-table CodeMirror-hint-default-table");
  252. });
  253. addMatches(
  254. result,
  255. search,
  256. tables, function(w) {
  257. return objectOrClass(w, "CodeMirror-hint-table");
  258. }
  259. );
  260. if (!disableKeywords)
  261. addMatches(result, search, keywords, function(w) {
  262. return objectOrClass(w.toUpperCase(), "CodeMirror-hint-keyword");
  263. });
  264. }
  265. return {list: result, from: Pos(cur.line, start), to: Pos(cur.line, end)};
  266. });
  267. });