Giter Club home page Giter Club logo

aiosql's Introduction

aiosql - Simple SQL in Python

SQL is code. Write it, version control it, comment it, and run it using files. Writing your SQL code in Python programs as strings doesn't allow you to easily reuse them in SQL GUIs or CLI tools like psql. With aiosql you can organize your SQL statements in .sql files, load them into your python application as methods to call without losing the ability to use them as you would any other SQL file.

This project supports standard PEP 249 and asyncio based drivers for SQLite (sqlite3, aiosqlite, apsw), PostgreSQL (psycopg (3), psycopg2, pg8000, pygresql, asyncpg), MySQL (PyMySQL, mysqlclient, mysql-connector) and MariaDB (mariadb) out of the box. Note that some detailed feature support may vary depending on the underlying driver and database engine actual capabilities.

This module is an implementation of Kris Jenkins' yesql Clojure library to the Python ecosystem. Extensions to support other database drivers can be written by you! See: Database Driver Adapters. Feel free to pull request!

Badges

Build status Code Coverage Tests Issues Contributors Pypi Downloads Stars Version Databases Drivers Language Count Top Language Python Versions Badges BSD 2-Clause License

Usage

Install from pypi, for instance by running pip install aiosql.

Then write parametric SQL queries in a file and execute it from Python methods, eg this greetings.sql file:

-- name: get_all_greetings
-- Get all the greetings in the database
select greeting_id, greeting
  from greetings
 order by 1;

-- name: get_user_by_username^
-- Get a user from the database using a named parameter
select user_id, username, name
  from users
 where username = :username;

This example has an imaginary SQLite database with greetings and users. It prints greetings in various languages to the user and showcases the basic feature of being able to load queries from a SQL file and call them by name in python code.

You can use aiosql to load the queries in this file for use in your Python application:

import aiosql
import sqlite3

queries = aiosql.from_path("greetings.sql", "sqlite3")

with sqlite3.connect("greetings.db") as conn:
    user = queries.get_user_by_username(conn, username="willvaughn")
    # user: (1, "willvaughn", "William")

    for _, greeting in queries.get_all_greetings(conn):
        # scan [(1, "Hi"), (2, "Aloha"), (3, "Hola"), …]
        print(f"{greeting}, {user[2]}!")
    # Hi, William!
    # Aloha, William!
    # …

Or even in an asynchroneous way, with two SQL queries running in parallel using aiosqlite and asyncio:

import asyncio
import aiosql
import aiosqlite

queries = aiosql.from_path("greetings.sql", "aiosqlite")

async def main():
    async with aiosqlite.connect("greetings.db") as conn:
        # Parallel queries!
        greetings, user = await asyncio.gather(
            queries.get_all_greetings(conn),
            queries.get_user_by_username(conn, username="willvaughn")
        )

        for _, greeting in greetings:
            print(f"{greeting}, {user[2]}!")

asyncio.run(main())

It may seem inconvenient to provide a connection on each call. You may have a look at the AnoDB DB class which wraps both a database connection and query functions in one connection-like extended object, including managing automatic reconnection if needed.

Why you might want to use this

  • You think SQL is pretty good, and writing SQL is an important part of your applications.
  • You don't want to write your SQL in strings intermixed with your python code.
  • You're not using an ORM like SQLAlchemy or Django , with large (100k lines) code imprints vs under 800 for aiosql, and you don't need to.
  • You want to be able to reuse your SQL in other contexts. Loading it into psql or other database tools.

Why you might NOT want to use this

  • You're looking for an ORM.
  • You aren't comfortable writing SQL code.
  • You don't have anything in your application that requires complicated SQL beyond basic CRUD operations.
  • Dynamically loaded objects built at runtime really bother you.

Table of Contents

.. toctree::
   :maxdepth: 2
   :caption: Contents:

   Getting Started <getting-started>
   Defining SQL Queries <defining-sql-queries>
   Advanced Topics <advanced-topics>
   Database Driver Adapters <database-driver-adapters>
   Contributing <contributing>
   API <pydoc/modules>

aiosql's People

Contributors

abo-abo avatar alex-eri avatar benji-york avatar danmurphy1217 avatar dlax avatar duijf avatar georgejdanforth avatar lancemayer avatar mitya57 avatar nackjicholson avatar seandstewart avatar singlecheeze avatar xlevus avatar zx80 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.