Get a steady, non-persistent PyGreSQL connection.
165112
def steady_connection(self):
        """"""
        return SteadyPgConnection(
            self._maxusage, self._setsession, self._closeable,
            *self._args, **self._kwargs)
1074589
def as_sql(self, compiler, connection):  # pylint: disable=arguments-differ
        """"""
        sql, params = super().as_sql(compiler, connection)
        params.append(self.path)
        return sql, params
754213
def flushdb(host=None, port=None, db=None, password=None):
    '''
    
    '''
    server = _connect(host, port, db, password)
    return server.flushdb()
689014
def _ensure_connection(self):
        """"""
        conn = self.connect()
        if conn.recycle and conn.recycle < time.time():
            logger.debug('Client session expired after %is. Recycling.', self._recycle)
            self.close()
            conn = self.connect()
        return conn
182937
def get_pg_core(connection_string, *, cursor_factory=None, edit_connection=None):
  """"""
  import psycopg2 as pq
  from psycopg2.extras import NamedTupleCursor

  def opener():
    """Opens a single PostgreSQL connection with the scope-captured connection string."""
    cn = pq.connect(connection_string)
    cn.cursor_factory = cursor_factory or NamedTupleCursor
    if edit_connection:
      edit_connection(cn)
    return cn

  return InjectedDataAccessCore(
    opener,
    default_connection_closer,
    ("%({0})s", "%s", "{0}::{1}"),
    empty_params=None,
    supports_timezones=True,
    supports_returning_syntax=True,
    get_autocommit=get_pg_autocommit,
    set_autocommit=set_pg_autocommit)
1036746
def as_sql(self, qn, connection):
        
        engine = connection.settings_dict['ENGINE'].rsplit('.', -1)[-1]
        if engine.startswith('postgres'):
            XOR_OPERATOR = '#'
        elif engine.startswith('sqlite'):
            raise NotImplementedError
        else:
            XOR_OPERATOR = '^'

        if self.bit:
            return ("%s.%s | %d" % (qn(self.table_alias), qn(self.column), self.bit.mask),
                    [])
        return ("%s.%s %s %d" % (qn(self.table_alias), qn(self.column), XOR_OPERATOR, self.bit.mask),
                [])
582269
def _get_serv(ret=None, commit=False):
    '''
    
    '''
    _options = _get_options(ret)
    try:
        conn = psycopg2.connect(host=_options.get('host'),
                                user=_options.get('user'),
                                password=_options.get('passwd'),
                                database=_options.get('db'),
                                port=_options.get('port'))

    except psycopg2.OperationalError as exc:
        raise salt.exceptions.SaltMasterError('postgres returner could not connect to database: {exc}'.format(exc=exc))

    cursor = conn.cursor()

    try:
        yield cursor
    except psycopg2.DatabaseError as err:
        error = err.args
        sys.stderr.write(six.text_type(error))
        cursor.execute("ROLLBACK")
        raise err
    else:
        if commit:
            cursor.execute("COMMIT")
        else:
            cursor.execute("ROLLBACK")
    finally:
        conn.close()
99151
def _conn(commit=False):
    '''
    
    '''
    defaults = {'host': 'localhost',
                'user': 'salt',
                'password': 'salt',
                'dbname': 'salt',
                'port': 5432}

    conn_kwargs = {}
    for key, value in defaults.items():
        conn_kwargs[key] = __opts__.get('queue.{0}.{1}'.format(__virtualname__, key), value)
    try:
        conn = psycopg2.connect(**conn_kwargs)
    except psycopg2.OperationalError as exc:
        raise SaltMasterError('pgjsonb returner could not connect to database: {exc}'.format(exc=exc))

    cursor = conn.cursor()

    try:
        yield cursor
    except psycopg2.DatabaseError as err:
        error = err.args
        sys.stderr.write(six.text_type(error))
        cursor.execute("ROLLBACK")
        raise err
    else:
        if commit:
            cursor.execute("COMMIT")
        else:
            cursor.execute("ROLLBACK")
    finally:
        conn.close()
1084882
def get_connection_info(info):
    """"""
    if isinstance(info, dict):
        return info.copy()
    elif info.startswith("postgres://") or info.startswith("postgresql://"):
        return parse_connection_string_url(info)
    else:
        return parse_connection_string_libpq(info)
224143
async def _connect(self) -> "Connection":
        """"""
        if self._connection is None:
            self._connection = await self._execute(self._connector)
        return self
666779
def get(no_create=False, server=None, port=None, force_uuid=None):
        """"""
        pid = os.getpid()
        thread = threading.current_thread()
        wdb = Wdb._instances.get((pid, thread))
        if not wdb and not no_create:
            wdb = object.__new__(Wdb)
            Wdb.__init__(wdb, server, port, force_uuid)
            wdb.pid = pid
            wdb.thread = thread
            Wdb._instances[(pid, thread)] = wdb
        elif wdb:
            if (server is not None and wdb.server != server
                    or port is not None and wdb.port != port):
                log.warn('Different server/port set, ignoring')
            else:
                wdb.reconnect_if_needed()
        return wdb
1311128
def _connect(self, database=None):
        
        conn_args = {
            'host': self.config['host'],
            'user': self.config['user'],
            'password': self.config['password'],
            'port': self.config['port'],
            'sslmode': self.config['sslmode'],
        }

        if database:
            conn_args['database'] = database
        else:
            conn_args['database'] = 'postgres'

        # libpq will use ~/.pgpass only if no password supplied
        if self.config['password_provider'] == 'pgpass':
            del conn_args['password']

        try:
            conn = psycopg2.connect(**conn_args)
        except Exception as e:
            self.log.error(e)
            raise e

        # Avoid using transactions, set isolation level to autocommit
        conn.set_isolation_level(0)
        return conn
1121273
def connection(connection, without_connection_test):
    """"""
    database.set_connection(connection=connection)

    if not without_connection_test:
        test_connection(connection)
543992
def connect_db(config):
    """"""
    rv = sqlite3.connect(config["database"]["uri"])
    rv.row_factory = sqlite3.Row
    return rv
577651
def dropdb(force=False):
    """"""

    if force:
        logger.info(
            "Terminating any other connections to %s on %s",
            repr(DB["NAME"]),
            repr(DB["HOST"]),
        )
        kill_other_psql_sessions()

    logger.info("Dropping database %s", repr(DB["NAME"]))
    return shell('dropdb -U "{USER}" -h "{HOST}" "{NAME}"'.format(**DB))
1140185
def get_mysql_core(connection_args, *, cursor_factory=None, edit_connection=None):
  """"""
  import pymysql

  def opener():
    """Opens a single connection with the scope-captured connection string."""
    cn = pymysql.connect(**connection_args)
    if cursor_factory:
      cn.cursorclass = cursor_factory
    if edit_connection:
      edit_connection(cn)
    return cn

  return InjectedDataAccessCore(
    opener,
    default_connection_closer,
    ("%({0})s", "%s", SQL_CAST),
    empty_params=None,
    supports_timezones=False,
    supports_returning_syntax=False,
    get_autocommit=get_mysql_autocommit,
    set_autocommit=set_mysql_autocommit)
240207
def _loadDB(self):
        """"""
        if not self._validID():
            raise NotFound, self._getID()
        (sql, fields) = self._prepareSQL("SELECT")
        curs = self.cursor()
        curs.execute(sql, self._getID())
        result = curs.fetchone()
        if not result:
            curs.close()
            raise NotFound, self._getID()
        self._loadFromRow(result, fields, curs)
        curs.close()
        self._updated = time.time()