Return string with fully composed psql command.

    Accepts optional keyword arguments: user, host, port and maintenance_db,
    as well as any number of positional arguments to be added to the end of
    the command.
964999
def _psql_cmd(*args, **kwargs):
    '''
    
    '''
    (user, host, port, maintenance_db) = _connection_defaults(
        kwargs.get('user'),
        kwargs.get('host'),
        kwargs.get('port'),
        kwargs.get('maintenance_db'))
    _PSQL_BIN = _find_pg_binary('psql')
    cmd = [_PSQL_BIN,
           '--no-align',
           '--no-readline',
           '--no-psqlrc',
           '--no-password']  # Never prompt, handled in _run_psql.
    if user:
        cmd += ['--username', user]
    if host:
        cmd += ['--host', host]
    if port:
        cmd += ['--port', six.text_type(port)]
    if not maintenance_db:
        maintenance_db = 'postgres'
    cmd.extend(['--dbname', maintenance_db])
    cmd.extend(args)
    return cmd
1356859
def make_mysql_url(username: str, password: str, dbname: str,
                   driver: str = "mysqldb", host: str = "localhost",
                   port: int = 3306, charset: str = "utf8") -> str:
    
    return "mysql+{driver}://{u}:{p}@{host}:{port}/{db}?charset={cs}".format(
        driver=driver,
        host=host,
        port=port,
        db=dbname,
        u=username,
        p=password,
        cs=charset,
    )
732419
def installed_extensions(user=None,
                         host=None,
                         port=None,
                         maintenance_db=None,
                         password=None,
                         runas=None):
    '''
    

    '''
    exts = []
    query = (
        'select a.*, b.nspname as schema_name '
        'from pg_extension a,  pg_namespace b where a.extnamespace = b.oid;'
    )
    ret = psql_query(query, user=user, host=host, port=port,
                     maintenance_db=maintenance_db,
                     password=password, runas=runas)
    exts = {}
    for row in ret:
        if 'extversion' in row and 'extname' in row:
            exts[row['extname']] = row
    return exts
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()
439414
def db_create(name,
              user=None,
              host=None,
              port=None,
              maintenance_db=None,
              password=None,
              tablespace=None,
              encoding=None,
              lc_collate=None,
              lc_ctype=None,
              owner=None,
              template=None,
              runas=None):
    '''
    

    '''

    # Base query to create a database
    query = 'CREATE DATABASE "{0}"'.format(name)

    # "With"-options to create a database
    with_args = salt.utils.odict.OrderedDict([
        ('TABLESPACE', _quote_ddl_value(tablespace, '"')),
        # owner needs to be enclosed in double quotes so postgres
        # doesn't get thrown by dashes in the name
        ('OWNER', _quote_ddl_value(owner, '"')),
        ('TEMPLATE', template),
        ('ENCODING', _quote_ddl_value(encoding)),
        ('LC_COLLATE', _quote_ddl_value(lc_collate)),
        ('LC_CTYPE', _quote_ddl_value(lc_ctype)),
    ])
    with_chunks = []
    for key, value in with_args.items():
        if value is not None:
            with_chunks += [key, '=', value]
    # Build a final query
    if with_chunks:
        with_chunks.insert(0, ' WITH')
        query += ' '.join(with_chunks)

    # Execute the command
    ret = _psql_prepare_and_run(['-c', query],
                                user=user, host=host, port=port,
                                maintenance_db=maintenance_db,
                                password=password, runas=runas)
    return ret['retcode'] == 0
1164216
def _init_client():
    
    if client is not None:
        return

    global _mysql_kwargs, _table_name
    _mysql_kwargs = {
        'host': __opts__.get('mysql.host', '127.0.0.1'),
        'user': __opts__.get('mysql.user', None),
        'passwd': __opts__.get('mysql.password', None),
        'db': __opts__.get('mysql.database', _DEFAULT_DATABASE_NAME),
        'port': __opts__.get('mysql.port', 3306),
        'unix_socket': __opts__.get('mysql.unix_socket', None),
        'connect_timeout': __opts__.get('mysql.connect_timeout', None),
        'autocommit': True,
    }
    _table_name = __opts__.get('mysql.table_name', _table_name)
    # TODO: handle SSL connection parameters

    for k, v in _mysql_kwargs.items():
        if v is None:
            _mysql_kwargs.pop(k)
    kwargs_copy = _mysql_kwargs.copy()
    kwargs_copy['passwd'] = "<hidden>"
    log.info("mysql_cache: Setting up client with params: %r", kwargs_copy)
    # The MySQL client is created later on by run_query
    _create_table()
