在GitHub上编辑

SQLGlot logo

SQLGlot是一个无依赖的SQL解析器、转换器、优化器和执行引擎。它可以用于格式化SQL或在24种不同方言之间进行转换,例如DuckDBPresto/TrinoSpark/DatabricksSnowflakeBigQuery。它的目标是读取各种SQL输入,并以目标方言输出语法和语义都正确的SQL。

这是一个非常全面的通用SQL解析器,拥有强大的测试套件。虽然完全用Python编写,但它也相当高性能

您可以轻松自定义解析器,分析查询,遍历表达式树,并以编程方式构建SQL。

SQLGlot可以检测多种语法错误,例如不平衡的括号、保留关键字的不正确使用等。这些错误会被高亮显示,根据配置不同,方言不兼容问题可以发出警告或引发错误。

了解更多关于SQLGlot的信息,请参阅API文档和表达式树入门指南

我们非常欢迎您为SQLGlot做出贡献;请阅读贡献指南入门文档开始参与!

目录

安装

来自PyPI:

pip3 install "sqlglot[rs]"

# Without Rust tokenizer (slower):
# pip3 install sqlglot

或者使用本地检出:

make install

开发要求(可选):

make install-dev

版本控制

给定一个版本号 MAJOR.MINOR.PATCH,SQLGlot 采用以下版本控制策略:

  • 当有向后兼容的修复或功能添加时,PATCH版本号会增加。
  • 当出现不向后兼容的修复或功能添加时,MINOR版本号会增加。
  • 当有重大不兼容修复或功能添加时,MAJOR版本号会增加。

联系我们

我们很乐意听取您的意见。加入我们的社区Slack频道

常见问题

我尝试解析本应有效的SQL语句但失败了,为什么会发生这种情况?

  • 大多数情况下,这类问题的发生是因为在解析过程中忽略了"源"方言。例如,以下是正确解析用Spark SQL编写的SQL查询的方法:parse_one(sql, dialect="spark")(或者:read="spark")。如果未指定方言,parse_one将尝试按照"SQLGlot方言"来解析查询,该方言设计为所有支持方言的超集。如果您已尝试指定方言但仍无法工作,请提交问题。

我尝试输出SQL,但它不是正确的方言!

  • 与解析类似,生成SQL也需要指定目标方言,否则默认会使用SQLGlot方言。例如,要将查询从Spark SQL转换为DuckDB,可以执行parse_one(sql, dialect="spark").sql(dialect="duckdb")(或者:transpile(sql, read="spark", write="duckdb"))。

sqlglot.dataframe发生了什么?

  • PySpark数据框API在v24版本中被移到了一个名为SQLFrame的独立库中。现在它允许您运行查询,而不仅仅是生成SQL。

示例

格式化与转译

轻松实现不同SQL方言之间的转换。例如,日期/时间函数在不同方言中存在差异,处理起来可能较为困难:

import sqlglot
sqlglot.transpile("SELECT EPOCH_MS(1618088028295)", read="duckdb", write="hive")[0]
'SELECT FROM_UNIXTIME(1618088028295 / POW(10, 3))'

SQLGlot 甚至可以转换自定义时间格式:

import sqlglot
sqlglot.transpile("SELECT STRFTIME(x, '%y-%-m-%S')", read="duckdb", write="hive")[0]
"SELECT DATE_FORMAT(x, 'yy-M-ss')"

标识符分隔符和数据类型也可以进行转换:

import sqlglot

# Spark SQL requires backticks (`) for delimited identifiers and uses `FLOAT` over `REAL`
sql = """WITH baz AS (SELECT a, c FROM foo WHERE a = 1) SELECT f.a, b.b, baz.c, CAST("b"."a" AS REAL) d FROM foo f JOIN bar b ON f.a = b.a LEFT JOIN baz ON f.a = baz.a"""

# Translates the query into Spark SQL, formats it, and delimits all of its identifiers
print(sqlglot.transpile(sql, write="spark", identify=True, pretty=True)[0])
WITH `baz` AS (
  SELECT
    `a`,
    `c`
  FROM `foo`
  WHERE
    `a` = 1
)
SELECT
  `f`.`a`,
  `b`.`b`,
  `baz`.`c`,
  CAST(`b`.`a` AS FLOAT) AS `d`
