def create_config_dir_for_first_use(): config_dir = os.path.dirname(config_location()) if not os.path.exists(config_dir): os.makedirs(config_dir) return True return False
def run(self): """ Spins up CLI. """ # raise error if interactive mode is set to false here if not self.interactive_mode: raise ValueError( "Invalid arguments: 'run' must be used in interactive mode! Please set " "interactive_mode to True.") # exit and return error if user enters interactive mode with -o argument enabled if self.output_file: raise ValueError( "Invalid arguments: -o must be used with interactive mode set to " "false.") history_file = self.config['main']['history_file'] if history_file == 'default': history_file = config_location() + 'history' history = MssqlFileHistory(os.path.expanduser(history_file)) self.refresh_completions(history=history, persist_priorities='none') self.prompt_session = self._build_cli(history) if not self.less_chatty: print('Version: {}'.format(__version__)) print('Mail: [email protected]') print('Home: http://github.com/dbcli/mssql-cli') try: while True: try: text = self.prompt_session.prompt() except KeyboardInterrupt: continue # The reason we check here instead of inside the mssqlcliclient is # because we want to raise the Exit exception which will be # caught by the try/except block that wraps the mssqlcliclient execute # statement. if self.quit_command(text): raise EOFError try: text = self.handle_editor_command(text) except RuntimeError as e: self.logger.error("sql: %r, error: %r", text, e) self.logger.error("traceback: %r", traceback.format_exc()) click.secho(str(e), err=True, fg='red') continue self.execute_query(text) self.now = dt.datetime.today() except EOFError: self.mssqlcliclient_main.shutdown() if not self.less_chatty: print(localized.goodbye())
def output_payload_to_file(payload): if payload: config_dir = os.path.dirname(config.config_location()) telemetry_file_path = os.path.join(config_dir, MSSQL_CLI_TELEMETRY_FILE) # Telemetry log file will only contain data points from the most recent session. with open(telemetry_file_path, "w+") as telemetry_file: json.dump(json.loads(payload), telemetry_file, indent=2)
def run(self): history_file = self.config['main']['history_file'] if history_file == 'default': history_file = config_location() + 'history' history = MssqlFileHistory(os.path.expanduser(history_file)) self.refresh_completions(history=history, persist_priorities='none') self.prompt_session = self._build_cli(history) if not self.less_chatty: print('Version: {}'.format(__version__)) print('Mail: [email protected]') print('Home: http://github.com/dbcli/mssql-cli') try: while True: try: text = self.prompt_session.prompt() except KeyboardInterrupt: continue # The reason we check here instead of inside the mssqlcliclient is # because we want to raise the Exit exception which will be # caught by the try/except block that wraps the mssqlcliclient execute # statement. if self.quit_command(text): raise EOFError try: text = self.handle_editor_command(text) except RuntimeError as e: self.logger.error("sql: %r, error: %r", text, e) self.logger.error("traceback: %r", traceback.format_exc()) click.secho(str(e), err=True, fg='red') continue # Initialize default metaquery in case execution fails query = MetaQuery(query=text, successful=False) query = self.execute_command(text, query) self.now = dt.datetime.today() if not query.contains_secure_statement: # Allow MssqlCompleter to learn user's preferred keywords, etc. with self._completer_lock: self.completer.extend_query_history(text) self.query_history.append(query) except EOFError: self.mssqlcliclient_main.shutdown() if not self.less_chatty: print('Goodbye!')
def _get_user_id(): config_dir = config.config_location() full_path = os.path.join(config_dir, MSSQL_CLI_TELEMETRY_ID_FILE) if _user_id_file_is_old(full_path) or not os.path.exists(full_path): with open(full_path, 'w') as file: user_id = _generate_user_id() file.write(user_id) return user_id else: with open(full_path, 'r') as file: user_id = file.read() return user_id
def initialize_logging(self): log_file = self.config['main']['log_file'] if log_file == 'default': log_file = config_location() + 'mssqlcli.log' ensure_dir_exists(log_file) log_level = self.config['main']['log_level'] # Disable logging if value is NONE by switching to a no-op handler. # Set log level to a high value so it doesn't even waste cycles getting # called. if log_level.upper() == 'NONE': handler = logging.NullHandler() else: # creates a log buffer with max size of 20 MB and 5 backup files handler = RotatingFileHandler(os.path.expanduser(log_file), encoding='utf-8', maxBytes=1024 * 1024 * 20, backupCount=5) level_map = { 'CRITICAL': logging.CRITICAL, 'ERROR': logging.ERROR, 'WARNING': logging.WARNING, 'INFO': logging.INFO, 'DEBUG': logging.DEBUG, 'NONE': logging.CRITICAL } log_level = level_map[log_level.upper()] formatter = logging.Formatter( '%(asctime)s (%(process)d/%(threadName)s) ' '%(name)s %(levelname)s - %(message)s') handler.setFormatter(formatter) root_logger = logging.getLogger('mssqlcli') root_logger.addHandler(handler) root_logger.setLevel(log_level) root_logger.info('Initializing mssqlcli logging.') root_logger.debug('Log file %r.', log_file)