Skip to content

Commit

Permalink
feat(api): add ibis.sql to easily get a formatted SQL string
Browse files Browse the repository at this point in the history
  • Loading branch information
cpcloud committed Sep 14, 2022
1 parent 68ba2fc commit d971cc3
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
1 change: 1 addition & 0 deletions docs/api/expressions/top_level.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ These methods and objects are available directly in the `ibis` module.
::: ibis.or_
::: ibis.param
::: ibis.show_sql
::: ibis.sql
::: ibis.random
::: ibis.range_window
::: ibis.row_number
Expand Down
20 changes: 19 additions & 1 deletion ibis/common/pretty.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,24 @@ def show_sql(
t0.a * 2 AS c
FROM t AS t0
"""
print(to_sql(expr, dialect=dialect), file=file)


def to_sql(expr: ir.Expr, dialect: str | None = None) -> str:
"""Return the formatted SQL string for an expression.
Parameters
----------
expr
Ibis expression.
dialect
SQL dialect to use for compilation.
Returns
-------
str
Formatted SQL string
"""
import sqlglot

# try to infer from a non-str expression or if not possible fallback to
Expand Down Expand Up @@ -87,4 +105,4 @@ def show_sql(
write=write,
pretty=True,
)
print(pretty, file=file)
return pretty
3 changes: 2 additions & 1 deletion ibis/expr/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import ibis.expr.schema as sch
import ibis.expr.types as ir
from ibis.backends.base import connect
from ibis.common.pretty import show_sql
from ibis.common.pretty import show_sql, to_sql
from ibis.expr.deferred import Deferred
from ibis.expr.random import random
from ibis.expr.schema import Schema
Expand Down Expand Up @@ -208,6 +208,7 @@
'Schema',
'sequence',
'show_sql',
'to_sql',
'struct',
'table',
'time',
Expand Down

0 comments on commit d971cc3

Please sign in to comment.