FROM `foo` AS `f`
JOIN `bar` AS `b`
  ON `f`.`a` = `b`.`a`
LEFT JOIN `baz`
  ON `f`.`a` = `baz`.`a`

注释也会在最大努力的基础上被保留:

sql = """
/* multi
   line
   comment
*/
SELECT
  tbl.cola /* comment 1 */ + tbl.colb /* comment 2 */,
  CAST(x AS SIGNED), # comment 3
  y               -- comment 4
FROM
  bar /* comment 5 */,
  tbl #          comment 6
"""

# Note: MySQL-specific comments (`#`) are converted into standard syntax
print(sqlglot.transpile(sql, read='mysql', pretty=True)[0])
/* multi
   line
   comment
*/
SELECT
  tbl.cola /* comment 1 */ + tbl.colb /* comment 2 */,
  CAST(x AS INT), /* comment 3 */
  y /* comment 4 */
FROM bar /* comment 5 */, tbl /*          comment 6 */

元数据

您可以通过表达式辅助工具探索SQL,例如在查询中查找列和表:

from sqlglot import parse_one, exp

# print all column references (a and b)
for column in parse_one("SELECT a, b + 1 AS c FROM d").find_all(exp.Column):
    print(column.alias_or_name)

# find all projections in select statements (a and c)
for select in parse_one("SELECT a, b + 1 AS c FROM d").find_all(exp.Select):
    for projection in select.expressions:
        print(projection.alias_or_name)

# find all tables (x, y, z)
for table in parse_one("SELECT * FROM x JOIN y JOIN z").find_all(exp.Table):
    print(table.name)

阅读ast primer以了解更多关于SQLGlot的内部工作原理。

解析器错误

当解析器检测到语法错误时,它会抛出一个ParseError错误:

