sqlglot.dialects.sqlite API documentation

Edit on GitHub

# sqlglot.dialects.sqlite

View Source

      1from __future__ import annotations
      2
      3from sqlglot import exp, generator, parser, tokens, transforms
      4from sqlglot.dialects.dialect import (
      5    Dialect,
      6    arrow_json_extract_scalar_sql,
      7    arrow_json_extract_sql,
      8    concat_to_dpipe_sql,
      9    count_if_to_sum,
     10    no_ilike_sql,
     11    no_pivot_sql,
     12    no_tablesample_sql,
     13    no_trycast_sql,
     14    rename_func,
     15)
     16from sqlglot.tokens import TokenType
     17
     18
     19def _date_add_sql(self: generator.Generator, expression: exp.DateAdd) -> str:
     20    modifier = expression.expression
     21    modifier = modifier.name if modifier.is_string else self.sql(modifier)
     22    unit = expression.args.get("unit")
     23    modifier = f"'{modifier} {unit.name}'" if unit else f"'{modifier}'"
     24    return self.func("DATE", expression.this, modifier)
     25
     26
     27def _transform_create(expression: exp.Expression) -> exp.Expression:
     28    """Move primary key to a column and enforce auto_increment on primary keys."""
     29    schema = expression.this
     30
     31    if isinstance(expression, exp.Create) and isinstance(schema, exp.Schema):
     32        defs = {}
     33        primary_key = None
     34
     35        for e in schema.expressions:
     36            if isinstance(e, exp.ColumnDef):
     37                defs[e.name] = e
     38            elif isinstance(e, exp.PrimaryKey):
     39                primary_key = e
     40
     41        if primary_key and len(primary_key.expressions) == 1:
     42            column = defs[primary_key.expressions[0].name]
     43            column.append(
     44                "constraints", exp.ColumnConstraint(kind=exp.PrimaryKeyColumnConstraint())
     45            )
     46            schema.expressions.remove(primary_key)
     47        else:
     48            for column in defs.values():
     49                auto_increment = None
     50                for constraint in column.constraints.copy():
     51                    if isinstance(constraint.kind, exp.PrimaryKeyColumnConstraint):
     52                        break
     53                    if isinstance(constraint.kind, exp.AutoIncrementColumnConstraint):
     54                        auto_increment = constraint
     55                if auto_increment:
     56                    column.constraints.remove(auto_increment)
     57
     58    return expression
     59
     60
     61class SQLite(Dialect):
     62    # https://sqlite.org/forum/forumpost/5e575586ac5c711b?raw
     63    RESOLVES_IDENTIFIERS_AS_UPPERCASE = None
     64
     65    class Tokenizer(tokens.Tokenizer):
     66        IDENTIFIERS = ['"', ("[", "]"), "`"]
     67        HEX_STRINGS = [("x'", "'"), ("X'", "'"), ("0x", ""), ("0X", "")]
     68
     69    class Parser(parser.Parser):
     70        FUNCTIONS = {
     71            **parser.Parser.FUNCTIONS,
     72            "EDITDIST3": exp.Levenshtein.from_arg_list,
     73        }
     74
     75    class Generator(generator.Generator):
     76        JOIN_HINTS = False
     77        TABLE_HINTS = False
     78
     79        TYPE_MAPPING = {
     80            **generator.Generator.TYPE_MAPPING,
     81            exp.DataType.Type.BOOLEAN: "INTEGER",
     82            exp.DataType.Type.TINYINT: "INTEGER",
     83            exp.DataType.Type.SMALLINT: "INTEGER",
     84            exp.DataType.Type.INT: "INTEGER",
     85            exp.DataType.Type.BIGINT: "INTEGER",
     86            exp.DataType.Type.FLOAT: "REAL",
     87            exp.DataType.Type.DOUBLE: "REAL",
     88            exp.DataType.Type.DECIMAL: "REAL",
     89            exp.DataType.Type.CHAR: "TEXT",
     90            exp.DataType.Type.NCHAR: "TEXT",
     91            exp.DataType.Type.VARCHAR: "TEXT",
     92            exp.DataType.Type.NVARCHAR: "TEXT",
     93            exp.DataType.Type.BINARY: "BLOB",
     94            exp.DataType.Type.VARBINARY: "BLOB",
     95        }
     96
     97        TOKEN_MAPPING = {
     98            TokenType.AUTO_INCREMENT: "AUTOINCREMENT",
     99        }
    100
    101        TRANSFORMS = {
    102            **generator.Generator.TRANSFORMS,
    103            exp.Concat: concat_to_dpipe_sql,
    104            exp.CountIf: count_if_to_sum,
    105            exp.Create: transforms.preprocess([_transform_create]),
    106            exp.CurrentDate: lambda *_: "CURRENT_DATE",
    107            exp.CurrentTime: lambda *_: "CURRENT_TIME",
    108            exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP",
    109            exp.DateAdd: _date_add_sql,
    110            exp.DateStrToDate: lambda self, e: self.sql(e, "this"),
    111            exp.ILike: no_ilike_sql,
    112            exp.JSONExtract: arrow_json_extract_sql,
    113            exp.JSONExtractScalar: arrow_json_extract_scalar_sql,
    114            exp.JSONBExtract: arrow_json_extract_sql,
    115            exp.JSONBExtractScalar: arrow_json_extract_scalar_sql,
    116            exp.Levenshtein: rename_func("EDITDIST3"),
    117            exp.LogicalOr: rename_func("MAX"),
    118            exp.LogicalAnd: rename_func("MIN"),
    119            exp.Pivot: no_pivot_sql,
    120            exp.SafeConcat: concat_to_dpipe_sql,
    121            exp.Select: transforms.preprocess(
    122                [transforms.eliminate_distinct_on, transforms.eliminate_qualify]
    123            ),
    124            exp.TableSample: no_tablesample_sql,
    125            exp.TimeStrToTime: lambda self, e: self.sql(e, "this"),
    126            exp.TryCast: no_trycast_sql,
    127        }
    128
    129        PROPERTIES_LOCATION = {
    130            k: exp.Properties.Location.UNSUPPORTED
    131            for k, v in generator.Generator.PROPERTIES_LOCATION.items()
    132        }
    133
    134        LIMIT_FETCH = "LIMIT"
    135
    136        def cast_sql(self, expression: exp.Cast) -> str:
    137            if expression.is_type("date"):
    138                return self.func("DATE", expression.this)
    139
    140            return super().cast_sql(expression)
    141
    142        def datediff_sql(self, expression: exp.DateDiff) -> str:
    143            unit = expression.args.get("unit")
    144            unit = unit.name.upper() if unit else "DAY"
    145
    146            sql = f"(JULIANDAY({self.sql(expression, 'this')}) - JULIANDAY({self.sql(expression, 'expression')}))"
    147
    148            if unit == "MONTH":
    149                sql = f"{sql} / 30.0"
    150            elif unit == "YEAR":
    151                sql = f"{sql} / 365.0"
    152            elif unit == "HOUR":
    153                sql = f"{sql} * 24.0"
    154            elif unit == "MINUTE":
    155                sql = f"{sql} * 1440.0"
    156            elif unit == "SECOND":
    157                sql = f"{sql} * 86400.0"
    158            elif unit == "MILLISECOND":
    159                sql = f"{sql} * 86400000.0"
    160            elif unit == "MICROSECOND":
    161                sql = f"{sql} * 86400000000.0"
    162            elif unit == "NANOSECOND":
    163                sql = f"{sql} * 8640000000000.0"
    164            else:
    165                self.unsupported("DATEDIFF unsupported for '{unit}'.")
    166
    167            return f"CAST({sql} AS INTEGER)"
    168
    169        # https://www.sqlite.org/lang_aggfunc.html#group_concat
    170        def groupconcat_sql(self, expression: exp.GroupConcat) -> str:
    171            this = expression.this
    172            distinct = expression.find(exp.Distinct)
    173
    174            if distinct:
    175                this = distinct.expressions[0]
    176                distinct_sql = "DISTINCT "
    177            else:
    178                distinct_sql = ""
    179
    180            if isinstance(expression.this, exp.Order):
    181                self.unsupported("SQLite GROUP_CONCAT doesn't support ORDER BY.")
    182                if expression.this.this and not distinct:
    183                    this = expression.this.this
    184
    185            separator = expression.args.get("separator")
    186            return f"GROUP_CONCAT({distinct_sql}{self.format_args(this, separator)})"
    187
    188        def least_sql(self, expression: exp.Least) -> str:
    189            if len(expression.expressions) > 1:
    190                return rename_func("MIN")(self, expression)
    191
    192            return self.expressions(expression)
    193
    194        def transaction_sql(self, expression: exp.Transaction) -> str:
    195            this = expression.this
    196            this = f" {this}" if this else ""
    197            return f"BEGIN{this} TRANSACTION"

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

     62class SQLite(Dialect):
     63    # https://sqlite.org/forum/forumpost/5e575586ac5c711b?raw
     64    RESOLVES_IDENTIFIERS_AS_UPPERCASE = None
     65
     66    class Tokenizer(tokens.Tokenizer):
     67        IDENTIFIERS = ['"', ("[", "]"), "`"]
     68        HEX_STRINGS = [("x'", "'"), ("X'", "'"), ("0x", ""), ("0X", "")]
     69
     70    class Parser(parser.Parser):
     71        FUNCTIONS = {
     72            **parser.Parser.FUNCTIONS,
     73            "EDITDIST3": exp.Levenshtein.from_arg_list,
     74        }
     75
     76    class Generator(generator.Generator):
     77        JOIN_HINTS = False
     78        TABLE_HINTS = False
     79
     80        TYPE_MAPPING = {
     81            **generator.Generator.TYPE_MAPPING,
     82            exp.DataType.Type.BOOLEAN: "INTEGER",
     83            exp.DataType.Type.TINYINT: "INTEGER",
     84            exp.DataType.Type.SMALLINT: "INTEGER",
     85            exp.DataType.Type.INT: "INTEGER",
     86            exp.DataType.Type.BIGINT: "INTEGER",
     87            exp.DataType.Type.FLOAT: "REAL",
     88            exp.DataType.Type.DOUBLE: "REAL",
     89            exp.DataType.Type.DECIMAL: "REAL",
     90            exp.DataType.Type.CHAR: "TEXT",
     91            exp.DataType.Type.NCHAR: "TEXT",
     92            exp.DataType.Type.VARCHAR: "TEXT",
     93            exp.DataType.Type.NVARCHAR: "TEXT",
     94            exp.DataType.Type.BINARY: "BLOB",
     95            exp.DataType.Type.VARBINARY: "BLOB",
     96        }
     97
     98        TOKEN_MAPPING = {
     99            TokenType.AUTO_INCREMENT: "AUTOINCREMENT",
    100        }
    101
    102        TRANSFORMS = {
    103            **generator.Generator.TRANSFORMS,
    104            exp.Concat: concat_to_dpipe_sql,
    105            exp.CountIf: count_if_to_sum,
    106            exp.Create: transforms.preprocess([_transform_create]),
    107            exp.CurrentDate: lambda *_: "CURRENT_DATE",
    108            exp.CurrentTime: lambda *_: "CURRENT_TIME",
    109            exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP",
    110            exp.DateAdd: _date_add_sql,
    111            exp.DateStrToDate: lambda self, e: self.sql(e, "this"),
    112            exp.ILike: no_ilike_sql,
    113            exp.JSONExtract: arrow_json_extract_sql,
    114            exp.JSONExtractScalar: arrow_json_extract_scalar_sql,
    115            exp.JSONBExtract: arrow_json_extract_sql,
    116            exp.JSONBExtractScalar: arrow_json_extract_scalar_sql,
    117            exp.Levenshtein: rename_func("EDITDIST3"),
    118            exp.LogicalOr: rename_func("MAX"),
    119            exp.LogicalAnd: rename_func("MIN"),
    120            exp.Pivot: no_pivot_sql,
    121            exp.SafeConcat: concat_to_dpipe_sql,
    122            exp.Select: transforms.preprocess(
    123                [transforms.eliminate_distinct_on, transforms.eliminate_qualify]
    124            ),
    125            exp.TableSample: no_tablesample_sql,
    126            exp.TimeStrToTime: lambda self, e: self.sql(e, "this"),
    127            exp.TryCast: no_trycast_sql,
    128        }
    129
    130        PROPERTIES_LOCATION = {
    131            k: exp.Properties.Location.UNSUPPORTED
    132            for k, v in generator.Generator.PROPERTIES_LOCATION.items()
    133        }
    134
    135        LIMIT_FETCH = "LIMIT"
    136
    137        def cast_sql(self, expression: exp.Cast) -> str:
    138            if expression.is_type("date"):
    139                return self.func("DATE", expression.this)
    140
    141            return super().cast_sql(expression)
    142
    143        def datediff_sql(self, expression: exp.DateDiff) -> str:
    144            unit = expression.args.get("unit")
    145            unit = unit.name.upper() if unit else "DAY"
    146
    147            sql = f"(JULIANDAY({self.sql(expression, 'this')}) - JULIANDAY({self.sql(expression, 'expression')}))"
    148
    149            if unit == "MONTH":
    150                sql = f"{sql} / 30.0"
    151            elif unit == "YEAR":
    152                sql = f"{sql} / 365.0"
    153            elif unit == "HOUR":
    154                sql = f"{sql} * 24.0"
    155            elif unit == "MINUTE":
    156                sql = f"{sql} * 1440.0"
    157            elif unit == "SECOND":
    158                sql = f"{sql} * 86400.0"
    159            elif unit == "MILLISECOND":
    160                sql = f"{sql} * 86400000.0"
    161            elif unit == "MICROSECOND":
    162                sql = f"{sql} * 86400000000.0"
    163            elif unit == "NANOSECOND":
    164                sql = f"{sql} * 8640000000000.0"
    165            else:
    166                self.unsupported("DATEDIFF unsupported for '{unit}'.")
    167
    168            return f"CAST({sql} AS INTEGER)"
    169
    170        # https://www.sqlite.org/lang_aggfunc.html#group_concat
    171        def groupconcat_sql(self, expression: exp.GroupConcat) -> str:
    172            this = expression.this
    173            distinct = expression.find(exp.Distinct)
    174
    175            if distinct:
    176                this = distinct.expressions[0]
    177                distinct_sql = "DISTINCT "
    178            else:
    179                distinct_sql = ""
    180
    181            if isinstance(expression.this, exp.Order):
    182                self.unsupported("SQLite GROUP_CONCAT doesn't support ORDER BY.")
    183                if expression.this.this and not distinct:
    184                    this = expression.this.this
    185
    186            separator = expression.args.get("separator")
    187            return f"GROUP_CONCAT({distinct_sql}{self.format_args(this, separator)})"
    188
    189        def least_sql(self, expression: exp.Least) -> str:
    190            if len(expression.expressions) > 1:
    191                return rename_func("MIN")(self, expression)
    192
    193            return self.expressions(expression)
    194
    195        def transaction_sql(self, expression: exp.Transaction) -> str:
    196            this = expression.this
    197            this = f" {this}" if this else ""
    198            return f"BEGIN{this} TRANSACTION"

