@@ -104,6 +104,8 @@ class DbCmd(ABC, cmd.Cmd):
104104 "Error: '{0}' is not the name of a table"
105105 " in this database or a column in this table"
106106 )
107+ ERROR_FAILED_SQL = 'SQL query "{query}" caused exception {exc}'
108+ ERROR_FAILED_DISPLAY = "Error: Failed to display: {}"
107109 ROW_COUNT_MSG = "Total row count: {}"
108110
109111 @abstractmethod
@@ -325,7 +327,7 @@ def do_counts(self, _arg: str) -> None:
325327 return
326328 table_name = self .table_name ()
327329 nonnull_columns = self .get_nonnull_columns (table_name )
328- colcounts = [f" , COUNT({ nnc } ) AS { nnc } " for nnc in nonnull_columns ]
330+ colcounts = [f' , COUNT(" { nnc } " ) AS " { nnc } "' for nnc in nonnull_columns ]
329331 with self .sync_engine .connect () as connection :
330332 result = (
331333 connection .execute (
@@ -353,19 +355,24 @@ def do_counts(self, _arg: str) -> None:
353355 def do_select (self , arg : str ) -> None :
354356 """Run a select query over the database and show the first 50 results."""
355357 max_select_rows = 50
358+ query = "SELECT " + arg
356359 with self .sync_engine .connect () as connection :
357360 try :
358- result = connection .execute (sqlalchemy .text ("SELECT " + arg ))
361+ result = connection .execute (sqlalchemy .text (query ))
359362 except sqlalchemy .exc .DatabaseError as exc :
360- self .print ("Failed to execute: {}" , exc )
363+ self .print (self . ERROR_FAILED_SQL , exc , query )
361364 return
362365 row_count = result .rowcount
363366 self .print (self .ROW_COUNT_MSG , row_count )
364367 if 50 < row_count :
365368 self .print ("Showing the first {} rows" , max_select_rows )
366369 fields = list (result .keys ())
367370 rows = result .fetchmany (max_select_rows )
368- self .print_table (fields , rows )
371+ try :
372+ self .print_table (fields , rows )
373+ except ValueError as exc :
374+ self .print (self .ERROR_FAILED_DISPLAY , exc )
375+ return
369376
370377 def do_peek (self , arg : str ) -> None :
371378 """
@@ -383,9 +390,9 @@ def do_peek(self, arg: str) -> None:
383390 col_names = arg .split ()
384391 if not col_names :
385392 col_names = self ._get_column_names ()
386- nonnulls = [cn + " IS NOT NULL" for cn in col_names ]
393+ nonnulls = [f'" { cn } " IS NOT NULL' for cn in col_names ]
387394 with self .sync_engine .connect () as connection :
388- cols = "," .join (col_names )
395+ cols = ", " .join (f'" { cn } "' for cn in col_names )
389396 where = "WHERE" if nonnulls else ""
390397 nonnull = " OR " .join (nonnulls )
391398 query = sqlalchemy .text (
@@ -395,7 +402,7 @@ def do_peek(self, arg: str) -> None:
395402 try :
396403 result = connection .execute (query )
397404 except sqlalchemy .exc .SQLAlchemyError as exc :
398- self .print (f'SQL query " { query } " caused exception { exc } ' )
405+ self .print (self . ERROR_FAILED_SQL , exc , query )
399406 return
400407 self .print_table (list (result .keys ()), result .fetchmany (max_peek_rows ))
401408
0 commit comments