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+ 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
@@ -956,32 +962,37 @@ def perform_simple_statement(self, statement):
956962 def print_result (self , result , table_meta ):
957963 self .decoding_errors = []
958964
959- self .writeresult ("" )
965+ if self .mode == 'csv' :
966+ printer = CsvTablePrinter (self )
967+ elif self .mode == 'json' :
968+ printer = JsonTablePrinter (self )
969+ else :
970+ self .writeresult ("" )
971+ printer = TabularTablePrinter (self , self .tty )
960972
961- def print_all (result , table_meta , tty ):
962- # Return the number of rows in total
973+ def print_all (result , table_meta , tty , printer ):
963974 num_rows = 0
964975 is_first = True
965976 while True :
966- # Always print for the first page even it is empty
967977 if result .current_rows or is_first :
968978 with_header = is_first or tty
969- self .print_static_result (result , table_meta , with_header , tty , num_rows )
979+ self .print_static_result (result , table_meta , with_header , tty , num_rows , printer )
970980 num_rows += len (result .current_rows )
971981 if result .has_more_pages :
972982 if self .shunted_query_out is None and tty :
973- # Only pause when not capturing.
974983 input ("---MORE---" )
975984 result .fetch_next_page ()
976985 else :
977- if not tty :
986+ if not tty and self . mode not in ( 'csv' , 'json' ) :
978987 self .writeresult ("" )
979988 break
980989 is_first = False
981990 return num_rows
982991
983- num_rows = print_all (result , table_meta , self .tty )
984- self .writeresult ("(%d rows)" % num_rows )
992+ num_rows = print_all (result , table_meta , self .tty , printer )
993+ printer .finish ()
994+ if self .mode not in ('csv' , 'json' ):
995+ self .writeresult ("(%d rows)" % num_rows )
985996
986997 if self .decoding_errors :
987998 for err in self .decoding_errors [:2 ]:
@@ -990,15 +1001,18 @@ def print_all(result, table_meta, tty):
9901001 self .writeresult ('%d more decoding errors suppressed.'
9911002 % (len (self .decoding_errors ) - 2 ), color = RED )
9921003
993- def print_static_result (self , result , table_meta , with_header , tty , row_count_offset = 0 ):
1004+ def print_static_result (self , result , table_meta , with_header , tty , row_count_offset = 0 , printer = None ):
9941005 if not result .column_names and not table_meta :
9951006 return
9961007
9971008 column_names = result .column_names or list (table_meta .columns .keys ())
9981009 formatted_names = [self .myformat_colname (name , table_meta ) for name in column_names ]
1010+
9991011 if not result .current_rows :
1000- # print header only
1001- self .print_formatted_result (formatted_names , None , with_header = True , tty = tty )
1012+ if printer is None or isinstance (printer , TabularTablePrinter ):
1013+ self .print_formatted_result (formatted_names , None , with_header = True , tty = tty )
1014+ elif with_header :
1015+ printer .print_header (formatted_names )
10021016 return
10031017
10041018 cql_types = []
@@ -1009,10 +1023,15 @@ def print_static_result(self, result, table_meta, with_header, tty, row_count_of
10091023
10101024 formatted_values = [list (map (self .myformat_value , [row [c ] for c in column_names ], cql_types )) for row in result .current_rows ]
10111025
1012- if self .expand_enabled :
1013- self .print_formatted_result_vertically (formatted_names , formatted_values , row_count_offset )
1026+ if printer is None :
1027+ if self .expand_enabled :
1028+ self .print_formatted_result_vertically (formatted_names , formatted_values , row_count_offset )
1029+ else :
1030+ self .print_formatted_result (formatted_names , formatted_values , with_header , tty )
10141031 else :
1015- self .print_formatted_result (formatted_names , formatted_values , with_header , tty )
1032+ if with_header :
1033+ printer .print_header (formatted_names )
1034+ printer .print_rows (formatted_names , formatted_values )
10161035
10171036 def print_formatted_result (self , formatted_names , formatted_values , with_header , tty ):
10181037 # determine column widths
@@ -2026,6 +2045,7 @@ def read_options(cmdlineargs, parser, config_file, cql_dir, environment=os.envir
20262045 argvalues .completekey = option_with_default (configs .get , 'ui' , 'completekey' ,
20272046 DEFAULT_COMPLETEKEY )
20282047 argvalues .color = option_with_default (configs .getboolean , 'ui' , 'color' )
2048+ argvalues .mode = option_with_default (configs .get , 'ui' , 'mode' , 'tabular' )
20292049 argvalues .time_format = raw_option_with_default (configs , 'ui' , 'time_format' ,
20302050 DEFAULT_TIMESTAMP_FORMAT )
20312051 argvalues .nanotime_format = raw_option_with_default (configs , 'ui' , 'nanotime_format' ,
@@ -2230,6 +2250,8 @@ def main(cmdline, pkgpath):
22302250 help = 'Force tty mode (command prompt).' )
22312251 parser .add_argument ('--disable-history' , default = False , action = 'store_true' ,
22322252 help = 'Disable saving of history (existing history will still be loaded)' )
2253+ parser .add_argument ('--mode' , choices = ['tabular' , 'csv' , 'json' ],
2254+ help = 'Specify the output format (tabular, csv, json). Default is tabular.' )
22332255
22342256 # This is a hidden option to suppress the warning when the -p/--password command line option is used.
22352257 # 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 +2379,7 @@ def main(cmdline, pkgpath):
23572379 display_double_precision = options .double_precision ,
23582380 display_timezone = timezone ,
23592381 max_trace_wait = options .max_trace_wait ,
2382+ mode = options .mode ,
23602383 ssl = options .ssl ,
23612384 single_statement = options .execute ,
23622385 request_timeout = options .request_timeout ,
0 commit comments