• This repository has been archived on 03/Sep/2021
  • Stars
    star
    208
  • Rank 189,015 (Top 4 %)
  • Language
    Python
  • License
    Other
  • Created over 10 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Easy SQL in Python

anosql

NOTICE: This project is now deprecated in favor of aiosql.

Unfortunately, I no longer have the time to devote to this project, and aiosql is now a lot more popular. I don't think it makes sense to maintain both. Open source ftw! Thanks for your hard work, Will!

pypi package version Documentation Status Travid build status

A Python library for using SQL

Inspired by the excellent Yesql library by Kris Jenkins. In my mother tongue, ano means yes.

If you are on python3.6+ or need anosql to work with asyncio-based database drivers, see the related project, aiosql.

Complete documentation is available at Read The Docs.

Installation

$ pip install anosql

Usage

Basics

Given a queries.sql file:

-- name: get-all-greetings
-- Get all the greetings in the database
SELECT * FROM greetings;

-- name: select-users
-- Get all the users from the database,
-- and return it as a dict
SELECT * FROM USERS;

We can issue SQL queries, like so:

import anosql
import psycopg2
import sqlite3

# PostgreSQL
conn = psycopg2.connect('...')
queries = anosql.from_path('queries.sql', 'psycopg2')

# Or, Sqlite3...
conn = sqlite3.connect('cool.db')
queries = anosql.from_path('queries.sql', 'sqlite3')

queries.get_all_greetings(conn)
# => [(1, 'en', 'Hi')]

queries.get_all_greetings.__doc__
# => Get all the greetings in the database

queries.get_all_greetings.sql
# => SELECT * FROM greetings;

queries.available_queries
# => ['get_all_greetings']

Parameters

Often, you want to change parts of the query dynamically, particularly values in the WHERE clause. You can use parameters to do this:

-- name: get-greetings-for-language
-- Get all the greetings in the database for given language
SELECT *
FROM greetings
WHERE lang = %s;

And they become positional parameters:

visitor_language = "en"
queries.get_greetings_for_language(conn, visitor_language)
# => [(1, 'en', 'Hi')]

One Row Query

Often, you would expect at most one row from a query, so that getting a list is not convenient. Appending ? to the query name makes it return either one tuple if it returned one row, or None in other cases.

-- name: get-a-greeting?
-- Get a greeting based on its id
SELECT *
FROM greetings
WHERE id = %s;

Then a tuple is returned:

queries.get_a_greeting(conn, 1)
# => (1, 'en', 'Hi')

Named Parameters

To make queries with many parameters more understandable and maintainable, you can give the parameters names:

-- name: get-greetings-for-language-and-length
-- Get all the greetings in the database for given language and length
SELECT *
FROM greetings
WHERE lang = :lang
AND len(greeting) <= :length_limit;

If you were writing a Postgresql query, you could also format the parameters as %s(lang) and %s(length_limit).

Then, call your queries like you would any Python function with named parameters:

visitor_language = "en"

greetings_for_texting = queries.get_greetings_for_language_and_length(
              conn, lang=visitor_language, length_limit=140)

Update/Insert/Delete

In order to run UPDATE, INSERT, or DELETE statements, you need to add ! to the end of your query name. Anosql will then execute it properly. It will also return the number of affected rows.

Insert queries returning autogenerated values

If you want the auto-generated primary key to be returned after you run an insert query, you can add <! to the end of your query name.

-- name: create-user<!
INSERT INTO person (name) VALUES (:name)

Adding custom query loaders.

Out of the box, anosql supports SQLite and PostgreSQL via the stdlib sqlite3 database driver and psycopg2. If you would like to extend anosql to communicate with other types of databases, you may create a driver adapter class and register it with anosql.core.register_driver_adapter().

Driver adapters are duck-typed classes which adhere to the below interface. Looking at anosql/adapters package is a good place to get started by looking at how the psycopg2 and sqlite3 adapters work.