import sqlglot
sqlglot.transpile("SELECT foo FROM (SELECT baz FROM t")
sqlglot.errors.ParseError: Expecting ). Line 1, Col: 34.
  SELECT foo FROM (SELECT baz FROM t
                                   ~

结构化语法错误可供编程使用:

import sqlglot
try:
    sqlglot.transpile("SELECT foo FROM (SELECT baz FROM t")
except sqlglot.errors.ParseError as e:
    print(e.errors)
[{
  'description': 'Expecting )',
  'line': 1,
  'col': 34,
  'start_context': 'SELECT foo FROM (SELECT baz FROM ',
  'highlight': 't',
  'end_context': '',
  'into_expression': None
}]

不支持的报错

It may not be possible to translate some queries between certain dialects. For these cases, SQLGlot may emit a warning and will proceed to do a best-effort translation by default:

import sqlglot
sqlglot.transpile("SELECT APPROX_DISTINCT(a, 0.1) FROM foo", read="presto", write="hive")
APPROX_COUNT_DISTINCT does not support accuracy
'SELECT APPROX_COUNT_DISTINCT(a) FROM foo'

可以通过设置unsupported_level属性来改变此行为。例如,我们可以将其设置为RAISEIMMEDIATE以确保抛出异常:

import sqlglot
sqlglot.transpile("SELECT APPROX_DISTINCT(a, 0.1) FROM foo", read="presto", write="hive", unsupported_level=sqlglot.ErrorLevel.RAISE)
sqlglot.errors.UnsupportedError: APPROX_COUNT_DISTINCT does not support accuracy

有些查询需要额外信息才能准确转译,例如查询中引用的表结构信息。这是因为某些转换是类型敏感的,意味着需要类型推断才能理解其语义。虽然qualifyannotate_types优化器规则可以辅助处理这种情况,但默认情况下不会启用它们,因为它们会带来显著的性能开销和复杂性。

SQL转译通常是一个复杂的问题,因此SQLGlot采用"渐进式"方法来解决。这意味着目前某些方言组合可能缺乏对部分输入的支持,但预计这种情况会随着时间推移而改善。我们非常欢迎有详细文档说明和经过测试的问题或PR,如需指导请随时联系我们

构建和修改SQL

SQLGlot支持逐步构建SQL表达式:

from sqlglot import select, condition

where = condition("x=1").and_("y=1")
select("*").from_("y").where(where).sql()
'SELECT * FROM y WHERE x = 1 AND y = 1'

可以修改解析后的语法树:

from sqlglot import parse_one
parse_one("SELECT x FROM y").from_("z").sql()
'SELECT x FROM z'

解析后的表达式也可以通过向树中的每个节点应用映射函数来进行递归转换:

from sqlglot import exp, parse_one

expression_tree = parse_one("SELECT a FROM x")

def transformer(node):
    if isinstance(node, exp.Column) and node.name == "a":
        return parse_one("FUN(a)")
    return node

transformed_tree = expression_tree.transform(transformer)
transformed_tree.sql()
'SELECT FUN(a) FROM x'

SQL优化器

SQLGlot可以将查询重写为"优化"形式。它运用多种技术来创建新的规范AST。这个AST可用于标准化查询或为实现实际引擎奠定基础。例如:

import sqlglot
from sqlglot.optimizer import optimize

print(
    optimize(
        sqlglot.parse_one("""
            SELECT A OR (B OR (C AND D))
            FROM x
            WHERE Z = date '2021-01-01' + INTERVAL '1' month OR 1 = 0
        """),
        schema={"x": {"A": "INT", "B": "INT", "C": "INT", "D": "INT", "Z": "STRING"}}
    ).sql(pretty=True)
)
SELECT
  (
    "x"."a" <> 0 OR "x"."b" <> 0 OR "x"."c" <> 0
  )
  AND (
    "x"."a" <> 0 OR "x"."b" <> 0 OR "x"."d" <> 0
  ) AS "_col_0"
FROM "x" AS "x"
WHERE
  CAST("x"."z" AS DATE) = CAST('2021-02-01' AS DATE)

AST 内省

您可以通过调用repr来查看解析后SQL的AST版本:

from sqlglot import parse_one
print(repr(parse_one("SELECT a + 1 AS z")))
Select(
  expressions=[
    Alias(
      this=Add(
        this=Column(
          this=Identifier(this=a, quoted=False)),
        expression=Literal(this=1, is_string=False)),
      alias=Identifier(this=z, quoted=False))])

AST差异

SQLGlot可以计算两个表达式之间的语义差异,并以将源表达式转换为目标表达式所需的一系列操作的形式输出变更:

from sqlglot import diff, parse_one
diff(parse_one("SELECT a + b, c, d"), parse_one("SELECT c, a - b, d"))
[
  Remove(expression=Add(
    this=Column(
      this=Identifier(this=a, quoted=False)),
    expression=Column(
      this=Identifier(this=b, quoted=False)))),
  Insert(expression=Sub(
    this=Column(
      this=Identifier(this=a, quoted=False)),
    expression=Column(
      this=Identifier(this=b, quoted=False)))),
  Keep(
    source=Column(this=Identifier(this=a, quoted=False)),
    target=Column(this=Identifier(this=a, quoted=False))),
  ...
]

另请参阅:SQL语义差异

自定义方言

Dialects 可以通过继承 Dialect 类来添加:

from sqlglot import exp
from sqlglot.dialects.dialect import Dialect
from sqlglot.generator import Generator
from sqlglot.tokens import Tokenizer, TokenType


class Custom(Dialect):
    class Tokenizer(Tokenizer):
        QUOTES = ["'", '"']
        IDENTIFIERS = ["`"]

        KEYWORDS = {
            **Tokenizer.KEYWORDS,
            "INT64": TokenType.BIGINT,
            "FLOAT64": TokenType.DOUBLE,
        }

    class Generator(Generator):
        TRANSFORMS = {exp.Array: lambda self, e: f"[{self.expressions(e)}]"}

        TYPE_MAPPING = {
            exp.DataType.Type.TINYINT: "INT64",
            exp.DataType.Type.SMALLINT: "INT64",
            exp.DataType.Type.INT: "INT64",
            exp.DataType.Type.BIGINT: "INT64",
            exp.DataType.Type.DECIMAL: "NUMERIC",
            exp.DataType.Type.FLOAT: "FLOAT64",
            exp.DataType.Type.DOUBLE: "FLOAT64",
            exp.DataType.Type.BOOLEAN: "BOOL",
            exp.DataType.Type.TEXT: "STRING",
        }

print(Dialect["custom"])
<class '__main__.Custom'>

SQL执行

SQLGlot能够解析SQL查询,其中表被表示为Python字典。该引擎并不追求速度,但对于单元测试和在Python对象上原生运行SQL非常有用。此外,其基础可以轻松与快速计算内核(如ArrowPandas)集成。

下面的示例展示了一个涉及聚合和连接操作的查询执行:

from sqlglot.executor import execute

tables = {
    "sushi": [
        {"id": 1, "price": 1.0},
        {"id": 2, "price": 2.0},
        {"id": 3, "price": 3.0},
    ],
    "order_items": [
        {"sushi_id": 1, "order_id": 1},
        {"sushi_id": 1, "order_id": 1},
        {"sushi_id": 2, "order_id": 1},
        {"sushi_id": 3, "order_id": 2},
    ],
    "orders": [
        {"id": 1, "user_id": 1},
        {"id": 2, "user_id": 2},
    ],
}

execute(
    """
    SELECT
      o.user_id,
      SUM(s.price) AS price
    FROM orders o
    JOIN order_items i
      ON o.id = i.order_id
    JOIN sushi s
      ON i.sushi_id = s.id
    GROUP BY o.user_id
    """,
    tables=tables
)
user_id price
      1   4.0
      2   3.0

另请参阅:Writing a Python SQL engine from scratch

使用者

文档

SQLGlot使用pdoc来提供其API文档。

托管版本可在SQLGlot网站上获取,或者您可以通过以下方式在本地构建:

make docs-serve

运行测试与代码检查

make style  # Only linter checks
make unit   # Only unit tests (or unit-rs, to use the Rust tokenizer)
make test   # Unit and integration tests (or test-rs, to use the Rust tokenizer)
make check  # Full test suite & linter checks

基准测试

Benchmarks 在Python 3.10.12上运行的基准测试结果(单位为秒)。

查询 sqlglot sqlglotrs sqlfluff sqltree sqlparse moz_sql_parser sqloxide
tpch 0.00944 (1.0) 0.00590 (0.625) 0.32116 (33.98) 0.00693 (0.734) 0.02858 (3.025) 0.03337 (3.532) 0.00073 (0.077)
short 0.00065 (1.0) 0.00044 (0.687) 0.03511 (53.82) 0.00049 (0.759) 0.00163 (2.506) 0.00234 (3.601) 0.00005 (0.073)
long 0.00889 (1.0) 0.00572 (0.643) 0.36982 (41.56) 0.00614 (0.690) 0.02530 (2.844) 0.02931 (3.294) 0.00059 (0.066)
crazy 0.02918 (1.0) 0.01991 (0.682) 1.88695 (64.66) 0.02003 (0.686) 7.46894 (255.9) 0.64994 (22.27) 0.00327 (0.112)

可选依赖项

SQLGlot使用dateutil来简化字面时间差表达式。如果找不到该模块,优化器将不会简化如下表达式:

x + interval '1' month

  1# ruff: noqa: F401
  2"""
  3.. include:: ../README.md
  4
  5----
  6"""
  7
  8from __future__ import annotations
  9
 10import logging
 11import typing as t
 12
 13from sqlglot import expressions as exp
 14from sqlglot.dialects.dialect import Dialect as Dialect, Dialects as Dialects
 15from sqlglot.diff import diff as diff
 16from sqlglot.errors import (
 17    ErrorLevel as ErrorLevel,
 18    ParseError as ParseError,
 19    TokenError as TokenError,
 20    UnsupportedError as UnsupportedError,
 21)
 22from sqlglot.expressions import (
 23    Expression as Expression,
 24    alias_ as alias,
 25    and_ as and_,
 26    case as case,
 27    cast as cast,
 28    column as column,
 29    condition as condition,
 30    delete as delete,
 31    except_ as except_,
 32    from_ as from_,
 33    func as func,
 34    insert as insert,
 35    intersect as intersect,
 36    maybe_parse as maybe_parse,
 37    merge as merge,
 38    not_ as not_,
 39    or_ as or_,
 40    select as select,
 41    subquery as subquery,
 42    table_ as table,
 43    to_column as to_column,
 44    to_identifier as to_identifier,
 45    to_table as to_table,
 46    union as union,
 47)
 48from sqlglot.generator import Generator as Generator
 49from sqlglot.parser import Parser as Parser
 50from sqlglot.schema import MappingSchema as MappingSchema, Schema as Schema
 51from sqlglot.tokens import Token as Token, Tokenizer as Tokenizer, TokenType as TokenType
 52
 53if t.TYPE_CHECKING:
 54    from sqlglot._typing import E
 55    from sqlglot.dialects.dialect import DialectType as DialectType
 56
 57logger = logging.getLogger("sqlglot")
 58
 59
 60try:
 61    from sqlglot._version import __version__, __version_tuple__
 62except ImportError:
 63    logger.error(
 64        "Unable to set __version__, run `pip install -e .` or `python setup.py develop` first."
 65    )
 66
 67
 68pretty = False
 69"""Whether to format generated SQL by default."""
 70
 71
 72def tokenize(sql: str, read: DialectType = None, dialect: DialectType = None) -> t.List[Token]:
 73    """
 74    Tokenizes the given SQL string.
 75
 76    Args:
 77        sql: the SQL code string to tokenize.
 78        read: the SQL dialect to apply during tokenizing (eg. "spark", "hive", "presto", "mysql").
 79        dialect: the SQL dialect (alias for read).
 80
 81    Returns:
 82        The resulting list of tokens.
 83    """
 84    return Dialect.get_or_raise(read or dialect).tokenize(sql)
 85
 86
 87def parse(
 88    sql: str, read: DialectType = None, dialect: DialectType = None, **opts
 89) -> t.List[t.Optional[Expression]]:
 90    """
 91    Parses the given SQL string into a collection of syntax trees, one per parsed SQL statement.
 92
 93    Args:
 94        sql: the SQL code string to parse.
 95        read: the SQL dialect to apply during parsing (eg. "spark", "hive", "presto", "mysql").
 96        dialect: the SQL dialect (alias for read).
 97        **opts: other `sqlglot.parser.Parser` options.
 98
 99    Returns:
100        The resulting syntax tree collection.
101    """
102    return Dialect.get_or_raise(read or dialect).parse(sql, **opts)
103
104
105@t.overload
106def parse_one(sql: str, *, into: t.Type[E], **opts) -> E: ...
107
108
109@t.overload
110def parse_one(sql: str, **opts) -> Expression: ...
111
112
113def parse_one(
114    sql: str,
115    read: DialectType = None,
116    dialect: DialectType = None,
117    into: t.Optional[exp.IntoType] = None,
118    **opts,
119) -> Expression:
120    """
121    Parses the given SQL string and returns a syntax tree for the first parsed SQL statement.
122
123    Args:
124        sql: the SQL code string to parse.
125        read: the SQL dialect to apply during parsing (eg. "spark", "hive", "presto", "mysql").
126        dialect: the SQL dialect (alias for read)
127        into: the SQLGlot Expression to parse into.
128        **opts: other `sqlglot.parser.Parser` options.
129
130    Returns:
131        The syntax tree for the first parsed statement.
132    """
133
134    dialect = Dialect.get_or_raise(read or dialect)
135
136    if into:
137        result = dialect.parse_into(into, sql, **opts)
138    else:
139        result = dialect.parse(sql, **opts)
140
141    for expression in result:
142        if not expression:
143            raise ParseError(f"No expression was parsed from '{sql}'")
144        return expression
145    else:
146        raise ParseError(f"No expression was parsed from '{sql}'")
147
148
149def transpile(
150    sql: str,
151    read: DialectType = None,
152    write: DialectType = None,
153    identity: bool = True,
154    error_level: t.Optional[ErrorLevel] = None,
155    **opts,
156) -> t.List[str]:
157    """
158    Parses the given SQL string in accordance with the source dialect and returns a list of SQL strings transformed
159    to conform to the target dialect. Each string in the returned list represents a single transformed SQL statement.
160
161    Args:
162        sql: the SQL code string to transpile.
163        read: the source dialect used to parse the input string (eg. "spark", "hive", "presto", "mysql").
164        write: the target dialect into which the input should be transformed (eg. "spark", "hive", "presto", "mysql").
165        identity: if set to `True` and if the target dialect is not specified the source dialect will be used as both:
166            the source and the target dialect.
167        error_level: the desired error level of the parser.
168        **opts: other `sqlglot.generator.Generator` options.
169
170    Returns:
171        The list of transpiled SQL statements.
172    """
173    write = (read if write is None else write) if identity else write
174    write = Dialect.get_or_raise(write)
175    return [
176        write.generate(expression, copy=False, **opts) if expression else ""
177        for expression in parse(sql, read, error_level=error_level)
178    ]
日志记录器 =
美化 = False

是否默认格式化生成的SQL。

def tokenize( sql: str, read: Union[str, sqlglot.dialects.Dialect, Type[sqlglot.dialects.Dialect], NoneType] = None, dialect: Union[str, sqlglot.dialects.Dialect, Type[sqlglot.dialects.Dialect], NoneType] = None) -> List[sqlglot.tokens.Token]:
73def tokenize(sql: str, read: DialectType = None, dialect: DialectType = None) -> t.List[Token]:
74    """
75    Tokenizes the given SQL string.
76
77    Args:
78        sql: the SQL code string to tokenize.
79        read: the SQL dialect to apply during tokenizing (eg. "spark", "hive", "presto", "mysql").
80        dialect: the SQL dialect (alias for read).
81
82    Returns:
83        The resulting list of tokens.
84    """
85    return Dialect.get_or_raise(read or dialect).tokenize(sql)

对给定的SQL字符串进行词法分析。

参数:
  • sql: 要标记化的SQL代码字符串。
  • read: 在标记化过程中要应用的SQL方言(例如:"spark"、"hive"、"presto"、"mysql")。
  • dialect: SQL方言(read的别名)。
返回值:

生成的令牌列表。

def 解析( sql: str, read: Union[str, sqlglot.dialects.Dialect, Type[sqlglot.dialects.Dialect], NoneType] = None, dialect: Union[str, sqlglot.dialects.Dialect, Type[sqlglot.dialects.Dialect], NoneType] = None, **opts) -> List[Optional[sqlglot.expressions.Expression]]:
 88def parse(
 89    sql: str, read: DialectType = None, dialect: DialectType = None, **opts
 90) -> t.List[t.Optional[Expression]]:
 91    """
 92    Parses the given SQL string into a collection of syntax trees, one per parsed SQL statement.
 93
 94    Args:
 95        sql: the SQL code string to parse.
 96        read: the SQL dialect to apply during parsing (eg. "spark", "hive", "presto", "mysql").
 97        dialect: the SQL dialect (alias for read).
 98        **opts: other `sqlglot.parser.Parser` options.
 99
100    Returns:
101        The resulting syntax tree collection.
102    """
103    return Dialect.get_or_raise(read or dialect).parse(sql, **opts)

将给定的SQL字符串解析为语法树集合,每个解析的SQL语句对应一棵语法树。

参数:
  • sql: 要解析的SQL代码字符串。
  • read: 解析时应用的SQL方言(例如:"spark", "hive", "presto", "mysql")。
  • dialect: SQL方言(read的别名)。
  • **opts: 其他 sqlglot.parser.Parser 选项。
返回值:

生成的语法树集合。

def parse_one( sql: str, read: Union[str, sqlglot.dialects.Dialect, Type[sqlglot.dialects.Dialect], NoneType] = None, dialect: Union[str, sqlglot.dialects.Dialect, Type[sqlglot.dialects.Dialect], NoneType] = None, into: Union[str, Type[sqlglot.expressions.Expression], Collection[Union[str, Type[sqlglot.expressions.Expression]]], NoneType] = None, **opts) -> sqlglot.expressions.Expression:
114def parse_one(
115    sql: str,
116    read: DialectType = None,
117    dialect: DialectType = None,
118    into: t.Optional[exp.IntoType] = None,
119    **opts,
120) -> Expression:
121    """
122    Parses the given SQL string and returns a syntax tree for the first parsed SQL statement.
123
124    Args:
125        sql: the SQL code string to parse.
126        read: the SQL dialect to apply during parsing (eg. "spark", "hive", "presto", "mysql").
127        dialect: the SQL dialect (alias for read)
128        into: the SQLGlot Expression to parse into.
129        **opts: other `sqlglot.parser.Parser` options.
130
131    Returns:
132        The syntax tree for the first parsed statement.
133    """
134
135    dialect = Dialect.get_or_raise(read or dialect)
136
137    if into:
138        result = dialect.parse_into(into, sql, **opts)
139    else:
140        result = dialect.parse(sql, **opts)
141
142    for expression in result:
143        if not expression:
144            raise ParseError(f"No expression was parsed from '{sql}'")
145        return expression
146    else:
147        raise ParseError(f"No expression was parsed from '{sql}'")

解析给定的SQL字符串并返回第一个解析的SQL语句的语法树。

参数:
  • sql: 要解析的SQL代码字符串。
  • read: 在解析过程中应用的SQL方言(例如:"spark"、"hive"、"presto"、"mysql")。
  • dialect: SQL方言(是read的别名)
  • into: 要解析为的SQLGlot表达式。
  • **opts: 其他 sqlglot.parser.Parser 选项。
返回值:

第一个解析语句的语法树。

def 转译( sql: str, read: Union[str, sqlglot.dialects.Dialect, Type[sqlglot.dialects.Dialect], NoneType] = None, write: Union[str, sqlglot.dialects.Dialect, Type[sqlglot.dialects.Dialect], NoneType] = None, identity: bool = True, error_level: Optional[sqlglot.errors.ErrorLevel] = None, **opts) -> List[str]:
150def transpile(
151    sql: str,
152    read: DialectType = None,
153    write: DialectType = None,
154    identity: bool = True,
155    error_level: t.Optional[ErrorLevel] = None,
156    **opts,
157) -> t.List[str]:
158    """
159    Parses the given SQL string in accordance with the source dialect and returns a list of SQL strings transformed
160    to conform to the target dialect. Each string in the returned list represents a single transformed SQL statement.
161
162    Args:
163        sql: the SQL code string to transpile.
164        read: the source dialect used to parse the input string (eg. "spark", "hive", "presto", "mysql").
165        write: the target dialect into which the input should be transformed (eg. "spark", "hive", "presto", "mysql").
166        identity: if set to `True` and if the target dialect is not specified the source dialect will be used as both:
167            the source and the target dialect.
168        error_level: the desired error level of the parser.
169        **opts: other `sqlglot.generator.Generator` options.
170
171    Returns:
172        The list of transpiled SQL statements.
173    """
174    write = (read if write is None else write) if identity else write
175    write = Dialect.get_or_raise(write)
176    return [
177        write.generate(expression, copy=False, **opts) if expression else ""
178        for expression in parse(sql, read, error_level=error_level)
179    ]

根据源方言解析给定的SQL字符串,并返回一个转换后的SQL字符串列表,使其符合目标方言。返回列表中的每个字符串代表一个单独的转换后的SQL语句。

参数:
  • sql: 要转换的SQL代码字符串。
  • read: 用于解析输入字符串的源方言(例如:"spark", "hive", "presto", "mysql")。
  • write: 输入应该转换成的目标方言(例如:"spark", "hive", "presto", "mysql")。
  • identity: 如果设置为True且未指定目标方言,则源方言将同时用作源方言和目标方言。
  • error_level: 解析器所需的错误级别。
  • **opts: 其他 sqlglot.generator.Generator 选项。
返回值:

转换后的SQL语句列表。