diff options
author | Melody Horn <melody@boringcactus.com> | 2021-04-11 22:21:29 -0600 |
---|---|---|
committer | Melody Horn <melody@boringcactus.com> | 2021-04-11 22:21:29 -0600 |
commit | 40e39981c511823df24da419799a84d7f8b88280 (patch) | |
tree | 270d3fe4a37602efaa67413cfffb4eeb72355080 /repos/db.py | |
parent | f535750f956e02fc9232fa8962a0987cb833c4f4 (diff) | |
download | where-packaged-40e39981c511823df24da419799a84d7f8b88280.tar.gz where-packaged-40e39981c511823df24da419799a84d7f8b88280.zip |
store info in an actual database
Diffstat (limited to 'repos/db.py')
-rw-r--r-- | repos/db.py | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/repos/db.py b/repos/db.py new file mode 100644 index 0000000..1cd95d5 --- /dev/null +++ b/repos/db.py @@ -0,0 +1,46 @@ +import os +from typing import Mapping, TYPE_CHECKING + +import psycopg2 + +if TYPE_CHECKING: + from .base import Version + +def connect(): + return psycopg2.connect(os.environ['DATABASE_URL']) + +def poke_table(force=False): + with connect() as conn: + with conn.cursor() as cur: + if force: + cur.execute('DROP TABLE IF EXISTS versions CASCADE;') + cur.execute('CREATE TABLE IF NOT EXISTS versions (' + 'repo text,' + 'package_name text,' + 'clean_version text,' + 'orig_version text,' + 'PRIMARY KEY (repo, package_name)' + ');') + +def write(repo: str, data: Mapping[str, 'Version']): + with connect() as conn: + with conn.cursor() as cur: + insert = 'INSERT INTO versions (repo, package_name, clean_version, orig_version)' \ + 'VALUES (%(repo)s, %(package_name)s, %(clean_version)s, %(orig_version)s)' \ + 'ON CONFLICT (repo, package_name) DO UPDATE SET ' \ + 'clean_version = EXCLUDED.clean_version,' \ + 'orig_version = EXCLUDED.orig_version' + for package, version in data.items(): + cur.execute(insert, {'repo': repo, 'package_name': package, 'clean_version': version.clean, 'orig_version': version.original}) + +def read(repo: str, package: str): + with connect() as conn: + with conn.cursor() as cur: + sql = 'SELECT clean_version, orig_version FROM versions ' \ + 'WHERE repo = %(repo)s AND package_name = %(package_name)s' + cur.execute(sql, {'repo': repo, 'package_name': package}) + result = cur.fetchone() + if result is None: + return None + clean, orig = result + return {'clean': clean, 'original': orig} |