17from abc
import abstractmethod
18from datetime
import date
19from typing
import Any, Callable, Dict, Mapping, Optional, Type, Union
21from minijinja
import render_str
23from nebulagraph_python.client.logger
import debug_flag
28logger = logging.getLogger(__name__)
31def unwrap_value(v: Union[TargetType, TargetPrimitiveType]) -> str:
32 """Convert python value to GQL string"""
34 def from_vector(x: NVector):
35 return f
"vector<{x.dimension}, float>([{', '.join(str(v) for v in x.values)}])"
38 Type[Union[TargetType, TargetPrimitiveType]], Callable[[Any], str]
40 str:
lambda x: json.dumps(x, ensure_ascii=
False).replace(
"'",
"\\'"),
43 bool:
lambda x: str(x).upper(),
44 list:
lambda x:
"[%s]" %
", ".join(unwrap_value(i)
for i
in x),
45 dict:
lambda x:
"{ %s }"
46 %
", ".join(f
"`{k}`: {unwrap_value(v)}" for k, v
in x.items()),
47 type(
None):
lambda x:
"NULL",
49 date:
lambda x: f
'date("{x.strftime("%Y-%m-%d")}")',
52 return mapping[type(v)](v)
54 raise InternalError(f
"Unsupported value type: {type(v)}")
from e
57def unwrap_props(props: Mapping[str, Any]):
58 return ", ".join(f
"`{k}`: {unwrap_value(v)}" for k, v
in props.items())
67 timeout: Optional[float] =
None,
68 do_ping: bool =
False,
75 stmt_args: Optional[Dict[str, Any]] =
None,
77 timeout: Optional[float] =
None,
78 do_ping: bool =
False,
80 """This is an util method to execute a statement and raise an error if the statement fails,
82 it will render the stmt_template with the stmt_args using Jinja2,
84 and then execute the statement, raise an error if the statement fails.
87 if stmt_args
is not None:
88 unwrap_args = {k: unwrap_value(v)
for k, v
in stmt_args.items()}
89 stmt = render_str(stmt, **unwrap_args)
90 logger.debug(
"Executing NebulaGraph statement:\n%s", stmt)
91 return await self.
execute(stmt, timeout=timeout, do_ping=do_ping)
97 width: Optional[int] =
None,
99 max_width: Optional[int] =
None,
101 collapse_padding: bool =
False,
103 """Execute a query and print the results in a formatted way using rich
107 query: The nGQL query to execute
108 style: Output style - either "table" (default) or "rows"
109 width: Fixed width for all columns. If None, width will be auto-calculated
110 min_width: Minimum width of columns when using table style
111 max_width: Maximum width of columns. If None, no maximum is enforced
112 padding: Number of spaces around cell contents in table style
113 collapse_padding: Reduce padding when cell contents are too wide
117 Exception if execution fails
121 result = await self.
execute(query)
128 collapse_padding=collapse_padding,
130 except Exception
as e:
131 from rich.console
import Console
132 from rich.traceback
import Traceback
135 console.print(f
"[bold red]Error executing query:[/bold red] {e!s}")
137 console.print(Traceback.from_exception(type(e), e, e.__traceback__))
139 async def pq(self, query: str, **kwargs):
140 """Print query result using rich"""
150 timeout: Optional[float] =
None,
151 do_ping: bool =
False,
158 stmt_args: Optional[Dict[str, Any]] =
None,
160 timeout: Optional[float] =
None,
161 do_ping: bool =
False,
163 """This is an util method to execute a statement and raise an error if the statement fails,
165 it will render the stmt_template with the stmt_args using Jinja2,
167 and then execute the statement, raise an error if the statement fails.
170 if stmt_args
is not None:
171 unwrap_args = {k: unwrap_value(v)
for k, v
in stmt_args.items()}
172 stmt = render_str(stmt, **unwrap_args)
173 logger.debug(
"Executing NebulaGraph statement:\n%s", stmt)
174 return self.
execute(stmt, timeout=timeout, do_ping=do_ping)
179 style: str =
"table",
180 width: Optional[int] =
None,
182 max_width: Optional[int] =
None,
184 collapse_padding: bool =
False,
186 """Execute a query and print the results in a formatted way using rich
190 query: The nGQL query to execute
191 style: Output style - either "table" (default) or "rows"
192 width: Fixed width for all columns. If None, width will be auto-calculated
193 min_width: Minimum width of columns when using table style
194 max_width: Maximum width of columns. If None, no maximum is enforced
195 padding: Number of spaces around cell contents in table style
196 collapse_padding: Reduce padding when cell contents are too wide
200 Exception if execution fails
211 collapse_padding=collapse_padding,
213 except Exception
as e:
214 from rich.console
import Console
215 from rich.traceback
import Traceback
218 console.print(f
"[bold red]Error executing query:[/bold red] {e!s}")
220 console.print(Traceback.from_exception(type(e), e, e.__traceback__))
222 def pq(self, query: str, **kwargs):
223 """Print query result using rich"""
ResultSet execute_py(self, str stmt, Optional[Dict[str, Any]] stmt_args=None, *Optional[float] timeout=None, bool do_ping=False)
None print_query_result(self, str query, str style="table", Optional[int] width=None, int min_width=8, Optional[int] max_width=None, int padding=1, bool collapse_padding=False)
ResultSet execute(self, str statement, *Optional[float] timeout=None, bool do_ping=False)
pq(self, str query, **kwargs)
ResultSet execute_py(self, str stmt, Optional[Dict[str, Any]] stmt_args=None, *Optional[float] timeout=None, bool do_ping=False)
None print_query_result(self, str query, str style="table", Optional[int] width=None, int min_width=8, Optional[int] max_width=None, int padding=1, bool collapse_padding=False)
ResultSet execute(self, str statement, *Optional[float] timeout=None, bool do_ping=False)
pq(self, str query, **kwargs)