codimd/public/vendor/codemirror/addon/hint/sql-hint.js

282 lines
8.4 KiB
JavaScript
Raw Normal View History

2015-05-04 07:53:29 +00:00
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"), require("../../mode/sql/sql"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "../../mode/sql/sql"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var tables;
var defaultTable;
var keywords;
var CONS = {
QUERY_DIV: ";",
ALIAS_KEYWORD: "AS"
};
var Pos = CodeMirror.Pos;
2016-04-20 10:11:40 +00:00
function isArray(val) { return Object.prototype.toString.call(val) == "[object Array]" }
2015-05-04 07:53:29 +00:00
function getKeywords(editor) {
var mode = editor.doc.modeOption;
if (mode === "sql") mode = "text/x-sql";
return CodeMirror.resolveMode(mode).keywords;
}
function getText(item) {
return typeof item == "string" ? item : item.text;
}
2016-04-20 10:11:40 +00:00
function wrapTable(name, value) {
if (isArray(value)) value = {columns: value}
if (!value.text) value.text = name
return value
}
function parseTables(input) {
var result = {}
if (isArray(input)) {
for (var i = input.length - 1; i >= 0; i--) {
var item = input[i]
result[getText(item).toUpperCase()] = wrapTable(getText(item), item)
}
} else if (input) {
for (var name in input)
result[name.toUpperCase()] = wrapTable(name, input[name])
}
return result
}
function getTable(name) {
return tables[name.toUpperCase()]
2015-05-04 07:53:29 +00:00
}
function shallowClone(object) {
var result = {};
for (var key in object) if (object.hasOwnProperty(key))
result[key] = object[key];
return result;
}
function match(string, word) {
var len = string.length;
var sub = getText(word).substr(0, len);
return string.toUpperCase() === sub.toUpperCase();
}
function addMatches(result, search, wordlist, formatter) {
2016-04-20 10:11:40 +00:00
if (isArray(wordlist)) {
for (var i = 0; i < wordlist.length; i++)
if (match(search, wordlist[i])) result.push(formatter(wordlist[i]))
} else {
for (var word in wordlist) if (wordlist.hasOwnProperty(word)) {
var val = wordlist[word]
if (!val || val === true)
val = word
else
val = val.displayText ? {text: val.text, displayText: val.displayText} : val.text
if (match(search, val)) result.push(formatter(val))
}
2015-05-04 07:53:29 +00:00
}
}
function cleanName(name) {
// Get rid name from backticks(`) and preceding dot(.)
if (name.charAt(0) == ".") {
name = name.substr(1);
}
return name.replace(/`/g, "");
}
function insertBackticks(name) {
var nameParts = getText(name).split(".");
for (var i = 0; i < nameParts.length; i++)
nameParts[i] = "`" + nameParts[i] + "`";
var escaped = nameParts.join(".");
if (typeof name == "string") return escaped;
name = shallowClone(name);
name.text = escaped;
return name;
}
function nameCompletion(cur, token, result, editor) {
2016-04-20 10:11:40 +00:00
// Try to complete table, column names and return start position of completion
2015-05-04 07:53:29 +00:00
var useBacktick = false;
var nameParts = [];
var start = token.start;
var cont = true;
while (cont) {
cont = (token.string.charAt(0) == ".");
useBacktick = useBacktick || (token.string.charAt(0) == "`");
start = token.start;
nameParts.unshift(cleanName(token.string));
token = editor.getTokenAt(Pos(cur.line, token.start));
if (token.string == ".") {
cont = true;
token = editor.getTokenAt(Pos(cur.line, token.start));
}
}
// Try to complete table names
var string = nameParts.join(".");
addMatches(result, string, tables, function(w) {
return useBacktick ? insertBackticks(w) : w;
});
// Try to complete columns from defaultTable
addMatches(result, string, defaultTable, function(w) {
return useBacktick ? insertBackticks(w) : w;
});
// Try to complete columns
string = nameParts.pop();
var table = nameParts.join(".");
2015-07-04 03:31:01 +00:00
var alias = false;
var aliasTable = table;
2015-05-04 07:53:29 +00:00
// Check if table is available. If not, find table by Alias
2016-04-20 10:11:40 +00:00
if (!getTable(table)) {
2015-07-04 03:31:01 +00:00
var oldTable = table;
2015-05-04 07:53:29 +00:00
table = findTableByAlias(table, editor);
2015-07-04 03:31:01 +00:00
if (table !== oldTable) alias = true;
}
2015-05-04 07:53:29 +00:00
2016-04-20 10:11:40 +00:00
var columns = getTable(table);
2015-05-04 07:53:29 +00:00
if (columns && columns.columns)
columns = columns.columns;
if (columns) {
addMatches(result, string, columns, function(w) {
2015-07-04 03:31:01 +00:00
var tableInsert = table;
if (alias == true) tableInsert = aliasTable;
2015-05-04 07:53:29 +00:00
if (typeof w == "string") {
2015-07-04 03:31:01 +00:00
w = tableInsert + "." + w;
2015-05-04 07:53:29 +00:00
} else {
w = shallowClone(w);
2015-07-04 03:31:01 +00:00
w.text = tableInsert + "." + w.text;
2015-05-04 07:53:29 +00:00
}
return useBacktick ? insertBackticks(w) : w;
});
}
return start;
}
function eachWord(lineText, f) {
if (!lineText) return;
var excepted = /[,;]/g;
var words = lineText.split(" ");
for (var i = 0; i < words.length; i++) {
f(words[i]?words[i].replace(excepted, '') : '');
}
}
function convertCurToNumber(cur) {
// max characters of a line is 999,999.
return cur.line + cur.ch / Math.pow(10, 6);
}
function convertNumberToCur(num) {
return Pos(Math.floor(num), +num.toString().split('.').pop());
}
function findTableByAlias(alias, editor) {
var doc = editor.doc;
var fullQuery = doc.getValue();
var aliasUpperCase = alias.toUpperCase();
var previousWord = "";
var table = "";
var separator = [];
var validRange = {
start: Pos(0, 0),
end: Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).length)
};
//add separator
var indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV);
while(indexOfSeparator != -1) {
separator.push(doc.posFromIndex(indexOfSeparator));
indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV, indexOfSeparator+1);
}
separator.unshift(Pos(0, 0));
separator.push(Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).text.length));
//find valid range
var prevItem = 0;
var current = convertCurToNumber(editor.getCursor());
2016-04-20 10:11:40 +00:00
for (var i = 0; i < separator.length; i++) {
2015-05-04 07:53:29 +00:00
var _v = convertCurToNumber(separator[i]);
if (current > prevItem && current <= _v) {
validRange = { start: convertNumberToCur(prevItem), end: convertNumberToCur(_v) };
break;
}
prevItem = _v;
}
var query = doc.getRange(validRange.start, validRange.end, false);
for (var i = 0; i < query.length; i++) {
var lineText = query[i];
eachWord(lineText, function(word) {
var wordUpperCase = word.toUpperCase();
2016-04-20 10:11:40 +00:00
if (wordUpperCase === aliasUpperCase && getTable(previousWord))
2015-05-04 07:53:29 +00:00
table = previousWord;
if (wordUpperCase !== CONS.ALIAS_KEYWORD)
previousWord = word;
});
if (table) break;
}
return table;
}
CodeMirror.registerHelper("hint", "sql", function(editor, options) {
2016-04-20 10:11:40 +00:00
tables = parseTables(options && options.tables)
2015-05-04 07:53:29 +00:00
var defaultTableName = options && options.defaultTable;
2015-07-04 03:31:01 +00:00
var disableKeywords = options && options.disableKeywords;
2016-04-20 10:11:40 +00:00
defaultTable = defaultTableName && getTable(defaultTableName);
2016-06-01 06:37:28 +00:00
keywords = getKeywords(editor);
2015-05-04 07:53:29 +00:00
if (defaultTableName && !defaultTable)
defaultTable = findTableByAlias(defaultTableName, editor);
defaultTable = defaultTable || [];
if (defaultTable.columns)
defaultTable = defaultTable.columns;
var cur = editor.getCursor();
var result = [];
var token = editor.getTokenAt(cur), start, end, search;
if (token.end > cur.ch) {
token.end = cur.ch;
token.string = token.string.slice(0, cur.ch - token.start);
}
if (token.string.match(/^[.`\w@]\w*$/)) {
search = token.string;
start = token.start;
end = token.end;
} else {
start = end = cur.ch;
search = "";
}
if (search.charAt(0) == "." || search.charAt(0) == "`") {
start = nameCompletion(cur, token, result, editor);
} else {
addMatches(result, search, tables, function(w) {return w;});
addMatches(result, search, defaultTable, function(w) {return w;});
2015-07-04 03:31:01 +00:00
if (!disableKeywords)
addMatches(result, search, keywords, function(w) {return w.toUpperCase();});
2015-05-04 07:53:29 +00:00
}
return {list: result, from: Pos(cur.line, start), to: Pos(cur.line, end)};
});
});