sqlglot.dialects.oracle API documentation

Edit on GitHub

# sqlglot.dialects.oracle

View Source

      1from __future__ import annotations
      2
      3from sqlglot import exp, generator, parser, tokens, transforms
      4from sqlglot.dialects.dialect import Dialect, no_ilike_sql, rename_func, trim_sql
      5from sqlglot.helper import csv
      6from sqlglot.tokens import TokenType
      7
      8
      9def _limit_sql(self, expression):
     10    return self.fetch_sql(exp.Fetch(direction="FIRST", count=expression.expression))
     11
     12
     13class Oracle(Dialect):
     14    # https://docs.oracle.com/database/121/SQLRF/sql_elements004.htm#SQLRF00212
     15    # https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
     16    time_mapping = {
     17        "AM": "%p",  # Meridian indicator with or without periods
     18        "A.M.": "%p",  # Meridian indicator with or without periods
     19        "PM": "%p",  # Meridian indicator with or without periods
     20        "P.M.": "%p",  # Meridian indicator with or without periods
     21        "D": "%u",  # Day of week (1-7)
     22        "DAY": "%A",  # name of day
     23        "DD": "%d",  # day of month (1-31)
     24        "DDD": "%j",  # day of year (1-366)
     25        "DY": "%a",  # abbreviated name of day
     26        "HH": "%I",  # Hour of day (1-12)
     27        "HH12": "%I",  # alias for HH
     28        "HH24": "%H",  # Hour of day (0-23)
     29        "IW": "%V",  # Calendar week of year (1-52 or 1-53), as defined by the ISO 8601 standard
     30        "MI": "%M",  # Minute (0-59)
     31        "MM": "%m",  # Month (01-12; January = 01)
     32        "MON": "%b",  # Abbreviated name of month
     33        "MONTH": "%B",  # Name of month
     34        "SS": "%S",  # Second (0-59)
     35        "WW": "%W",  # Week of year (1-53)
     36        "YY": "%y",  # 15
     37        "YYYY": "%Y",  # 2015
     38    }
     39
     40    class Parser(parser.Parser):
     41        FUNCTIONS = {
     42            **parser.Parser.FUNCTIONS,  # type: ignore
     43            "DECODE": exp.Matches.from_arg_list,
     44        }
     45
     46    class Generator(generator.Generator):
     47        LOCKING_READS_SUPPORTED = True
     48
     49        TYPE_MAPPING = {
     50            **generator.Generator.TYPE_MAPPING,  # type: ignore
     51            exp.DataType.Type.TINYINT: "NUMBER",
     52            exp.DataType.Type.SMALLINT: "NUMBER",
     53            exp.DataType.Type.INT: "NUMBER",
     54            exp.DataType.Type.BIGINT: "NUMBER",
     55            exp.DataType.Type.DECIMAL: "NUMBER",
     56            exp.DataType.Type.DOUBLE: "DOUBLE PRECISION",
     57            exp.DataType.Type.VARCHAR: "VARCHAR2",
     58            exp.DataType.Type.NVARCHAR: "NVARCHAR2",
     59            exp.DataType.Type.TEXT: "CLOB",
     60            exp.DataType.Type.BINARY: "BLOB",
     61            exp.DataType.Type.VARBINARY: "BLOB",
     62        }
     63
     64        TRANSFORMS = {
     65            **generator.Generator.TRANSFORMS,  # type: ignore
     66            **transforms.UNALIAS_GROUP,  # type: ignore
     67            exp.ILike: no_ilike_sql,
     68            exp.Limit: _limit_sql,
     69            exp.Trim: trim_sql,
     70            exp.Matches: rename_func("DECODE"),
     71            exp.StrToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')}, {self.format_time(e)})",
     72            exp.TimeToStr: lambda self, e: f"TO_CHAR({self.sql(e, 'this')}, {self.format_time(e)})",
     73            exp.UnixToTime: lambda self, e: f"TO_DATE('1970-01-01','YYYY-MM-DD') + ({self.sql(e, 'this')} / 86400)",
     74            exp.Substring: rename_func("SUBSTR"),
     75        }
     76
     77        def query_modifiers(self, expression, *sqls):
     78            return csv(
     79                *sqls,
     80                *[self.sql(sql) for sql in expression.args.get("joins") or []],
     81                self.sql(expression, "match"),
     82                *[self.sql(sql) for sql in expression.args.get("laterals") or []],
     83                self.sql(expression, "where"),
     84                self.sql(expression, "group"),
     85                self.sql(expression, "having"),
     86                self.sql(expression, "qualify"),
     87                self.seg("WINDOW ") + self.expressions(expression, "windows", flat=True)
     88                if expression.args.get("windows")
     89                else "",
     90                self.sql(expression, "distribute"),
     91                self.sql(expression, "sort"),
     92                self.sql(expression, "cluster"),
     93                self.sql(expression, "order"),
     94                self.sql(expression, "offset"),  # offset before limit in oracle
     95                self.sql(expression, "limit"),
     96                self.sql(expression, "lock"),
     97                sep="",
     98            )
     99
    100        def offset_sql(self, expression):
    101            return f"{super().offset_sql(expression)} ROWS"
    102
    103        def table_sql(self, expression):
    104            return super().table_sql(expression, sep=" ")
    105
    106    class Tokenizer(tokens.Tokenizer):
    107        KEYWORDS = {
    108            **tokens.Tokenizer.KEYWORDS,
    109            "MATCH_RECOGNIZE": TokenType.MATCH_RECOGNIZE,
    110            "MINUS": TokenType.EXCEPT,
    111            "START": TokenType.BEGIN,
    112            "TOP": TokenType.TOP,
    113            "VARCHAR2": TokenType.VARCHAR,
    114            "NVARCHAR2": TokenType.NVARCHAR,
    115        }