##### Inherited Members

sqlglot.dialects.dialect.Dialect
  get_or_raise
  format_time
  normalize_identifier
  case_sensitive
  can_identify
  quote_identifier
  parse
  parse_into
  generate
  transpile
  tokenize
  parser
  generator

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

    66    class Tokenizer(tokens.Tokenizer):
    67        IDENTIFIERS = ['"', ("[", "]"), "`"]
    68        HEX_STRINGS = [("x'", "'"), ("X'", "'"), ("0x", ""), ("0X", "")]

##### Inherited Members

sqlglot.tokens.Tokenizer
  reset
  tokenize
  peek

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

    70    class Parser(parser.Parser):
    71        FUNCTIONS = {
    72            **parser.Parser.FUNCTIONS,
    73            "EDITDIST3": exp.Levenshtein.from_arg_list,
    74        }

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

###### Arguments:

- error_level: The desired error level. Default: ErrorLevel.IMMEDIATE
- error_message_context: Determines the amount of context to capture from a query string when displaying the error message (in number of characters). Default: 100
- 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

##### Inherited Members

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

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

     76    class Generator(generator.Generator):
     77        JOIN_HINTS = False
     78        TABLE_HINTS = False
     79
     80        TYPE_MAPPING = {
     81            **generator.Generator.TYPE_MAPPING,
     82            exp.DataType.Type.BOOLEAN: "INTEGER",
     83            exp.DataType.Type.TINYINT: "INTEGER",
     84            exp.DataType.Type.SMALLINT: "INTEGER",
     85            exp.DataType.Type.INT: "INTEGER",
     86            exp.DataType.Type.BIGINT: "INTEGER",
     87            exp.DataType.Type.FLOAT: "REAL",
     88            exp.DataType.Type.DOUBLE: "REAL",
     89            exp.DataType.Type.DECIMAL: "REAL",
     90            exp.DataType.Type.CHAR: "TEXT",
     91            exp.DataType.Type.NCHAR: "TEXT",
     92            exp.DataType.Type.VARCHAR: "TEXT",
     93            exp.DataType.Type.NVARCHAR: "TEXT",
     94            exp.DataType.Type.BINARY: "BLOB",
     95            exp.DataType.Type.VARBINARY: "BLOB",
     96        }
     97
     98        TOKEN_MAPPING = {
     99            TokenType.AUTO_INCREMENT: "AUTOINCREMENT",
    100        }
    101
    102        TRANSFORMS = {
    103            **generator.Generator.TRANSFORMS,
    104            exp.Concat: concat_to_dpipe_sql,
    105            exp.CountIf: count_if_to_sum,
    106            exp.Create: transforms.preprocess([_transform_create]),
    107            exp.CurrentDate: lambda *_: "CURRENT_DATE",
    108            exp.CurrentTime: lambda *_: "CURRENT_TIME",
    109            exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP",
    110            exp.DateAdd: _date_add_sql,
    111            exp.DateStrToDate: lambda self, e: self.sql(e, "this"),
    112            exp.ILike: no_ilike_sql,
    113            exp.JSONExtract: arrow_json_extract_sql,
    114            exp.JSONExtractScalar: arrow_json_extract_scalar_sql,
    115            exp.JSONBExtract: arrow_json_extract_sql,
    116            exp.JSONBExtractScalar: arrow_json_extract_scalar_sql,
    117            exp.Levenshtein: rename_func("EDITDIST3"),
    118            exp.LogicalOr: rename_func("MAX"),
    119            exp.LogicalAnd: rename_func("MIN"),
    120            exp.Pivot: no_pivot_sql,
    121            exp.SafeConcat: concat_to_dpipe_sql,
    122            exp.Select: transforms.preprocess(
    123                [transforms.eliminate_distinct_on, transforms.eliminate_qualify]
    124            ),
    125            exp.TableSample: no_tablesample_sql,
    126            exp.TimeStrToTime: lambda self, e: self.sql(e, "this"),
    127            exp.TryCast: no_trycast_sql,
    128        }
    129
    130        PROPERTIES_LOCATION = {
    131            k: exp.Properties.Location.UNSUPPORTED
    132            for k, v in generator.Generator.PROPERTIES_LOCATION.items()
    133        }
    134
    135        LIMIT_FETCH = "LIMIT"
    136
    137        def cast_sql(self, expression: exp.Cast) -> str:
    138            if expression.is_type("date"):
    139                return self.func("DATE", expression.this)
    140
    141            return super().cast_sql(expression)
    142
    143        def datediff_sql(self, expression: exp.DateDiff) -> str:
    144            unit = expression.args.get("unit")
    145            unit = unit.name.upper() if unit else "DAY"
    146
    147            sql = f"(JULIANDAY({self.sql(expression, 'this')}) - JULIANDAY({self.sql(expression, 'expression')}))"
    148
    149            if unit == "MONTH":
    150                sql = f"{sql} / 30.0"
    151            elif unit == "YEAR":
    152                sql = f"{sql} / 365.0"
    153            elif unit == "HOUR":
    154                sql = f"{sql} * 24.0"
    155            elif unit == "MINUTE":
    156                sql = f"{sql} * 1440.0"
    157            elif unit == "SECOND":
    158                sql = f"{sql} * 86400.0"
    159            elif unit == "MILLISECOND":
    160                sql = f"{sql} * 86400000.0"
    161            elif unit == "MICROSECOND":
    162                sql = f"{sql} * 86400000000.0"
    163            elif unit == "NANOSECOND":
    164                sql = f"{sql} * 8640000000000.0"
    165            else:
    166                self.unsupported("DATEDIFF unsupported for '{unit}'.")
    167
    168            return f"CAST({sql} AS INTEGER)"
    169
    170        # https://www.sqlite.org/lang_aggfunc.html#group_concat
    171        def groupconcat_sql(self, expression: exp.GroupConcat) -> str:
    172            this = expression.this
    173            distinct = expression.find(exp.Distinct)
    174
    175            if distinct:
    176                this = distinct.expressions[0]
    177                distinct_sql = "DISTINCT "
    178            else:
    179                distinct_sql = ""
    180
    181            if isinstance(expression.this, exp.Order):
    182                self.unsupported("SQLite GROUP_CONCAT doesn't support ORDER BY.")
    183                if expression.this.this and not distinct:
    184                    this = expression.this.this
    185
    186            separator = expression.args.get("separator")
    187            return f"GROUP_CONCAT({distinct_sql}{self.format_args(this, separator)})"
    188
    189        def least_sql(self, expression: exp.Least) -> str:
    190            if len(expression.expressions) > 1:
    191                return rename_func("MIN")(self, expression)
    192
    193            return self.expressions(expression)
    194
    195        def transaction_sql(self, expression: exp.Transaction) -> str:
    196            this = expression.this
    197            this = f" {this}" if this else ""
    198            return f"BEGIN{this} TRANSACTION"

