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