To register a new loader:

import anosql
import anosql.core

class MyDbAdapter():
    def process_sql(self, name, op_type, sql):
        pass

    def select(self, conn, sql, parameters):
        pass

    @contextmanager
    def select_cursor(self, conn, sql, parameters):
        pass

    def insert_update_delete(self, conn, sql, parameters):
        pass

    def insert_update_delete_many(self, conn, sql, parameters):
        pass

    def insert_returning(self, conn, sql, parameters):
        pass

    def execute_script(self, conn, sql):
        pass


anosql.core.register_driver_adapter("mydb", MyDbAdapter)

# To use make a connection to your db, and pass "mydb" as the db_type:
import mydbdriver
conn = mydbriver.connect("...")

anosql.load_queries("path/to/sql/", "mydb")
greetings = anosql.get_greetings(conn)

conn.close()

If your adapter constructor takes arguments, you can register a function which can build your adapter instance:

def adapter_factory():
    return MyDbAdapter("foo", 42)

anosql.register_driver_adapter("mydb", adapter_factory)

Tests

$ pip install tox
$ tox

License

BSD, short and sweet

More Repositories

1

vim-snippets

vim-snipmate default snippets (Previously snipmate-snippets)
Vim Snippet
4,813
star
2

140medley

A micro-framework or a collection of small, helpful utilities for common javascript tasks.
JavaScript
351
star
3

smithy

A tiny git forge written in Go
Go
220
star
4

bibles

Machine-readable versions of popular English translations of the Bible
166
star
5

redish

A multi-threaded, TCP, key-value store inspired by Redis implemented in Haskell.
Haskell
137
star
6

node-thumbnail

Thumbnail worker queue for node.js
JavaScript
102
star
7

lenscap

Lenscap is a static site generator for creating beautiful photo narratives
Python
97
star
8

django-chef

django with chef template (no longer maintained)
Ruby
86
star
9

base16-st

Colors for the st terminal
C
82
star
10

inertia

A Lisp to Javascript compiler
JavaScript
78
star
11

vim2pygments

Convert vim colorschemes to Pygments styles
Python
72
star
12

suggestr.js

The dead simple javascript autocompleter
JavaScript
68
star
13

dockerfile.vim

Syntax highlighting for Dockerfiles
Vim Script
54
star
14

mutt-notmuch-py

Python
46
star
15

oauth-service

OAuth service in Django/Flask (proof of concept/example app)
Python
41
star
16

kindle-highlight-parser

Parse the highlights file from your Kindle and display it in JSON or Markdown
Go
41
star
17

socrates

socrates is a static site generator written in Python
Python
31
star
18

writer.vim

vim plugin for writing prose
Vim Script
25
star
19

dotfiles

My awesome dotfiles.
Emacs Lisp
25
star
20

clitwi

A dead-simple command line Twitter client
Python
21
star
21

cljs-node

A leiningen template for cljs scripts that target nodejs
Clojure
18
star
22

sheepskin

Document authoring utility
Shell
18
star
23

gif-maker

Make animated gifs from video clips
Shell
16
star
24

nigel

A simple IRC bot that responds to commands. Inspired by Hubot. Implemented in Python.
Python
15
star
25

ajax.js

Super simple ajax utility
JavaScript
14
star
26

jordan

Clojure library for Compojure that allows you to specify which routes require the user to be logged in or to be an administrator
Clojure
14
star
27

heroku-sprunge

Roll your own sprunge on your domain
Python
13
star
28

rembrant

rembrant is a photo organizational tool and an online gallery builder
JavaScript
9
star
29

Posterous-App-Engine

Posterous-style blogging on App Engine
Python
9
star
30

wharf-ci

Jenkins-like, docker-based, GitHub-backed build system
CSS
7
star
31

bond

Bond - the spy agent
Clojure
6
star
32

westminster-reference-bible

6
star
33

film-simulations

Fuji X Film Simulation Settings
Python
6
star
34

