Set the owner of all schemas, functions, tables, views and sequences to
    the given username.

    CLI Example:

    .. code-block:: bash

        salt '*' postgres.owner_to 'dbname' 'username'

def owner_to(dbname,
             ownername,
             user=None,
             host=None,
             port=None,
             password=None,
             runas=None):
    '''
    Set the owner of all schemas, functions, tables, views and sequences to
    the given username.

    CLI Example:

    .. code-block:: bash

        salt '*' postgres.owner_to 'dbname' 'username'
    '''

    sqlfile = tempfile.NamedTemporaryFile()
    sqlfile.write('begin;\n')
    sqlfile.write(
        'alter database "{0}" owner to "{1}";\n'.format(
            dbname, ownername
        )
    )

    queries = (
        # schemas
        ('alter schema {n} owner to {owner};',
         'select quote_ident(schema_name) as n from '
         'information_schema.schemata;'),
        # tables and views
        ('alter table {n} owner to {owner};',
         'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as '
         'n from information_schema.tables where table_schema not in '
         '(\'pg_catalog\', \'information_schema\');'),
        # functions
        ('alter function {n} owner to {owner};',
         'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p '
         'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where '
         'ns.nspname not in (\'pg_catalog\', \'information_schema\') '
         ' and not p.proisagg;'),
        # aggregate functions
        ('alter aggregate {n} owner to {owner};',
         'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p '
         'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where '
         'ns.nspname not in (\'pg_catalog\', \'information_schema\') '
         'and p.proisagg;'),
        # sequences
        ('alter sequence {n} owner to {owner};',
         'select quote_ident(sequence_schema)||\'.\'||'
         'quote_ident(sequence_name) as n from information_schema.sequences;')
    )

    for fmt, query in queries:
        ret = psql_query(query, user=user, host=host, port=port,
                         maintenance_db=dbname, password=password, runas=runas)
        for row in ret:
            sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n')

    sqlfile.write('commit;\n')
    sqlfile.flush()
    os.chmod(sqlfile.name, 0o644)  # ensure psql can read the file

    # run the generated sqlfile in the db
    cmdret = _psql_prepare_and_run(['-f', sqlfile.name],
                                   user=user,
                                   runas=runas,
                                   host=host,
                                   port=port,
                                   password=password,
                                   maintenance_db=dbname)
    return cmdret