scylla-cqlsh 6.0.26__cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of scylla-cqlsh might be problematic. Click here for more details.

cqlsh/cqlsh.py ADDED
@@ -0,0 +1,2758 @@
1
+ #!/usr/bin/env python3
2
+
3
+ # Licensed to the Apache Software Foundation (ASF) under one
4
+ # or more contributor license agreements. See the NOTICE file
5
+ # distributed with this work for additional information
6
+ # regarding copyright ownership. The ASF licenses this file
7
+ # to you under the Apache License, Version 2.0 (the
8
+ # "License"); you may not use this file except in compliance
9
+ # with the License. You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+
19
+ import cmd
20
+ import codecs
21
+ import configparser
22
+ import csv
23
+ import errno
24
+ import getpass
25
+ import optparse
26
+ import os
27
+ import platform
28
+ import re
29
+ import stat
30
+ import subprocess
31
+ import sys
32
+ import traceback
33
+ import warnings
34
+ import webbrowser
35
+ import logging
36
+ from contextlib import contextmanager
37
+ from glob import glob
38
+ from io import StringIO
39
+ from uuid import UUID
40
+
41
+ if sys.version_info < (3, 6):
42
+ sys.exit("\ncqlsh requires Python 3.6+\n")
43
+
44
+ # see CASSANDRA-10428
45
+ if platform.python_implementation().startswith('Jython'):
46
+ sys.exit("\nCQL Shell does not run on Jython\n")
47
+
48
+ UTF8 = 'utf-8'
49
+
50
+ description = "CQL Shell for Apache Cassandra"
51
+
52
+ readline = None
53
+ try:
54
+ # check if tty first, cause readline doesn't check, and only cares
55
+ # about $TERM. we don't want the funky escape code stuff to be
56
+ # output if not a tty.
57
+ if sys.stdin.isatty():
58
+ import readline
59
+ except ImportError:
60
+ pass
61
+
62
+ CQL_LIB_PREFIX = 'scylla-driver-'
63
+
64
+ CASSANDRA_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')
65
+ CASSANDRA_CQL_HTML_FALLBACK = 'https://cassandra.apache.org/doc/latest/cql/index.html'
66
+
67
+ # default location of local CQL.html
68
+ if os.path.exists(CASSANDRA_PATH + '/doc/cql3/CQL.html'):
69
+ # default location of local CQL.html
70
+ CASSANDRA_CQL_HTML = 'file://' + CASSANDRA_PATH + '/doc/cql3/CQL.html'
71
+ elif os.path.exists('/usr/share/doc/cassandra/CQL.html'):
72
+ # fallback to package file
73
+ CASSANDRA_CQL_HTML = 'file:///usr/share/doc/cassandra/CQL.html'
74
+ else:
75
+ # fallback to online version
76
+ CASSANDRA_CQL_HTML = CASSANDRA_CQL_HTML_FALLBACK
77
+
78
+ # On Linux, the Python webbrowser module uses the 'xdg-open' executable
79
+ # to open a file/URL. But that only works, if the current session has been
80
+ # opened from _within_ a desktop environment. I.e. 'xdg-open' will fail,
81
+ # if the session's been opened via ssh to a remote box.
82
+ #
83
+ try:
84
+ webbrowser.register_standard_browsers() # registration is otherwise lazy in Python3
85
+ except AttributeError:
86
+ pass
87
+ if webbrowser._tryorder and webbrowser._tryorder[0] == 'xdg-open' and os.environ.get('XDG_DATA_DIRS', '') == '':
88
+ # only on Linux (some OS with xdg-open)
89
+ webbrowser._tryorder.remove('xdg-open')
90
+ webbrowser._tryorder.append('xdg-open')
91
+
92
+ # use bundled lib for python-cql if available. if there
93
+ # is a ../lib dir, use bundled libs there preferentially.
94
+ ZIPLIB_DIRS = [os.path.join(CASSANDRA_PATH, 'lib')]
95
+
96
+ if platform.system() == 'Linux':
97
+ ZIPLIB_DIRS.append('/usr/share/cassandra/lib')
98
+
99
+ if os.environ.get('CQLSH_NO_BUNDLED', ''):
100
+ ZIPLIB_DIRS = ()
101
+
102
+
103
+ def find_zip(libprefix):
104
+ for ziplibdir in ZIPLIB_DIRS:
105
+ zips = glob(os.path.join(ziplibdir, libprefix + '*.zip'))
106
+ if zips:
107
+ return max(zips) # probably the highest version, if multiple
108
+
109
+
110
+ cql_zip = find_zip(CQL_LIB_PREFIX)
111
+ if cql_zip:
112
+ sys.path.insert(0, cql_zip)
113
+
114
+ # the driver needs dependencies
115
+ third_parties = ('six-', 'pure_sasl-', 'PyYAML-')
116
+
117
+ for lib in third_parties:
118
+ lib_zip = find_zip(lib)
119
+ if lib_zip:
120
+ sys.path.insert(0, lib_zip)
121
+
122
+ warnings.filterwarnings("ignore", r".*blist.*")
123
+ try:
124
+ import cassandra
125
+ except ImportError as e:
126
+ sys.exit("\nPython Cassandra driver not installed, or not on PYTHONPATH.\n"
127
+ 'You might try "pip install cassandra-driver".\n\n'
128
+ 'Python: %s\n'
129
+ 'Module load path: %r\n\n'
130
+ 'Error: %s\n' % (sys.executable, sys.path, e))
131
+
132
+ from cassandra.auth import PlainTextAuthProvider
133
+ from cassandra.cluster import Cluster, EXEC_PROFILE_DEFAULT, ExecutionProfile
134
+ from cassandra.connection import UnixSocketEndPoint
135
+ from cassandra.cqltypes import cql_typename
136
+ from cassandra.marshal import int64_unpack
137
+ from cassandra.metadata import (ColumnMetadata, KeyspaceMetadata, TableMetadata, protect_name, protect_names, protect_value)
138
+ from cassandra.policies import WhiteListRoundRobinPolicy
139
+ from cassandra.query import SimpleStatement, ordered_dict_factory, TraceUnavailable
140
+ from cassandra.util import datetime_from_timestamp
141
+ from cassandra.connection import DRIVER_NAME, DRIVER_VERSION
142
+
143
+ # cqlsh should run correctly when run out of a Cassandra source tree,
144
+ # out of an unpacked Cassandra tarball, and after a proper package install.
145
+ cqlshlibdir = os.path.join(CASSANDRA_PATH, 'pylib')
146
+ if os.path.isdir(cqlshlibdir):
147
+ sys.path.insert(0, cqlshlibdir)
148
+
149
+ from cqlshlib import cql3handling, pylexotron, sslhandling, cqlshhandling, authproviderhandling
150
+ from cqlshlib.copyutil import ExportTask, ImportTask
151
+ from cqlshlib.displaying import (ANSI_RESET, BLUE, COLUMN_NAME_COLORS, CYAN,
152
+ RED, YELLOW, WHITE, FormattedValue, colorme)
153
+ from cqlshlib.formatting import (DEFAULT_DATE_FORMAT, DEFAULT_NANOTIME_FORMAT,
154
+ DEFAULT_TIMESTAMP_FORMAT, CqlType, DateTimeFormat,
155
+ format_by_type)
156
+ from cqlshlib.tracing import print_trace, print_trace_session
157
+ from cqlshlib.util import get_file_encoding_bomsize
158
+ from cqlshlib.util import is_file_secure, trim_if_present
159
+
160
+ try:
161
+ from cqlshlib._version import __version__ as version
162
+ except ImportError:
163
+ # Get the version relative to the current file, suppressing UserWarnings from setuptools_scm
164
+ from setuptools_scm import get_version
165
+
166
+ with warnings.catch_warnings():
167
+ warnings.simplefilter("ignore", UserWarning)
168
+ version = get_version(root='..', relative_to=__file__, tag_regex=r'^(?P<prefix>v)?(?P<version>[^\+-]+)(?P<suffix>-scylla)?$')
169
+
170
+
171
+ DEFAULT_HOST = '127.0.0.1'
172
+ DEFAULT_PORT = 9042
173
+ DEFAULT_SSL = False
174
+ DEFAULT_CONNECT_TIMEOUT_SECONDS = 5
175
+ DEFAULT_REQUEST_TIMEOUT_SECONDS = 10
176
+
177
+ DEFAULT_FLOAT_PRECISION = 5
178
+ DEFAULT_DOUBLE_PRECISION = 5
179
+ DEFAULT_MAX_TRACE_WAIT = 10
180
+
181
+ if readline is not None and readline.__doc__ is not None and 'libedit' in readline.__doc__:
182
+ DEFAULT_COMPLETEKEY = '\t'
183
+ else:
184
+ DEFAULT_COMPLETEKEY = 'tab'
185
+
186
+ cqldocs = None
187
+ cqlruleset = None
188
+
189
+ epilog = """Connects to %(DEFAULT_HOST)s:%(DEFAULT_PORT)d by default. These
190
+ defaults can be changed by setting $CQLSH_HOST and/or $CQLSH_PORT. When a
191
+ host (and optional port number) are given on the command line, they take
192
+ precedence over any defaults.""" % globals()
193
+
194
+ parser = optparse.OptionParser(description=description, epilog=epilog,
195
+ usage="Usage: %prog [options] [host [port]]",
196
+ version='cqlsh ' + version)
197
+ parser.add_option("-C", "--color", action='store_true', dest='color',
198
+ help='Always use color output')
199
+ parser.add_option("--no-color", action='store_false', dest='color',
200
+ help='Never use color output')
201
+ parser.add_option("--browser", dest='browser', help="""The browser to use to display CQL help, where BROWSER can be:
202
+ - one of the supported browsers in https://docs.python.org/3/library/webbrowser.html.
203
+ - browser path followed by %s, example: /usr/bin/google-chrome-stable %s""")
204
+ parser.add_option('--ssl', action='store_true', help='Use SSL', default=False)
205
+ parser.add_option("-u", "--username", help="Authenticate as user.")
206
+ parser.add_option("-p", "--password", help="Authenticate using password.")
207
+ parser.add_option('-k', '--keyspace', help='Authenticate to the given keyspace.')
208
+ parser.add_option("-f", "--file", help="Execute commands from FILE, then exit")
209
+ parser.add_option('--debug', action='store_true',
210
+ help='Show additional debugging information')
211
+ parser.add_option('--driver-debug', action='store_true',
212
+ help='Show additional driver debugging information')
213
+ parser.add_option('--coverage', action='store_true',
214
+ help='Collect coverage data')
215
+ parser.add_option("--encoding", help="Specify a non-default encoding for output."
216
+ + " (Default: %s)" % (UTF8,))
217
+ parser.add_option("--cqlshrc", help="Specify an alternative cqlshrc file location.")
218
+ parser.add_option("--credentials", help="Specify an alternative credentials file location.")
219
+ parser.add_option('--cqlversion', default=None,
220
+ help='Specify a particular CQL version, '
221
+ 'by default the highest version supported by the server will be used.'
222
+ ' Examples: "3.0.3", "3.1.0"')
223
+ parser.add_option("--protocol-version", type="int", default=None,
224
+ help='Specify a specific protocol version otherwise the client will default and downgrade as necessary')
225
+
226
+ parser.add_option("-e", "--execute", help='Execute the statement and quit.')
227
+ parser.add_option("--connect-timeout", default=DEFAULT_CONNECT_TIMEOUT_SECONDS, dest='connect_timeout',
228
+ help='Specify the connection timeout in seconds (default: %default seconds).')
229
+ parser.add_option("--request-timeout", default=DEFAULT_REQUEST_TIMEOUT_SECONDS, dest='request_timeout',
230
+ help='Specify the default request timeout in seconds (default: %default seconds).')
231
+ parser.add_option("-t", "--tty", action='store_true', dest='tty',
232
+ help='Force tty mode (command prompt).')
233
+ parser.add_option('-v', action="version", help='Print the current version of cqlsh.')
234
+ parser.add_option("--cloudconf", default=None, help='Configuration file for Scylla Cloud Serverless')
235
+
236
+ # This is a hidden option to suppress the warning when the -p/--password command line option is used.
237
+ # 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.
238
+ # Use of this option in scripting is discouraged. Please use a (temporary) credentials file where possible.
239
+ # The Cassandra distributed tests (dtests) also use this option in some tests when a well-known password is supplied via the command line.
240
+ parser.add_option("--insecure-password-without-warning", action='store_true', dest='insecure_password_without_warning',
241
+ help=optparse.SUPPRESS_HELP)
242
+
243
+ opt_values = optparse.Values()
244
+ (options, arguments) = parser.parse_args(sys.argv[1:], values=opt_values)
245
+
246
+ # BEGIN history/config definition
247
+
248
+
249
+ def mkdirp(path):
250
+ """Creates all parent directories up to path parameter or fails when path exists, but it is not a directory."""
251
+
252
+ try:
253
+ os.makedirs(path)
254
+ except OSError:
255
+ if not os.path.isdir(path):
256
+ raise
257
+
258
+
259
+ def resolve_cql_history_file():
260
+ default_cql_history = os.path.expanduser(os.path.join('~', '.cassandra', 'cqlsh_history'))
261
+ if 'CQL_HISTORY' in os.environ:
262
+ return os.environ['CQL_HISTORY']
263
+ else:
264
+ return default_cql_history
265
+
266
+
267
+ HISTORY = resolve_cql_history_file()
268
+ HISTORY_DIR = os.path.dirname(HISTORY)
269
+
270
+ try:
271
+ mkdirp(HISTORY_DIR)
272
+ except OSError:
273
+ print('\nWarning: Cannot create directory at `%s`. Command history will not be saved. Please check what was the environment property CQL_HISTORY set to.\n' % HISTORY_DIR)
274
+
275
+ DEFAULT_CQLSHRC = os.path.expanduser(os.path.join('~', '.cassandra', 'cqlshrc'))
276
+
277
+ if hasattr(options, 'cqlshrc'):
278
+ CONFIG_FILE = os.path.expanduser(options.cqlshrc)
279
+ if not os.path.exists(CONFIG_FILE):
280
+ print('\nWarning: Specified cqlshrc location `%s` does not exist. Using `%s` instead.\n' % (CONFIG_FILE, DEFAULT_CQLSHRC))
281
+ CONFIG_FILE = DEFAULT_CQLSHRC
282
+ else:
283
+ CONFIG_FILE = DEFAULT_CQLSHRC
284
+
285
+ CQL_DIR = os.path.dirname(CONFIG_FILE)
286
+
287
+ CQL_ERRORS = (
288
+ cassandra.AlreadyExists, cassandra.AuthenticationFailed, cassandra.CoordinationFailure,
289
+ cassandra.InvalidRequest, cassandra.Timeout, cassandra.Unauthorized, cassandra.OperationTimedOut,
290
+ cassandra.cluster.NoHostAvailable,
291
+ cassandra.connection.ConnectionBusy, cassandra.connection.ProtocolError, cassandra.connection.ConnectionException,
292
+ cassandra.protocol.ErrorMessage, cassandra.protocol.InternalError, cassandra.query.TraceUnavailable
293
+ )
294
+
295
+ debug_completion = bool(os.environ.get('CQLSH_DEBUG_COMPLETION', '') == 'YES')
296
+
297
+
298
+ class NoKeyspaceError(Exception):
299
+ pass
300
+
301
+
302
+ class KeyspaceNotFound(Exception):
303
+ pass
304
+
305
+
306
+ class ColumnFamilyNotFound(Exception):
307
+ pass
308
+
309
+
310
+ class IndexNotFound(Exception):
311
+ pass
312
+
313
+
314
+ class MaterializedViewNotFound(Exception):
315
+ pass
316
+
317
+
318
+ class ObjectNotFound(Exception):
319
+ pass
320
+
321
+
322
+ class VersionNotSupported(Exception):
323
+ pass
324
+
325
+
326
+ class UserTypeNotFound(Exception):
327
+ pass
328
+
329
+
330
+ class FunctionNotFound(Exception):
331
+ pass
332
+
333
+
334
+ class AggregateNotFound(Exception):
335
+ pass
336
+
337
+
338
+ class DecodeError(Exception):
339
+ verb = 'decode'
340
+
341
+ def __init__(self, thebytes, err, colname=None):
342
+ self.thebytes = thebytes
343
+ self.err = err
344
+ self.colname = colname
345
+
346
+ def __str__(self):
347
+ return str(self.thebytes)
348
+
349
+ def message(self):
350
+ what = 'value %r' % (self.thebytes,)
351
+ if self.colname is not None:
352
+ what = 'value %r (for column %r)' % (self.thebytes, self.colname)
353
+ return 'Failed to %s %s : %s' \
354
+ % (self.verb, what, self.err)
355
+
356
+ def __repr__(self):
357
+ return '<%s %s>' % (self.__class__.__name__, self.message())
358
+
359
+
360
+ def maybe_ensure_text(val):
361
+ return str(val) if val else val
362
+
363
+
364
+ class FormatError(DecodeError):
365
+ verb = 'format'
366
+
367
+
368
+ def full_cql_version(ver):
369
+ while ver.count('.') < 2:
370
+ ver += '.0'
371
+ ver_parts = ver.split('-', 1) + ['']
372
+ vertuple = tuple(list(map(int, ver_parts[0].split('.'))) + [ver_parts[1]])
373
+ return ver, vertuple
374
+
375
+
376
+ def format_value(val, cqltype, encoding, addcolor=False, date_time_format=None,
377
+ float_precision=None, colormap=None, nullval=None):
378
+ if isinstance(val, DecodeError):
379
+ if addcolor:
380
+ return colorme(repr(val.thebytes), colormap, 'error')
381
+ else:
382
+ return FormattedValue(repr(val.thebytes))
383
+ return format_by_type(val, cqltype=cqltype, encoding=encoding, colormap=colormap,
384
+ addcolor=addcolor, nullval=nullval, date_time_format=date_time_format,
385
+ float_precision=float_precision)
386
+
387
+
388
+ def show_warning_without_quoting_line(message, category, filename, lineno, file=None, line=None):
389
+ if file is None:
390
+ file = sys.stderr
391
+ try:
392
+ file.write(warnings.formatwarning(message, category, filename, lineno, line=''))
393
+ except IOError:
394
+ pass
395
+
396
+
397
+ warnings.showwarning = show_warning_without_quoting_line
398
+ warnings.filterwarnings('always', category=cql3handling.UnexpectedTableStructure)
399
+
400
+
401
+ def insert_driver_hooks():
402
+
403
+ class DateOverFlowWarning(RuntimeWarning):
404
+ pass
405
+
406
+ # Native datetime types blow up outside of datetime.[MIN|MAX]_YEAR. We will fall back to an int timestamp
407
+ def deserialize_date_fallback_int(byts, protocol_version):
408
+ timestamp_ms = int64_unpack(byts)
409
+ try:
410
+ return datetime_from_timestamp(timestamp_ms / 1000.0)
411
+ except OverflowError:
412
+ warnings.warn(DateOverFlowWarning("Some timestamps are larger than Python datetime can represent. "
413
+ "Timestamps are displayed in milliseconds from epoch."))
414
+ return timestamp_ms
415
+
416
+ cassandra.cqltypes.DateType.deserialize = staticmethod(deserialize_date_fallback_int)
417
+
418
+ if hasattr(cassandra, 'deserializers'):
419
+ del cassandra.deserializers.DesDateType
420
+
421
+ # Return cassandra.cqltypes.EMPTY instead of None for empty values
422
+ cassandra.cqltypes.CassandraType.support_empty_values = True
423
+
424
+
425
+ class Shell(cmd.Cmd):
426
+ custom_prompt = os.getenv('CQLSH_PROMPT', '')
427
+ if custom_prompt != '':
428
+ custom_prompt += "\n"
429
+ default_prompt = custom_prompt + "cqlsh> "
430
+ continue_prompt = " ... "
431
+ keyspace_prompt = custom_prompt + "cqlsh:{}> "
432
+ keyspace_continue_prompt = "{} ... "
433
+ show_line_nums = False
434
+ debug = False
435
+ coverage = False
436
+ coveragerc_path = None
437
+ stop = False
438
+ last_hist = None
439
+ shunted_query_out = None
440
+ use_paging = True
441
+
442
+ default_page_size = 100
443
+
444
+ def __init__(self, hostname, port, color=False,
445
+ username=None, encoding=None, stdin=None, tty=True,
446
+ completekey=DEFAULT_COMPLETEKEY, browser=None, use_conn=None,
447
+ cqlver=None, keyspace=None,
448
+ tracing_enabled=False, expand_enabled=False,
449
+ display_nanotime_format=DEFAULT_NANOTIME_FORMAT,
450
+ display_timestamp_format=DEFAULT_TIMESTAMP_FORMAT,
451
+ display_date_format=DEFAULT_DATE_FORMAT,
452
+ display_float_precision=DEFAULT_FLOAT_PRECISION,
453
+ display_double_precision=DEFAULT_DOUBLE_PRECISION,
454
+ display_timezone=None,
455
+ max_trace_wait=DEFAULT_MAX_TRACE_WAIT,
456
+ ssl=False,
457
+ single_statement=None,
458
+ request_timeout=DEFAULT_REQUEST_TIMEOUT_SECONDS,
459
+ protocol_version=None,
460
+ connect_timeout=DEFAULT_CONNECT_TIMEOUT_SECONDS,
461
+ is_subshell=False,
462
+ auth_provider=None,
463
+ cloudconf=None):
464
+ cmd.Cmd.__init__(self, completekey=completekey)
465
+ self.hostname = hostname
466
+ self.port = port
467
+ self.auth_provider = auth_provider
468
+ self.username = username
469
+
470
+ if isinstance(auth_provider, PlainTextAuthProvider):
471
+ self.username = auth_provider.username
472
+ if not auth_provider.password:
473
+ # if no password is provided, we need to query the user to get one.
474
+ password = getpass.getpass()
475
+ self.auth_provider = PlainTextAuthProvider(username=auth_provider.username, password=password)
476
+
477
+ self.cloudconf = cloudconf
478
+ self.keyspace = keyspace
479
+ self.ssl = ssl
480
+ self.tracing_enabled = tracing_enabled
481
+ self.page_size = self.default_page_size
482
+ self.expand_enabled = expand_enabled
483
+ if use_conn:
484
+ self.conn = use_conn
485
+ else:
486
+ kwargs = {}
487
+ if protocol_version is not None:
488
+ kwargs['protocol_version'] = protocol_version
489
+
490
+ self.profiles = {
491
+ EXEC_PROFILE_DEFAULT: ExecutionProfile(consistency_level=cassandra.ConsistencyLevel.ONE,
492
+ request_timeout=request_timeout,
493
+ row_factory=ordered_dict_factory)
494
+ }
495
+
496
+ if cloudconf is None:
497
+ if os.path.exists(self.hostname) and stat.S_ISSOCK(os.stat(self.hostname).st_mode):
498
+ kwargs['contact_points'] = (UnixSocketEndPoint(self.hostname),)
499
+ self.profiles[EXEC_PROFILE_DEFAULT].load_balancing_policy = WhiteListRoundRobinPolicy([UnixSocketEndPoint(self.hostname)])
500
+ else:
501
+ kwargs['contact_points'] = (self.hostname,)
502
+ self.profiles[EXEC_PROFILE_DEFAULT].load_balancing_policy = WhiteListRoundRobinPolicy([self.hostname])
503
+ kwargs['port'] = self.port
504
+ kwargs['ssl_context'] = sslhandling.ssl_settings(hostname, CONFIG_FILE) if ssl else None
505
+ # workaround until driver would know not to lose the DNS names for `server_hostname`
506
+ kwargs['ssl_options'] = {'server_hostname': self.hostname} if ssl else None
507
+ else:
508
+ assert 'scylla' in DRIVER_NAME.lower(), f"{DRIVER_NAME} {DRIVER_VERSION} isn't supported by scylla_cloud"
509
+ kwargs['scylla_cloud'] = cloudconf
510
+
511
+ self.conn = Cluster(cql_version=cqlver,
512
+ auth_provider=self.auth_provider,
513
+ control_connection_timeout=connect_timeout,
514
+ connect_timeout=connect_timeout,
515
+ execution_profiles=self.profiles,
516
+ **kwargs)
517
+ self.owns_connection = not use_conn
518
+
519
+ if keyspace:
520
+ self.session = self.conn.connect(keyspace)
521
+ else:
522
+ self.session = self.conn.connect()
523
+
524
+ if browser == "":
525
+ browser = None
526
+ self.browser = browser
527
+ self.color = color
528
+
529
+ self.display_nanotime_format = display_nanotime_format
530
+ self.display_timestamp_format = display_timestamp_format
531
+ self.display_date_format = display_date_format
532
+
533
+ self.display_float_precision = display_float_precision
534
+ self.display_double_precision = display_double_precision
535
+
536
+ self.display_timezone = display_timezone
537
+
538
+ self.scylla_version = None
539
+
540
+ self.get_connection_versions()
541
+ self.get_scylla_version()
542
+ self.set_expanded_cql_version(self.connection_versions['cql'])
543
+
544
+ self.current_keyspace = keyspace
545
+
546
+ self.max_trace_wait = max_trace_wait
547
+ self.session.max_trace_wait = max_trace_wait
548
+
549
+ self.tty = tty
550
+ self.encoding = encoding
551
+
552
+ self.output_codec = codecs.lookup(encoding)
553
+
554
+ self.statement = StringIO()
555
+ self.lineno = 1
556
+ self.in_comment = False
557
+
558
+ self.prompt = ''
559
+ if stdin is None:
560
+ stdin = sys.stdin
561
+
562
+ if tty:
563
+ self.reset_prompt()
564
+ self.report_connection()
565
+ print('Use HELP for help.')
566
+ else:
567
+ self.show_line_nums = True
568
+ self.stdin = stdin
569
+ self.query_out = sys.stdout
570
+ self.consistency_level = cassandra.ConsistencyLevel.ONE
571
+ self.serial_consistency_level = cassandra.ConsistencyLevel.SERIAL
572
+
573
+ self.empty_lines = 0
574
+ self.statement_error = False
575
+ self.single_statement = single_statement
576
+ self.is_subshell = is_subshell
577
+
578
+ @property
579
+ def batch_mode(self):
580
+ return not self.tty
581
+
582
+ def set_expanded_cql_version(self, ver):
583
+ ver, vertuple = full_cql_version(ver)
584
+ self.cql_version = ver
585
+ self.cql_ver_tuple = vertuple
586
+
587
+ def cqlver_atleast(self, major, minor=0, patch=0):
588
+ return self.cql_ver_tuple[:3] >= (major, minor, patch)
589
+
590
+ def myformat_value(self, val, cqltype=None, **kwargs):
591
+ if isinstance(val, DecodeError):
592
+ self.decoding_errors.append(val)
593
+ try:
594
+ dtformats = DateTimeFormat(timestamp_format=self.display_timestamp_format,
595
+ date_format=self.display_date_format, nanotime_format=self.display_nanotime_format,
596
+ timezone=self.display_timezone)
597
+ precision = self.display_double_precision if cqltype is not None and cqltype.type_name == 'double' \
598
+ else self.display_float_precision
599
+ return format_value(val, cqltype=cqltype, encoding=self.output_codec.name,
600
+ addcolor=self.color, date_time_format=dtformats,
601
+ float_precision=precision, **kwargs)
602
+ except Exception as e:
603
+ err = FormatError(val, e)
604
+ self.decoding_errors.append(err)
605
+ return format_value(err, cqltype=cqltype, encoding=self.output_codec.name, addcolor=self.color)
606
+
607
+ def myformat_colname(self, name, table_meta=None):
608
+ column_colors = COLUMN_NAME_COLORS.copy()
609
+ # check column role and color appropriately
610
+ if table_meta:
611
+ if name in [col.name for col in table_meta.partition_key]:
612
+ column_colors.default_factory = lambda: RED
613
+ elif name in [col.name for col in table_meta.clustering_key]:
614
+ column_colors.default_factory = lambda: CYAN
615
+ elif name in table_meta.columns and table_meta.columns[name].is_static:
616
+ column_colors.default_factory = lambda: WHITE
617
+ return self.myformat_value(name, colormap=column_colors)
618
+
619
+ def report_connection(self):
620
+ self.show_host()
621
+ self.show_version()
622
+
623
+ def show_host(self):
624
+ if self.cloudconf is not None:
625
+ print("Connected to {0} at Scylla Cloud."
626
+ .format(self.applycolor(self.get_cluster_name(), BLUE)))
627
+ else:
628
+ print("Connected to {0} at {1}:{2}"
629
+ .format(self.applycolor(self.get_cluster_name(), BLUE),
630
+ self.hostname,
631
+ self.port))
632
+
633
+ def show_version(self):
634
+ vers = self.connection_versions.copy()
635
+ vers['shver'] = version
636
+ # system.Versions['cql'] apparently does not reflect changes with
637
+ # set_cql_version.
638
+ vers['cql'] = self.cql_version
639
+ if self.scylla_version:
640
+ vers['build'] = "Scylla {0}".format(self.scylla_version)
641
+ else:
642
+ vers['build'] = "Cassandra %(build)s" % vers
643
+ print("[cqlsh %(shver)s | %(build)s | CQL spec %(cql)s | Native protocol v%(protocol)s]" % vers)
644
+
645
+ def show_session(self, sessionid, partial_session=False):
646
+ print_trace_session(self, self.session, sessionid, partial_session)
647
+
648
+ def show_replicas(self, token_value, keyspace=None):
649
+ ks = self.current_keyspace if keyspace is None else keyspace
650
+ token_map = self.conn.metadata.token_map
651
+ nodes = token_map.get_replicas(ks, token_map.token_class(token_value))
652
+ addresses = [x.address for x in nodes]
653
+ print(f"{addresses}")
654
+
655
+ def get_connection_versions(self):
656
+ result, = self.session.execute("select * from system.local where key = 'local'")
657
+ vers = {
658
+ 'build': result['release_version'],
659
+ 'protocol': self.conn.protocol_version,
660
+ 'cql': result['cql_version'],
661
+ }
662
+ self.connection_versions = vers
663
+
664
+ def get_scylla_version(self):
665
+ try:
666
+ result, = self.session.execute("SELECT * FROM system.versions WHERE key = 'local'")
667
+ self.scylla_version = result['version']
668
+ except CQL_ERRORS:
669
+ pass
670
+
671
+ def get_keyspace_names(self):
672
+ return list(self.conn.metadata.keyspaces)
673
+
674
+ def get_columnfamily_names(self, ksname=None):
675
+ if ksname is None:
676
+ ksname = self.current_keyspace
677
+
678
+ return list(self.get_keyspace_meta(ksname).tables)
679
+
680
+ def get_materialized_view_names(self, ksname=None):
681
+ if ksname is None:
682
+ ksname = self.current_keyspace
683
+
684
+ return list(self.get_keyspace_meta(ksname).views)
685
+
686
+ def get_index_names(self, ksname=None):
687
+ if ksname is None:
688
+ ksname = self.current_keyspace
689
+
690
+ return list(self.get_keyspace_meta(ksname).indexes)
691
+
692
+ def get_column_names(self, ksname, cfname):
693
+ if ksname is None:
694
+ ksname = self.current_keyspace
695
+ layout = self.get_table_meta(ksname, cfname)
696
+ return list(layout.columns)
697
+
698
+ def get_usertype_names(self, ksname=None):
699
+ if ksname is None:
700
+ ksname = self.current_keyspace
701
+
702
+ return list(self.get_keyspace_meta(ksname).user_types)
703
+
704
+ def get_usertype_layout(self, ksname, typename):
705
+ if ksname is None:
706
+ ksname = self.current_keyspace
707
+
708
+ ks_meta = self.get_keyspace_meta(ksname)
709
+
710
+ try:
711
+ user_type = ks_meta.user_types[typename]
712
+ except KeyError:
713
+ raise UserTypeNotFound("User type {!r} not found".format(typename))
714
+
715
+ return list(zip(user_type.field_names, user_type.field_types))
716
+
717
+ def get_userfunction_names(self, ksname=None):
718
+ if ksname is None:
719
+ ksname = self.current_keyspace
720
+
721
+ return [f.name for f in list(self.get_keyspace_meta(ksname).functions.values())]
722
+
723
+ def get_useraggregate_names(self, ksname=None):
724
+ if ksname is None:
725
+ ksname = self.current_keyspace
726
+
727
+ return [f.name for f in list(self.get_keyspace_meta(ksname).aggregates.values())]
728
+
729
+ def get_cluster_name(self):
730
+ return self.conn.metadata.cluster_name
731
+
732
+ def get_partitioner(self):
733
+ return self.conn.metadata.partitioner
734
+
735
+ def get_keyspace_meta(self, ksname):
736
+ if ksname in self.conn.metadata.keyspaces:
737
+ return self.conn.metadata.keyspaces[ksname]
738
+
739
+ raise KeyspaceNotFound('Keyspace %r not found.' % ksname)
740
+
741
+ def get_keyspaces(self):
742
+ return list(self.conn.metadata.keyspaces.values())
743
+
744
+ def get_ring(self, ks):
745
+ self.conn.metadata.token_map.rebuild_keyspace(ks, build_if_absent=True)
746
+ return self.conn.metadata.token_map.tokens_to_hosts_by_ks[ks]
747
+
748
+ def get_table_meta(self, ksname, tablename):
749
+ if ksname is None:
750
+ ksname = self.current_keyspace
751
+ ksmeta = self.get_keyspace_meta(ksname)
752
+ if tablename not in ksmeta.tables:
753
+ if ksname == 'system_auth' and tablename in ['roles', 'role_permissions']:
754
+ self.get_fake_auth_table_meta(ksname, tablename)
755
+ else:
756
+ raise ColumnFamilyNotFound("Column family {} not found".format(tablename))
757
+ else:
758
+ return ksmeta.tables[tablename]
759
+
760
+ def get_fake_auth_table_meta(self, ksname, tablename):
761
+ # may be using external auth implementation so internal tables
762
+ # aren't actually defined in schema. In this case, we'll fake
763
+ # them up
764
+ if tablename == 'roles':
765
+ ks_meta = KeyspaceMetadata(ksname, True, None, None)
766
+ table_meta = TableMetadata(ks_meta, 'roles')
767
+ table_meta.columns['role'] = ColumnMetadata(table_meta, 'role', cassandra.cqltypes.UTF8Type)
768
+ table_meta.columns['is_superuser'] = ColumnMetadata(table_meta, 'is_superuser', cassandra.cqltypes.BooleanType)
769
+ table_meta.columns['can_login'] = ColumnMetadata(table_meta, 'can_login', cassandra.cqltypes.BooleanType)
770
+ elif tablename == 'role_permissions':
771
+ ks_meta = KeyspaceMetadata(ksname, True, None, None)
772
+ table_meta = TableMetadata(ks_meta, 'role_permissions')
773
+ table_meta.columns['role'] = ColumnMetadata(table_meta, 'role', cassandra.cqltypes.UTF8Type)
774
+ table_meta.columns['resource'] = ColumnMetadata(table_meta, 'resource', cassandra.cqltypes.UTF8Type)
775
+ table_meta.columns['permission'] = ColumnMetadata(table_meta, 'permission', cassandra.cqltypes.UTF8Type)
776
+ else:
777
+ raise ColumnFamilyNotFound("Column family {} not found".format(tablename))
778
+
779
+ def get_index_meta(self, ksname, idxname):
780
+ if ksname is None:
781
+ ksname = self.current_keyspace
782
+ ksmeta = self.get_keyspace_meta(ksname)
783
+
784
+ if idxname not in ksmeta.indexes:
785
+ raise IndexNotFound("Index {} not found".format(idxname))
786
+
787
+ return ksmeta.indexes[idxname]
788
+
789
+ def get_view_meta(self, ksname, viewname):
790
+ if ksname is None:
791
+ ksname = self.current_keyspace
792
+ ksmeta = self.get_keyspace_meta(ksname)
793
+
794
+ if viewname not in ksmeta.views:
795
+ raise MaterializedViewNotFound("Materialized view '{}' not found".format(viewname))
796
+ return ksmeta.views[viewname]
797
+
798
+ def get_object_meta(self, ks, name):
799
+ if name is None:
800
+ if ks and ks in self.conn.metadata.keyspaces:
801
+ return self.conn.metadata.keyspaces[ks]
802
+ elif self.current_keyspace is None:
803
+ raise ObjectNotFound("'{}' not found in keyspaces".format(ks))
804
+ else:
805
+ name = ks
806
+ ks = self.current_keyspace
807
+
808
+ if ks is None:
809
+ ks = self.current_keyspace
810
+
811
+ ksmeta = self.get_keyspace_meta(ks)
812
+
813
+ if name in ksmeta.tables:
814
+ return ksmeta.tables[name]
815
+ elif name in ksmeta.indexes:
816
+ return ksmeta.indexes[name]
817
+ elif name in ksmeta.views:
818
+ return ksmeta.views[name]
819
+
820
+ raise ObjectNotFound("'{}' not found in keyspace '{}'".format(name, ks))
821
+
822
+ def get_trigger_names(self, ksname=None):
823
+ if ksname is None:
824
+ ksname = self.current_keyspace
825
+
826
+ return [trigger.name
827
+ for table in list(self.get_keyspace_meta(ksname).tables.values())
828
+ for trigger in list(table.triggers.values())]
829
+
830
+ def reset_statement(self):
831
+ self.reset_prompt()
832
+ self.statement.truncate(0)
833
+ self.statement.seek(0)
834
+ self.empty_lines = 0
835
+
836
+ def reset_prompt(self):
837
+ if self.current_keyspace is None:
838
+ self.set_prompt(self.default_prompt, True)
839
+ else:
840
+ self.set_prompt(self.keyspace_prompt.format(self.current_keyspace), True)
841
+
842
+ def set_continue_prompt(self):
843
+ if self.empty_lines >= 3:
844
+ self.set_prompt("Statements are terminated with a ';'. You can press CTRL-C to cancel an incomplete statement.")
845
+ self.empty_lines = 0
846
+ return
847
+ if self.current_keyspace is None:
848
+ self.set_prompt(self.continue_prompt)
849
+ else:
850
+ spaces = ' ' * len(str(self.current_keyspace))
851
+ self.set_prompt(self.keyspace_continue_prompt.format(spaces))
852
+ self.empty_lines = self.empty_lines + 1 if not self.lastcmd else 0
853
+
854
+ @contextmanager
855
+ def prepare_loop(self):
856
+ readline = None
857
+ if self.tty and self.completekey:
858
+ try:
859
+ import readline
860
+ except ImportError:
861
+ pass
862
+ else:
863
+ old_completer = readline.get_completer()
864
+ readline.set_completer(self.complete)
865
+ if readline.__doc__ is not None and 'libedit' in readline.__doc__:
866
+ readline.parse_and_bind("bind -e")
867
+ readline.parse_and_bind("bind '" + self.completekey + "' rl_complete")
868
+ readline.parse_and_bind("bind ^R em-inc-search-prev")
869
+ else:
870
+ readline.parse_and_bind(self.completekey + ": complete")
871
+ # start coverage collection if requested, unless in subshell
872
+ if self.coverage and not self.is_subshell:
873
+ # check for coveragerc file, write it if missing
874
+ if os.path.exists(CQL_DIR):
875
+ self.coveragerc_path = os.path.join(CQL_DIR, '.coveragerc')
876
+ covdata_path = os.path.join(CQL_DIR, '.coverage')
877
+ if not os.path.isfile(self.coveragerc_path):
878
+ with open(self.coveragerc_path, 'w') as f:
879
+ f.writelines(["[run]\n",
880
+ "concurrency = multiprocessing\n",
881
+ "data_file = {}\n".format(covdata_path),
882
+ "parallel = true\n"]
883
+ )
884
+ # start coverage
885
+ import coverage
886
+ self.cov = coverage.Coverage(config_file=self.coveragerc_path)
887
+ self.cov.start()
888
+ try:
889
+ yield
890
+ finally:
891
+ if readline is not None:
892
+ readline.set_completer(old_completer)
893
+ if self.coverage and not self.is_subshell:
894
+ self.stop_coverage()
895
+
896
+ def get_input_line(self, prompt=''):
897
+ if self.tty:
898
+ self.lastcmd = input(str(prompt))
899
+ line = self.lastcmd + '\n'
900
+ else:
901
+ self.lastcmd = self.stdin.readline()
902
+ line = self.lastcmd
903
+ if not len(line):
904
+ raise EOFError
905
+ self.lineno += 1
906
+ return line
907
+
908
+ def use_stdin_reader(self, until='', prompt=''):
909
+ until += '\n'
910
+ while True:
911
+ try:
912
+ newline = self.get_input_line(prompt=prompt)
913
+ except EOFError:
914
+ return
915
+ if newline == until:
916
+ return
917
+ yield newline
918
+
919
+ def cmdloop(self, intro=None):
920
+ """
921
+ Adapted from cmd.Cmd's version, because there is literally no way with
922
+ cmd.Cmd.cmdloop() to tell the difference between "EOF" showing up in
923
+ input and an actual EOF.
924
+ """
925
+ with self.prepare_loop():
926
+ while not self.stop:
927
+ try:
928
+ if self.single_statement:
929
+ line = self.single_statement
930
+ self.stop = True
931
+ else:
932
+ line = self.get_input_line(self.prompt)
933
+ self.statement.write(line)
934
+ if self.onecmd(self.statement.getvalue()):
935
+ self.reset_statement()
936
+ except EOFError:
937
+ self.handle_eof()
938
+ except CQL_ERRORS as cqlerr:
939
+ self.printerr(cqlerr.message)
940
+ except KeyboardInterrupt:
941
+ self.reset_statement()
942
+ print('')
943
+
944
+ def strip_comment_blocks(self, statementtext):
945
+ comment_block_in_literal_string = re.search('["].*[/][*].*[*][/].*["]', statementtext)
946
+ if not comment_block_in_literal_string:
947
+ result = re.sub('[/][*].*[*][/]', "", statementtext)
948
+ if '*/' in result and '/*' not in result and not self.in_comment:
949
+ raise SyntaxError("Encountered comment block terminator without being in comment block")
950
+ if '/*' in result:
951
+ result = re.sub('[/][*].*', "", result)
952
+ self.in_comment = True
953
+ if '*/' in result:
954
+ result = re.sub('.*[*][/]', "", result)
955
+ self.in_comment = False
956
+ if self.in_comment and not re.findall('[/][*]|[*][/]', statementtext):
957
+ result = ''
958
+ return result
959
+ return statementtext
960
+
961
+ def onecmd(self, statementtext):
962
+ """
963
+ Returns true if the statement is complete and was handled (meaning it
964
+ can be reset).
965
+ """
966
+ statementtext = self.strip_comment_blocks(statementtext)
967
+ try:
968
+ statements, endtoken_escaped = cqlruleset.cql_split_statements(statementtext)
969
+ except pylexotron.LexingError as e:
970
+ if self.show_line_nums:
971
+ self.printerr('Invalid syntax at line {0}, char {1}'
972
+ .format(e.linenum, e.charnum))
973
+ else:
974
+ self.printerr('Invalid syntax at char {0}'.format(e.charnum))
975
+ statementline = statementtext.split('\n')[e.linenum - 1]
976
+ self.printerr(' {0}'.format(statementline))
977
+ self.printerr(' {0}^'.format(' ' * e.charnum))
978
+ return True
979
+
980
+ while statements and not statements[-1]:
981
+ statements = statements[:-1]
982
+ if not statements:
983
+ return True
984
+ if endtoken_escaped or statements[-1][-1][0] != 'endtoken':
985
+ self.set_continue_prompt()
986
+ return
987
+ for st in statements:
988
+ try:
989
+ self.handle_statement(st, statementtext)
990
+ except Exception as e:
991
+ if self.debug:
992
+ traceback.print_exc()
993
+ else:
994
+ self.printerr(e)
995
+ return True
996
+
997
+ def handle_eof(self):
998
+ if self.tty:
999
+ print('')
1000
+ statement = self.statement.getvalue()
1001
+ if statement.strip():
1002
+ if not self.onecmd(statement):
1003
+ self.printerr('Incomplete statement at end of file')
1004
+ self.do_exit()
1005
+
1006
+ def handle_statement(self, tokens, srcstr):
1007
+ # Concat multi-line statements and insert into history
1008
+ if readline is not None:
1009
+ nl_count = srcstr.count("\n")
1010
+
1011
+ new_hist = srcstr.replace("\n", " ").rstrip()
1012
+
1013
+ if nl_count > 1 and self.last_hist != new_hist:
1014
+ readline.add_history(new_hist)
1015
+
1016
+ self.last_hist = new_hist
1017
+ cmdword = tokens[0][1]
1018
+ if cmdword == '?':
1019
+ cmdword = 'help'
1020
+
1021
+ cmdword_lower = cmdword.lower()
1022
+
1023
+ # Describe statements get special treatment: we first want to
1024
+ # send the request to the server and only when it fails will
1025
+ # we attempt to perform it locally. That's why we don't want
1026
+ # to follow the logic below that starts with parsing.
1027
+ #
1028
+ # The reason for that is changes in Scylla may need to be reflected
1029
+ # in the grammar used in cqlsh. We want Scylla to be "independent"
1030
+ # in that regard, so unless necessary, we don't want to do the parsing
1031
+ # here.
1032
+ if cmdword_lower == 'describe' or cmdword_lower == 'desc':
1033
+ return self.perform_describe(cmdword, tokens, srcstr)
1034
+
1035
+ custom_handler = getattr(self, 'do_' + cmdword.lower(), None)
1036
+ if custom_handler:
1037
+ parsed = cqlruleset.cql_whole_parse_tokens(tokens, srcstr=srcstr,
1038
+ startsymbol='cqlshCommand')
1039
+ if parsed and not parsed.remainder:
1040
+ # successful complete parse
1041
+ return custom_handler(parsed)
1042
+ else:
1043
+ return self.handle_parse_error(cmdword, tokens, parsed, srcstr)
1044
+ return self.perform_statement(cqlruleset.cql_extract_orig(tokens, srcstr))
1045
+
1046
+ def handle_parse_error(self, cmdword, tokens, parsed, srcstr):
1047
+ if cmdword.lower() in ('select', 'insert', 'update', 'delete', 'truncate',
1048
+ 'create', 'drop', 'alter', 'grant', 'revoke',
1049
+ 'batch', 'list'):
1050
+ # hey, maybe they know about some new syntax we don't. type
1051
+ # assumptions won't work, but maybe the query will.
1052
+ return self.perform_statement(cqlruleset.cql_extract_orig(tokens, srcstr))
1053
+ if parsed:
1054
+ self.printerr('Improper %s command (problem at %r).' % (cmdword, parsed.remainder[0]))
1055
+ else:
1056
+ self.printerr(f'Improper {cmdword} command.')
1057
+
1058
+ def do_use(self, parsed):
1059
+ ksname = parsed.get_binding('ksname')
1060
+ success, _ = self.perform_simple_statement(SimpleStatement(parsed.extract_orig()))
1061
+ if success:
1062
+ if ksname[0] == '"' and ksname[-1] == '"':
1063
+ self.current_keyspace = self.cql_unprotect_name(ksname)
1064
+ else:
1065
+ self.current_keyspace = ksname.lower()
1066
+
1067
+ def do_select(self, parsed):
1068
+ tracing_was_enabled = self.tracing_enabled
1069
+ ksname = parsed.get_binding('ksname')
1070
+ stop_tracing = ksname == 'system_traces' or (ksname is None and self.current_keyspace == 'system_traces')
1071
+ self.tracing_enabled = self.tracing_enabled and not stop_tracing
1072
+ statement = parsed.extract_orig()
1073
+ self.perform_statement(statement)
1074
+ self.tracing_enabled = tracing_was_enabled
1075
+
1076
+ def perform_statement(self, statement):
1077
+
1078
+ stmt = SimpleStatement(statement, consistency_level=self.consistency_level, serial_consistency_level=self.serial_consistency_level, fetch_size=self.page_size if self.use_paging else None)
1079
+ success, future = self.perform_simple_statement(stmt)
1080
+
1081
+ if future:
1082
+ if future.warnings:
1083
+ self.print_warnings(future.warnings)
1084
+
1085
+ if self.tracing_enabled:
1086
+ try:
1087
+ for trace in future.get_all_query_traces(max_wait_per=self.max_trace_wait, query_cl=self.consistency_level):
1088
+ print_trace(self, trace)
1089
+ except TraceUnavailable:
1090
+ msg = "Statement trace did not complete within %d seconds; trace data may be incomplete." % (self.session.max_trace_wait,)
1091
+ self.writeresult(msg, color=RED)
1092
+ for trace_id in future.get_query_trace_ids():
1093
+ self.show_session(trace_id, partial_session=True)
1094
+ except Exception as err:
1095
+ self.printerr("Unable to fetch query trace: %s" % (str(err),))
1096
+
1097
+ return success
1098
+
1099
+ def parse_for_select_meta(self, query_string):
1100
+ try:
1101
+ parsed = cqlruleset.cql_parse(query_string)[1]
1102
+ except IndexError:
1103
+ return None
1104
+ ks = self.cql_unprotect_name(parsed.get_binding('ksname', None))
1105
+ name = self.cql_unprotect_name(parsed.get_binding('cfname', None))
1106
+ try:
1107
+ return self.get_table_meta(ks, name)
1108
+ except ColumnFamilyNotFound:
1109
+ try:
1110
+ return self.get_view_meta(ks, name)
1111
+ except MaterializedViewNotFound:
1112
+ raise ObjectNotFound("'{}' not found in keyspace '{}'".format(name, ks))
1113
+
1114
+ def parse_for_update_meta(self, query_string):
1115
+ try:
1116
+ parsed = cqlruleset.cql_parse(query_string)[1]
1117
+ except IndexError:
1118
+ return None
1119
+ ks = self.cql_unprotect_name(parsed.get_binding('ksname', None))
1120
+ cf = self.cql_unprotect_name(parsed.get_binding('cfname'))
1121
+ return self.get_table_meta(ks, cf)
1122
+
1123
+ def perform_simple_statement(self, statement):
1124
+ if not statement:
1125
+ return False, None
1126
+
1127
+ future = self.session.execute_async(statement, trace=self.tracing_enabled)
1128
+ result = None
1129
+ try:
1130
+ result = future.result()
1131
+ except CQL_ERRORS as err:
1132
+ err_msg = err.message if hasattr(err, 'message') else str(err)
1133
+ self.printerr(str(err.__class__.__name__) + ": " + err_msg)
1134
+ except Exception:
1135
+ import traceback
1136
+ self.printerr(traceback.format_exc())
1137
+
1138
+ # Even if statement failed we try to refresh schema if not agreed (see CASSANDRA-9689)
1139
+ if not future.is_schema_agreed:
1140
+ try:
1141
+ self.conn.refresh_schema_metadata(5) # will throw exception if there is a schema mismatch
1142
+ except Exception:
1143
+ self.printwarn("Warning: schema version mismatch detected; check the schema versions of your "
1144
+ "nodes in system.local and system.peers.")
1145
+ self.conn.refresh_schema_metadata(-1)
1146
+
1147
+ if result is None:
1148
+ return False, None
1149
+
1150
+ if statement.query_string[:6].lower() == 'select':
1151
+ self.print_result(result, self.parse_for_select_meta(statement.query_string))
1152
+ elif statement.query_string.lower().startswith("list users") or statement.query_string.lower().startswith("list roles"):
1153
+ self.print_result(result, self.get_table_meta('system_auth', 'roles'))
1154
+ elif statement.query_string.lower().startswith("list"):
1155
+ self.print_result(result, self.get_table_meta('system_auth', 'role_permissions'))
1156
+ elif result:
1157
+ # CAS INSERT/UPDATE
1158
+ self.writeresult("")
1159
+ self.print_static_result(result, self.parse_for_update_meta(statement.query_string), with_header=True, tty=self.tty)
1160
+ self.flush_output()
1161
+ return True, future
1162
+
1163
+ def print_result(self, result, table_meta):
1164
+ self.decoding_errors = []
1165
+
1166
+ self.writeresult("")
1167
+
1168
+ def print_all(result, table_meta, tty):
1169
+ # Return the number of rows in total
1170
+ num_rows = 0
1171
+ is_first = True
1172
+ while True:
1173
+ # Always print for the first page even it is empty
1174
+ if result.current_rows or is_first:
1175
+ with_header = is_first or tty
1176
+ self.print_static_result(result, table_meta, with_header, tty, num_rows)
1177
+ num_rows += len(result.current_rows)
1178
+ if result.has_more_pages:
1179
+ if self.shunted_query_out is None and tty:
1180
+ # Only pause when not capturing.
1181
+ input("---MORE---")
1182
+ result.fetch_next_page()
1183
+ else:
1184
+ if not tty:
1185
+ self.writeresult("")
1186
+ break
1187
+ is_first = False
1188
+ return num_rows
1189
+
1190
+ num_rows = print_all(result, table_meta, self.tty)
1191
+ self.writeresult("(%d rows)" % num_rows)
1192
+
1193
+ if self.decoding_errors:
1194
+ for err in self.decoding_errors[:2]:
1195
+ self.writeresult(err.message(), color=RED)
1196
+ if len(self.decoding_errors) > 2:
1197
+ self.writeresult('%d more decoding errors suppressed.'
1198
+ % (len(self.decoding_errors) - 2), color=RED)
1199
+
1200
+ def print_static_result(self, result, table_meta, with_header, tty, row_count_offset=0):
1201
+ if not result.column_names and not table_meta:
1202
+ return
1203
+
1204
+ column_names = result.column_names or list(table_meta.columns.keys())
1205
+ formatted_names = [self.myformat_colname(name, table_meta) for name in column_names]
1206
+ if not result.current_rows:
1207
+ # print header only
1208
+ self.print_formatted_result(formatted_names, None, with_header=True, tty=tty)
1209
+ return
1210
+
1211
+ cql_types = []
1212
+ if result.column_types:
1213
+ ks_name = table_meta.keyspace_name if table_meta else self.current_keyspace
1214
+ ks_meta = self.conn.metadata.keyspaces.get(ks_name, None)
1215
+ cql_types = [CqlType(cql_typename(t), ks_meta) for t in result.column_types]
1216
+
1217
+ formatted_values = [list(map(self.myformat_value, [row[c] for c in column_names], cql_types)) for row in result.current_rows]
1218
+
1219
+ if self.expand_enabled:
1220
+ self.print_formatted_result_vertically(formatted_names, formatted_values, row_count_offset)
1221
+ else:
1222
+ self.print_formatted_result(formatted_names, formatted_values, with_header, tty)
1223
+
1224
+ def print_formatted_result(self, formatted_names, formatted_values, with_header, tty):
1225
+ # determine column widths
1226
+ widths = [n.displaywidth for n in formatted_names]
1227
+ if formatted_values is not None:
1228
+ for fmtrow in formatted_values:
1229
+ for num, col in enumerate(fmtrow):
1230
+ widths[num] = max(widths[num], col.displaywidth)
1231
+
1232
+ # print header
1233
+ if with_header:
1234
+ header = ' | '.join(hdr.ljust(w, color=self.color) for (hdr, w) in zip(formatted_names, widths))
1235
+ self.writeresult(' ' + header.rstrip())
1236
+ self.writeresult('-%s-' % '-+-'.join('-' * w for w in widths))
1237
+
1238
+ # stop if there are no rows
1239
+ if formatted_values is None:
1240
+ self.writeresult("")
1241
+ return
1242
+
1243
+ # print row data
1244
+ for row in formatted_values:
1245
+ line = ' | '.join(col.rjust(w, color=self.color) for (col, w) in zip(row, widths))
1246
+ self.writeresult(' ' + line)
1247
+
1248
+ if tty:
1249
+ self.writeresult("")
1250
+
1251
+ def print_formatted_result_vertically(self, formatted_names, formatted_values, row_count_offset):
1252
+ max_col_width = max([n.displaywidth for n in formatted_names])
1253
+ max_val_width = max([n.displaywidth for row in formatted_values for n in row])
1254
+
1255
+ # for each row returned, list all the column-value pairs
1256
+ for i, row in enumerate(formatted_values):
1257
+ self.writeresult("@ Row %d" % (row_count_offset + i + 1))
1258
+ self.writeresult('-%s-' % '-+-'.join(['-' * max_col_width, '-' * max_val_width]))
1259
+ for field_id, field in enumerate(row):
1260
+ column = formatted_names[field_id].ljust(max_col_width, color=self.color)
1261
+ value = field.ljust(field.displaywidth, color=self.color)
1262
+ self.writeresult(' ' + " | ".join([column, value]))
1263
+ self.writeresult('')
1264
+
1265
+ def print_warnings(self, warnings):
1266
+ if warnings is None or len(warnings) == 0:
1267
+ return
1268
+
1269
+ self.writeresult('')
1270
+ self.writeresult('Warnings :')
1271
+ for warning in warnings:
1272
+ self.writeresult(warning)
1273
+ self.writeresult('')
1274
+
1275
+ def emptyline(self):
1276
+ pass
1277
+
1278
+ def parseline(self, line):
1279
+ # this shouldn't be needed
1280
+ raise NotImplementedError
1281
+
1282
+ def complete(self, text, state):
1283
+ if readline is None:
1284
+ return
1285
+ if state == 0:
1286
+ try:
1287
+ self.completion_matches = self.find_completions(text)
1288
+ except Exception:
1289
+ if debug_completion:
1290
+ import traceback
1291
+ traceback.print_exc()
1292
+ else:
1293
+ raise
1294
+ try:
1295
+ return self.completion_matches[state]
1296
+ except IndexError:
1297
+ return None
1298
+
1299
+ def find_completions(self, text):
1300
+ curline = readline.get_line_buffer()
1301
+ prevlines = self.statement.getvalue()
1302
+ wholestmt = prevlines + curline
1303
+ begidx = readline.get_begidx() + len(prevlines)
1304
+ stuff_to_complete = wholestmt[:begidx]
1305
+ return cqlruleset.cql_complete(stuff_to_complete, text, cassandra_conn=self,
1306
+ debug=debug_completion, startsymbol='cqlshCommand')
1307
+
1308
+ def set_prompt(self, prompt, prepend_user=False):
1309
+ if prepend_user and self.username:
1310
+ self.prompt = "{0}@{1}".format(self.username, prompt)
1311
+ return
1312
+ self.prompt = prompt
1313
+
1314
+ def cql_unprotect_name(self, namestr):
1315
+ if namestr is None:
1316
+ return
1317
+ return cqlruleset.dequote_name(namestr)
1318
+
1319
+ def cql_unprotect_value(self, valstr):
1320
+ if valstr is not None:
1321
+ return cqlruleset.dequote_value(valstr)
1322
+
1323
+ def print_recreate_keyspace(self, ksdef, out):
1324
+ out.write(ksdef.export_as_string())
1325
+ out.write("\n")
1326
+
1327
+ def print_recreate_columnfamily(self, ksname, cfname, out):
1328
+ """
1329
+ Output CQL commands which should be pasteable back into a CQL session
1330
+ to recreate the given table.
1331
+
1332
+ Writes output to the given out stream.
1333
+ """
1334
+ out.write(self.get_table_meta(ksname, cfname).export_as_string())
1335
+ out.write("\n")
1336
+
1337
+ def print_recreate_index(self, ksname, idxname, out):
1338
+ """
1339
+ Output CQL commands which should be pasteable back into a CQL session
1340
+ to recreate the given index.
1341
+
1342
+ Writes output to the given out stream.
1343
+ """
1344
+ out.write(self.get_index_meta(ksname, idxname).export_as_string())
1345
+ out.write("\n")
1346
+
1347
+ def print_recreate_materialized_view(self, ksname, viewname, out):
1348
+ """
1349
+ Output CQL commands which should be pasteable back into a CQL session
1350
+ to recreate the given materialized view.
1351
+
1352
+ Writes output to the given out stream.
1353
+ """
1354
+ out.write(self.get_view_meta(ksname, viewname).export_as_string())
1355
+ out.write("\n")
1356
+
1357
+ def print_recreate_object(self, ks, name, out):
1358
+ """
1359
+ Output CQL commands which should be pasteable back into a CQL session
1360
+ to recreate the given object (ks, table or index).
1361
+
1362
+ Writes output to the given out stream.
1363
+ """
1364
+ out.write(self.get_object_meta(ks, name).export_as_string())
1365
+ out.write("\n")
1366
+
1367
+ def describe_keyspaces_client(self):
1368
+ print('')
1369
+ cmd.Cmd.columnize(self, protect_names(self.get_keyspace_names()))
1370
+ print('')
1371
+
1372
+ def describe_keyspace_client(self, ksname):
1373
+ print('')
1374
+ self.print_recreate_keyspace(self.get_keyspace_meta(ksname), sys.stdout)
1375
+ print('')
1376
+
1377
+ def describe_columnfamily_client(self, ksname, cfname):
1378
+ if ksname is None:
1379
+ ksname = self.current_keyspace
1380
+ if ksname is None:
1381
+ raise NoKeyspaceError("No keyspace specified and no current keyspace")
1382
+ print('')
1383
+ self.print_recreate_columnfamily(ksname, cfname, sys.stdout)
1384
+ print('')
1385
+
1386
+ def describe_index_client(self, ksname, idxname):
1387
+ print('')
1388
+ self.print_recreate_index(ksname, idxname, sys.stdout)
1389
+ print('')
1390
+
1391
+ def describe_materialized_view_client(self, ksname, viewname):
1392
+ if ksname is None:
1393
+ ksname = self.current_keyspace
1394
+ if ksname is None:
1395
+ raise NoKeyspaceError("No keyspace specified and no current keyspace")
1396
+ print('')
1397
+ self.print_recreate_materialized_view(ksname, viewname, sys.stdout)
1398
+ print('')
1399
+
1400
+ def describe_object_client(self, ks, name):
1401
+ print('')
1402
+ self.print_recreate_object(ks, name, sys.stdout)
1403
+ print('')
1404
+
1405
+ def describe_columnfamilies_client(self, ksname):
1406
+ print('')
1407
+ if ksname is None:
1408
+ for k in self.get_keyspaces():
1409
+ name = protect_name(k.name)
1410
+ print('Keyspace %s' % (name,))
1411
+ print('---------%s' % ('-' * len(name)))
1412
+ cmd.Cmd.columnize(self, protect_names(self.get_columnfamily_names(k.name)))
1413
+ print('')
1414
+ else:
1415
+ cmd.Cmd.columnize(self, protect_names(self.get_columnfamily_names(ksname)))
1416
+ print('')
1417
+
1418
+ def describe_functions_client(self, ksname):
1419
+ print('')
1420
+ if ksname is None:
1421
+ for ksmeta in self.get_keyspaces():
1422
+ name = protect_name(ksmeta.name)
1423
+ print('Keyspace %s' % (name,))
1424
+ print('---------%s' % ('-' * len(name)))
1425
+ self._columnize_unicode(list(ksmeta.functions.keys()))
1426
+ else:
1427
+ ksmeta = self.get_keyspace_meta(ksname)
1428
+ self._columnize_unicode(list(ksmeta.functions.keys()))
1429
+
1430
+ def describe_function_client(self, ksname, functionname):
1431
+ if ksname is None:
1432
+ ksname = self.current_keyspace
1433
+ if ksname is None:
1434
+ raise NoKeyspaceError("No keyspace specified and no current keyspace")
1435
+ print('')
1436
+ ksmeta = self.get_keyspace_meta(ksname)
1437
+ functions = [f for f in list(ksmeta.functions.values()) if f.name == functionname]
1438
+ if len(functions) == 0:
1439
+ raise FunctionNotFound("User defined function {} not found".format(functionname))
1440
+ print("\n\n".join(func.export_as_string() for func in functions))
1441
+ print('')
1442
+
1443
+ def describe_aggregates_client(self, ksname):
1444
+ print('')
1445
+ if ksname is None:
1446
+ for ksmeta in self.get_keyspaces():
1447
+ name = protect_name(ksmeta.name)
1448
+ print('Keyspace %s' % (name,))
1449
+ print('---------%s' % ('-' * len(name)))
1450
+ self._columnize_unicode(list(ksmeta.aggregates.keys()))
1451
+ else:
1452
+ ksmeta = self.get_keyspace_meta(ksname)
1453
+ self._columnize_unicode(list(ksmeta.aggregates.keys()))
1454
+
1455
+ def describe_aggregate_client(self, ksname, aggregatename):
1456
+ if ksname is None:
1457
+ ksname = self.current_keyspace
1458
+ if ksname is None:
1459
+ raise NoKeyspaceError("No keyspace specified and no current keyspace")
1460
+ print('')
1461
+ ksmeta = self.get_keyspace_meta(ksname)
1462
+ aggregates = [f for f in list(ksmeta.aggregates.values()) if f.name == aggregatename]
1463
+ if len(aggregates) == 0:
1464
+ raise FunctionNotFound("User defined aggregate {} not found".format(aggregatename))
1465
+ print("\n\n".join(aggr.export_as_string() for aggr in aggregates))
1466
+ print('')
1467
+
1468
+ def describe_usertypes_client(self, ksname):
1469
+ print('')
1470
+ if ksname is None:
1471
+ for ksmeta in self.get_keyspaces():
1472
+ name = protect_name(ksmeta.name)
1473
+ print('Keyspace %s' % (name,))
1474
+ print('---------%s' % ('-' * len(name)))
1475
+ self._columnize_unicode(list(ksmeta.user_types.keys()), quote=True)
1476
+ else:
1477
+ ksmeta = self.get_keyspace_meta(ksname)
1478
+ self._columnize_unicode(list(ksmeta.user_types.keys()), quote=True)
1479
+
1480
+ def describe_usertype_client(self, ksname, typename):
1481
+ if ksname is None:
1482
+ ksname = self.current_keyspace
1483
+ if ksname is None:
1484
+ raise NoKeyspaceError("No keyspace specified and no current keyspace")
1485
+ print('')
1486
+ ksmeta = self.get_keyspace_meta(ksname)
1487
+ try:
1488
+ usertype = ksmeta.user_types[typename]
1489
+ except KeyError:
1490
+ raise UserTypeNotFound("User type {} not found".format(typename))
1491
+ print(usertype.export_as_string())
1492
+
1493
+ def _columnize_unicode(self, name_list, quote=False):
1494
+ """
1495
+ Used when columnizing identifiers that may contain unicode
1496
+ """
1497
+ names = [n for n in name_list]
1498
+ if quote:
1499
+ names = protect_names(names)
1500
+ cmd.Cmd.columnize(self, names)
1501
+ print('')
1502
+
1503
+ def describe_cluster_client(self):
1504
+ print('\nCluster: %s' % self.get_cluster_name())
1505
+ p = trim_if_present(self.get_partitioner(), 'org.apache.cassandra.dht.')
1506
+ print('Partitioner: %s\n' % p)
1507
+ # TODO: snitch?
1508
+ # snitch = trim_if_present(self.get_snitch(), 'org.apache.cassandra.locator.')
1509
+ # print 'Snitch: %s\n' % snitch
1510
+ if self.current_keyspace is not None and self.current_keyspace != 'system':
1511
+ print("Range ownership:")
1512
+ ring = self.get_ring(self.current_keyspace)
1513
+ for entry in list(ring.items()):
1514
+ print(' %39s [%s]' % (str(entry[0].value), ', '.join([host.address for host in entry[1]])))
1515
+ print('')
1516
+
1517
+ def describe_schema_client(self, include_system=False):
1518
+ print('')
1519
+ for k in self.get_keyspaces():
1520
+ if include_system or k.name not in cql3handling.SYSTEM_KEYSPACES:
1521
+ self.print_recreate_keyspace(k, sys.stdout)
1522
+ print('')
1523
+
1524
+ # Precondition: the first token in `srcstr.lower()` is either `describe` or `desc`.
1525
+ def perform_describe(self, cmdword, tokens, srcstr):
1526
+ """
1527
+ DESCRIBE [cqlsh only]
1528
+
1529
+ (DESC may be used as a shorthand.)
1530
+
1531
+ Outputs information about the connected Cassandra cluster, or about
1532
+ the data objects stored in the cluster. Use in one of the following ways:
1533
+
1534
+ DESCRIBE KEYSPACES
1535
+
1536
+ Output the names of all keyspaces.
1537
+
1538
+ DESCRIBE KEYSPACE [<keyspacename>]
1539
+
1540
+ Output CQL commands that could be used to recreate the given keyspace,
1541
+ and the objects in it (such as tables, types, functions, etc.).
1542
+ In some cases, as the CQL interface matures, there will be some metadata
1543
+ about a keyspace that is not representable with CQL. That metadata will not be shown.
1544
+ The '<keyspacename>' argument may be omitted, in which case the current
1545
+ keyspace will be described.
1546
+
1547
+ DESCRIBE TABLES
1548
+
1549
+ Output the names of all tables in the current keyspace, or in all
1550
+ keyspaces if there is no current keyspace.
1551
+
1552
+ DESCRIBE TABLE [<keyspace>.]<tablename>
1553
+
1554
+ Output CQL commands that could be used to recreate the given table.
1555
+ In some cases, as above, there may be table metadata which is not
1556
+ representable and which will not be shown.
1557
+
1558
+ DESCRIBE INDEX <indexname>
1559
+
1560
+ Output the CQL command that could be used to recreate the given index.
1561
+ In some cases, there may be index metadata which is not representable
1562
+ and which will not be shown.
1563
+
1564
+ DESCRIBE MATERIALIZED VIEW <viewname>
1565
+
1566
+ Output the CQL command that could be used to recreate the given materialized view.
1567
+ In some cases, there may be materialized view metadata which is not representable
1568
+ and which will not be shown.
1569
+
1570
+ DESCRIBE CLUSTER
1571
+
1572
+ Output information about the connected Cassandra cluster, such as the
1573
+ cluster name, and the partitioner and snitch in use. When you are
1574
+ connected to a non-system keyspace, also shows endpoint-range
1575
+ ownership information for the Cassandra ring.
1576
+
1577
+ DESCRIBE [FULL] SCHEMA
1578
+
1579
+ Output CQL commands that could be used to recreate the entire (non-system) schema.
1580
+ Works as though "DESCRIBE KEYSPACE k" was invoked for each non-system keyspace
1581
+ k. Use DESCRIBE FULL SCHEMA to include the system keyspaces.
1582
+
1583
+ DESCRIBE TYPES
1584
+
1585
+ Output the names of all user-defined-types in the current keyspace, or in all
1586
+ keyspaces if there is no current keyspace.
1587
+
1588
+ DESCRIBE TYPE [<keyspace>.]<type>
1589
+
1590
+ Output the CQL command that could be used to recreate the given user-defined-type.
1591
+
1592
+ DESCRIBE FUNCTIONS
1593
+
1594
+ Output the names of all user-defined-functions in the current keyspace, or in all
1595
+ keyspaces if there is no current keyspace.
1596
+
1597
+ DESCRIBE FUNCTION [<keyspace>.]<function>
1598
+
1599
+ Output the CQL command that could be used to recreate the given user-defined-function.
1600
+
1601
+ DESCRIBE AGGREGATES
1602
+
1603
+ Output the names of all user-defined-aggregates in the current keyspace, or in all
1604
+ keyspaces if there is no current keyspace.
1605
+
1606
+ DESCRIBE AGGREGATE [<keyspace>.]<aggregate>
1607
+
1608
+ Output the CQL command that could be used to recreate the given user-defined-aggregate.
1609
+
1610
+ DESCRIBE <objname>
1611
+
1612
+ Output CQL commands that could be used to recreate the entire object schema,
1613
+ where object can be either a keyspace or a table or an index or a materialized
1614
+ view (in this order).
1615
+ """
1616
+
1617
+ def perform_describe_locally(parsed):
1618
+ what = parsed.matched[1][1].lower()
1619
+ if what == 'functions':
1620
+ self.describe_functions_client(self.current_keyspace)
1621
+ elif what == 'function':
1622
+ ksname = self.cql_unprotect_name(parsed.get_binding('ksname', None))
1623
+ functionname = self.cql_unprotect_name(parsed.get_binding('udfname'))
1624
+ self.describe_function_client(ksname, functionname)
1625
+ elif what == 'aggregates':
1626
+ self.describe_aggregates_client(self.current_keyspace)
1627
+ elif what == 'aggregate':
1628
+ ksname = self.cql_unprotect_name(parsed.get_binding('ksname', None))
1629
+ aggregatename = self.cql_unprotect_name(parsed.get_binding('udaname'))
1630
+ self.describe_aggregate_client(ksname, aggregatename)
1631
+ elif what == 'keyspaces':
1632
+ self.describe_keyspaces_client()
1633
+ elif what == 'keyspace':
1634
+ ksname = self.cql_unprotect_name(parsed.get_binding('ksname', ''))
1635
+ if not ksname:
1636
+ ksname = self.current_keyspace
1637
+ if ksname is None:
1638
+ self.printerr('Not in any keyspace.')
1639
+ return
1640
+ self.describe_keyspace_client(ksname)
1641
+ elif what in ('columnfamily', 'table'):
1642
+ ks = self.cql_unprotect_name(parsed.get_binding('ksname', None))
1643
+ cf = self.cql_unprotect_name(parsed.get_binding('cfname'))
1644
+ self.describe_columnfamily_client(ks, cf)
1645
+ elif what == 'index':
1646
+ ks = self.cql_unprotect_name(parsed.get_binding('ksname', None))
1647
+ idx = self.cql_unprotect_name(parsed.get_binding('idxname', None))
1648
+ self.describe_index_client(ks, idx)
1649
+ elif what == 'materialized' and parsed.matched[2][1].lower() == 'view':
1650
+ ks = self.cql_unprotect_name(parsed.get_binding('ksname', None))
1651
+ mv = self.cql_unprotect_name(parsed.get_binding('mvname'))
1652
+ self.describe_materialized_view_client(ks, mv)
1653
+ elif what in ('columnfamilies', 'tables'):
1654
+ self.describe_columnfamilies_client(self.current_keyspace)
1655
+ elif what == 'types':
1656
+ self.describe_usertypes_client(self.current_keyspace)
1657
+ elif what == 'type':
1658
+ ks = self.cql_unprotect_name(parsed.get_binding('ksname', None))
1659
+ ut = self.cql_unprotect_name(parsed.get_binding('utname'))
1660
+ self.describe_usertype_client(ks, ut)
1661
+ elif what == 'cluster':
1662
+ self.describe_cluster_client()
1663
+ elif what == 'schema':
1664
+ self.describe_schema_client(False)
1665
+ elif what == 'full' and parsed.matched[2][1].lower() == 'schema':
1666
+ self.describe_schema_client(True)
1667
+ elif what:
1668
+ ks = self.cql_unprotect_name(parsed.get_binding('ksname', None))
1669
+ name = self.cql_unprotect_name(parsed.get_binding('cfname'))
1670
+ if not name:
1671
+ name = self.cql_unprotect_name(parsed.get_binding('idxname', None))
1672
+ if not name:
1673
+ name = self.cql_unprotect_name(parsed.get_binding('mvname', None))
1674
+ self.describe_object_client(ks, name)
1675
+
1676
+ stmt = SimpleStatement(srcstr, consistency_level=cassandra.ConsistencyLevel.LOCAL_ONE,
1677
+ fetch_size=self.page_size if self.use_paging else None)
1678
+ future = self.session.execute_async(stmt)
1679
+ try:
1680
+ result = future.result()
1681
+
1682
+ # The second token in the statement indicates which
1683
+ # kind of DESCRIBE we're performing.
1684
+ what = srcstr.split()[1].lower().rstrip(';')
1685
+
1686
+ if what in ('columnfamilies', 'tables', 'types', 'functions', 'aggregates'):
1687
+ self.describe_list(result)
1688
+ elif what == 'keyspaces':
1689
+ self.describe_keyspaces(result)
1690
+ elif what == 'cluster':
1691
+ self.describe_cluster(result)
1692
+ elif what:
1693
+ self.describe_element(result)
1694
+
1695
+ except cassandra.protocol.SyntaxException:
1696
+ # Server doesn't support DESCRIBE query, retry with
1697
+ # client-side DESCRIBE implementation
1698
+ parsed = cqlruleset.cql_whole_parse_tokens(tokens, srcstr=srcstr,
1699
+ startsymbol='cqlshCommand')
1700
+ if parsed and not parsed.remainder:
1701
+ return perform_describe_locally(parsed)
1702
+ else:
1703
+ return self.handle_parse_error(cmdword, tokens, parsed, srcstr)
1704
+ except CQL_ERRORS as err:
1705
+ err_msg = err.message if hasattr(err, 'message') else str(err)
1706
+ self.printerr(err_msg.partition("message=")[2].strip('"'))
1707
+ except Exception:
1708
+ import traceback
1709
+ self.printerr(traceback.format_exc())
1710
+
1711
+ if future:
1712
+ if future.warnings:
1713
+ self.print_warnings(future.warnings)
1714
+
1715
+ def describe_keyspaces(self, rows):
1716
+ """
1717
+ Print the output for a DESCRIBE KEYSPACES query
1718
+ """
1719
+ names = [r['name'] for r in rows]
1720
+
1721
+ print('')
1722
+ cmd.Cmd.columnize(self, names)
1723
+ print('')
1724
+
1725
+ def describe_list(self, rows):
1726
+ """
1727
+ Print the output for all the DESCRIBE queries for element names (e.g DESCRIBE TABLES, DESCRIBE FUNCTIONS ...)
1728
+ """
1729
+ keyspace = None
1730
+ names = list()
1731
+ for row in rows:
1732
+ if row['keyspace_name'] != keyspace:
1733
+ if keyspace is not None:
1734
+ self.print_keyspace_element_names(keyspace, names)
1735
+
1736
+ keyspace = row['keyspace_name']
1737
+ names = list()
1738
+
1739
+ names.append(str(row['name']))
1740
+
1741
+ if keyspace is not None:
1742
+ self.print_keyspace_element_names(keyspace, names)
1743
+ print('')
1744
+
1745
+ def print_keyspace_element_names(self, keyspace, names):
1746
+ print('')
1747
+ if self.current_keyspace is None:
1748
+ print('Keyspace %s' % (keyspace))
1749
+ print('---------%s' % ('-' * len(keyspace)))
1750
+ cmd.Cmd.columnize(self, names)
1751
+
1752
+ def describe_element(self, rows):
1753
+ """
1754
+ Print the output for all the DESCRIBE queries where an element name as been specified (e.g DESCRIBE TABLE, DESCRIBE INDEX ...)
1755
+ """
1756
+ for row in rows:
1757
+ print('')
1758
+ self.query_out.write(row['create_statement'])
1759
+ print('')
1760
+
1761
+ def describe_cluster(self, rows):
1762
+ """
1763
+ Print the output for a DESCRIBE CLUSTER query.
1764
+
1765
+ If a specified keyspace was in use the returned ResultSet will contains a 'range_ownership' column,
1766
+ otherwise not.
1767
+ """
1768
+ for row in rows:
1769
+ print('\nCluster: %s' % row['cluster'])
1770
+ print('Partitioner: %s' % row['partitioner'])
1771
+ print('Snitch: %s\n' % row['snitch'])
1772
+ if 'range_ownership' in row:
1773
+ print("Range ownership:")
1774
+ for entry in list(row['range_ownership'].items()):
1775
+ print(' %39s [%s]' % (entry[0], ', '.join([host for host in entry[1]])))
1776
+ print('')
1777
+
1778
+ def do_copy(self, parsed):
1779
+ r"""
1780
+ COPY [cqlsh only]
1781
+
1782
+ COPY x FROM: Imports CSV data into a Cassandra table
1783
+ COPY x TO: Exports data from a Cassandra table in CSV format.
1784
+
1785
+ COPY <table_name> [ ( column [, ...] ) ]
1786
+ FROM ( '<file_pattern_1, file_pattern_2, ... file_pattern_n>' | STDIN )
1787
+ [ WITH <option>='value' [AND ...] ];
1788
+
1789
+ File patterns are either file names or valid python glob expressions, e.g. *.csv or folder/*.csv.
1790
+
1791
+ COPY <table_name> [ ( column [, ...] ) ]
1792
+ TO ( '<filename>' | STDOUT )
1793
+ [ WITH <option>='value' [AND ...] ];
1794
+
1795
+ Available common COPY options and defaults:
1796
+
1797
+ DELIMITER=',' - character that appears between records
1798
+ QUOTE='"' - quoting character to be used to quote fields
1799
+ ESCAPE='\' - character to appear before the QUOTE char when quoted
1800
+ HEADER=false - whether to ignore the first line
1801
+ NULL='' - string that represents a null value
1802
+ DATETIMEFORMAT= - timestamp strftime format
1803
+ '%Y-%m-%d %H:%M:%S%z' defaults to time_format value in cqlshrc
1804
+ MAXATTEMPTS=5 - the maximum number of attempts per batch or range
1805
+ REPORTFREQUENCY=0.25 - the frequency with which we display status updates in seconds
1806
+ DECIMALSEP='.' - the separator for decimal values
1807
+ THOUSANDSSEP='' - the separator for thousands digit groups
1808
+ BOOLSTYLE='True,False' - the representation for booleans, case insensitive, specify true followed by false,
1809
+ for example yes,no or 1,0
1810
+ NUMPROCESSES=n - the number of worker processes, by default the number of cores minus one
1811
+ capped at 16
1812
+ CONFIGFILE='' - a configuration file with the same format as .cqlshrc (see the Python ConfigParser
1813
+ documentation) where you can specify WITH options under the following optional
1814
+ sections: [copy], [copy-to], [copy-from], [copy:ks.table], [copy-to:ks.table],
1815
+ [copy-from:ks.table], where <ks> is your keyspace name and <table> is your table
1816
+ name. Options are read from these sections, in the order specified
1817
+ above, and command line options always override options in configuration files.
1818
+ Depending on the COPY direction, only the relevant copy-from or copy-to sections
1819
+ are used. If no configfile is specified then .cqlshrc is searched instead.
1820
+ RATEFILE='' - an optional file where to print the output statistics
1821
+
1822
+ Available COPY FROM options and defaults:
1823
+
1824
+ CHUNKSIZE=5000 - the size of chunks passed to worker processes
1825
+ INGESTRATE=100000 - an approximate ingest rate in rows per second
1826
+ MINBATCHSIZE=10 - the minimum size of an import batch
1827
+ MAXBATCHSIZE=20 - the maximum size of an import batch
1828
+ MAXROWS=-1 - the maximum number of rows, -1 means no maximum
1829
+ SKIPROWS=0 - the number of rows to skip
1830
+ SKIPCOLS='' - a comma separated list of column names to skip
1831
+ MAXPARSEERRORS=-1 - the maximum global number of parsing errors, -1 means no maximum
1832
+ MAXINSERTERRORS=1000 - the maximum global number of insert errors, -1 means no maximum
1833
+ ERRFILE='' - a file where to store all rows that could not be imported, by default this is
1834
+ import_ks_table.err where <ks> is your keyspace and <table> is your table name.
1835
+ PREPAREDSTATEMENTS=True - whether to use prepared statements when importing, by default True. Set this to
1836
+ False if you don't mind shifting data parsing to the cluster. The cluster will also
1837
+ have to compile every batch statement. For large and oversized clusters
1838
+ this will result in a faster import but for smaller clusters it may generate
1839
+ timeouts.
1840
+ TTL=3600 - the time to live in seconds, by default data will not expire
1841
+
1842
+ Available COPY TO options and defaults:
1843
+
1844
+ ENCODING='utf8' - encoding for CSV output
1845
+ PAGESIZE='1000' - the page size for fetching results
1846
+ PAGETIMEOUT=10 - the page timeout in seconds for fetching results
1847
+ BEGINTOKEN='' - the minimum token string to consider when exporting data
1848
+ ENDTOKEN='' - the maximum token string to consider when exporting data
1849
+ MAXREQUESTS=6 - the maximum number of requests each worker process can work on in parallel
1850
+ MAXOUTPUTSIZE='-1' - the maximum size of the output file measured in number of lines,
1851
+ beyond this maximum the output file will be split into segments,
1852
+ -1 means unlimited.
1853
+ FLOATPRECISION=5 - the number of digits displayed after the decimal point for cql float values
1854
+ DOUBLEPRECISION=12 - the number of digits displayed after the decimal point for cql double values
1855
+
1856
+ When entering CSV data on STDIN, you can use the sequence "\."
1857
+ on a line by itself to end the data input.
1858
+ """
1859
+
1860
+ ks = self.cql_unprotect_name(parsed.get_binding('ksname', None))
1861
+ if ks is None:
1862
+ ks = self.current_keyspace
1863
+ if ks is None:
1864
+ raise NoKeyspaceError("Not in any keyspace.")
1865
+ table = self.cql_unprotect_name(parsed.get_binding('cfname'))
1866
+ columns = parsed.get_binding('colnames', None)
1867
+ if columns is not None:
1868
+ columns = list(map(self.cql_unprotect_name, columns))
1869
+ else:
1870
+ # default to all known columns
1871
+ columns = self.get_column_names(ks, table)
1872
+
1873
+ fname = parsed.get_binding('fname', None)
1874
+ if fname is not None:
1875
+ fname = self.cql_unprotect_value(fname)
1876
+
1877
+ copyoptnames = list(map(str.lower, parsed.get_binding('optnames', ())))
1878
+ copyoptvals = list(map(self.cql_unprotect_value, parsed.get_binding('optvals', ())))
1879
+ opts = dict(list(zip(copyoptnames, copyoptvals)))
1880
+
1881
+ direction = parsed.get_binding('dir').upper()
1882
+ if direction == 'FROM':
1883
+ task = ImportTask(self, ks, table, columns, fname, opts, self.conn.protocol_version, CONFIG_FILE)
1884
+ elif direction == 'TO':
1885
+ task = ExportTask(self, ks, table, columns, fname, opts, self.conn.protocol_version, CONFIG_FILE)
1886
+ else:
1887
+ raise SyntaxError("Unknown direction %s" % direction)
1888
+
1889
+ task.run()
1890
+
1891
+ def do_show(self, parsed):
1892
+ """
1893
+ SHOW [cqlsh only]
1894
+
1895
+ Displays information about the current cqlsh session. Can be called in
1896
+ the following ways:
1897
+
1898
+ SHOW VERSION
1899
+
1900
+ Shows the version and build of the connected Cassandra instance, as
1901
+ well as the version of the CQL spec that the connected Cassandra
1902
+ instance understands.
1903
+
1904
+ SHOW HOST
1905
+
1906
+ Shows where cqlsh is currently connected.
1907
+
1908
+ SHOW SESSION <sessionid>
1909
+
1910
+ Pretty-prints the requested tracing session.
1911
+
1912
+ SHOW REPLICAS <token> (<keyspace>)
1913
+
1914
+ Lists the replica nodes by IP address for the given token. The current
1915
+ keyspace is used if one is not specified.
1916
+ """
1917
+ showwhat = parsed.get_binding('what').lower()
1918
+ if showwhat == 'version':
1919
+ self.get_connection_versions()
1920
+ self.get_scylla_version()
1921
+ self.show_version()
1922
+ elif showwhat == 'host':
1923
+ self.show_host()
1924
+ elif showwhat.startswith('session'):
1925
+ session_id = parsed.get_binding('sessionid').lower()
1926
+ self.show_session(UUID(session_id))
1927
+ elif showwhat.startswith('replicas'):
1928
+ token_id = parsed.get_binding('token')
1929
+ keyspace = parsed.get_binding('keyspace')
1930
+ self.show_replicas(token_id, keyspace)
1931
+ else:
1932
+ self.printerr('Wait, how do I show %r?' % (showwhat,))
1933
+
1934
+ def do_source(self, parsed):
1935
+ """
1936
+ SOURCE [cqlsh only]
1937
+
1938
+ Executes a file containing CQL statements. Gives the output for each
1939
+ statement in turn, if any, or any errors that occur along the way.
1940
+
1941
+ Errors do NOT abort execution of the CQL source file.
1942
+
1943
+ Usage:
1944
+
1945
+ SOURCE '<file>';
1946
+
1947
+ That is, the path to the file to be executed must be given inside a
1948
+ string literal. The path is interpreted relative to the current working
1949
+ directory. The tilde shorthand notation ('~/mydir') is supported for
1950
+ referring to $HOME.
1951
+
1952
+ See also the --file option to cqlsh.
1953
+ """
1954
+ fname = parsed.get_binding('fname')
1955
+ fname = os.path.expanduser(self.cql_unprotect_value(fname))
1956
+ try:
1957
+ encoding, bom_size = get_file_encoding_bomsize(fname)
1958
+ f = codecs.open(fname, 'r', encoding)
1959
+ f.seek(bom_size)
1960
+ except IOError as e:
1961
+ self.printerr('Could not open %r: %s' % (fname, e))
1962
+ return
1963
+ subshell = Shell(self.hostname, self.port, color=self.color,
1964
+ username=self.username,
1965
+ encoding=self.encoding, stdin=f, tty=False, use_conn=self.conn,
1966
+ cqlver=self.cql_version, keyspace=self.current_keyspace,
1967
+ tracing_enabled=self.tracing_enabled,
1968
+ display_nanotime_format=self.display_nanotime_format,
1969
+ display_timestamp_format=self.display_timestamp_format,
1970
+ display_date_format=self.display_date_format,
1971
+ display_float_precision=self.display_float_precision,
1972
+ display_double_precision=self.display_double_precision,
1973
+ display_timezone=self.display_timezone,
1974
+ max_trace_wait=self.max_trace_wait, ssl=self.ssl,
1975
+ request_timeout=self.session.default_timeout,
1976
+ connect_timeout=self.conn.connect_timeout,
1977
+ is_subshell=True,
1978
+ auth_provider=self.auth_provider,
1979
+ cloudconf=self.cloudconf)
1980
+ # duplicate coverage related settings in subshell
1981
+ if self.coverage:
1982
+ subshell.coverage = True
1983
+ subshell.coveragerc_path = self.coveragerc_path
1984
+ subshell.cmdloop()
1985
+ f.close()
1986
+
1987
+ def do_capture(self, parsed):
1988
+ """
1989
+ CAPTURE [cqlsh only]
1990
+
1991
+ Begins capturing command output and appending it to a specified file.
1992
+ Output will not be shown at the console while it is captured.
1993
+
1994
+ Usage:
1995
+
1996
+ CAPTURE '<file>';
1997
+ CAPTURE OFF;
1998
+ CAPTURE;
1999
+
2000
+ That is, the path to the file to be appended to must be given inside a
2001
+ string literal. The path is interpreted relative to the current working
2002
+ directory. The tilde shorthand notation ('~/mydir') is supported for
2003
+ referring to $HOME.
2004
+
2005
+ Only query result output is captured. Errors and output from cqlsh-only
2006
+ commands will still be shown in the cqlsh session.
2007
+
2008
+ To stop capturing output and show it in the cqlsh session again, use
2009
+ CAPTURE OFF.
2010
+
2011
+ To inspect the current capture configuration, use CAPTURE with no
2012
+ arguments.
2013
+ """
2014
+ fname = parsed.get_binding('fname')
2015
+ if fname is None:
2016
+ if self.shunted_query_out is not None:
2017
+ print("Currently capturing query output to %r." % (self.query_out.name,))
2018
+ else:
2019
+ print("Currently not capturing query output.")
2020
+ return
2021
+
2022
+ if fname.upper() == 'OFF':
2023
+ if self.shunted_query_out is None:
2024
+ self.printerr('Not currently capturing output.')
2025
+ return
2026
+ self.query_out.close()
2027
+ self.query_out = self.shunted_query_out
2028
+ self.color = self.shunted_color
2029
+ self.shunted_query_out = None
2030
+ del self.shunted_color
2031
+ return
2032
+
2033
+ if self.shunted_query_out is not None:
2034
+ self.printerr('Already capturing output to %s. Use CAPTURE OFF'
2035
+ ' to disable.' % (self.query_out.name,))
2036
+ return
2037
+
2038
+ fname = os.path.expanduser(self.cql_unprotect_value(fname))
2039
+ try:
2040
+ f = open(fname, 'a')
2041
+ except IOError as e:
2042
+ self.printerr('Could not open %r for append: %s' % (fname, e))
2043
+ return
2044
+ self.shunted_query_out = self.query_out
2045
+ self.shunted_color = self.color
2046
+ self.query_out = f
2047
+ self.color = False
2048
+ print('Now capturing query output to %r.' % (fname,))
2049
+
2050
+ def do_tracing(self, parsed):
2051
+ """
2052
+ TRACING [cqlsh]
2053
+
2054
+ Enables or disables request tracing.
2055
+
2056
+ TRACING ON
2057
+
2058
+ Enables tracing for all further requests.
2059
+
2060
+ TRACING OFF
2061
+
2062
+ Disables tracing.
2063
+
2064
+ TRACING
2065
+
2066
+ TRACING with no arguments shows the current tracing status.
2067
+ """
2068
+ self.tracing_enabled = SwitchCommand("TRACING", "Tracing").execute(self.tracing_enabled, parsed, self.printerr)
2069
+
2070
+ def do_expand(self, parsed):
2071
+ """
2072
+ EXPAND [cqlsh]
2073
+
2074
+ Enables or disables expanded (vertical) output.
2075
+
2076
+ EXPAND ON
2077
+
2078
+ Enables expanded (vertical) output.
2079
+
2080
+ EXPAND OFF
2081
+
2082
+ Disables expanded (vertical) output.
2083
+
2084
+ EXPAND
2085
+
2086
+ EXPAND with no arguments shows the current value of expand setting.
2087
+ """
2088
+ self.expand_enabled = SwitchCommand("EXPAND", "Expanded output").execute(self.expand_enabled, parsed, self.printerr)
2089
+
2090
+ def do_consistency(self, parsed):
2091
+ """
2092
+ CONSISTENCY [cqlsh only]
2093
+
2094
+ Overrides default consistency level (default level is ONE).
2095
+
2096
+ CONSISTENCY <level>
2097
+
2098
+ Sets consistency level for future requests.
2099
+
2100
+ Valid consistency levels:
2101
+
2102
+ ANY, ONE, TWO, THREE, QUORUM, ALL, LOCAL_ONE, LOCAL_QUORUM, EACH_QUORUM, SERIAL and LOCAL_SERIAL.
2103
+
2104
+ SERIAL and LOCAL_SERIAL may be used only for SELECTs; will be rejected with updates.
2105
+
2106
+ CONSISTENCY
2107
+
2108
+ CONSISTENCY with no arguments shows the current consistency level.
2109
+ """
2110
+ level = parsed.get_binding('level')
2111
+ if level is None:
2112
+ print('Current consistency level is %s.' % (cassandra.ConsistencyLevel.value_to_name[self.consistency_level]))
2113
+ return
2114
+
2115
+ self.consistency_level = cassandra.ConsistencyLevel.name_to_value[level.upper()]
2116
+ print('Consistency level set to %s.' % (level.upper(),))
2117
+
2118
+ def do_serial(self, parsed):
2119
+ """
2120
+ SERIAL CONSISTENCY [cqlsh only]
2121
+
2122
+ Overrides serial consistency level (default level is SERIAL).
2123
+
2124
+ SERIAL CONSISTENCY <level>
2125
+
2126
+ Sets consistency level for future conditional updates.
2127
+
2128
+ Valid consistency levels:
2129
+
2130
+ SERIAL, LOCAL_SERIAL.
2131
+
2132
+ SERIAL CONSISTENCY
2133
+
2134
+ SERIAL CONSISTENCY with no arguments shows the current consistency level.
2135
+ """
2136
+ level = parsed.get_binding('level')
2137
+ if level is None:
2138
+ print('Current serial consistency level is %s.' % (cassandra.ConsistencyLevel.value_to_name[self.serial_consistency_level]))
2139
+ return
2140
+
2141
+ self.serial_consistency_level = cassandra.ConsistencyLevel.name_to_value[level.upper()]
2142
+ print('Serial consistency level set to %s.' % (level.upper(),))
2143
+
2144
+ def do_login(self, parsed):
2145
+ """
2146
+ LOGIN [cqlsh only]
2147
+
2148
+ Changes login information without requiring restart.
2149
+
2150
+ LOGIN <username> (<password>)
2151
+
2152
+ Login using the specified username. If password is specified, it will be used
2153
+ otherwise, you will be prompted to enter.
2154
+ """
2155
+ username = parsed.get_binding('username')
2156
+ password = parsed.get_binding('password')
2157
+ if password is None:
2158
+ password = getpass.getpass()
2159
+ else:
2160
+ password = password[1:-1]
2161
+
2162
+ auth_provider = PlainTextAuthProvider(username=username, password=password)
2163
+
2164
+ kwargs = {}
2165
+ if self.cloudconf is None:
2166
+ kwargs['contact_points'] = (self.hostname,)
2167
+ kwargs['port'] = self.port
2168
+ kwargs['ssl_context'] = self.conn.ssl_context
2169
+ kwargs['ssl_options'] = self.conn.ssl_options
2170
+ else:
2171
+ kwargs['scylla_cloud'] = self.cloudconf
2172
+
2173
+ conn = Cluster(cql_version=self.conn.cql_version,
2174
+ protocol_version=self.conn.protocol_version,
2175
+ auth_provider=auth_provider,
2176
+ control_connection_timeout=self.conn.connect_timeout,
2177
+ connect_timeout=self.conn.connect_timeout,
2178
+ execution_profiles=self.profiles,
2179
+ **kwargs)
2180
+
2181
+ if self.current_keyspace:
2182
+ session = conn.connect(self.current_keyspace)
2183
+ else:
2184
+ session = conn.connect()
2185
+
2186
+ # Copy session properties
2187
+ session.max_trace_wait = self.session.max_trace_wait
2188
+
2189
+ # Update after we've connected in case we fail to authenticate
2190
+ self.conn = conn
2191
+ self.auth_provider = auth_provider
2192
+ self.username = username
2193
+ self.session = session
2194
+
2195
+ def do_exit(self, parsed=None):
2196
+ """
2197
+ EXIT/QUIT [cqlsh only]
2198
+
2199
+ Exits cqlsh.
2200
+ """
2201
+ self.stop = True
2202
+ if self.owns_connection:
2203
+ self.conn.shutdown()
2204
+ do_quit = do_exit
2205
+
2206
+ def do_clear(self, parsed):
2207
+ """
2208
+ CLEAR/CLS [cqlsh only]
2209
+
2210
+ Clears the console.
2211
+ """
2212
+ subprocess.call('clear', shell=True)
2213
+ do_cls = do_clear
2214
+
2215
+ def do_debug(self, parsed):
2216
+ import pdb
2217
+ pdb.set_trace()
2218
+
2219
+ def get_help_topics(self):
2220
+ topics = [t[3:] for t in dir(self) if t.startswith('do_') and getattr(self, t, None).__doc__]
2221
+ for hide_from_help in ('quit',):
2222
+ topics.remove(hide_from_help)
2223
+ return topics
2224
+
2225
+ def columnize(self, slist, *a, **kw):
2226
+ return cmd.Cmd.columnize(self, sorted([u.upper() for u in slist]), *a, **kw)
2227
+
2228
+ def do_help(self, parsed):
2229
+ """
2230
+ HELP [cqlsh only]
2231
+
2232
+ Gives information about cqlsh commands. To see available topics,
2233
+ enter "HELP" without any arguments. To see help on a topic,
2234
+ use "HELP <topic>".
2235
+ """
2236
+ topics = parsed.get_binding('topic', ())
2237
+ if not topics:
2238
+ shell_topics = [t.upper() for t in self.get_help_topics()]
2239
+ self.print_topics("\nDocumented shell commands:", shell_topics, 15, 80)
2240
+ cql_topics = [t.upper() for t in cqldocs.get_help_topics()]
2241
+ self.print_topics("CQL help topics:", cql_topics, 15, 80)
2242
+ return
2243
+ for t in topics:
2244
+ if t.lower() in self.get_help_topics():
2245
+ doc = getattr(self, 'do_' + t.lower()).__doc__
2246
+ self.stdout.write(doc + "\n")
2247
+ elif t.lower() in cqldocs.get_help_topics():
2248
+ urlpart = cqldocs.get_help_topic(t)
2249
+ if urlpart is not None:
2250
+ url = "%s#%s" % (CASSANDRA_CQL_HTML, urlpart)
2251
+ if self.browser is not None:
2252
+ opened = webbrowser.get(self.browser).open_new_tab(url)
2253
+ else:
2254
+ opened = webbrowser.open_new_tab(url)
2255
+ if not opened:
2256
+ self.printerr("*** No browser to display CQL help. URL for help topic %s : %s" % (t, url))
2257
+ else:
2258
+ self.printerr("*** No help on %s" % (t,))
2259
+
2260
+ def do_unicode(self, parsed):
2261
+ """
2262
+ Textual input/output
2263
+
2264
+ When control characters, or other characters which can't be encoded
2265
+ in your current locale, are found in values of 'text' or 'ascii'
2266
+ types, it will be shown as a backslash escape. If color is enabled,
2267
+ any such backslash escapes will be shown in a different color from
2268
+ the surrounding text.
2269
+
2270
+ Unicode code points in your data will be output intact, if the
2271
+ encoding for your locale is capable of decoding them. If you prefer
2272
+ that non-ascii characters be shown with Python-style "\\uABCD"
2273
+ escape sequences, invoke cqlsh with an ASCII locale (for example,
2274
+ by setting the $LANG environment variable to "C").
2275
+ """
2276
+
2277
+ def do_paging(self, parsed):
2278
+ """
2279
+ PAGING [cqlsh]
2280
+
2281
+ Enables or disables query paging.
2282
+
2283
+ PAGING ON
2284
+
2285
+ Enables query paging for all further queries.
2286
+
2287
+ PAGING OFF
2288
+
2289
+ Disables paging.
2290
+
2291
+ PAGING
2292
+
2293
+ PAGING with no arguments shows the current query paging status.
2294
+ """
2295
+ (self.use_paging, requested_page_size) = SwitchCommandWithValue(
2296
+ "PAGING", "Query paging", value_type=int).execute(self.use_paging, parsed, self.printerr)
2297
+ if self.use_paging and requested_page_size is not None:
2298
+ self.page_size = requested_page_size
2299
+ if self.use_paging:
2300
+ print(("Page size: {}".format(self.page_size)))
2301
+ else:
2302
+ self.page_size = self.default_page_size
2303
+
2304
+ def applycolor(self, text, color=None):
2305
+ if not color or not self.color:
2306
+ return text
2307
+ return color + text + ANSI_RESET
2308
+
2309
+ def writeresult(self, text, color=None, newline=True, out=None):
2310
+ if out is None:
2311
+ out = self.query_out
2312
+
2313
+ # convert Exceptions, etc to text
2314
+ if not isinstance(text, str):
2315
+ text = str(text)
2316
+
2317
+ to_write = self.applycolor(text, color) + ('\n' if newline else '')
2318
+ out.write(to_write)
2319
+
2320
+ def flush_output(self):
2321
+ self.query_out.flush()
2322
+
2323
+ def printerr(self, text, color=RED, newline=True, shownum=None):
2324
+ self.statement_error = True
2325
+ if shownum is None:
2326
+ shownum = self.show_line_nums
2327
+ if shownum:
2328
+ text = '%s:%d:%s' % (self.stdin.name, self.lineno, text)
2329
+ self.writeresult(text, color, newline=newline, out=sys.stderr)
2330
+
2331
+ def printwarn(self, text, color=YELLOW, newline=True, shownum=None):
2332
+ if shownum is None:
2333
+ shownum = self.show_line_nums
2334
+ if shownum:
2335
+ text = '%s:%d:%s' % (self.stdin.name, self.lineno, text)
2336
+ self.writeresult(text, color, newline=newline, out=sys.stderr)
2337
+
2338
+ def stop_coverage(self):
2339
+ if self.coverage and self.cov is not None:
2340
+ self.cov.stop()
2341
+ self.cov.save()
2342
+ self.cov = None
2343
+
2344
+
2345
+ class SwitchCommand(object):
2346
+ command = None
2347
+ description = None
2348
+
2349
+ def __init__(self, command, desc):
2350
+ self.command = command
2351
+ self.description = desc
2352
+
2353
+ def execute(self, state, parsed, printerr):
2354
+ switch = parsed.get_binding('switch')
2355
+ if switch is None:
2356
+ if state:
2357
+ print("%s is currently enabled. Use %s OFF to disable"
2358
+ % (self.description, self.command))
2359
+ else:
2360
+ print("%s is currently disabled. Use %s ON to enable."
2361
+ % (self.description, self.command))
2362
+ return state
2363
+
2364
+ if switch.upper() == 'ON':
2365
+ if state:
2366
+ printerr('%s is already enabled. Use %s OFF to disable.'
2367
+ % (self.description, self.command))
2368
+ return state
2369
+ print('Now %s is enabled' % (self.description,))
2370
+ return True
2371
+
2372
+ if switch.upper() == 'OFF':
2373
+ if not state:
2374
+ printerr('%s is not enabled.' % (self.description,))
2375
+ return state
2376
+ print('Disabled %s.' % (self.description,))
2377
+ return False
2378
+
2379
+
2380
+ class SwitchCommandWithValue(SwitchCommand):
2381
+ """The same as SwitchCommand except it also accepts a value in place of ON.
2382
+
2383
+ This returns a tuple of the form: (SWITCH_VALUE, PASSED_VALUE)
2384
+ eg: PAGING 50 returns (True, 50)
2385
+ PAGING OFF returns (False, None)
2386
+ PAGING ON returns (True, None)
2387
+
2388
+ The value_type must match for the PASSED_VALUE, otherwise it will return None.
2389
+ """
2390
+ def __init__(self, command, desc, value_type=int):
2391
+ SwitchCommand.__init__(self, command, desc)
2392
+ self.value_type = value_type
2393
+
2394
+ def execute(self, state, parsed, printerr):
2395
+ binary_switch_value = SwitchCommand.execute(self, state, parsed, printerr)
2396
+ switch = parsed.get_binding('switch')
2397
+ try:
2398
+ value = self.value_type(switch)
2399
+ binary_switch_value = True
2400
+ except (ValueError, TypeError):
2401
+ value = None
2402
+ return binary_switch_value, value
2403
+
2404
+
2405
+ def option_with_default(cparser_getter, section, option, default=None):
2406
+ try:
2407
+ return cparser_getter(section, option)
2408
+ except configparser.Error:
2409
+ return default
2410
+
2411
+
2412
+ def raw_option_with_default(configs, section, option, default=None):
2413
+ """
2414
+ Same (almost) as option_with_default() but won't do any string interpolation.
2415
+ Useful for config values that include '%' symbol, e.g. time format string.
2416
+ """
2417
+ try:
2418
+ return configs.get(section, option, raw=True)
2419
+ except configparser.Error:
2420
+ return default
2421
+
2422
+
2423
+ def should_use_color():
2424
+ if not sys.stdout.isatty():
2425
+ return False
2426
+ if os.environ.get('TERM', '') in ('dumb', ''):
2427
+ return False
2428
+ try:
2429
+ p = subprocess.Popen(['tput', 'colors'], stdout=subprocess.PIPE)
2430
+ stdout, _ = p.communicate()
2431
+ if int(stdout.strip()) < 8:
2432
+ return False
2433
+ except (OSError, ImportError, ValueError):
2434
+ # oh well, we tried. at least we know there's a $TERM and it's
2435
+ # not "dumb".
2436
+ pass
2437
+ return True
2438
+
2439
+
2440
+ def read_options(cmdlineargs, environment):
2441
+ configs = configparser.ConfigParser()
2442
+ configs.read(CONFIG_FILE)
2443
+
2444
+ rawconfigs = configparser.RawConfigParser()
2445
+ rawconfigs.read(CONFIG_FILE)
2446
+
2447
+ username_from_cqlshrc = option_with_default(configs.get, 'authentication', 'username')
2448
+ password_from_cqlshrc = option_with_default(rawconfigs.get, 'authentication', 'password')
2449
+ if username_from_cqlshrc or password_from_cqlshrc:
2450
+ if password_from_cqlshrc and not is_file_secure(os.path.expanduser(CONFIG_FILE)):
2451
+ print("\nWarning: Password is found in an insecure cqlshrc file. The file is owned or readable by other users on the system.",
2452
+ end='', file=sys.stderr)
2453
+ print("\nNotice: Credentials in the cqlshrc file is deprecated and will be ignored in the future."
2454
+ "\nPlease use a credentials file to specify the username and password.\n"
2455
+ "\nTo use basic authentication, place the username and password in the [PlainTextAuthProvider] section of the credentials file.\n", file=sys.stderr)
2456
+
2457
+ optvalues = optparse.Values()
2458
+
2459
+ optvalues.username = None
2460
+ optvalues.password = None
2461
+ optvalues.credentials = os.path.expanduser(option_with_default(configs.get, 'authentication', 'credentials',
2462
+ os.path.join(CQL_DIR, 'credentials')))
2463
+ optvalues.keyspace = option_with_default(configs.get, 'authentication', 'keyspace')
2464
+ optvalues.browser = option_with_default(configs.get, 'ui', 'browser', None)
2465
+ optvalues.completekey = option_with_default(configs.get, 'ui', 'completekey',
2466
+ DEFAULT_COMPLETEKEY)
2467
+ optvalues.color = option_with_default(configs.getboolean, 'ui', 'color')
2468
+ optvalues.time_format = raw_option_with_default(configs, 'ui', 'time_format',
2469
+ DEFAULT_TIMESTAMP_FORMAT)
2470
+ optvalues.nanotime_format = raw_option_with_default(configs, 'ui', 'nanotime_format',
2471
+ DEFAULT_NANOTIME_FORMAT)
2472
+ optvalues.date_format = raw_option_with_default(configs, 'ui', 'date_format',
2473
+ DEFAULT_DATE_FORMAT)
2474
+ optvalues.float_precision = option_with_default(configs.getint, 'ui', 'float_precision',
2475
+ DEFAULT_FLOAT_PRECISION)
2476
+ optvalues.double_precision = option_with_default(configs.getint, 'ui', 'double_precision',
2477
+ DEFAULT_DOUBLE_PRECISION)
2478
+ optvalues.field_size_limit = option_with_default(configs.getint, 'csv', 'field_size_limit', csv.field_size_limit())
2479
+ optvalues.max_trace_wait = option_with_default(configs.getfloat, 'tracing', 'max_trace_wait',
2480
+ DEFAULT_MAX_TRACE_WAIT)
2481
+ optvalues.timezone = option_with_default(configs.get, 'ui', 'timezone', None)
2482
+
2483
+ optvalues.debug = False
2484
+ optvalues.driver_debug = False
2485
+ optvalues.coverage = False
2486
+ if 'CQLSH_COVERAGE' in environment.keys():
2487
+ optvalues.coverage = True
2488
+
2489
+ optvalues.file = None
2490
+ optvalues.ssl = option_with_default(configs.getboolean, 'connection', 'ssl', DEFAULT_SSL)
2491
+ optvalues.encoding = option_with_default(configs.get, 'ui', 'encoding', UTF8)
2492
+
2493
+ optvalues.tty = option_with_default(configs.getboolean, 'ui', 'tty', sys.stdin.isatty())
2494
+ optvalues.protocol_version = option_with_default(configs.getint, 'protocol', 'version', 4)
2495
+ optvalues.cqlversion = option_with_default(configs.get, 'cql', 'version', None)
2496
+ optvalues.connect_timeout = option_with_default(configs.getint, 'connection', 'timeout', DEFAULT_CONNECT_TIMEOUT_SECONDS)
2497
+ optvalues.request_timeout = option_with_default(configs.getint, 'connection', 'request_timeout', DEFAULT_REQUEST_TIMEOUT_SECONDS)
2498
+ optvalues.execute = None
2499
+ optvalues.insecure_password_without_warning = False
2500
+ optvalues.cloudconf = option_with_default(configs.getboolean, 'connection', 'cloudconf', None)
2501
+
2502
+ (options, arguments) = parser.parse_args(cmdlineargs, values=optvalues)
2503
+
2504
+ # Credentials from cqlshrc will be expanded,
2505
+ # credentials from the command line are also expanded if there is a space...
2506
+ # we need the following so that these two scenarios will work
2507
+ # cqlsh --credentials=~/.cassandra/creds
2508
+ # cqlsh --credentials ~/.cassandra/creds
2509
+ options.credentials = os.path.expanduser(options.credentials)
2510
+
2511
+ if not is_file_secure(options.credentials):
2512
+ print("\nWarning: Credentials file '{0}' exists but is not used, because:"
2513
+ "\n a. the file owner is not the current user; or"
2514
+ "\n b. the file is readable by group or other."
2515
+ "\nPlease ensure the file is owned by the current user and is not readable by group or other."
2516
+ "\nOn a Linux or UNIX-like system, you often can do this by using the `chown` and `chmod` commands:"
2517
+ "\n chown YOUR_USERNAME credentials"
2518
+ "\n chmod 600 credentials\n".format(options.credentials),
2519
+ file=sys.stderr)
2520
+ options.credentials = '' # ConfigParser.read() will ignore unreadable files
2521
+
2522
+ if not options.username:
2523
+ credentials = configparser.ConfigParser()
2524
+ credentials.read(options.credentials)
2525
+
2526
+ # use the username from credentials file but fallback to cqlshrc if username is absent from the command line parameters
2527
+ options.username = option_with_default(credentials.get, 'plain_text_auth', 'username', username_from_cqlshrc)
2528
+
2529
+ if not options.password:
2530
+ rawcredentials = configparser.RawConfigParser()
2531
+ rawcredentials.read(options.credentials)
2532
+
2533
+ # handling password in the same way as username, priority cli > credentials > cqlshrc
2534
+ options.password = option_with_default(rawcredentials.get, 'plain_text_auth', 'password', password_from_cqlshrc)
2535
+ elif not options.insecure_password_without_warning:
2536
+ print("\nWarning: Using a password on the command line interface can be insecure."
2537
+ "\nRecommendation: use the credentials file to securely provide the password.\n", file=sys.stderr)
2538
+
2539
+ # Make sure some user values read from the command line are in unicode
2540
+ options.execute = maybe_ensure_text(options.execute)
2541
+ options.username = maybe_ensure_text(options.username)
2542
+ options.password = maybe_ensure_text(options.password)
2543
+ options.keyspace = maybe_ensure_text(options.keyspace)
2544
+
2545
+ if options.cloudconf is not None:
2546
+ if len(arguments) > 0:
2547
+ parser.error("Cannot use --cloudconf with hostname or port")
2548
+ if options.ssl:
2549
+ parser.error("Cannot use --cloudconf with --ssl. Cloud connection encryption parameters are provided by cloud config bundle.")
2550
+
2551
+
2552
+ hostname = option_with_default(configs.get, 'connection', 'hostname', DEFAULT_HOST)
2553
+ port = option_with_default(configs.get, 'connection', 'port', DEFAULT_PORT)
2554
+
2555
+ try:
2556
+ options.connect_timeout = int(options.connect_timeout)
2557
+ except ValueError:
2558
+ parser.error('"%s" is not a valid connect timeout.' % (options.connect_timeout,))
2559
+ options.connect_timeout = DEFAULT_CONNECT_TIMEOUT_SECONDS
2560
+
2561
+ try:
2562
+ options.request_timeout = int(options.request_timeout)
2563
+ except ValueError:
2564
+ parser.error('"%s" is not a valid request timeout.' % (options.request_timeout,))
2565
+ options.request_timeout = DEFAULT_REQUEST_TIMEOUT_SECONDS
2566
+
2567
+ hostname = environment.get('CQLSH_HOST', hostname)
2568
+ port = environment.get('CQLSH_PORT', port)
2569
+
2570
+ if len(arguments) > 0:
2571
+ hostname = arguments[0]
2572
+ if len(arguments) > 1:
2573
+ port = arguments[1]
2574
+
2575
+ if options.file or options.execute:
2576
+ options.tty = False
2577
+
2578
+ if options.execute and not options.execute.endswith(';'):
2579
+ options.execute += ';'
2580
+
2581
+ if optvalues.color in (True, False):
2582
+ options.color = optvalues.color
2583
+ else:
2584
+ if options.file is not None:
2585
+ options.color = False
2586
+ else:
2587
+ options.color = should_use_color()
2588
+
2589
+ if options.cqlversion is not None:
2590
+ options.cqlversion, cqlvertup = full_cql_version(options.cqlversion)
2591
+ if cqlvertup[0] < 3:
2592
+ parser.error('%r is not a supported CQL version.' % options.cqlversion)
2593
+ options.cqlmodule = cql3handling
2594
+
2595
+ try:
2596
+ port = int(port)
2597
+ except ValueError:
2598
+ parser.error('%r is not a valid port number.' % port)
2599
+ return options, hostname, port
2600
+
2601
+
2602
+ def setup_cqlruleset(cqlmodule):
2603
+ global cqlruleset
2604
+ cqlruleset = cqlmodule.CqlRuleSet
2605
+ cqlruleset.append_rules(cqlshhandling.cqlsh_extra_syntax_rules)
2606
+ for rulename, termname, func in cqlshhandling.cqlsh_syntax_completers:
2607
+ cqlruleset.completer_for(rulename, termname)(func)
2608
+ cqlruleset.commands_end_with_newline.update(cqlshhandling.my_commands_ending_with_newline)
2609
+
2610
+
2611
+ def setup_cqldocs(cqlmodule):
2612
+ global cqldocs
2613
+ cqldocs = cqlmodule.cqldocs
2614
+
2615
+
2616
+ def init_history():
2617
+ if readline is not None:
2618
+ try:
2619
+ readline.read_history_file(HISTORY)
2620
+ except IOError:
2621
+ pass
2622
+ delims = readline.get_completer_delims()
2623
+ delims.replace("'", "")
2624
+ delims += '.'
2625
+ readline.set_completer_delims(delims)
2626
+
2627
+
2628
+ def save_history():
2629
+ if readline is not None:
2630
+ try:
2631
+ readline.write_history_file(HISTORY)
2632
+ except IOError:
2633
+ pass
2634
+
2635
+
2636
+ def main(options, hostname, port):
2637
+ if options.driver_debug:
2638
+ logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
2639
+ stream=sys.stdout)
2640
+ logging.getLogger("cassandra").setLevel(logging.DEBUG)
2641
+
2642
+ setup_cqlruleset(options.cqlmodule)
2643
+ setup_cqldocs(options.cqlmodule)
2644
+ init_history()
2645
+ csv.field_size_limit(options.field_size_limit)
2646
+
2647
+ if options.file is None:
2648
+ stdin = None
2649
+ else:
2650
+ try:
2651
+ encoding, bom_size = get_file_encoding_bomsize(options.file)
2652
+ stdin = codecs.open(options.file, 'r', encoding)
2653
+ stdin.seek(bom_size)
2654
+ except IOError as e:
2655
+ sys.exit("Can't open %r: %s" % (options.file, e))
2656
+
2657
+ if options.debug:
2658
+ sys.stderr.write("Using CQL driver: %s\n" % (cassandra,))
2659
+ sys.stderr.write("Using connect timeout: %s seconds\n" % (options.connect_timeout,))
2660
+ sys.stderr.write("Using '%s' encoding\n" % (options.encoding,))
2661
+ sys.stderr.write("Using ssl: %s\n" % (options.ssl,))
2662
+ sys.stderr.write("Using cloudconf: %s\n" % (options.cloudconf,))
2663
+
2664
+ # create timezone based on settings, environment or auto-detection
2665
+ timezone = None
2666
+ if options.timezone or 'TZ' in os.environ:
2667
+ try:
2668
+ import pytz
2669
+ if options.timezone:
2670
+ try:
2671
+ timezone = pytz.timezone(options.timezone)
2672
+ except Exception:
2673
+ sys.stderr.write("Warning: could not recognize timezone '%s' specified in cqlshrc\n\n" % (options.timezone))
2674
+ if 'TZ' in os.environ:
2675
+ try:
2676
+ timezone = pytz.timezone(os.environ['TZ'])
2677
+ except Exception:
2678
+ sys.stderr.write("Warning: could not recognize timezone '%s' from environment value TZ\n\n" % (os.environ['TZ']))
2679
+ except ImportError:
2680
+ sys.stderr.write("Warning: Timezone defined and 'pytz' module for timezone conversion not installed. Timestamps will be displayed in UTC timezone.\n\n")
2681
+
2682
+ # try auto-detect timezone if tzlocal is installed
2683
+ if not timezone:
2684
+ try:
2685
+ from tzlocal import get_localzone
2686
+ timezone = get_localzone()
2687
+ except ImportError:
2688
+ # we silently ignore and fallback to UTC unless a custom timestamp format (which likely
2689
+ # does contain a TZ part) was specified
2690
+ if options.time_format != DEFAULT_TIMESTAMP_FORMAT:
2691
+ sys.stderr.write("Warning: custom timestamp format specified in cqlshrc, "
2692
+ + "but local timezone could not be detected.\n"
2693
+ + "Either install Python 'tzlocal' module for auto-detection "
2694
+ + "or specify client timezone in your cqlshrc.\n\n")
2695
+
2696
+ try:
2697
+ shell = Shell(hostname,
2698
+ port,
2699
+ color=options.color,
2700
+ username=options.username,
2701
+ stdin=stdin,
2702
+ tty=options.tty,
2703
+ completekey=options.completekey,
2704
+ browser=options.browser,
2705
+ protocol_version=options.protocol_version,
2706
+ cqlver=options.cqlversion,
2707
+ keyspace=options.keyspace,
2708
+ display_timestamp_format=options.time_format,
2709
+ display_nanotime_format=options.nanotime_format,
2710
+ display_date_format=options.date_format,
2711
+ display_float_precision=options.float_precision,
2712
+ display_double_precision=options.double_precision,
2713
+ display_timezone=timezone,
2714
+ max_trace_wait=options.max_trace_wait,
2715
+ ssl=options.ssl,
2716
+ single_statement=options.execute,
2717
+ request_timeout=options.request_timeout,
2718
+ connect_timeout=options.connect_timeout,
2719
+ encoding=options.encoding,
2720
+ auth_provider=authproviderhandling.load_auth_provider(
2721
+ config_file=CONFIG_FILE,
2722
+ cred_file=options.credentials,
2723
+ username=options.username,
2724
+ password=options.password),
2725
+ cloudconf=options.cloudconf)
2726
+ except KeyboardInterrupt:
2727
+ sys.exit('Connection aborted.')
2728
+ except CQL_ERRORS as e:
2729
+ sys.exit('Connection error: %s' % (e,))
2730
+ except VersionNotSupported as e:
2731
+ sys.exit('Unsupported CQL version: %s' % (e,))
2732
+ if options.debug:
2733
+ shell.debug = True
2734
+ if options.coverage:
2735
+ shell.coverage = True
2736
+ import signal
2737
+
2738
+ def handle_sighup():
2739
+ shell.stop_coverage()
2740
+ shell.do_exit()
2741
+
2742
+ signal.signal(signal.SIGHUP, handle_sighup)
2743
+
2744
+ shell.cmdloop()
2745
+ save_history()
2746
+
2747
+ if shell.batch_mode and shell.statement_error:
2748
+ sys.exit(2)
2749
+
2750
+
2751
+ # always call this regardless of module name: when a sub-process is spawned
2752
+ # on Windows then the module name is not __main__, see CASSANDRA-9304 (Windows support was dropped in CASSANDRA-16956)
2753
+ insert_driver_hooks()
2754
+
2755
+ if __name__ == '__main__':
2756
+ main(*read_options(sys.argv[1:], os.environ))
2757
+
2758
+ # vim: set ft=python et ts=4 sw=4 :