Skip to main content

pypostgres aims to provide the simplest way to interact with PostgreSQL databases.

Project description

Python

Python Postgres


Python Postgres is an abstraction over psycopg and aims to provide the simplest way to interact with PostgreSQL databases in Python.

I have just started this project, and it is not ready for production use. I am still working on every aspect of it and may abandon it at any point without warning.


Installation

pip install python_postgres 

Basic Usage

from python_postgres import Postgres

pg = Postgres("pgadmin", "password", "pg-is-king.postgres.database.azure.com")


async def main():
    await pg.open()  # Open the connection pool, this requires a running event loop.
    files = await pg("SELECT * FROM files")
    await pg("INSERT INTO files (name, size) VALUES (%s, %s)", [("file1", 1024), ("file2", 2048)])

    async with pg.transaction() as tran:
        file_id = (
            await tran(
                "INSERT INTO files (name, size) VALUES VALUES (%s, %s) RETURNING file_id;",
                ("you_may_not_exist", 0),
            )
        )[0]
        await tran("INSERT INTO pages (page_number, file_id) VALUES (%s, %s);", (4, file_id))
        raise ValueError("Oopsie")
    await pg.close()  # Close the connection pool. Python Postgres will attempt to automatically
    # close the pool when the instance is garbage collected, but this is not guaranteed to succeed.
    # Be civilized and close it yourself.

A more in-depth look

The basic idea of this project is to provide one callable instance of the Postgres class. The Postgres class manages a connection pool in the background and will get a connection from the pool when called, spawn a binary cursor on it, run your query, return the results (or the number of rows affected), and then return the connection to the pool. As a query, you can pass either a literal - string or bytes - or a SQL or Composed object from the psycopg library.

In Essence, the Postgres class is syntactic sugar for turning this:

async def exec_query(
        query: LiteralString | bytes | SQL | Composed,
        params: tuple | list[tuple],
        is_retry: bool = False,
) -> list[tuple]:
    try:
        async with con_pool.connection() as con:  # type: psycopg.AsyncConnection
            async with con.cursor(binary=True) as cur:  # type: psycopg.AsyncCursor
                if isinstance(params, list):
                    await cur.executemany(query, params)
                else:
                    await cur.execute(query, params)
                await con.commit()
                return (
                    await cur.fetchall()
                    if cur.pgresult and cur.pgresult.ntuples > 0
                    else cur.rowcount or -1
                )
    except psycopg.OperationalError as error:
        if is_retry:
            raise IOError from error
        await con_pool.check()
        await exec_query(query, params, True)
    except psycopg.Error as error:
        raise IOError from error


await exec_query("SELECT * FROM files WHERE id = %s", (1234,))

into

await pg("SELECT * FROM files WHERE id = %s", (1234,))

Notes

Other than providing simpler syntax through a thin abstraction, this project inherits all the design choices of psycopg, including the caching of query execution plans

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

python_postgres-0.0.2.tar.gz (4.7 kB view details)

Uploaded Source

Built Distribution

python_postgres-0.0.2-py3-none-any.whl (5.7 kB view details)

Uploaded Python 3

File details

Details for the file python_postgres-0.0.2.tar.gz.

File metadata

  • Download URL: python_postgres-0.0.2.tar.gz
  • Upload date:
  • Size: 4.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.4 CPython/3.13.0 Windows/11

File hashes

Hashes for python_postgres-0.0.2.tar.gz
Algorithm Hash digest
SHA256 4f82efbac046eb84de5301bc7bd31ca3813311ce4199b924d86187664b000786
MD5 1cc65d1930f9ad7c2e7d13d0bb30a074
BLAKE2b-256 a18caaf0f8695e58d1a2dfd638e36efc7e912b74808d3c68b4adaaca0b64425c

See more details on using hashes here.

File details

Details for the file python_postgres-0.0.2-py3-none-any.whl.

File metadata

File hashes

Hashes for python_postgres-0.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 6577bc0131af7a813ffeeda6174575034ea79cba70111d1ba72df0323c9a53a1
MD5 7a19c5fbb2da3e944530e5e7940a9b80
BLAKE2b-256 fa0c622b9f0f8010b25b25d5492ffb528a88b247d3248d9b670e24660b617acb

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page