MCPcopy Create free account
hub / github.com/pgadmin-org/pgadmin4 / extract_ctes

Function extract_ctes

web/pgadmin/utils/sqlautocomplete/parseutils/ctes.py:47–91  ·  view source on GitHub ↗

Extract constant table expresseions from a query Returns tuple (ctes, remainder_sql) ctes is a list of TableExpression namedtuples remainder_sql is the text from the original query after the CTEs have been stripped.

(sql)

Source from the content-addressed store, hash-verified

45
46
47def extract_ctes(sql):
48 """Extract constant table expresseions from a query
49
50 Returns tuple (ctes, remainder_sql)
51
52 ctes is a list of TableExpression namedtuples
53 remainder_sql is the text from the original query after the CTEs have
54 been stripped.
55 """
56
57 p = parse(sql)[0]
58
59 # Make sure the first meaningful token is "WITH" which is necessary to
60 # define CTEs
61 idx, tok = p.token_next(-1, skip_ws=True, skip_cm=True)
62 if not (tok and tok.ttype == CTE):
63 return [], sql
64
65 # Get the next (meaningful) token, which should be the first CTE
66 idx, tok = p.token_next(idx)
67 if not tok:
68 return ([], "")
69 start_pos = token_start_pos(p.tokens, idx)
70 ctes = []
71
72 if isinstance(tok, IdentifierList):
73 # Multiple ctes
74 for t in tok.get_identifiers():
75 cte_start_offset = token_start_pos(tok.tokens, tok.token_index(t))
76 cte = get_cte_from_token(t, start_pos + cte_start_offset)
77 if not cte:
78 continue
79 ctes.append(cte)
80 elif isinstance(tok, Identifier):
81 # A single CTE
82 cte = get_cte_from_token(tok, start_pos)
83 if cte:
84 ctes.append(cte)
85
86 idx = p.token_index(tok) + 1
87
88 # Collapse everything after the ctes into a remainder query
89 remainder = "".join(str(tok) for tok in p.tokens[idx:])
90
91 return ctes, remainder
92
93
94def get_cte_from_token(tok, pos0):

Callers 1

isolate_query_ctesFunction · 0.85

Calls 4

token_start_posFunction · 0.85
get_cte_from_tokenFunction · 0.85
appendMethod · 0.80
joinMethod · 0.80

Tested by

no test coverage detected