Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 11 additions & 9 deletions benchmarks/bench.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,7 @@

short = "select 1 as a, case when 1 then 1 when 2 then 2 else 3 end as b, c from x"

crazy = "SELECT 1+"
crazy += "+".join(str(i) for i in range(500))
crazy = "SELECT 1+" + "+".join(str(i) for i in range(500))

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 60-61 refactored with the following changes:

crazy += " AS a, 2*"
crazy += "*".join(str(i) for i in range(500))
crazy += " AS b FROM x"
Expand Down Expand Up @@ -200,7 +199,7 @@ def diff(row, column):
column = row[column]
if isinstance(column, str):
return " (N/A)"
return f" ({str(column / row['sqlglot'])[0:5]})"
return f" ({str(column / row['sqlglot'])[:5]})"
Comment on lines -203 to +202

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function diff refactored with the following changes:



libs = [
Expand All @@ -219,7 +218,9 @@ def diff(row, column):
table.append(row)
for lib in libs:
try:
row[lib] = np.mean(timeit.repeat(lambda: globals()[lib + "_parse"](sql), number=3))
row[lib] = np.mean(
timeit.repeat(lambda: globals()[f"{lib}_parse"](sql), number=3)
)
Comment on lines -222 to +223

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 222-238 refactored with the following changes:

except Exception as e:
print(e)
row[lib] = "error"
Expand All @@ -230,11 +231,12 @@ def diff(row, column):
lines = [border(column.rjust(width) for column, width in widths.items())]
lines.append(border(str("-" * width) for width in widths.values()))

for i, row in enumerate(table):
lines.append(border(
(str(row[column])[0:7] + diff(row, column)).rjust(width)[0 : width]
lines.extend(
border(
(str(row[column])[:7] + diff(row, column)).rjust(width)[:width]
for column, width in widths.items()
))

)
for row in table
)
for line in lines:
print(line)
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

def sqlglotrs_version():
with open("sqlglotrs/Cargo.toml") as fd:
for line in fd.readlines():
for line in fd:

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function sqlglotrs_version refactored with the following changes:

if line.strip().startswith("version"):
return line.split("=")[1].strip().strip('"')
raise ValueError("Could not find version in Cargo.toml")
Expand Down
4 changes: 1 addition & 3 deletions sqlglot/dataframe/sql/column.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,9 +194,7 @@ def ensure_literal(cls, value) -> Column:

if isinstance(value, cls):
value = value.expression
if not isinstance(value, exp.Literal):
return lit(value)
return Column(value)
return lit(value) if not isinstance(value, exp.Literal) else Column(value)

def copy(self) -> Column:
return Column(self.expression.copy())
Expand Down
34 changes: 15 additions & 19 deletions sqlglot/dataframe/sql/dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,12 @@ def latest_cte_name(self) -> str:
from_exp = self.expression.args["from"]
if from_exp.alias_or_name:
return from_exp.alias_or_name
table_alias = from_exp.find(exp.TableAlias)
if not table_alias:
if table_alias := from_exp.find(exp.TableAlias):
return table_alias.alias_or_name
else:
raise RuntimeError(
f"Could not find an alias name for this expression: {self.expression}"
)
return table_alias.alias_or_name
return self.expression.ctes[-1].alias

@property
Expand Down Expand Up @@ -186,11 +186,10 @@ def _resolve_pending_hints(self) -> DataFrame:
hint_expression.append("expressions", hint)
df.pending_hints.remove(hint)

join_aliases = {
if join_aliases := {
join_table.alias_or_name
for join_table in get_tables_from_expression_with_join(expression)
}
if join_aliases:
}:
for hint in df.pending_join_hints:
for sequence_id_expression in hint.expressions:
sequence_id_or_name = sequence_id_expression.alias_or_name
Expand Down Expand Up @@ -249,8 +248,7 @@ def _cache(self, storage_level: str):
@classmethod
def _add_ctes_to_expression(cls, expression: exp.Select, ctes: t.List[exp.CTE]) -> exp.Select:
expression = expression.copy()
with_expression = expression.args.get("with")
if with_expression:
if with_expression := expression.args.get("with"):
existing_ctes = with_expression.expressions
existsing_cte_names = {x.alias_or_name for x in existing_ctes}
for cte in ctes:
Expand Down Expand Up @@ -281,8 +279,7 @@ def _get_select_expressions(
] = []
main_select_ctes: t.List[exp.CTE] = []
for cte in self.expression.ctes:
cache_storage_level = cte.args.get("cache_storage_level")
if cache_storage_level:
if cache_storage_level := cte.args.get("cache_storage_level"):
select_expression = cte.this.copy()
select_expression.set("with", exp.With(expressions=copy(main_select_ctes)))
select_expression.set("cte_alias_name", cte.alias_or_name)
Expand Down Expand Up @@ -374,12 +371,12 @@ def select(self, *cols, **kwargs) -> DataFrame:
cols = self._ensure_and_normalize_cols(cols)
kwargs["append"] = kwargs.get("append", False)
if self.expression.args.get("joins"):
ambiguous_cols = [
if ambiguous_cols := [
col
for col in cols
if isinstance(col.column_expression, exp.Column) and not col.column_expression.table
]
if ambiguous_cols:
if isinstance(col.column_expression, exp.Column)
and not col.column_expression.table
]:
join_table_identifiers = [
x.this for x in get_tables_from_expression_with_join(self.expression)
]
Expand Down Expand Up @@ -546,7 +543,7 @@ def orderBy(
ascending = [True] * len(columns)
elif not isinstance(ascending, list):
ascending = [ascending] * len(columns)
ascending = [bool(x) for i, x in enumerate(ascending)]
ascending = [bool(x) for x in ascending]
assert len(columns) == len(
ascending
), "The length of items in ascending must equal the number of columns provided"
Expand Down Expand Up @@ -655,8 +652,7 @@ def dropna(
num_nulls = nulls_added_together.alias("num_nulls")
new_df = new_df.select(num_nulls, append=True)
filtered_df = new_df.where(F.col("num_nulls") < F.lit(minimum_num_nulls))
final_df = filtered_df.select(*all_columns)
return final_df
return filtered_df.select(*all_columns)

@operation(Operation.FROM)
def fillna(
Expand Down Expand Up @@ -695,7 +691,7 @@ def fillna(
)
for column, value in zip(columns, value_columns)
}
null_replacement_mapping = {**all_column_mapping, **null_replacement_mapping}
null_replacement_mapping = all_column_mapping | null_replacement_mapping
null_replacement_columns = [
null_replacement_mapping[column.alias_or_name] for column in all_columns
]
Expand Down Expand Up @@ -745,7 +741,7 @@ def replace(
column.expression.alias_or_name
)

replacement_mapping = {**all_column_mapping, **replacement_mapping}
replacement_mapping = all_column_mapping | replacement_mapping
replacement_columns = [replacement_mapping[column.alias_or_name] for column in all_columns]
new_df = new_df.select(*replacement_columns)
return new_df
Expand Down
41 changes: 21 additions & 20 deletions sqlglot/dataframe/sql/normalize.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,27 +37,28 @@ def replace_alias_name_with_cte_name(
def replace_branch_and_sequence_ids_with_cte_name(
spark: SparkSession, expression_context: exp.Select, id: exp.Identifier
):
if id.alias_or_name in spark.known_ids:
# Check if we have a join and if both the tables in that join share a common branch id
# If so we need to have this reference the left table by default unless the id is a sequence
# id then it keeps that reference. This handles the weird edge case in spark that shouldn't
# be common in practice
if expression_context.args.get("joins") and id.alias_or_name in spark.known_branch_ids:
join_table_aliases = [
x.alias_or_name for x in get_tables_from_expression_with_join(expression_context)
]
ctes_in_join = [
cte for cte in expression_context.ctes if cte.alias_or_name in join_table_aliases
]
if ctes_in_join[0].args["branch_id"] == ctes_in_join[1].args["branch_id"]:
assert len(ctes_in_join) == 2
_set_alias_name(id, ctes_in_join[0].alias_or_name)
return
if id.alias_or_name not in spark.known_ids:
return
# Check if we have a join and if both the tables in that join share a common branch id
# If so we need to have this reference the left table by default unless the id is a sequence
# id then it keeps that reference. This handles the weird edge case in spark that shouldn't
# be common in practice
if expression_context.args.get("joins") and id.alias_or_name in spark.known_branch_ids:
join_table_aliases = [
x.alias_or_name for x in get_tables_from_expression_with_join(expression_context)
]
ctes_in_join = [
cte for cte in expression_context.ctes if cte.alias_or_name in join_table_aliases
]
if ctes_in_join[0].args["branch_id"] == ctes_in_join[1].args["branch_id"]:
assert len(ctes_in_join) == 2
_set_alias_name(id, ctes_in_join[0].alias_or_name)
return

for cte in reversed(expression_context.ctes):
if id.alias_or_name in (cte.args["branch_id"], cte.args["sequence_id"]):
_set_alias_name(id, cte.alias_or_name)
return
for cte in reversed(expression_context.ctes):
if id.alias_or_name in (cte.args["branch_id"], cte.args["sequence_id"]):
_set_alias_name(id, cte.alias_or_name)
return


def _set_alias_name(id: exp.Identifier, name: str):
Expand Down
5 changes: 2 additions & 3 deletions sqlglot/dataframe/sql/readwriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,8 @@ def table(self, tableName: str) -> DataFrame:
)
)
.select(
*(
column
for column in sqlglot.schema.column_names(
*iter(
sqlglot.schema.column_names(
tableName, dialect=SparkSession().dialect
)
)
Expand Down
2 changes: 1 addition & 1 deletion sqlglot/dataframe/sql/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ def _random_sequence_id(self):

@property
def _random_id(self) -> str:
id = "r" + uuid.uuid4().hex
id = f"r{uuid.uuid4().hex}"
self.known_ids.add(id)
return id

Expand Down
2 changes: 1 addition & 1 deletion sqlglot/dataframe/sql/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

class DataType:
def __repr__(self) -> str:
return self.__class__.__name__ + "()"
return f"{self.__class__.__name__}()"

def __hash__(self) -> int:
return hash(str(self))
Expand Down
9 changes: 3 additions & 6 deletions sqlglot/dialects/bigquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,11 @@ def _unqualify_unnest(expression: exp.Expression) -> exp.Expression:
from sqlglot.optimizer.scope import find_all_in_scope

if isinstance(expression, exp.Select):
unnest_aliases = {
if unnest_aliases := {
unnest.alias
for unnest in find_all_in_scope(expression, exp.Unnest)
if isinstance(unnest.parent, (exp.From, exp.Join))
}
if unnest_aliases:
}:
for column in expression.find_all(exp.Column):
if column.table in unnest_aliases:
column.set("table", None)
Expand Down Expand Up @@ -124,9 +123,7 @@ def _alias_ordered_group(expression: exp.Expression) -> exp.Expression:
}

for e in group.expressions:
alias = aliases.get(e)

if alias:
if alias := aliases.get(e):
e.replace(exp.column(alias))

return expression
Expand Down
19 changes: 8 additions & 11 deletions sqlglot/dialects/clickhouse.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,9 +239,10 @@ def _parse_join_parts(
self,
) -> t.Tuple[t.Optional[Token], t.Optional[Token], t.Optional[Token]]:
is_global = self._match(TokenType.GLOBAL) and self._prev
kind_pre = self._match_set(self.JOIN_KINDS, advance=False) and self._prev

if kind_pre:
if (
kind_pre := self._match_set(self.JOIN_KINDS, advance=False)
and self._prev
):
kind = self._match_set(self.JOIN_KINDS) and self._prev
side = self._match_set(self.JOIN_SIDES) and self._prev
return is_global, side, kind
Expand Down Expand Up @@ -272,9 +273,7 @@ def _parse_function(
)

if isinstance(func, exp.Anonymous):
params = self._parse_func_params(func)

if params:
if params := self._parse_func_params(func):
return self.expression(
exp.ParameterizedAgg,
this=func.this,
Expand All @@ -299,8 +298,7 @@ def _parse_func_params(

def _parse_quantile(self) -> exp.Quantile:
this = self._parse_lambda()
params = self._parse_func_params()
if params:
if params := self._parse_func_params():
return self.expression(exp.Quantile, this=params[0], quantile=this)
return self.expression(exp.Quantile, this=this, quantile=exp.Literal.number(0.5))

Expand All @@ -317,8 +315,7 @@ def _parse_primary_key(
def _parse_on_property(self) -> t.Optional[exp.Expression]:
index = self._index
if self._match_text_seq("CLUSTER"):
this = self._parse_id_var()
if this:
if this := self._parse_id_var():
return self.expression(exp.OnCluster, this=this)
else:
self._retreat(index)
Expand Down Expand Up @@ -487,7 +484,7 @@ def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:

def parameterizedagg_sql(self, expression: exp.Anonymous) -> str:
params = self.expressions(expression, key="params", flat=True)
return self.func(expression.name, *expression.expressions) + f"({params})"
return f"{self.func(expression.name, *expression.expressions)}({params})"

def placeholder_sql(self, expression: exp.Placeholder) -> str:
return f"{{{expression.name}: {self.sql(expression, 'kind')}}}"
Expand Down
Loading