1159699
def database_caller_creator(self, number_of_rows, username, password, host, port, name=None, custom=None):
        '''
        '''
        cursor = None
        conn = None

        if name:
            dbname = name
        else:
            dbname = 'postgresql_' + str_generator(self).lower()
        try:
            # createdb
            conn = psycopg2.connect(
                user=username, password=password, host=host, port=port)
            conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
            cur = conn.cursor()
            cur.execute('CREATE DATABASE %s;' % dbname)
            cur.close()
            conn.close()
            # reconnect to the new database
            conn = psycopg2.connect(user=username, password=password,
                                    host=host, port=port, database=dbname)
            cursor = conn.cursor()
            logger.warning('Database created and opened succesfully: %s' % dbname, extra=d)
        except Exception as err:
            logger.error(err, extra=d)
            raise

        if custom:
            self.custom_db_creator(number_of_rows, cursor, conn, custom)
            cursor.close()
            conn.close()
            sys.exit(0)

        return cursor, conn
380606
def get_mysql_connection(host, user, port, password, database, ssl={}):
    

    return pymysql.connect(host=host,
                           user=user,
                           port=port,
                           password=password,
                           db=database,
                           charset='utf8mb4',
                           cursorclass=pymysql.cursors.DictCursor,
                           client_flag=pymysql.constants.CLIENT.MULTI_STATEMENTS,
                           ssl=ssl
                           )
1302793
def get_default_connection_details():
    

    return {
        'host': os.environ.get('MYSQL_HOST', '127.0.0.1'),
        'user': os.environ.get('MYSQL_USER', 'vagrant'),
        'password': os.environ.get('MYSQL_PASSWORD', 'vagrant'),
        'database': os.environ.get('MYSQL_DB', 'thanatos'),
    }
1030133
def get_postgresql_args(db_config, extra_args=None):
    
    db = db_config['NAME']

    mapping = [('--username={0}', db_config.get('USER')),
               ('--host={0}', db_config.get('HOST')),
               ('--port={0}', db_config.get('PORT'))]
    args = apply_arg_values(mapping)

    if extra_args is not None:
        args.extend(shlex.split(extra_args))
    args.append(db)

    return args
580097
def _parsed_version(user=None, host=None, port=None, maintenance_db=None,
                    password=None, runas=None):
    '''
    
    '''

    psql_version = version(
        user,
        host=host,
        port=port,
        maintenance_db=maintenance_db,
        password=password,
        runas=runas,
    )

    if psql_version:
        return _LooseVersion(psql_version)
    else:
        log.warning('Attempt to parse version of Postgres server failed. '
                    'Is the server responding?')
        return None