class Oracle(sqlglot.dialects.dialect.Dialect): View Source

     14class Oracle(Dialect):
     15    # https://docs.oracle.com/database/121/SQLRF/sql_elements004.htm#SQLRF00212
     16    # https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
     17    time_mapping = {
     18        "AM": "%p",  # Meridian indicator with or without periods
     19        "A.M.": "%p",  # Meridian indicator with or without periods
     20        "PM": "%p",  # Meridian indicator with or without periods
     21        "P.M.": "%p",  # Meridian indicator with or without periods
     22        "D": "%u",  # Day of week (1-7)
     23        "DAY": "%A",  # name of day
     24        "DD": "%d",  # day of month (1-31)
     25        "DDD": "%j",  # day of year (1-366)
     26        "DY": "%a",  # abbreviated name of day
     27        "HH": "%I",  # Hour of day (1-12)
     28        "HH12": "%I",  # alias for HH
     29        "HH24": "%H",  # Hour of day (0-23)
     30        "IW": "%V",  # Calendar week of year (1-52 or 1-53), as defined by the ISO 8601 standard
     31        "MI": "%M",  # Minute (0-59)
     32        "MM": "%m",  # Month (01-12; January = 01)
     33        "MON": "%b",  # Abbreviated name of month
     34        "MONTH": "%B",  # Name of month
     35        "SS": "%S",  # Second (0-59)
     36        "WW": "%W",  # Week of year (1-53)
     37        "YY": "%y",  # 15
     38        "YYYY": "%Y",  # 2015
     39    }
     40
     41    class Parser(parser.Parser):
     42        FUNCTIONS = {
     43            **parser.Parser.FUNCTIONS,  # type: ignore
     44            "DECODE": exp.Matches.from_arg_list,
     45        }
     46
     47    class Generator(generator.Generator):
     48        LOCKING_READS_SUPPORTED = True
     49
     50        TYPE_MAPPING = {
     51            **generator.Generator.TYPE_MAPPING,  # type: ignore
     52            exp.DataType.Type.TINYINT: "NUMBER",
     53            exp.DataType.Type.SMALLINT: "NUMBER",
     54            exp.DataType.Type.INT: "NUMBER",
     55            exp.DataType.Type.BIGINT: "NUMBER",
     56            exp.DataType.Type.DECIMAL: "NUMBER",
     57            exp.DataType.Type.DOUBLE: "DOUBLE PRECISION",
     58            exp.DataType.Type.VARCHAR: "VARCHAR2",
     59            exp.DataType.Type.NVARCHAR: "NVARCHAR2",
     60            exp.DataType.Type.TEXT: "CLOB",
     61            exp.DataType.Type.BINARY: "BLOB",
     62            exp.DataType.Type.VARBINARY: "BLOB",
     63        }
     64
     65        TRANSFORMS = {
     66            **generator.Generator.TRANSFORMS,  # type: ignore
     67            **transforms.UNALIAS_GROUP,  # type: ignore
     68            exp.ILike: no_ilike_sql,
     69            exp.Limit: _limit_sql,
     70            exp.Trim: trim_sql,
     71            exp.Matches: rename_func("DECODE"),
     72            exp.StrToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')}, {self.format_time(e)})",
     73            exp.TimeToStr: lambda self, e: f"TO_CHAR({self.sql(e, 'this')}, {self.format_time(e)})",
     74            exp.UnixToTime: lambda self, e: f"TO_DATE('1970-01-01','YYYY-MM-DD') + ({self.sql(e, 'this')} / 86400)",
     75            exp.Substring: rename_func("SUBSTR"),
     76        }
     77
     78        def query_modifiers(self, expression, *sqls):
     79            return csv(
     80                *sqls,
     81                *[self.sql(sql) for sql in expression.args.get("joins") or []],
     82                self.sql(expression, "match"),
     83                *[self.sql(sql) for sql in expression.args.get("laterals") or []],
     84                self.sql(expression, "where"),
     85                self.sql(expression, "group"),
     86                self.sql(expression, "having"),
     87                self.sql(expression, "qualify"),
     88                self.seg("WINDOW ") + self.expressions(expression, "windows", flat=True)
     89                if expression.args.get("windows")
     90                else "",
     91                self.sql(expression, "distribute"),
     92                self.sql(expression, "sort"),
     93                self.sql(expression, "cluster"),
     94                self.sql(expression, "order"),
     95                self.sql(expression, "offset"),  # offset before limit in oracle
     96                self.sql(expression, "limit"),
     97                self.sql(expression, "lock"),
     98                sep="",
     99            )
    100
    101        def offset_sql(self, expression):
    102            return f"{super().offset_sql(expression)} ROWS"
    103
    104        def table_sql(self, expression):
    105            return super().table_sql(expression, sep=" ")
    106
    107    class Tokenizer(tokens.Tokenizer):
    108        KEYWORDS = {
    109            **tokens.Tokenizer.KEYWORDS,
    110            "MATCH_RECOGNIZE": TokenType.MATCH_RECOGNIZE,
    111            "MINUS": TokenType.EXCEPT,
    112            "START": TokenType.BEGIN,
    113            "TOP": TokenType.TOP,
    114            "VARCHAR2": TokenType.VARCHAR,
    115            "NVARCHAR2": TokenType.NVARCHAR,
    116        }

