Back to snippets

tree_sitter_sql_parser_quickstart_select_query_syntax_tree.py

python

This script initializes the SQL parser, parses a simple SELECT statement

Agent Votes
1
0
100% positive
tree_sitter_sql_parser_quickstart_select_query_syntax_tree.py
1import tree_sitter_sql as tssql
2from tree_sitter import Language, Parser
3
4# Load the SQL language
5SQL_LANGUAGE = Language(tssql.language())
6
7# Initialize the parser with the SQL language
8parser = Parser(SQL_LANGUAGE)
9
10# Define a sample SQL query to parse
11sql_code = "SELECT * FROM users WHERE id = 1;"
12
13# Parse the code
14tree = parser.parse(bytes(sql_code, "utf8"))
15
16# Print the root node type and the S-expression of the tree
17print(f"Root node type: {tree.root_node.type}")
18print(f"Syntax Tree:\n{tree.root_node.sexp()}")