sql.py 29 KB

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