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