Generator converts a given syntax tree to the corresponding SQL string.

###### Arguments:

- pretty: Whether or not to format the produced SQL string. Default: False.
- identify: Determines when an identifier should be quoted. Possible values are: False (default): Never quote, except in cases where it's mandatory by the dialect. True or 'always': Always quote. 'safe': Only quote identifiers that are case insensitive.
- normalize: Whether or not to normalize identifiers to lowercase. Default: False.
- pad: Determines the pad size in a formatted string. Default: 2.
- indent: Determines the indentation size in a formatted string. Default: 2.
- normalize_functions: Whether or not to normalize all function names. Possible values are: "upper" or True (default): Convert names to uppercase. "lower": Convert names to lowercase. False: Disables function name normalization.
- unsupported_level: Determines the generator's behavior when it encounters unsupported expressions. Default ErrorLevel.WARN.
- max_unsupported: 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: Determines whether or not the comma is leading or trailing in select expressions. This is only relevant when generating in pretty mode. 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 cast_sql(self, expression: sqlglot.expressions.Cast) -> str: View Source

    137        def cast_sql(self, expression: exp.Cast) -> str:
    138            if expression.is_type("date"):
    139                return self.func("DATE", expression.this)
    140
    141            return super().cast_sql(expression)

def datediff_sql(self, expression: sqlglot.expressions.DateDiff) -> str: View Source

    143        def datediff_sql(self, expression: exp.DateDiff) -> str:
    144            unit = expression.args.get("unit")
    145            unit = unit.name.upper() if unit else "DAY"
    146
    147            sql = f"(JULIANDAY({self.sql(expression, 'this')}) - JULIANDAY({self.sql(expression, 'expression')}))"
    148
    149            if unit == "MONTH":
    150                sql = f"{sql} / 30.0"
    151            elif unit == "YEAR":
    152                sql = f"{sql} / 365.0"
    153            elif unit == "HOUR":
    154                sql = f"{sql} * 24.0"
    155            elif unit == "MINUTE":
    156                sql = f"{sql} * 1440.0"
    157            elif unit == "SECOND":
    158                sql = f"{sql} * 86400.0"
    159            elif unit == "MILLISECOND":
    160                sql = f"{sql} * 86400000.0"
    161            elif unit == "MICROSECOND":
    162                sql = f"{sql} * 86400000000.0"
    163            elif unit == "NANOSECOND":
    164                sql = f"{sql} * 8640000000000.0"
    165            else:
    166                self.unsupported("DATEDIFF unsupported for '{unit}'.")
    167
    168            return f"CAST({sql} AS INTEGER)"