Oracle()

##### Inherited Members

sqlglot.dialects.dialect.Dialect
  get_or_raise
  format_time
  parse
  parse_into
  generate
  transpile
  parser
  generator

class Oracle.Parser(sqlglot.parser.Parser): View Source

    41    class Parser(parser.Parser):
    42        FUNCTIONS = {
    43            **parser.Parser.FUNCTIONS,  # type: ignore
    44            "DECODE": exp.Matches.from_arg_list,
    45        }

Parser consumes a list of tokens produced by the `sqlglot.tokens.Tokenizer` and produces a parsed syntax tree.

###### Arguments:

- error_level: the desired error level. Default: ErrorLevel.RAISE
- error_message_context: determines the amount of context to capture from a query string when displaying the error message (in number of characters). Default: 50.
- index_offset: Index offset for arrays eg ARRAY[0] vs ARRAY[1] as the head of a list. Default: 0
- alias_post_tablesample: If the table alias comes after tablesample. Default: False
- max_errors: Maximum number of error messages to include in a raised ParseError. This is only relevant if error_level is ErrorLevel.RAISE. Default: 3
- null_ordering: Indicates the default null ordering method to use if not explicitly set. Options are "nulls_are_small", "nulls_are_large", "nulls_are_last". Default: "nulls_are_small"