renaissance.css

The perfect page in CSS
CSS
5
star
35

honza.github.com

My website
HTML
5
star
36

vim.io

CoffeeScript
5
star
37

keylogger

keylogger output analyzer
Clojure
5
star
38

heroku-bouncer

Keep your app alive
4
star
39

email-parsing

Email parsing in Clojure
Clojure
4
star
40

solarized-pygments

Solarized pygments style
Python
4
star
41

photolab.coffee

Photolab is a photo organizational and sorting tool.
CoffeeScript
4
star
42

greek-new-testament

This is a tool which helps you read and study the New Testament in the original Greek.
Python
4
star
43

renodiff

Convert your git patch to a reno release note
Python
4
star
44

greekapp

This is a Django app that allows you to interact with the text of the New Testament in its original language.
Python
3
star
45

textual-criticism-game

3
star
46

pypass

python-based random password generator
Python
3
star
47

photolab.py

Python
3
star
48

server-sanity

Vim Script
3
star
49

jslintnode.js

Run your javascript files through the JSLint tool from the comfort of your command prompt.
JavaScript
3
star
50

1689

TeX
3
star
51

django-riemann

Send logs from Django to Riemann
Python
3
star
52

gopro-tools

Shell
3
star
53

ansel

Ansel, the photo gallery
Clojure
2
star
54

hnios

HN for iOS
Python
2
star
55

punctuation

Add real HTML punctuation
Python
2
star
56

todo.js

A fast, reliable, extensible, powerful todo list application written in Javascript.
JavaScript
2
star
57

film-detect

Rust
2
star
58

license.js

Detect a project's open source license on Github
JavaScript
2
star
59

stickies-app

StickiesApp
JavaScript
2
star
60

amara-chrome

JavaScript
2
star
61

clj-gpx

Clojure
2
star
62

textus-receptus

2
star
63

rediclus

A simple Redis clone in Clojure
Clojure
2
star
64

pygmented-markdown

Markdown script that parses your code with Pygments
Python
2
star
65

grab-free-machine

Python
2
star
66

finances.js

This is an example, proof-of-concept, application to showcase backbone.js
JavaScript
2
star
67

bolt

Real-time chat/Twitter clone in Node.js, Express, Socket.io, Redis
JavaScript
2
star
68

nathan-university

Homework for the "Create your own programming language" course at http://nathansuniversity.com/.
JavaScript
2
star
69

riddle

Riddle is a simple theme for Sphinx
1
star
70

merge-upstream

Shell
1
star
71

c25k-org

1
star
72

sifra

Python
1
star
73

gauges-clj

Clojure
1
star
74

web-development

1
star
75

trumpett

trumpett is a Twitter client for Android
Java
1
star
76

gemini

Rust
1
star
77

documents

1
star
78

hilltopfm

PHP
1
star
79

srt.clj

SRT parser in Clojure
Clojure
1
star
80

raised

Python
1
star
81

MdChrome

Markdown preview Chrome extension
JavaScript
1
star
82

magit-gerrit-plus

Emacs Lisp
1
star
83

CoffeeTodo

This is here for archiving purposes. It will probably be deleted soon.
Python
1
star
84

ggl

global git log
Rust
1
star
85

fluent-forever-625

1
star
86

bedfordbaptist.touch

Android application to allow quick access to Bedford Baptist Church information.
Java
1
star
87

gitutils

Fun git scripts written in Python
Python
1
star
88

cs-todo

Todo app in ClojureScript
CSS
1
star
89

chaperone

Chaperone is a command line, time tracking utility
Python
1
star
90

osis

A golang library for parsing OSIS values to English
Go
1
star
91

django-persistent-models

A drop-in replacement for django.db.models.Model that provides a persistent version of the model class
1
star
92

pyselecta

Fuzzy search
Go
1
star
93

vote

Python
1
star
94

filmdetect

Go
1
star
95

pannote

Search your text files
Python
1
star