Last active
August 24, 2023 08:33
-
-
Save wonderbeyond/98c4622f45138e2839a2796750ebb977 to your computer and use it in GitHub Desktop.
Execute SQL on remote Postgres server.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import argparse | |
import urllib.parse | |
import textwrap | |
import psycopg2 | |
import psycopg2.extras | |
def main(): | |
parser = argparse.ArgumentParser( | |
description=textwrap.dedent(""" | |
Execute SQL on remote Postgres server. | |
Example: | |
pgcall postgres://user:pass@host:5432/mydb -c 'SELECT version()' | |
"""), | |
formatter_class=argparse.RawDescriptionHelpFormatter, | |
) | |
parser.add_argument('db_url', nargs=1) | |
parser.add_argument('-c', '--sql', required=True) | |
args = parser.parse_args() | |
db_url = urllib.parse.urlparse(args.db_url[0]) | |
with psycopg2.connect( | |
dbname=db_url.path[1:], | |
user=db_url.username, | |
password=db_url.password, | |
host=db_url.hostname, | |
port=db_url.port, | |
) as conn: | |
with conn.cursor( | |
cursor_factory=psycopg2.extras.DictCursor | |
) as cur: | |
cur.execute(args.sql) | |
for row in cur: | |
print(dict(row)) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment