-
Notifications
You must be signed in to change notification settings - Fork 15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
WIP: Add JSON serializer for ASTs and store them upon node creation #699
Open
shangyian
wants to merge
5
commits into
DataJunction:main
Choose a base branch
from
shangyian:json-serialize-ast
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
a91f459
Add JSON serializer for query ASTs and store them upon node creation
shangyian 96e9bf7
Fix lint
shangyian b7eff1c
Update json serializer so that we automatically short-circuit circula…
shangyian a18c3a8
Undo sql test changes
shangyian 780f793
Add json deserialization and incorporate into query building
shangyian File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
27 changes: 27 additions & 0 deletions
27
...ion-server/alembic/versions/2023_08_07_1432-789f91d2d69e_add_query_ast_to_noderevision.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
"""Add query ast to noderevision | ||
|
||
Revision ID: 789f91d2d69e | ||
Revises: ccc77abcf899 | ||
Create Date: 2023-08-07 14:32:54.290688+00:00 | ||
|
||
""" | ||
# pylint: disable=no-member, invalid-name, missing-function-docstring, unused-import, no-name-in-module | ||
|
||
import sqlalchemy as sa | ||
import sqlmodel | ||
|
||
from alembic import op | ||
|
||
# revision identifiers, used by Alembic. | ||
revision = "789f91d2d69e" | ||
down_revision = "ccc77abcf899" | ||
branch_labels = None | ||
depends_on = None | ||
|
||
|
||
def upgrade(): | ||
op.add_column("noderevision", sa.Column("query_ast", sa.JSON(), nullable=True)) | ||
|
||
|
||
def downgrade(): | ||
op.drop_column("noderevision", "query_ast") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -102,6 +102,17 @@ class Node(ABC): | |
|
||
_is_compiled: bool = False | ||
|
||
@property | ||
def json_ignore_keys(self): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I like this pattern 🙂 |
||
return ["parent", "parent_key", "_is_compiled"] | ||
|
||
def __json_encode__(self): | ||
return { | ||
key: self.__dict__[key] | ||
for key in self.__dict__ | ||
if key not in self.json_ignore_keys | ||
} | ||
|
||
def __post_init__(self): | ||
self.add_self_as_parent() | ||
|
||
|
@@ -624,6 +635,10 @@ def identifier(self, quotes: bool = True) -> str: | |
f"{namespace}{quote_style}{self.name}{quote_style}" # pylint: disable=C0301 | ||
) | ||
|
||
@property | ||
def json_ignore_keys(self): | ||
return ["names", "parent", "parent_key"] | ||
|
||
|
||
TNamed = TypeVar("TNamed", bound="Named") # pylint: disable=C0103 | ||
|
||
|
@@ -705,6 +720,10 @@ class Column(Aliasable, Named, Expression): | |
_expression: Optional[Expression] = field(repr=False, default=None) | ||
_is_compiled: bool = False | ||
|
||
@property | ||
def json_ignore_keys(self): | ||
return ["parent", "parent_key", "columns"] | ||
|
||
@property | ||
def type(self): | ||
if self._type: | ||
|
@@ -985,6 +1004,18 @@ class TableExpression(Aliasable, Expression): | |
# ref (referenced) columns are columns used elsewhere from this table | ||
_ref_columns: List[Column] = field(init=False, repr=False, default_factory=list) | ||
|
||
@property | ||
def json_ignore_keys(self): | ||
return [ | ||
"parent", | ||
"parent_key", | ||
# "_is_compiled", | ||
"_columns", | ||
# "column_list", | ||
"_ref_columns", | ||
# "columns", | ||
] | ||
|
||
@property | ||
def columns(self) -> List[Expression]: | ||
""" | ||
|
@@ -1229,6 +1260,11 @@ class BinaryOpKind(DJEnum): | |
Minus = "-" | ||
Modulo = "%" | ||
|
||
def __json_encode__(self): | ||
return { | ||
"value": self.value, | ||
} | ||
|
||
|
||
@dataclass(eq=False) | ||
class BinaryOp(Operation): | ||
|
@@ -2003,6 +2039,19 @@ class FunctionTable(FunctionTableExpression): | |
Represents a table-valued function used in a statement | ||
""" | ||
|
||
@property | ||
def json_ignore_keys(self): | ||
return [ | ||
"parent", | ||
"parent_key", | ||
"_is_compiled", | ||
"_table", | ||
"_columns", | ||
"column_list", | ||
"_ref_columns", | ||
"columns", | ||
] | ||
|
||
def __str__(self) -> str: | ||
alias = f" {self.alias}" if self.alias else "" | ||
as_ = " AS " if self.as_ else "" | ||
|
86 changes: 86 additions & 0 deletions
86
datajunction-server/datajunction_server/sql/parsing/ast_json_encoder.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
""" | ||
JSON encoder for AST objects | ||
""" | ||
from json import JSONEncoder | ||
|
||
from sqlmodel import select | ||
|
||
from datajunction_server.models import Node | ||
from datajunction_server.sql.parsing import ast | ||
|
||
|
||
def remove_circular_refs(obj, _seen: set = None): | ||
""" | ||
Short-circuits circular references in AST nodes | ||
""" | ||
if _seen is None: | ||
_seen = set() | ||
if id(obj) in _seen: | ||
return None | ||
_seen.add(id(obj)) | ||
if issubclass(obj.__class__, ast.Node): | ||
serializable_keys = [ | ||
key for key in obj.__dict__.keys() if key not in obj.json_ignore_keys | ||
] | ||
for key in serializable_keys: | ||
setattr(obj, key, remove_circular_refs(getattr(obj, key), _seen)) | ||
_seen.remove(id(obj)) | ||
return obj | ||
|
||
|
||
class ASTEncoder(JSONEncoder): | ||
""" | ||
JSON encoder for AST objects. Disables the original circular check in favor | ||
of our own version with _processed so that we can catch and handle circular | ||
traversals. | ||
""" | ||
|
||
def __init__(self, *args, **kwargs): | ||
kwargs["check_circular"] = False | ||
self.markers = set() | ||
super().__init__(*args, **kwargs) | ||
|
||
def default(self, o): | ||
o = remove_circular_refs(o) | ||
json_dict = { | ||
"__class__": o.__class__.__name__, | ||
} | ||
if hasattr(o, "__json_encode__"): # pragma: no cover | ||
json_dict = {**json_dict, **o.__json_encode__()} | ||
return json_dict | ||
|
||
|
||
def ast_decoder(session, json_dict): | ||
""" | ||
Decodes json dict back into an AST entity | ||
""" | ||
class_name = json_dict["__class__"] | ||
clazz = getattr(ast, class_name) | ||
|
||
# Instantiate the class | ||
instance = clazz( | ||
**{ | ||
k: v | ||
for k, v in json_dict.items() | ||
if k not in {"__class__", "_type", "laterals", "_is_compiled"} | ||
}, | ||
) | ||
|
||
# Set attributes where possible | ||
for key, value in json_dict.items(): | ||
if key not in {"__class__", "_is_compiled"}: | ||
if hasattr(instance, key) and class_name not in {"BinaryOpKind"}: | ||
setattr(instance, key, value) | ||
|
||
if class_name == "NodeRevision": | ||
# Overwrite with DB object if it's a node revision | ||
instance = ( | ||
session.exec(select(Node).where(Node.name == json_dict["name"])) | ||
.one() | ||
.current | ||
) | ||
elif class_name == "Column": | ||
# Add in a reference to the table from the column | ||
instance._table.parent = instance # pylint: disable=protected-access | ||
instance._table.parent_key = "_table" # pylint: disable=protected-access | ||
return instance |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yep, this just handles serializing and storing the ast. As I mentioned below, I might try some basic deserialization to make sure it works for query building, but I'll put the actual implementation in a separate PR :)