##### Inherited Members

sqlglot.parser.Parser
  Parser
  reset
  parse
  parse_into
  check_errors
  raise_error
  expression
  validate_expression

class Oracle.Generator(sqlglot.generator.Generator): View Source

     47    class Generator(generator.Generator):
     48        LOCKING_READS_SUPPORTED = True
     49
     50        TYPE_MAPPING = {
     51            **generator.Generator.TYPE_MAPPING,  # type: ignore
     52            exp.DataType.Type.TINYINT: "NUMBER",
     53            exp.DataType.Type.SMALLINT: "NUMBER",
     54            exp.DataType.Type.INT: "NUMBER",
     55            exp.DataType.Type.BIGINT: "NUMBER",
     56            exp.DataType.Type.DECIMAL: "NUMBER",
     57            exp.DataType.Type.DOUBLE: "DOUBLE PRECISION",
     58            exp.DataType.Type.VARCHAR: "VARCHAR2",
     59            exp.DataType.Type.NVARCHAR: "NVARCHAR2",
     60            exp.DataType.Type.TEXT: "CLOB",
     61            exp.DataType.Type.BINARY: "BLOB",
     62            exp.DataType.Type.VARBINARY: "BLOB",
     63        }
     64
     65        TRANSFORMS = {
     66            **generator.Generator.TRANSFORMS,  # type: ignore
     67            **transforms.UNALIAS_GROUP,  # type: ignore
     68            exp.ILike: no_ilike_sql,
     69            exp.Limit: _limit_sql,
     70            exp.Trim: trim_sql,
     71            exp.Matches: rename_func("DECODE"),
     72            exp.StrToTime: lambda self, e: f"TO_TIMESTAMP({self.sql(e, 'this')}, {self.format_time(e)})",
     73            exp.TimeToStr: lambda self, e: f"TO_CHAR({self.sql(e, 'this')}, {self.format_time(e)})",
     74            exp.UnixToTime: lambda self, e: f"TO_DATE('1970-01-01','YYYY-MM-DD') + ({self.sql(e, 'this')} / 86400)",
     75            exp.Substring: rename_func("SUBSTR"),
     76        }
     77
     78        def query_modifiers(self, expression, *sqls):
     79            return csv(
     80                *sqls,
     81                *[self.sql(sql) for sql in expression.args.get("joins") or []],
     82                self.sql(expression, "match"),
     83                *[self.sql(sql) for sql in expression.args.get("laterals") or []],
     84                self.sql(expression, "where"),
     85                self.sql(expression, "group"),
     86                self.sql(expression, "having"),
     87                self.sql(expression, "qualify"),
     88                self.seg("WINDOW ") + self.expressions(expression, "windows", flat=True)
     89                if expression.args.get("windows")
     90                else "",
     91                self.sql(expression, "distribute"),
     92                self.sql(expression, "sort"),
     93                self.sql(expression, "cluster"),
     94                self.sql(expression, "order"),
     95                self.sql(expression, "offset"),  # offset before limit in oracle
     96                self.sql(expression, "limit"),
     97                self.sql(expression, "lock"),
     98                sep="",
     99            )
    100
    101        def offset_sql(self, expression):
    102            return f"{super().offset_sql(expression)} ROWS"
    103
    104        def table_sql(self, expression):
    105            return super().table_sql(expression, sep=" ")

Generator interprets the given syntax tree and produces a SQL string as an output.

###### Arguments:

