from __future__ import print_function
from __future__ import unicode_literals
import warnings
from pgspecial.namedqueries import NamedQueries
warnings.filterwarnings("ignore", category=UserWarning, module='psycopg2')
import os
import re
import sys
import traceback
import logging
import threading
import shutil
import functools
import humanize
import datetime as dt
import itertools
from time import time, sleep
from codecs import open
from cli_helpers.tabular_output import TabularOutputFormatter
from cli_helpers.tabular_output.preprocessors import (align_decimals,
format_numbers)
import click
try:
import setproctitle
except ImportError:
setproctitle = None
from prompt_toolkit.completion import DynamicCompleter
from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
from prompt_toolkit.shortcuts import PromptSession, CompleteStyle
from prompt_toolkit.document import Document
from prompt_toolkit.filters import HasFocus, IsDone
from prompt_toolkit.lexers import PygmentsLexer
from prompt_toolkit.layout.processors import (ConditionalProcessor,
HighlightMatchingBracketProcessor,
TabsProcessor)
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from pygments.lexers.sql import PostgresLexer
from pgspecial.main import (PGSpecial, NO_QUERY, PAGER_OFF, PAGER_LONG_OUTPUT)
import pgspecial as special
try:
import keyring
except ImportError:
keyring = None
from .pgcompleter import PGCompleter
from .pgtoolbar import create_toolbar_tokens_func
from .pgstyle import style_factory, style_factory_output
from .pgexecute import PGExecute
from .pgbuffer import pg_is_multiline
from .completion_refresher import CompletionRefresher
from .config import (get_casing_file,
load_config, config_location, ensure_dir_exists, get_config)
from .key_bindings import pgcli_bindings
from .encodingutils import utf8tounicode
from .encodingutils import text_type
from .packages.prompt_utils import confirm_destructive_query
from .__init__ import __version__
click.disable_unicode_literals_warning = True
try:
from urlparse import urlparse, unquote, parse_qs
except ImportError:
from urllib.parse import urlparse, unquote, parse_qs
from getpass import getuser
from psycopg2 import OperationalError, InterfaceError
import psycopg2
from collections import namedtuple
from textwrap import dedent
# Ref: https://stackoverflow.com/questions/30425105/filter-special-chars-such-as-color-codes-from-shell-output
COLOR_CODE_REGEX = re.compile(r'\x1b(\[.*?[@-~]|\].*?(\x07|\x1b\\))')
# Query tuples are used for maintaining history
MetaQuery = namedtuple(
'Query',
[
'query', # The entire text of the command
'successful', # True If all subqueries were successful
'total_time', # Time elapsed executing the query
'meta_changed', # True if any subquery executed create/alter/drop
'db_changed', # True if any subquery changed the database
'path_changed', # True if any subquery changed the search path
'mutated', # True if any subquery executed insert/update/delete
'is_special', # True if the query is a special command
])
MetaQuery.__new__.__defaults__ = ('', False, 0, False, False, False, False)
OutputSettings = namedtuple(
'OutputSettings',
'table_format dcmlfmt floatfmt missingval expanded max_width case_function style_output'
)
OutputSettings.__new__.__defaults__ = (
None, None, None, '<null>', False, None, lambda x: x, None
)
class PgCliQuitError(Exception):
pass
class PGCli(object):
default_prompt = '\\u@\\h:\\d> '
max_len_prompt = 30
def set_default_pager(self, config):
configured_pager = config['main'].get('pager')
os_environ_pager = os.environ.get('PAGER')
if configured_pager:
self.logger.info(
'Default pager found in config file: "{}"'.format(configured_pager))
os.environ['PAGER'] = configured_pager
elif os_environ_pager:
self.<