sql.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. # -*- coding: utf-8 -*-
  2. """
  3. pygments.lexers.sql
  4. ~~~~~~~~~~~~~~~~~~~
  5. Lexers for various SQL dialects and related interactive sessions.
  6. Postgres specific lexers:
  7. `PostgresLexer`
  8. A SQL lexer for the PostgreSQL dialect. Differences w.r.t. the SQL
  9. lexer are:
  10. - keywords and data types list parsed from the PG docs (run the
  11. `_postgres_builtins` module to update them);
  12. - Content of $-strings parsed using a specific lexer, e.g. the content
  13. of a PL/Python function is parsed using the Python lexer;
  14. - parse PG specific constructs: E-strings, $-strings, U&-strings,
  15. different operators and punctuation.
  16. `PlPgsqlLexer`
  17. A lexer for the PL/pgSQL language. Adds a few specific construct on
  18. top of the PG SQL lexer (such as <<label>>).
  19. `PostgresConsoleLexer`
  20. A lexer to highlight an interactive psql session:
  21. - identifies the prompt and does its best to detect the end of command
  22. in multiline statement where not all the lines are prefixed by a
  23. prompt, telling them apart from the output;
  24. - highlights errors in the output and notification levels;
  25. - handles psql backslash commands.
  26. The ``tests/examplefiles`` contains a few test files with data to be
  27. parsed by these lexers.
  28. :copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS.
  29. :license: BSD, see LICENSE for details.
  30. """
  31. import re
  32. from pygments.lexer import Lexer, RegexLexer, do_insertions, bygroups, words
  33. from pygments.token import Punctuation, Whitespace, Text, Comment, Operator, \
  34. Keyword, Name, String, Number, Generic
  35. from pygments.lexers import get_lexer_by_name, ClassNotFound
  36. from pygments.util import iteritems
  37. from pygments.lexers._postgres_builtins import KEYWORDS, DATATYPES, \
  38. PSEUDO_TYPES, PLPGSQL_KEYWORDS
  39. from pygments.lexers import _tsql_builtins
  40. __all__ = ['PostgresLexer', 'PlPgsqlLexer', 'PostgresConsoleLexer',
  41. 'SqlLexer', 'TransactSqlLexer', 'MySqlLexer',
  42. 'SqliteConsoleLexer', 'RqlLexer']
  43. line_re = re.compile('.*?\n')
  44. language_re = re.compile(r"\s+LANGUAGE\s+'?(\w+)'?", re.IGNORECASE)
  45. do_re = re.compile(r'\bDO\b', re.IGNORECASE)
  46. # Regular expressions for analyse_text()
  47. name_between_bracket_re = re.compile(r'\[[a-zA-Z_]\w*\]')
  48. name_between_backtick_re = re.compile(r'`[a-zA-Z_]\w*`')
  49. tsql_go_re = re.compile(r'\bgo\b', re.IGNORECASE)
  50. tsql_declare_re = re.compile(r'\bdeclare\s+@', re.IGNORECASE)
  51. tsql_variable_re = re.compile(r'@[a-zA-Z_]\w*\b')
  52. def language_callback(lexer, match):
  53. """Parse the content of a $-string using a lexer
  54. The lexer is chosen looking for a nearby LANGUAGE or assumed as
  55. plpgsql if inside a DO statement and no LANGUAGE has been found.
  56. """
  57. lx = None
  58. m = language_re.match(lexer.text[match.end():match.end()+100])
  59. if m is not None:
  60. lx = lexer._get_lexer(m.group(1))
  61. else:
  62. m = list(language_re.finditer(
  63. lexer.text[max(0, match.start()-100):match.start()]))
  64. if m:
  65. lx = lexer._get_lexer(m[-1].group(1))
  66. else:
  67. m = list(do_re.finditer(
  68. lexer.text[max(0, match.start()-25):match.start()]))
  69. if m:
  70. lx = lexer._get_lexer('plpgsql')
  71. # 1 = $, 2 = delimiter, 3 = $
  72. yield (match.start(1), String, match.group(1))
  73. yield (match.start(2), String.Delimiter, match.group(2))
  74. yield (match.start(3), String, match.group(3))
  75. # 4 = string contents
  76. if lx:
  77. for x in lx.get_tokens_unprocessed(match.group(4)):
  78. yield x
  79. else:
  80. yield (match.start(4), String, match.group(4))
  81. # 5 = $, 6 = delimiter, 7 = $
  82. yield (match.start(5), String, match.group(5))
  83. yield (match.start(6), String.Delimiter, match.group(6))
  84. yield (match.start(7), String, match.group(7))
  85. class PostgresBase(object):
  86. """Base class for Postgres-related lexers.
  87. This is implemented as a mixin to avoid the Lexer metaclass kicking in.
  88. this way the different lexer don't have a common Lexer ancestor. If they
  89. had, _tokens could be created on this ancestor and not updated for the
  90. other classes, resulting e.g. in PL/pgSQL parsed as SQL. This shortcoming
  91. seem to suggest that regexp lexers are not really subclassable.
  92. """
  93. def get_tokens_unprocessed(self, text, *args):
  94. # Have a copy of the entire text to be used by `language_callback`.
  95. self.text = text
  96. for x in super(PostgresBase, self).get_tokens_unprocessed(
  97. text, *args):
  98. yield x
  99. def _get_lexer(self, lang):
  100. if lang.lower() == 'sql':
  101. return get_lexer_by_name('postgresql', **self.options)
  102. tries = [lang]
  103. if lang.startswith('pl'):
  104. tries.append(lang[2:])
  105. if lang.endswith('u'):
  106. tries.append(lang[:-1])
  107. if lang.startswith('pl') and lang.endswith('u'):
  108. tries.append(lang[2:-1])
  109. for lx in tries:
  110. try:
  111. return get_lexer_by_name(lx, **self.options)
  112. except ClassNotFound:
  113. pass
  114. else:
  115. # TODO: better logging
  116. # print >>sys.stderr, "language not found:", lang
  117. return None
  118. class PostgresLexer(PostgresBase, RegexLexer):
  119. """
  120. Lexer for the PostgreSQL dialect of SQL.
  121. .. versionadded:: 1.5
  122. """
  123. name = 'PostgreSQL SQL dialect'
  124. aliases = ['postgresql', 'postgres']
  125. mimetypes = ['text/x-postgresql']
  126. flags = re.IGNORECASE
  127. tokens = {
  128. 'root': [
  129. (r'\s+', Text),
  130. (r'--.*\n?', Comment.Single),
  131. (r'/\*', Comment.Multiline, 'multiline-comments'),
  132. (r'(' + '|'.join(s.replace(" ", r"\s+")
  133. for s in DATATYPES + PSEUDO_TYPES) + r')\b',
  134. Name.Builtin),
  135. (words(KEYWORDS, suffix=r'\b'), Keyword),
  136. (r'[+*/<>=~!@#%^&|`?-]+', Operator),
  137. (r'::', Operator), # cast
  138. (r'\$\d+', Name.Variable),
  139. (r'([0-9]*\.[0-9]*|[0-9]+)(e[+-]?[0-9]+)?', Number.Float),
  140. (r'[0-9]+', Number.Integer),
  141. (r"((?:E|U&)?)(')", bygroups(String.Affix, String.Single), 'string'),
  142. # quoted identifier
  143. (r'((?:U&)?)(")', bygroups(String.Affix, String.Name), 'quoted-ident'),
  144. (r'(?s)(\$)([^$]*)(\$)(.*?)(\$)(\2)(\$)', language_callback),
  145. (r'[a-z_]\w*', Name),
  146. # psql variable in SQL
  147. (r""":(['"]?)[a-z]\w*\b\1""", Name.Variable),
  148. (r'[;:()\[\]{},.]', Punctuation),
  149. ],
  150. 'multiline-comments': [
  151. (r'/\*', Comment.Multiline, 'multiline-comments'),
  152. (r'\*/', Comment.Multiline, '#pop'),
  153. (r'[^/*]+', Comment.Multiline),
  154. (r'[/*]', Comment.Multiline)
  155. ],
  156. 'string': [
  157. (r"[^']+", String.Single),
  158. (r"''", String.Single),
  159. (r"'", String.Single, '#pop'),
  160. ],
  161. 'quoted-ident': [
  162. (r'[^"]+', String.Name),
  163. (r'""', String.Name),
  164. (r'"', String.Name, '#pop'),
  165. ],
  166. }
  167. class PlPgsqlLexer(PostgresBase, RegexLexer):
  168. """
  169. Handle the extra syntax in Pl/pgSQL language.
  170. .. versionadded:: 1.5
  171. """
  172. name = 'PL/pgSQL'
  173. aliases = ['plpgsql']
  174. mimetypes = ['text/x-plpgsql']
  175. flags = re.IGNORECASE
  176. tokens = {k: l[:] for (k, l) in iteritems(PostgresLexer.tokens)}
  177. # extend the keywords list
  178. for i, pattern in enumerate(tokens['root']):
  179. if pattern[1] == Keyword:
  180. tokens['root'][i] = (
  181. words(KEYWORDS + PLPGSQL_KEYWORDS, suffix=r'\b'),
  182. Keyword)
  183. del i
  184. break
  185. else:
  186. assert 0, "SQL keywords not found"
  187. # Add specific PL/pgSQL rules (before the SQL ones)
  188. tokens['root'][:0] = [
  189. (r'\%[a-z]\w*\b', Name.Builtin), # actually, a datatype
  190. (r':=', Operator),
  191. (r'\<\<[a-z]\w*\>\>', Name.Label),
  192. (r'\#[a-z]\w*\b', Keyword.Pseudo), # #variable_conflict
  193. ]
  194. class PsqlRegexLexer(PostgresBase, RegexLexer):
  195. """
  196. Extend the PostgresLexer adding support specific for psql commands.
  197. This is not a complete psql lexer yet as it lacks prompt support
  198. and output rendering.
  199. """
  200. name = 'PostgreSQL console - regexp based lexer'
  201. aliases = [] # not public
  202. flags = re.IGNORECASE
  203. tokens = {k: l[:] for (k, l) in iteritems(PostgresLexer.tokens)}
  204. tokens['root'].append(
  205. (r'\\[^\s]+', Keyword.Pseudo, 'psql-command'))
  206. tokens['psql-command'] = [
  207. (r'\n', Text, 'root'),
  208. (r'\s+', Text),
  209. (r'\\[^\s]+', Keyword.Pseudo),
  210. (r""":(['"]?)[a-z]\w*\b\1""", Name.Variable),
  211. (r"'(''|[^'])*'", String.Single),
  212. (r"`([^`])*`", String.Backtick),
  213. (r"[^\s]+", String.Symbol),
  214. ]
  215. re_prompt = re.compile(r'^(\S.*?)??[=\-\(\$\'\"][#>]')
  216. re_psql_command = re.compile(r'\s*\\')
  217. re_end_command = re.compile(r';\s*(--.*?)?$')
  218. re_psql_command = re.compile(r'(\s*)(\\.+?)(\s+)$')
  219. re_error = re.compile(r'(ERROR|FATAL):')
  220. re_message = re.compile(
  221. r'((?:DEBUG|INFO|NOTICE|WARNING|ERROR|'
  222. r'FATAL|HINT|DETAIL|CONTEXT|LINE [0-9]+):)(.*?\n)')
  223. class lookahead(object):
  224. """Wrap an iterator and allow pushing back an item."""
  225. def __init__(self, x):
  226. self.iter = iter(x)
  227. self._nextitem = None
  228. def __iter__(self):
  229. return self
  230. def send(self, i):
  231. self._nextitem = i
  232. return i
  233. def __next__(self):
  234. if self._nextitem is not None:
  235. ni = self._nextitem
  236. self._nextitem = None
  237. return ni
  238. return next(self.iter)
  239. next = __next__
  240. class PostgresConsoleLexer(Lexer):
  241. """
  242. Lexer for psql sessions.
  243. .. versionadded:: 1.5
  244. """
  245. name = 'PostgreSQL console (psql)'
  246. aliases = ['psql', 'postgresql-console', 'postgres-console']
  247. mimetypes = ['text/x-postgresql-psql']
  248. def get_tokens_unprocessed(self, data):
  249. sql = PsqlRegexLexer(**self.options)
  250. lines = lookahead(line_re.findall(data))
  251. # prompt-output cycle
  252. while 1:
  253. # consume the lines of the command: start with an optional prompt
  254. # and continue until the end of command is detected
  255. curcode = ''
  256. insertions = []
  257. for line in lines:
  258. # Identify a shell prompt in case of psql commandline example
  259. if line.startswith('$') and not curcode:
  260. lexer = get_lexer_by_name('console', **self.options)
  261. for x in lexer.get_tokens_unprocessed(line):
  262. yield x
  263. break
  264. # Identify a psql prompt
  265. mprompt = re_prompt.match(line)
  266. if mprompt is not None:
  267. insertions.append((len(curcode),
  268. [(0, Generic.Prompt, mprompt.group())]))
  269. curcode += line[len(mprompt.group()):]
  270. else:
  271. curcode += line
  272. # Check if this is the end of the command
  273. # TODO: better handle multiline comments at the end with
  274. # a lexer with an external state?
  275. if re_psql_command.match(curcode) \
  276. or re_end_command.search(curcode):
  277. break
  278. # Emit the combined stream of command and prompt(s)
  279. for item in do_insertions(insertions,
  280. sql.get_tokens_unprocessed(curcode)):
  281. yield item
  282. # Emit the output lines
  283. out_token = Generic.Output
  284. for line in lines:
  285. mprompt = re_prompt.match(line)
  286. if mprompt is not None:
  287. # push the line back to have it processed by the prompt
  288. lines.send(line)
  289. break
  290. mmsg = re_message.match(line)
  291. if mmsg is not None:
  292. if mmsg.group(1).startswith("ERROR") \
  293. or mmsg.group(1).startswith("FATAL"):
  294. out_token = Generic.Error
  295. yield (mmsg.start(1), Generic.Strong, mmsg.group(1))
  296. yield (mmsg.start(2), out_token, mmsg.group(2))
  297. else:
  298. yield (0, out_token, line)
  299. else:
  300. return
  301. class SqlLexer(RegexLexer):
  302. """
  303. Lexer for Structured Query Language. Currently, this lexer does
  304. not recognize any special syntax except ANSI SQL.
  305. """
  306. name = 'SQL'
  307. aliases = ['sql']
  308. filenames = ['*.sql']
  309. mimetypes = ['text/x-sql']
  310. flags = re.IGNORECASE
  311. tokens = {
  312. 'root': [
  313. (r'\s+', Text),
  314. (r'--.*\n?', Comment.Single),
  315. (r'/\*', Comment.Multiline, 'multiline-comments'),
  316. (words((
  317. 'ABORT', 'ABS', 'ABSOLUTE', 'ACCESS', 'ADA', 'ADD', 'ADMIN', 'AFTER',
  318. 'AGGREGATE', 'ALIAS', 'ALL', 'ALLOCATE', 'ALTER', 'ANALYSE', 'ANALYZE',
  319. 'AND', 'ANY', 'ARE', 'AS', 'ASC', 'ASENSITIVE', 'ASSERTION', 'ASSIGNMENT',
  320. 'ASYMMETRIC', 'AT', 'ATOMIC', 'AUTHORIZATION', 'AVG', 'BACKWARD',
  321. 'BEFORE', 'BEGIN', 'BETWEEN', 'BITVAR', 'BIT_LENGTH', 'BOTH', 'BREADTH',
  322. 'BY', 'C', 'CACHE', 'CALL', 'CALLED', 'CARDINALITY', 'CASCADE',
  323. 'CASCADED', 'CASE', 'CAST', 'CATALOG', 'CATALOG_NAME', 'CHAIN',
  324. 'CHARACTERISTICS', 'CHARACTER_LENGTH', 'CHARACTER_SET_CATALOG',
  325. 'CHARACTER_SET_NAME', 'CHARACTER_SET_SCHEMA', 'CHAR_LENGTH', 'CHECK',
  326. 'CHECKED', 'CHECKPOINT', 'CLASS', 'CLASS_ORIGIN', 'CLOB', 'CLOSE',
  327. 'CLUSTER', 'COALSECE', 'COBOL', 'COLLATE', 'COLLATION',
  328. 'COLLATION_CATALOG', 'COLLATION_NAME', 'COLLATION_SCHEMA', 'COLUMN',
  329. 'COLUMN_NAME', 'COMMAND_FUNCTION', 'COMMAND_FUNCTION_CODE', 'COMMENT',
  330. 'COMMIT', 'COMMITTED', 'COMPLETION', 'CONDITION_NUMBER', 'CONNECT',
  331. 'CONNECTION', 'CONNECTION_NAME', 'CONSTRAINT', 'CONSTRAINTS',
  332. 'CONSTRAINT_CATALOG', 'CONSTRAINT_NAME', 'CONSTRAINT_SCHEMA',
  333. 'CONSTRUCTOR', 'CONTAINS', 'CONTINUE', 'CONVERSION', 'CONVERT',
  334. 'COPY', 'CORRESPONTING', 'COUNT', 'CREATE', 'CREATEDB', 'CREATEUSER',
  335. 'CROSS', 'CUBE', 'CURRENT', 'CURRENT_DATE', 'CURRENT_PATH',
  336. 'CURRENT_ROLE', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_USER',
  337. 'CURSOR', 'CURSOR_NAME', 'CYCLE', 'DATA', 'DATABASE',
  338. 'DATETIME_INTERVAL_CODE', 'DATETIME_INTERVAL_PRECISION', 'DAY',
  339. 'DEALLOCATE', 'DECLARE', 'DEFAULT', 'DEFAULTS', 'DEFERRABLE',
  340. 'DEFERRED', 'DEFINED', 'DEFINER', 'DELETE', 'DELIMITER', 'DELIMITERS',
  341. 'DEREF', 'DESC', 'DESCRIBE', 'DESCRIPTOR', 'DESTROY', 'DESTRUCTOR',
  342. 'DETERMINISTIC', 'DIAGNOSTICS', 'DICTIONARY', 'DISCONNECT', 'DISPATCH',
  343. 'DISTINCT', 'DO', 'DOMAIN', 'DROP', 'DYNAMIC', 'DYNAMIC_FUNCTION',
  344. 'DYNAMIC_FUNCTION_CODE', 'EACH', 'ELSE', 'ELSIF', 'ENCODING',
  345. 'ENCRYPTED', 'END', 'END-EXEC', 'EQUALS', 'ESCAPE', 'EVERY', 'EXCEPTION',
  346. 'EXCEPT', 'EXCLUDING', 'EXCLUSIVE', 'EXEC', 'EXECUTE', 'EXISTING',
  347. 'EXISTS', 'EXPLAIN', 'EXTERNAL', 'EXTRACT', 'FALSE', 'FETCH', 'FINAL',
  348. 'FIRST', 'FOR', 'FORCE', 'FOREIGN', 'FORTRAN', 'FORWARD', 'FOUND', 'FREE',
  349. 'FREEZE', 'FROM', 'FULL', 'FUNCTION', 'G', 'GENERAL', 'GENERATED', 'GET',
  350. 'GLOBAL', 'GO', 'GOTO', 'GRANT', 'GRANTED', 'GROUP', 'GROUPING',
  351. 'HANDLER', 'HAVING', 'HIERARCHY', 'HOLD', 'HOST', 'IDENTITY', 'IF',
  352. 'IGNORE', 'ILIKE', 'IMMEDIATE', 'IMMUTABLE', 'IMPLEMENTATION', 'IMPLICIT',
  353. 'IN', 'INCLUDING', 'INCREMENT', 'INDEX', 'INDITCATOR', 'INFIX',
  354. 'INHERITS', 'INITIALIZE', 'INITIALLY', 'INNER', 'INOUT', 'INPUT',
  355. 'INSENSITIVE', 'INSERT', 'INSTANTIABLE', 'INSTEAD', 'INTERSECT', 'INTO',
  356. 'INVOKER', 'IS', 'ISNULL', 'ISOLATION', 'ITERATE', 'JOIN', 'KEY',
  357. 'KEY_MEMBER', 'KEY_TYPE', 'LANCOMPILER', 'LANGUAGE', 'LARGE', 'LAST',
  358. 'LATERAL', 'LEADING', 'LEFT', 'LENGTH', 'LESS', 'LEVEL', 'LIKE', 'LIMIT',
  359. 'LISTEN', 'LOAD', 'LOCAL', 'LOCALTIME', 'LOCALTIMESTAMP', 'LOCATION',
  360. 'LOCATOR', 'LOCK', 'LOWER', 'MAP', 'MATCH', 'MAX', 'MAXVALUE',
  361. 'MESSAGE_LENGTH', 'MESSAGE_OCTET_LENGTH', 'MESSAGE_TEXT', 'METHOD', 'MIN',
  362. 'MINUTE', 'MINVALUE', 'MOD', 'MODE', 'MODIFIES', 'MODIFY', 'MONTH',
  363. 'MORE', 'MOVE', 'MUMPS', 'NAMES', 'NATIONAL', 'NATURAL', 'NCHAR', 'NCLOB',
  364. 'NEW', 'NEXT', 'NO', 'NOCREATEDB', 'NOCREATEUSER', 'NONE', 'NOT',
  365. 'NOTHING', 'NOTIFY', 'NOTNULL', 'NULL', 'NULLABLE', 'NULLIF', 'OBJECT',
  366. 'OCTET_LENGTH', 'OF', 'OFF', 'OFFSET', 'OIDS', 'OLD', 'ON', 'ONLY',
  367. 'OPEN', 'OPERATION', 'OPERATOR', 'OPTION', 'OPTIONS', 'OR', 'ORDER',
  368. 'ORDINALITY', 'OUT', 'OUTER', 'OUTPUT', 'OVERLAPS', 'OVERLAY',
  369. 'OVERRIDING', 'OWNER', 'PAD', 'PARAMETER', 'PARAMETERS', 'PARAMETER_MODE',
  370. 'PARAMATER_NAME', 'PARAMATER_ORDINAL_POSITION',
  371. 'PARAMETER_SPECIFIC_CATALOG', 'PARAMETER_SPECIFIC_NAME',
  372. 'PARAMATER_SPECIFIC_SCHEMA', 'PARTIAL', 'PASCAL', 'PENDANT', 'PLACING',
  373. 'PLI', 'POSITION', 'POSTFIX', 'PRECISION', 'PREFIX', 'PREORDER',
  374. 'PREPARE', 'PRESERVE', 'PRIMARY', 'PRIOR', 'PRIVILEGES', 'PROCEDURAL',
  375. 'PROCEDURE', 'PUBLIC', 'READ', 'READS', 'RECHECK', 'RECURSIVE', 'REF',
  376. 'REFERENCES', 'REFERENCING', 'REINDEX', 'RELATIVE', 'RENAME',
  377. 'REPEATABLE', 'REPLACE', 'RESET', 'RESTART', 'RESTRICT', 'RESULT',
  378. 'RETURN', 'RETURNED_LENGTH', 'RETURNED_OCTET_LENGTH', 'RETURNED_SQLSTATE',
  379. 'RETURNS', 'REVOKE', 'RIGHT', 'ROLE', 'ROLLBACK', 'ROLLUP', 'ROUTINE',
  380. 'ROUTINE_CATALOG', 'ROUTINE_NAME', 'ROUTINE_SCHEMA', 'ROW', 'ROWS',
  381. 'ROW_COUNT', 'RULE', 'SAVE_POINT', 'SCALE', 'SCHEMA', 'SCHEMA_NAME',
  382. 'SCOPE', 'SCROLL', 'SEARCH', 'SECOND', 'SECURITY', 'SELECT', 'SELF',
  383. 'SENSITIVE', 'SERIALIZABLE', 'SERVER_NAME', 'SESSION', 'SESSION_USER',
  384. 'SET', 'SETOF', 'SETS', 'SHARE', 'SHOW', 'SIMILAR', 'SIMPLE', 'SIZE',
  385. 'SOME', 'SOURCE', 'SPACE', 'SPECIFIC', 'SPECIFICTYPE', 'SPECIFIC_NAME',
  386. 'SQL', 'SQLCODE', 'SQLERROR', 'SQLEXCEPTION', 'SQLSTATE', 'SQLWARNINIG',
  387. 'STABLE', 'START', 'STATE', 'STATEMENT', 'STATIC', 'STATISTICS', 'STDIN',
  388. 'STDOUT', 'STORAGE', 'STRICT', 'STRUCTURE', 'STYPE', 'SUBCLASS_ORIGIN',
  389. 'SUBLIST', 'SUBSTRING', 'SUM', 'SYMMETRIC', 'SYSID', 'SYSTEM',
  390. 'SYSTEM_USER', 'TABLE', 'TABLE_NAME', ' TEMP', 'TEMPLATE', 'TEMPORARY',
  391. 'TERMINATE', 'THAN', 'THEN', 'TIMESTAMP', 'TIMEZONE_HOUR',
  392. 'TIMEZONE_MINUTE', 'TO', 'TOAST', 'TRAILING', 'TRANSATION',
  393. 'TRANSACTIONS_COMMITTED', 'TRANSACTIONS_ROLLED_BACK', 'TRANSATION_ACTIVE',
  394. 'TRANSFORM', 'TRANSFORMS', 'TRANSLATE', 'TRANSLATION', 'TREAT', 'TRIGGER',
  395. 'TRIGGER_CATALOG', 'TRIGGER_NAME', 'TRIGGER_SCHEMA', 'TRIM', 'TRUE',
  396. 'TRUNCATE', 'TRUSTED', 'TYPE', 'UNCOMMITTED', 'UNDER', 'UNENCRYPTED',
  397. 'UNION', 'UNIQUE', 'UNKNOWN', 'UNLISTEN', 'UNNAMED', 'UNNEST', 'UNTIL',
  398. 'UPDATE', 'UPPER', 'USAGE', 'USER', 'USER_DEFINED_TYPE_CATALOG',
  399. 'USER_DEFINED_TYPE_NAME', 'USER_DEFINED_TYPE_SCHEMA', 'USING', 'VACUUM',
  400. 'VALID', 'VALIDATOR', 'VALUES', 'VARIABLE', 'VERBOSE', 'VERSION', 'VIEW',
  401. 'VOLATILE', 'WHEN', 'WHENEVER', 'WHERE', 'WITH', 'WITHOUT', 'WORK',
  402. 'WRITE', 'YEAR', 'ZONE'), suffix=r'\b'),
  403. Keyword),
  404. (words((
  405. 'ARRAY', 'BIGINT', 'BINARY', 'BIT', 'BLOB', 'BOOLEAN', 'CHAR',
  406. 'CHARACTER', 'DATE', 'DEC', 'DECIMAL', 'FLOAT', 'INT', 'INTEGER',
  407. 'INTERVAL', 'NUMBER', 'NUMERIC', 'REAL', 'SERIAL', 'SMALLINT',
  408. 'VARCHAR', 'VARYING', 'INT8', 'SERIAL8', 'TEXT'), suffix=r'\b'),
  409. Name.Builtin),
  410. (r'[+*/<>=~!@#%^&|`?-]', Operator),
  411. (r'[0-9]+', Number.Integer),
  412. # TODO: Backslash escapes?
  413. (r"'(''|[^'])*'", String.Single),
  414. (r'"(""|[^"])*"', String.Symbol), # not a real string literal in ANSI SQL
  415. (r'[a-z_][\w$]*', Name), # allow $s in strings for Oracle
  416. (r'[;:()\[\],.]', Punctuation)
  417. ],
  418. 'multiline-comments': [
  419. (r'/\*', Comment.Multiline, 'multiline-comments'),
  420. (r'\*/', Comment.Multiline, '#pop'),
  421. (r'[^/*]+', Comment.Multiline),
  422. (r'[/*]', Comment.Multiline)
  423. ]
  424. }
  425. def analyse_text(text):
  426. return 0.01
  427. class TransactSqlLexer(RegexLexer):
  428. """
  429. Transact-SQL (T-SQL) is Microsoft's and Sybase's proprietary extension to
  430. SQL.
  431. The list of keywords includes ODBC and keywords reserved for future use..
  432. """
  433. name = 'Transact-SQL'
  434. aliases = ['tsql', 't-sql']
  435. filenames = ['*.sql']
  436. mimetypes = ['text/x-tsql']
  437. # Use re.UNICODE to allow non ASCII letters in names.
  438. flags = re.IGNORECASE | re.UNICODE
  439. tokens = {
  440. 'root': [
  441. (r'\s+', Whitespace),
  442. (r'(?m)--.*?$\n?', Comment.Single),
  443. (r'/\*', Comment.Multiline, 'multiline-comments'),
  444. (words(_tsql_builtins.OPERATORS), Operator),
  445. (words(_tsql_builtins.OPERATOR_WORDS, suffix=r'\b'), Operator.Word),
  446. (words(_tsql_builtins.TYPES, suffix=r'\b'), Name.Class),
  447. (words(_tsql_builtins.FUNCTIONS, suffix=r'\b'), Name.Function),
  448. (r'(goto)(\s+)(\w+\b)', bygroups(Keyword, Whitespace, Name.Label)),
  449. (words(_tsql_builtins.KEYWORDS, suffix=r'\b'), Keyword),
  450. (r'(\[)([^]]+)(\])', bygroups(Operator, Name, Operator)),
  451. (r'0x[0-9a-f]+', Number.Hex),
  452. # Float variant 1, for example: 1., 1.e2, 1.2e3
  453. (r'[0-9]+\.[0-9]*(e[+-]?[0-9]+)?', Number.Float),
  454. # Float variant 2, for example: .1, .1e2
  455. (r'\.[0-9]+(e[+-]?[0-9]+)?', Number.Float),
  456. # Float variant 3, for example: 123e45
  457. (r'[0-9]+e[+-]?[0-9]+', Number.Float),
  458. (r'[0-9]+', Number.Integer),
  459. (r"'(''|[^'])*'", String.Single),
  460. (r'"(""|[^"])*"', String.Symbol),
  461. (r'[;(),.]', Punctuation),
  462. # Below we use \w even for the first "real" character because
  463. # tokens starting with a digit have already been recognized
  464. # as Number above.
  465. (r'@@\w+', Name.Builtin),
  466. (r'@\w+', Name.Variable),
  467. (r'(\w+)(:)', bygroups(Name.Label, Punctuation)),
  468. (r'#?#?\w+', Name), # names for temp tables and anything else
  469. (r'\?', Name.Variable.Magic), # parameter for prepared statements
  470. ],
  471. 'multiline-comments': [
  472. (r'/\*', Comment.Multiline, 'multiline-comments'),
  473. (r'\*/', Comment.Multiline, '#pop'),
  474. (r'[^/*]+', Comment.Multiline),
  475. (r'[/*]', Comment.Multiline)
  476. ]
  477. }
  478. def analyse_text(text):
  479. rating = 0
  480. if tsql_declare_re.search(text):
  481. # Found T-SQL variable declaration.
  482. rating = 1.0
  483. else:
  484. name_between_backtick_count = len(
  485. name_between_backtick_re.findall(text))
  486. name_between_bracket_count = len(
  487. name_between_bracket_re.findall(text))
  488. # We need to check if there are any names using
  489. # backticks or brackets, as otherwise both are 0
  490. # and 0 >= 2 * 0, so we would always assume it's true
  491. dialect_name_count = name_between_backtick_count + name_between_bracket_count
  492. if dialect_name_count >= 1 and \
  493. name_between_bracket_count >= 2 * name_between_backtick_count:
  494. # Found at least twice as many [name] as `name`.
  495. rating += 0.5
  496. elif name_between_bracket_count > name_between_backtick_count:
  497. rating += 0.2
  498. elif name_between_bracket_count > 0:
  499. rating += 0.1
  500. if tsql_variable_re.search(text) is not None:
  501. rating += 0.1
  502. if tsql_go_re.search(text) is not None:
  503. rating += 0.1
  504. return rating
  505. class MySqlLexer(RegexLexer):
  506. """
  507. Special lexer for MySQL.
  508. """
  509. name = 'MySQL'
  510. aliases = ['mysql']
  511. mimetypes = ['text/x-mysql']
  512. flags = re.IGNORECASE
  513. tokens = {
  514. 'root': [
  515. (r'\s+', Text),
  516. (r'(#|--\s+).*\n?', Comment.Single),
  517. (r'/\*', Comment.Multiline, 'multiline-comments'),
  518. (r'[0-9]+', Number.Integer),
  519. (r'[0-9]*\.[0-9]+(e[+-][0-9]+)', Number.Float),
  520. (r"'(\\\\|\\'|''|[^'])*'", String.Single),
  521. (r'"(\\\\|\\"|""|[^"])*"', String.Double),
  522. (r"`(\\\\|\\`|``|[^`])*`", String.Symbol),
  523. (r'[+*/<>=~!@#%^&|`?-]', Operator),
  524. (r'\b(tinyint|smallint|mediumint|int|integer|bigint|date|'
  525. r'datetime|time|bit|bool|tinytext|mediumtext|longtext|text|'
  526. r'tinyblob|mediumblob|longblob|blob|float|double|double\s+'
  527. r'precision|real|numeric|dec|decimal|timestamp|year|char|'
  528. r'varchar|varbinary|varcharacter|enum|set)(\b\s*)(\()?',
  529. bygroups(Keyword.Type, Text, Punctuation)),
  530. (r'\b(add|all|alter|analyze|and|as|asc|asensitive|before|between|'
  531. r'bigint|binary|blob|both|by|call|cascade|case|change|char|'
  532. r'character|check|collate|column|condition|constraint|continue|'
  533. r'convert|create|cross|current_date|current_time|'
  534. r'current_timestamp|current_user|cursor|database|databases|'
  535. r'day_hour|day_microsecond|day_minute|day_second|dec|decimal|'
  536. r'declare|default|delayed|delete|desc|describe|deterministic|'
  537. r'distinct|distinctrow|div|double|drop|dual|each|else|elseif|'
  538. r'enclosed|escaped|exists|exit|explain|fetch|flush|float|float4|'
  539. r'float8|for|force|foreign|from|fulltext|grant|group|having|'
  540. r'high_priority|hour_microsecond|hour_minute|hour_second|if|'
  541. r'ignore|in|index|infile|inner|inout|insensitive|insert|int|'
  542. r'int1|int2|int3|int4|int8|integer|interval|into|is|iterate|'
  543. r'join|key|keys|kill|leading|leave|left|like|limit|lines|load|'
  544. r'localtime|localtimestamp|lock|long|loop|low_priority|match|'
  545. r'minute_microsecond|minute_second|mod|modifies|natural|'
  546. r'no_write_to_binlog|not|numeric|on|optimize|option|optionally|'
  547. r'or|order|out|outer|outfile|precision|primary|procedure|purge|'
  548. r'raid0|read|reads|real|references|regexp|release|rename|repeat|'
  549. r'replace|require|restrict|return|revoke|right|rlike|schema|'
  550. r'schemas|second_microsecond|select|sensitive|separator|set|'
  551. r'show|smallint|soname|spatial|specific|sql|sql_big_result|'
  552. r'sql_calc_found_rows|sql_small_result|sqlexception|sqlstate|'
  553. r'sqlwarning|ssl|starting|straight_join|table|terminated|then|'
  554. r'to|trailing|trigger|undo|union|unique|unlock|unsigned|update|'
  555. r'usage|use|using|utc_date|utc_time|utc_timestamp|values|'
  556. r'varying|when|where|while|with|write|x509|xor|year_month|'
  557. r'zerofill)\b', Keyword),
  558. # TODO: this list is not complete
  559. (r'\b(auto_increment|engine|charset|tables)\b', Keyword.Pseudo),
  560. (r'(true|false|null)', Name.Constant),
  561. (r'([a-z_]\w*)(\s*)(\()',
  562. bygroups(Name.Function, Text, Punctuation)),
  563. (r'[a-z_]\w*', Name),
  564. (r'@[a-z0-9]*[._]*[a-z0-9]*', Name.Variable),
  565. (r'[;:()\[\],.]', Punctuation)
  566. ],
  567. 'multiline-comments': [
  568. (r'/\*', Comment.Multiline, 'multiline-comments'),
  569. (r'\*/', Comment.Multiline, '#pop'),
  570. (r'[^/*]+', Comment.Multiline),
  571. (r'[/*]', Comment.Multiline)
  572. ]
  573. }
  574. def analyse_text(text):
  575. rating = 0
  576. name_between_backtick_count = len(
  577. name_between_backtick_re.findall(text))
  578. name_between_bracket_count = len(
  579. name_between_bracket_re.findall(text))
  580. # Same logic as above in the TSQL analysis
  581. dialect_name_count = name_between_backtick_count + name_between_bracket_count
  582. if dialect_name_count >= 1 and \
  583. name_between_backtick_count >= 2 * name_between_bracket_count:
  584. # Found at least twice as many `name` as [name].
  585. rating += 0.5
  586. elif name_between_backtick_count > name_between_bracket_count:
  587. rating += 0.2
  588. elif name_between_backtick_count > 0:
  589. rating += 0.1
  590. return rating
  591. class SqliteConsoleLexer(Lexer):
  592. """
  593. Lexer for example sessions using sqlite3.
  594. .. versionadded:: 0.11
  595. """
  596. name = 'sqlite3con'
  597. aliases = ['sqlite3']
  598. filenames = ['*.sqlite3-console']
  599. mimetypes = ['text/x-sqlite3-console']
  600. def get_tokens_unprocessed(self, data):
  601. sql = SqlLexer(**self.options)
  602. curcode = ''
  603. insertions = []
  604. for match in line_re.finditer(data):
  605. line = match.group()
  606. if line.startswith('sqlite> ') or line.startswith(' ...> '):
  607. insertions.append((len(curcode),
  608. [(0, Generic.Prompt, line[:8])]))
  609. curcode += line[8:]
  610. else:
  611. if curcode:
  612. for item in do_insertions(insertions,
  613. sql.get_tokens_unprocessed(curcode)):
  614. yield item
  615. curcode = ''
  616. insertions = []
  617. if line.startswith('SQL error: '):
  618. yield (match.start(), Generic.Traceback, line)
  619. else:
  620. yield (match.start(), Generic.Output, line)
  621. if curcode:
  622. for item in do_insertions(insertions,
  623. sql.get_tokens_unprocessed(curcode)):
  624. yield item
  625. class RqlLexer(RegexLexer):
  626. """
  627. Lexer for Relation Query Language.
  628. `RQL <http://www.logilab.org/project/rql>`_
  629. .. versionadded:: 2.0
  630. """
  631. name = 'RQL'
  632. aliases = ['rql']
  633. filenames = ['*.rql']
  634. mimetypes = ['text/x-rql']
  635. flags = re.IGNORECASE
  636. tokens = {
  637. 'root': [
  638. (r'\s+', Text),
  639. (r'(DELETE|SET|INSERT|UNION|DISTINCT|WITH|WHERE|BEING|OR'
  640. r'|AND|NOT|GROUPBY|HAVING|ORDERBY|ASC|DESC|LIMIT|OFFSET'
  641. r'|TODAY|NOW|TRUE|FALSE|NULL|EXISTS)\b', Keyword),
  642. (r'[+*/<>=%-]', Operator),
  643. (r'(Any|is|instance_of|CWEType|CWRelation)\b', Name.Builtin),
  644. (r'[0-9]+', Number.Integer),
  645. (r'[A-Z_]\w*\??', Name),
  646. (r"'(''|[^'])*'", String.Single),
  647. (r'"(""|[^"])*"', String.Single),
  648. (r'[;:()\[\],.]', Punctuation)
  649. ],
  650. }