def groupconcat_sql(self, expression: sqlglot.expressions.GroupConcat) -> str: View Source

    171        def groupconcat_sql(self, expression: exp.GroupConcat) -> str:
    172            this = expression.this
    173            distinct = expression.find(exp.Distinct)
    174
    175            if distinct:
    176                this = distinct.expressions[0]
    177                distinct_sql = "DISTINCT "
    178            else:
    179                distinct_sql = ""
    180
    181            if isinstance(expression.this, exp.Order):
    182                self.unsupported("SQLite GROUP_CONCAT doesn't support ORDER BY.")
    183                if expression.this.this and not distinct:
    184                    this = expression.this.this
    185
    186            separator = expression.args.get("separator")
    187            return f"GROUP_CONCAT({distinct_sql}{self.format_args(this, separator)})"

def least_sql(self, expression: sqlglot.expressions.Least) -> str: View Source

    189        def least_sql(self, expression: exp.Least) -> str:
    190            if len(expression.expressions) > 1:
    191                return rename_func("MIN")(self, expression)
    192
    193            return self.expressions(expression)

def transaction_sql(self, expression: sqlglot.expressions.Transaction) -> str: View Source

    195        def transaction_sql(self, expression: exp.Transaction) -> str:
    196            this = expression.this
    197            this = f" {this}" if this else ""
    198            return f"BEGIN{this} TRANSACTION"

