Add postgresql.script() for running arbitrary SQL script

This commit is contained in:
Lance Edgar 2020-12-13 15:54:03 -06:00
parent ab822411be
commit 8b8df95633

View file

@ -71,6 +71,23 @@ def sql(c, sql, database='', port=None, **kwargs):
return c.sudo(cmd, user='postgres', **kwargs) return c.sudo(cmd, user='postgres', **kwargs)
def script(c, path, database='', port=None, user=None, password=None):
"""
Execute a SQL script. By default this will run as 'postgres' user, but can
use PGPASSWORD authentication if necessary.
"""
port = '--port={}'.format(port) if port else ''
if user and password:
kw = dict(pw=password, user=user, port=port, path=path, db=database)
return c.sudo(" PGPASSWORD='{pw}' psql --host=localhost {port} --username='{user}' --file='{path}' {db}".format(**kw),
echo=False)
else: # run as postgres
kw = dict(port=port, path=path, db=database)
return c.sudo("psql {port} --file='{path}' {db}".format(**kw),
user='postgres')
def user_exists(c, name, port=None): def user_exists(c, name, port=None):
""" """
Determine if a given PostgreSQL user exists. Determine if a given PostgreSQL user exists.