566460
def pgexport(
    database_uri,
    table_name,
    filename,
    encoding="utf-8",
    dialect=csv.excel,
    callback=None,
    timeout=0.1,
    chunk_size=8388608,
):
    

    if isinstance(dialect, six.text_type):
        dialect = csv.get_dialect(dialect)

    # Prepare the `psql` command to be executed to export data
    command = get_psql_copy_command(
        database_uri=database_uri,
        direction="TO",
        encoding=encoding,
        header=None,  # Needed when direction = 'TO'
        table_name=table_name,
        dialect=dialect,
    )
    fobj = open_compressed(filename, mode="wb")
    try:
        process = subprocess.Popen(
            shlex.split(command),
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
        total_written = 0
        data = process.stdout.read(chunk_size)
        while data != b"":
            written = fobj.write(data)
            total_written += written
            if callback:
                callback(written, total_written)
            data = process.stdout.read(chunk_size)
        stdout, stderr = process.communicate()
        if stderr != b"":
            raise RuntimeError(stderr.decode("utf-8"))

    except FileNotFoundError:
        raise RuntimeError("Command `psql` not found")

    except BrokenPipeError:
        raise RuntimeError(process.stderr.read().decode("utf-8"))

    return {"bytes_written": total_written}
412200
def super_psql(self, args):
        
        argv = [
            PostgresFinder.find_root() / 'psql',
            '--quiet',
            '-U', self.superuser,
            '-h', self.host,
            '-p', self.port,
        ] + args
        subprocess.check_call(argv)
964213
def _get_object_owner(name,
        object_type,
        prepend='public',
        maintenance_db=None,
        user=None,
        host=None,
        port=None,
        password=None,
        runas=None):
    '''
    
    '''
    if object_type == 'table':
        query = (' '.join([
            'SELECT tableowner AS name',
            'FROM pg_tables',
            "WHERE schemaname = '{0}'",
            "AND tablename = '{1}'"
        ])).format(prepend, name)
    elif object_type == 'sequence':
        query = (' '.join([
            'SELECT rolname AS name',
            'FROM pg_catalog.pg_class c',
            'JOIN pg_roles r',
            'ON c.relowner = r.oid',
            'JOIN pg_catalog.pg_namespace n',
            'ON n.oid = c.relnamespace',
            "WHERE relkind='S'",
            "AND nspname='{0}'",
            "AND relname = '{1}'",
        ])).format(prepend, name)
    elif object_type == 'schema':
        query = (' '.join([
            'SELECT rolname AS name',
            'FROM pg_namespace n',
            'JOIN pg_roles r',
            'ON n.nspowner = r.oid',
            "WHERE nspname = '{0}'",
        ])).format(name)
    elif object_type == 'function':
        query = (' '.join([
            'SELECT proname AS name',
            'FROM pg_catalog.pg_proc p',
            'JOIN pg_catalog.pg_namespace n',
            'ON n.oid = p.pronamespace',
            "WHERE nspname = '{0}'",
            "AND p.oid::regprocedure::text = '{1}'",
            'ORDER BY proname, proargtypes',
        ])).format(prepend, name)
    elif object_type == 'tablespace':
        query = (' '.join([
            'SELECT rolname AS name',
            'FROM pg_tablespace t',
            'JOIN pg_roles r',
            'ON t.spcowner = r.oid',
            "WHERE spcname = '{0}'",
        ])).format(name)
    elif object_type == 'language':
        query = (' '.join([
            'SELECT rolname AS name',
            'FROM pg_language l',
            'JOIN pg_roles r',
            'ON l.lanowner = r.oid',
            "WHERE lanname = '{0}'",
        ])).format(name)
    elif object_type == 'database':
        query = (' '.join([
            'SELECT rolname AS name',
            'FROM pg_database d',
            'JOIN pg_roles r',
            'ON d.datdba = r.oid',
            "WHERE datname = '{0}'",
        ])).format(name)

    rows = psql_query(
        query,
        runas=runas,
        host=host,
        user=user,
        port=port,
        maintenance_db=maintenance_db,
        password=password)
    try:
        ret = rows[0]['name']
    except IndexError:
        ret = None

    return ret
898739
def user_info(user, host='localhost', **connection_args):
    '''
    
    '''
    dbc = _connect(**connection_args)
    if dbc is None:
        return False

    cur = dbc.cursor(MySQLdb.cursors.DictCursor)
    qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
           'Host = %(host)s')
    args = {}
    args['user'] = user
    args['host'] = host

    try:
        _execute(cur, qry, args)
    except MySQLdb.OperationalError as exc:
        err = 'MySQL Error {0}: {1}'.format(*exc.args)
        __context__['mysql.error'] = err
        log.error(err)
        return False
    result = cur.fetchone()
    log.debug(result)
    return result
242235
public function getDbConnectionCmd()
    {
        $dbParams = $this->getDbConnectionParams();
        
        $dbConnectionCmd = 'mysql -u ' . $dbParams['user']
                         . ' -h ' . $dbParams['host']
                         . ' -P ' . $dbParams['port'];
        
        if (strlen($dbParams['password']) > 0) {
            $dbConnectionCmd .= ' -p"' . $dbParams['password'] . '"';
        }
        
        return $dbConnectionCmd;
    }
819946
def database_url(self):
        
        return 'postgres://{}:{}@{}/{}'.format(
            self.user, self.password, self.name, self.database)