4646from cqlshlib import cql3handling , pylexotron , sslhandling , cqlshhandling , authproviderhandling
4747from cqlshlib .copyutil import ExportTask , ImportTask
4848from cqlshlib .displaying import (ANSI_RESET , BLUE , COLUMN_NAME_COLORS , CYAN ,
49- RED , WHITE , FormattedValue , colorme )
49+ RED , WHITE , FormattedValue , colorme ,
50+ TablePrinter , TabularTablePrinter , CsvTablePrinter , JsonTablePrinter )
5051from cqlshlib .formatting import (DEFAULT_DATE_FORMAT , DEFAULT_NANOTIME_FORMAT ,
5152 DEFAULT_TIMESTAMP_FORMAT , CqlType , DateTimeFormat ,
5253 format_by_type )
@@ -284,13 +285,18 @@ def __init__(self, hostname, port, config_file, color=False,
284285 connect_timeout = DEFAULT_CONNECT_TIMEOUT_SECONDS ,
285286 is_subshell = False ,
286287 auth_provider = None ,
287- disable_history = False ):
288+ disable_history = False ,
289+ mode = 'tabular' ):
288290 cmd .Cmd .__init__ (self , completekey = completekey )
289291 self .hostname = hostname
290292 self .port = port
291293 self .auth_provider = auth_provider
292294 self .username = username
293295 self .config_file = config_file
296+ self .mode = mode
297+
298+ if self .mode in ('csv' , 'json' ):
299+ self .color = False
294300
295301 if isinstance (auth_provider , PlainTextAuthProvider ):
296302 self .username = auth_provider .username
@@ -947,7 +953,8 @@ def perform_simple_statement(self, statement):
947953 elif result :
948954 # CAS INSERT/UPDATE
949955 self .writeresult ("" )
950- self .print_static_result (result , self .parse_for_update_meta (statement .query_string ), with_header = True , tty = self .tty )
956+ self .print_static_result (result , self .parse_for_update_meta (statement .query_string ), with_header = True , tty = self .tty ,
957+ printer = TablePrinter .factory (self .mode , self ))
951958 if self .elapsed_enabled :
952959 self .writeresult ("(%dms elapsed)" % elapsed )
953960 self .flush_output ()
@@ -956,32 +963,33 @@ def perform_simple_statement(self, statement):
956963 def print_result (self , result , table_meta ):
957964 self .decoding_errors = []
958965
959- self .writeresult ("" )
966+ if self .mode not in ('csv' , 'json' ):
967+ self .writeresult ("" )
968+ printer = TablePrinter .factory (self .mode , self )
960969
961- def print_all (result , table_meta , tty ):
962- # Return the number of rows in total
970+ def print_all (result , table_meta , tty , printer ):
963971 num_rows = 0
964972 is_first = True
965973 while True :
966- # Always print for the first page even it is empty
967974 if result .current_rows or is_first :
968975 with_header = is_first or tty
969- self .print_static_result (result , table_meta , with_header , tty , num_rows )
976+ self .print_static_result (result , table_meta , with_header , tty , num_rows , printer )
970977 num_rows += len (result .current_rows )
971978 if result .has_more_pages :
972979 if self .shunted_query_out is None and tty :
973- # Only pause when not capturing.
974980 input ("---MORE---" )
975981 result .fetch_next_page ()
976982 else :
977- if not tty :
983+ if not tty and self . mode not in ( 'csv' , 'json' ) :
978984 self .writeresult ("" )
979985 break
980986 is_first = False
981987 return num_rows
982988
983- num_rows = print_all (result , table_meta , self .tty )
984- self .writeresult ("(%d rows)" % num_rows )
989+ num_rows = print_all (result , table_meta , self .tty , printer )
990+ printer .finish ()
991+ if self .mode not in ('csv' , 'json' ):
992+ self .writeresult ("(%d rows)" % num_rows )
985993
986994 if self .decoding_errors :
987995 for err in self .decoding_errors [:2 ]:
@@ -990,15 +998,16 @@ def print_all(result, table_meta, tty):
990998 self .writeresult ('%d more decoding errors suppressed.'
991999 % (len (self .decoding_errors ) - 2 ), color = RED )
9921000
993- def print_static_result (self , result , table_meta , with_header , tty , row_count_offset = 0 ):
1001+ def print_static_result (self , result , table_meta , with_header , tty , row_count_offset = 0 , printer = None ):
9941002 if not result .column_names and not table_meta :
9951003 return
9961004
9971005 column_names = result .column_names or list (table_meta .columns .keys ())
9981006 formatted_names = [self .myformat_colname (name , table_meta ) for name in column_names ]
1007+
9991008 if not result .current_rows :
1000- # print header only
1001- self . print_formatted_result ( formatted_names , None , with_header = True , tty = tty )
1009+ if with_header :
1010+ printer . print_header ( formatted_names )
10021011 return
10031012
10041013 cql_types = []
@@ -1009,10 +1018,9 @@ def print_static_result(self, result, table_meta, with_header, tty, row_count_of
10091018
10101019 formatted_values = [list (map (self .myformat_value , [row [c ] for c in column_names ], cql_types )) for row in result .current_rows ]
10111020
1012- if self .expand_enabled :
1013- self .print_formatted_result_vertically (formatted_names , formatted_values , row_count_offset )
1014- else :
1015- self .print_formatted_result (formatted_names , formatted_values , with_header , tty )
1021+ if with_header :
1022+ printer .print_header (formatted_names )
1023+ printer .print_rows (formatted_names , formatted_values )
10161024
10171025 def print_formatted_result (self , formatted_names , formatted_values , with_header , tty ):
10181026 # determine column widths
@@ -2026,6 +2034,7 @@ def read_options(cmdlineargs, parser, config_file, cql_dir, environment=os.envir
20262034 argvalues .completekey = option_with_default (configs .get , 'ui' , 'completekey' ,
20272035 DEFAULT_COMPLETEKEY )
20282036 argvalues .color = option_with_default (configs .getboolean , 'ui' , 'color' )
2037+ argvalues .mode = option_with_default (configs .get , 'ui' , 'mode' , 'tabular' )
20292038 argvalues .time_format = raw_option_with_default (configs , 'ui' , 'time_format' ,
20302039 DEFAULT_TIMESTAMP_FORMAT )
20312040 argvalues .nanotime_format = raw_option_with_default (configs , 'ui' , 'nanotime_format' ,
@@ -2230,6 +2239,8 @@ def main(cmdline, pkgpath):
22302239 help = 'Force tty mode (command prompt).' )
22312240 parser .add_argument ('--disable-history' , default = False , action = 'store_true' ,
22322241 help = 'Disable saving of history (existing history will still be loaded)' )
2242+ parser .add_argument ('--mode' , choices = ['tabular' , 'csv' , 'json' ],
2243+ help = 'Specify the output format (tabular, csv, json). Default is tabular.' )
22332244
22342245 # This is a hidden option to suppress the warning when the -p/--password command line option is used.
22352246 # Power users may use this option if they know no other people has access to the system where cqlsh is run or don't care about security.
@@ -2357,6 +2368,7 @@ def main(cmdline, pkgpath):
23572368 display_double_precision = options .double_precision ,
23582369 display_timezone = timezone ,
23592370 max_trace_wait = options .max_trace_wait ,
2371+ mode = options .mode ,
23602372 ssl = options .ssl ,
23612373 single_statement = options .execute ,
23622374 request_timeout = options .request_timeout ,
0 commit comments