SQLObject
My new favourite toy is SQLObject, an object-relational mapper which makes heavy use of Python’s special method names to create objects which can be used to transparently access and modify data in a relational database. I tried to write something like this in PHP once before and failed miserably, but SQLObject has such an elegant design that I’m just annoyed I didn’t find out about it sooner. Here’s some example code, adapted from the SQLOBject site:
from SQLObject import *
# Set up a database connection
__connection__ = PyPgSQLConnection()
# This class defines a table
class Person(SQLObject):
firstName = StringCol(length=100)
middleInitial = StringCol(length=1, default=None)
lastName = StringCol(length=100)
# Now create the table (if running for the first time)
Person.createTable()
# Create a record for me
p = Person.new(firstName='Simon', lastName='Willison')
print p
# Outputs <Person 1 firstName='Simon' middleInitial=None lastName='Willison'>
# Set my middle initial (updates the database)
p.middleInitial = 'P'
# Print my full name
print p.firstName, p.middleInitial, p.lastName
SQLObject has plenty more tricks up its sleeve: it can create class definitions by introspecting a database table, handle one to many and many to many joins, and generate complicated SELECT statements on the fly using simple, database independant syntax. It comes with support for MySQL, Postgres and SQLite. Postgres support uses the psycopg module, but we use pyPgSQL so I wrote a simple connection wrapper to support that module which I’ve submitted to the SQLObject mailing list.
More recent articles
- Weeknotes: Parquet in Datasette Lite, various talks, more LLM hacking - 4th June 2023
- It's infuriatingly hard to understand how closed models train on their input - 4th June 2023
- ChatGPT should include inline tips - 30th May 2023
- Lawyer cites fake cases invented by ChatGPT, judge is not amused - 27th May 2023
- llm, ttok and strip-tags - CLI tools for working with ChatGPT and other LLMs - 18th May 2023
- Delimiters won't save you from prompt injection - 11th May 2023
- Weeknotes: sqlite-utils 3.31, download-esm, Python in a sandbox - 10th May 2023
- Leaked Google document: "We Have No Moat, And Neither Does OpenAI" - 4th May 2023
- Midjourney 5.1 - 4th May 2023
- Prompt injection explained, with video, slides, and a transcript - 2nd May 2023