Skip to main content

A simple MariaDB/Postgres client based on SQLAlchemy core

Project description

dbmasta (simple mariadb/postgres interface)

Overview

This Python package provides a simple interface for interacting with MariaDB databases using SQLAlchemy Core. It abstracts some common database operations into more manageable Python methods, allowing for easy database queries, inserts, updates, and deletes.

Installation

To install this package, run the following pip command. Note: this requires SQLAlchemy 2.0.27 or greater

pip install dbmasta

Basic Usage

Configuration

First, configure the database client with the necessary credentials:

from dbmasta import DataBase, AsyncDataBase

# Initialize the database client
db = DataBase(
    dict(
        username='username', 
        password='password', 
        host='host', 
        port=3306, 
        default_database='database_name'
        )
    )
# Async Version
db = AsyncDataBase(
    dict(
        username='username', 
        password='password', 
        host='host', 
        port=3306, 
        default_database='database_name'
        )
    )


# Initiliaze using environment variables
db = DataBase.env()
# Async Version
db = AsyncDataBase.env()

Executing Queries

You can execute a simple SELECT query to fetch data:

import datetime as dt

# Create parameters
params = {
    "date": db.before(dt.date(2024,1,1), inclusive=True)
}

# Execute the query
dbr = db.select("database", "table", params)

# Examine the results
if dbr.successful:
    print(dbr.records)
else:
    print(dbr.error_info)

Complex Queries

The following query would generate this text:

import datetime as dt

# Create parameters
params = {
    "_OR_": db.or_(
        [
            {"date": db.after(dt.date(2020,1,1)), "category": "sales"},
            {"date": db.before(dt.date(2020,1,1)), "category": db.not_(db.in_, ["purchases","adjustments","sales"])},
        ]
    ),
    "_AND_": db.and_(
        [
            {"keyfield": db.starts_with("SJ")},
            {"keyfield": db.not_(db.ends_with("2E"))}
        ]
    )
    "status": "under_review"
}

# Execute the query
dbr = db.select("database", "table", params)

# Examine the results
if dbr.successful:
    print(dbr.records)
else:
    print(dbr.error_info)

The raw text of the query can be retrieved from the attribute dbr.raw_query from the DataBaseResponse object, which the DataBase.select method returns. The text in the above example would be as follows:

SELECT * FROM `database`.`table`
WHERE ((`date` > '2020-01-01' and `category`='sales') or 
(`date` < '2020-01-01' and `category` not in ('sales')))
AND `keyfield` LIKE 'SJ%' AND `keyfield` NOT LIKE '%2E'
AND `status`='under_review';

Or in simple terms... Get all records under_review where the keyfield starts with SJ, but doesn't end with 2E. Pull these if either:

  • dated after 2020-01-01 and categorized as a sale
  • dated before 2020-01-01 and not categorized as sale,purchase or adjustment.

Result Modification from DataBase.select

In addition to complex conditions for filtering records, you can:

  • sort records

    db.select(..., order_by="column_name", reverse=True)
    
  • limit and offset results

    # for offset pagination
    db.select(..., limit=100, offset=0)
    
  • filter columns

    # only receive the data for the fields you provide
    db.select(..., columns=["keyfield", "name", "date"])
    
  • get textual output (without executing)

    # this will not execute the query, but will return the raw query needed to execute
    raw_textual_query = db.select(..., textual=True)
    print(raw_textual_query)
    new_query = f"INSERT INTO `filteredtable` ({raw_textual_query[:-1]});
    dbr = db.run(new_query)
    
  • get model output by providing a model factory

    from pydantic import BaseModel
    import datetime as dt
    
    class Record(BaseModel):
        keyfield: str
        date: dt.date
        status: str
    
    model_factory = lambda row: Record(**row)
    
    # only receive the data for the fields you provide
    dbr = db.select(..., response_model=model_factory)
    # each record will be an instance of Record
    

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

dbmasta-0.1.20.tar.gz (33.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

dbmasta-0.1.20-py3-none-any.whl (40.0 kB view details)

Uploaded Python 3

File details

Details for the file dbmasta-0.1.20.tar.gz.

File metadata

  • Download URL: dbmasta-0.1.20.tar.gz
  • Upload date:
  • Size: 33.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.3

File hashes

Hashes for dbmasta-0.1.20.tar.gz
Algorithm Hash digest
SHA256 b052d68409b630570926d928f96f3d4d22c9c922be25fe72db9ebc09e9c6cc92
MD5 9d0952206bb4f39b33967847e56b721b
BLAKE2b-256 da3c15e362209a9383a8aeb3c3ae32bad5c07bfec88136599d91d6dffef84b82

See more details on using hashes here.

File details

Details for the file dbmasta-0.1.20-py3-none-any.whl.

File metadata

  • Download URL: dbmasta-0.1.20-py3-none-any.whl
  • Upload date:
  • Size: 40.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.3

File hashes

Hashes for dbmasta-0.1.20-py3-none-any.whl
Algorithm Hash digest
SHA256 4e2617fc64557ba33d2a43e289d2f4a69bca3b5f28d613fc88eb4af1d40bb80b
MD5 5e4aa3a4683f91a58774bcf5dc91a38b
BLAKE2b-256 d176624a8acd4024b6228f5ba45f4ba77fb5f2b9c3cb784f07e1d32a87d3cadb

See more details on using hashes here.

Supported by

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