- time_mapping (dict): the dictionary of custom time mappings in which the key represents a python time format and the output the target time format
- time_trie (trie): a trie of the time_mapping keys
- pretty (bool): if set to True the returned string will be formatted. Default: False.
- quote_start (str): specifies which starting character to use to delimit quotes. Default: '.
- quote_end (str): specifies which ending character to use to delimit quotes. Default: '.
- identifier_start (str): specifies which starting character to use to delimit identifiers. Default: ".
- identifier_end (str): specifies which ending character to use to delimit identifiers. Default: ".
- identify (bool): if set to True all identifiers will be delimited by the corresponding character.
- normalize (bool): if set to True all identifiers will lower cased
- string_escape (str): specifies a string escape character. Default: '.
- identifier_escape (str): specifies an identifier escape character. Default: ".
- pad (int): determines padding in a formatted string. Default: 2.
- indent (int): determines the size of indentation in a formatted string. Default: 4.
- unnest_column_only (bool): if true unnest table aliases are considered only as column aliases
- normalize_functions (str): normalize function names, "upper", "lower", or None Default: "upper"
- alias_post_tablesample (bool): if the table alias comes after tablesample Default: False
- unsupported_level (ErrorLevel): determines the generator's behavior when it encounters unsupported expressions. Default ErrorLevel.WARN.
- null_ordering (str): Indicates the default null ordering method to use if not explicitly set. Options are "nulls_are_small", "nulls_are_large", "nulls_are_last". Default: "nulls_are_small"
- max_unsupported (int): Maximum number of unsupported messages to include in a raised UnsupportedError. This is only relevant if unsupported_level is ErrorLevel.RAISE. Default: 3
- leading_comma (bool): if the the comma is leading or trailing in select statements Default: False
- max_text_width: The max number of characters in a segment before creating new lines in pretty mode. The default is on the smaller end because the length only represents a segment and not the true line length. Default: 80
- comments: Whether or not to preserve comments in the output SQL code. Default: True

def query_modifiers(self, expression, *sqls): View Source

    78        def query_modifiers(self, expression, *sqls):
    79            return csv(
    80                *sqls,
    81                *[self.sql(sql) for sql in expression.args.get("joins") or []],
    82                self.sql(expression, "match"),
    83                *[self.sql(sql) for sql in expression.args.get("laterals") or []],
    84                self.sql(expression, "where"),
    85                self.sql(expression, "group"),
    86                self.sql(expression, "having"),
    87                self.sql(expression, "qualify"),
    88                self.seg("WINDOW ") + self.expressions(expression, "windows", flat=True)
    89                if expression.args.get("windows")
    90                else "",
    91                self.sql(expression, "distribute"),
    92                self.sql(expression, "sort"),
    93                self.sql(expression, "cluster"),
    94                self.sql(expression, "order"),
    95                self.sql(expression, "offset"),  # offset before limit in oracle
    96                self.sql(expression, "limit"),
    97                self.sql(expression, "lock"),
    98                sep="",
    99            )

def offset_sql(self, expression): View Source

    101        def offset_sql(self, expression):
    102            return f"{super().offset_sql(expression)} ROWS"

def table_sql(self, expression): View Source

    104        def table_sql(self, expression):
    105            return super().table_sql(expression, sep=" ")

##### Inherited Members

