MCPcopy
hub / github.com/dbcli/pgcli / extract_table_identifiers

Function extract_table_identifiers

pgcli/packages/parseutils/tables.py:75–125  ·  view source on GitHub ↗

yields tuples of TableReference namedtuples

(token_stream, allow_functions=True)

Source from the content-addressed store, hash-verified

73
74
75def extract_table_identifiers(token_stream, allow_functions=True):
76 """yields tuples of TableReference namedtuples"""
77
78 # We need to do some massaging of the names because postgres is case-
79 # insensitive and '"Foo"' is not the same table as 'Foo' (while 'foo' is)
80 def parse_identifier(item):
81 name = item.get_real_name()
82 schema_name = item.get_parent_name()
83 alias = item.get_alias()
84 if not name:
85 schema_name = None
86 name = item.get_name()
87 alias = alias or name
88 schema_quoted = schema_name and item.value[0] == '"'
89 if schema_name and not schema_quoted:
90 schema_name = schema_name.lower()
91 quote_count = item.value.count('"')
92 name_quoted = quote_count > 2 or (quote_count and not schema_quoted)
93 alias_quoted = alias and item.value[-1] == '"'
94 if alias_quoted or name_quoted and not alias and name.islower():
95 alias = '"' + (alias or name) + '"'
96 if name and not name_quoted and not name.islower():
97 if not alias:
98 alias = name
99 name = name.lower()
100 return schema_name, name, alias
101
102 try:
103 for item in token_stream:
104 if isinstance(item, IdentifierList):
105 for identifier in item.get_identifiers():
106 # Sometimes Keywords (such as FROM ) are classified as
107 # identifiers which don't have the get_real_name() method.
108 try:
109 schema_name = identifier.get_parent_name()
110 real_name = identifier.get_real_name()
111 is_function = allow_functions and _identifier_is_function(identifier)
112 except AttributeError:
113 continue
114 if real_name:
115 yield TableReference(schema_name, real_name, identifier.get_alias(), is_function)
116 elif isinstance(item, Identifier):
117 schema_name, real_name, alias = parse_identifier(item)
118 is_function = allow_functions and _identifier_is_function(item)
119
120 yield TableReference(schema_name, real_name, alias, is_function)
121 elif isinstance(item, Function):
122 schema_name, real_name, alias = parse_identifier(item)
123 yield TableReference(None, real_name, alias, allow_functions)
124 except StopIteration:
125 return
126
127
128# extract_tables is inspired from examples in the sqlparse lib.

Callers 1

extract_tablesFunction · 0.85

Calls 2

_identifier_is_functionFunction · 0.85
parse_identifierFunction · 0.85

Tested by

no test coverage detected