@classmethod
def can_identify(text: str, identify: str | bool = 'safe') -> bool: View Source

    247    @classmethod
    248    def can_identify(cls, text: str, identify: str | bool = "safe") -> bool:
    249        """Checks if text can be identified given an identify option.
    250
    251        Args:
    252            text: The text to check.
    253            identify:
    254                "always" or `True`: Always returns true.
    255                "safe": True if the identifier is case-insensitive.
    256
    257        Returns:
    258            Whether or not the given text can be identified.
    259        """
    260        if identify is True or identify == "always":
    261            return True
    262
    263        if identify == "safe":
    264            return not cls.case_sensitive(text)
    265
    266        return False

Checks if text can be identified given an identify option.

###### Arguments:

- text: The text to check.
- identify: "always" or `True`: Always returns true. "safe": True if the identifier is case-insensitive.

###### Returns:

> Whether or not the given text can be identified.

##### 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
  columnposition_sql
  columndef_sql
  columnconstraint_sql
  autoincrementcolumnconstraint_sql
  compresscolumnconstraint_sql
  generatedasidentitycolumnconstraint_sql
  notnullcolumnconstraint_sql
  primarykeycolumnconstraint_sql
  uniquecolumnconstraint_sql
  createable_sql
  create_sql
  clone_sql
  describe_sql
  prepend_ctes
  with_sql
  cte_sql
  tablealias_sql
  bitstring_sql
  hexstring_sql
  bytestring_sql
  rawstring_sql
  datatypesize_sql
  datatype_sql
  directory_sql
  delete_sql
  drop_sql
  except_sql
  except_op
  fetch_sql
  filter_sql
  hint_sql
  index_sql
  identifier_sql
  inputoutputformat_sql
  national_sql
  partition_sql
  properties_sql
  root_properties
  properties
  with_properties
  locate_properties
  property_sql
  likeproperty_sql
  fallbackproperty_sql
  journalproperty_sql
  freespaceproperty_sql
  checksumproperty_sql
  mergeblockratioproperty_sql
  datablocksizeproperty_sql
  blockcompressionproperty_sql
  isolatedloadingproperty_sql
  lockingproperty_sql
  withdataproperty_sql
  insert_sql
  intersect_sql
  intersect_op
  introducer_sql
  pseudotype_sql
  onconflict_sql
  returning_sql
  rowformatdelimitedproperty_sql
  table_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
  offset_sql
  setitem_sql
  set_sql
  pragma_sql
  lock_sql
  literal_sql
  escape_str
  loaddata_sql
  null_sql
  boolean_sql
  order_sql
  cluster_sql
  distribute_sql
  sort_sql
  ordered_sql
  matchrecognize_sql
  query_modifiers
  offset_limit_modifiers
  after_having_modifiers
  after_limit_modifiers
  select_sql
  schema_sql
  schema_columns_sql
  star_sql
  parameter_sql
  sessionparameter_sql
  placeholder_sql
  subquery_sql
  qualify_sql
  union_sql
  union_op
  unnest_sql
  where_sql
  window_sql
  partition_by_sql
  windowspec_sql
  withingroup_sql
  between_sql
  bracket_sql
  all_sql
  any_sql
  exists_sql
  case_sql
  constraint_sql
  nextvaluefor_sql
  extract_sql
  trim_sql
  safeconcat_sql
  check_sql
  foreignkey_sql
  primarykey_sql
  if_sql
  matchagainst_sql
  jsonkeyvalue_sql
  jsonobject_sql
  openjsoncolumndef_sql
  openjson_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
  currentdate_sql
  collate_sql
  command_sql
  comment_sql
  mergetreettlaction_sql
  mergetreettl_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
  safedpipe_sql
  div_sql
  overlaps_sql
  distance_sql
  dot_sql
  eq_sql
  escape_sql
  glob_sql
  gt_sql
  gte_sql
  ilike_sql
  ilikeany_sql
  is_sql
  like_sql
  likeany_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
  func
  format_args
  text_width
  format_time
  expressions
  op_expressions
  naked_property
  set_operation
  tag_sql
  token_sql
  userdefinedfunction_sql
  joinhint_sql
  kwarg_sql
  when_sql
  merge_sql
  tochar_sql
  dictproperty_sql
  dictrange_sql
  dictsubproperty_sql
  oncluster_sql