sqlglot.generator.Generator
  Generator
  generate
  unsupported
  sep
  seg
  pad_comment
  maybe_comment
  wrap
  no_identify
  normalize_func
  indent
  sql
  uncache_sql
  cache_sql
  characterset_sql
  column_sql
  columndef_sql
  columnconstraint_sql
  autoincrementcolumnconstraint_sql
  checkcolumnconstraint_sql
  commentcolumnconstraint_sql
  collatecolumnconstraint_sql
  encodecolumnconstraint_sql
  defaultcolumnconstraint_sql
  generatedasidentitycolumnconstraint_sql
  notnullcolumnconstraint_sql
  primarykeycolumnconstraint_sql
  uniquecolumnconstraint_sql
  create_sql
  describe_sql
  prepend_ctes
  with_sql
  cte_sql
  tablealias_sql
  bitstring_sql
  hexstring_sql
  datatype_sql
  directory_sql
  delete_sql
  drop_sql
  except_sql
  except_op
  fetch_sql
  filter_sql
  hint_sql
  index_sql
  identifier_sql
  national_sql
  partition_sql
  properties_sql
  root_properties
  properties
  with_properties
  locate_properties
  property_sql
  likeproperty_sql
  fallbackproperty_sql
  journalproperty_sql
  freespaceproperty_sql
  afterjournalproperty_sql
  checksumproperty_sql
  mergeblockratioproperty_sql
  datablocksizeproperty_sql
  blockcompressionproperty_sql
  isolatedloadingproperty_sql
  insert_sql
  intersect_sql
  intersect_op
  introducer_sql
  pseudotype_sql
  rowformatdelimitedproperty_sql
  tablesample_sql
  pivot_sql
  tuple_sql
  update_sql
  values_sql
  var_sql
  into_sql
  from_sql
  group_sql
  having_sql
  join_sql
  lambda_sql
  lateral_sql
  limit_sql
  lock_sql
  literal_sql
  loaddata_sql
  null_sql
  boolean_sql
  order_sql
  cluster_sql
  distribute_sql
  sort_sql
  ordered_sql
  matchrecognize_sql
  select_sql
  schema_sql
  star_sql
  structkwarg_sql
  parameter_sql
  sessionparameter_sql
  placeholder_sql
  subquery_sql
  qualify_sql
  union_sql
  union_op
  unnest_sql
  where_sql
  window_sql
  partition_by_sql
  window_spec_sql
  withingroup_sql
  between_sql
  bracket_sql
  all_sql
  any_sql
  exists_sql
  case_sql
  constraint_sql
  extract_sql
  trim_sql
  concat_sql
  check_sql
  foreignkey_sql
  primarykey_sql
  unique_sql
  if_sql
  in_sql
  in_unnest_op
  interval_sql
  return_sql
  reference_sql
  anonymous_sql
  paren_sql
  neg_sql
  not_sql
  alias_sql
  aliases_sql
  attimezone_sql
  add_sql
  and_sql
  connector_sql
  bitwiseand_sql
  bitwiseleftshift_sql
  bitwisenot_sql
  bitwiseor_sql
  bitwiserightshift_sql
  bitwisexor_sql
  cast_sql
  currentdate_sql
  collate_sql
  command_sql
  transaction_sql
  commit_sql
  rollback_sql
  altercolumn_sql
  renametable_sql
  altertable_sql
  droppartition_sql
  addconstraint_sql
  distinct_sql
  ignorenulls_sql
  respectnulls_sql
  intdiv_sql
  dpipe_sql
  div_sql
  distance_sql
  dot_sql
  eq_sql
  escape_sql
  glob_sql
  gt_sql
  gte_sql
  ilike_sql
  is_sql
  like_sql
  similarto_sql
  lt_sql
  lte_sql
  mod_sql
  mul_sql
  neq_sql
  nullsafeeq_sql
  nullsafeneq_sql
  or_sql
  slice_sql
  sub_sql
  trycast_sql
  use_sql
  binary
  function_fallback_sql
  format_args
  text_width
  format_time
  expressions
  op_expressions
  naked_property
  set_operation
  tag_sql
  token_sql
  userdefinedfunction_sql
  userdefinedfunctionkwarg_sql
  joinhint_sql
  kwarg_sql
  when_sql
  merge_sql

class Oracle.Tokenizer(sqlglot.tokens.Tokenizer): View Source

    107    class Tokenizer(tokens.Tokenizer):
    108        KEYWORDS = {
    109            **tokens.Tokenizer.KEYWORDS,
    110            "MATCH_RECOGNIZE": TokenType.MATCH_RECOGNIZE,
    111            "MINUS": TokenType.EXCEPT,
    112            "START": TokenType.BEGIN,
    113            "TOP": TokenType.TOP,
    114            "VARCHAR2": TokenType.VARCHAR,
    115            "NVARCHAR2": TokenType.NVARCHAR,
    116        }

##### Inherited Members

sqlglot.tokens.Tokenizer
  Tokenizer
  reset
  tokenize