Some Bits: Nelson's log

Adding static type signatures to PugSQL

Got distracted by a yak today; trying to add Python static type checking to PugSQL generated code. I got something that kind of works but it’d take some effort to make really useful. The basic idea is to create a .pyi file for PugSQL’s queries module.

The challenge with PugSQL is it’s generating functions dynamically. At runtime it reads a .sql file that says “create a function called pugsql.compiler.Module.count_links()”. So of course VS.Code’s static type checker pylance/pyright has no idea what count_links() is and it displays a red squigglely line.

I kludged it by using PyRight’s type stub support. I used PyRight to autogenerate type signatures for pugsql, including a file named typings/pugsql/compiler.py. (These generated signatures were not very good; the command line guessing tool does less of a good job guessing types that VS.Code’s interactive stuff.)

Then I edited that file to add some type signatures for my custom methods I am creating using PugSQL.

    def count_links(self) -> int:
            ...
    def select_recent(self, count: int) -> list[dict]:
            ...
    def upsert_link(self, *args: dict[str, Any]) -> None:
            ...

count_links is the simplest, it’s a basic select count(*) from links query. Takes no arguments, returns a number. select_recent pulls off N rows and returns them as a list of dicts (select * from links limit 10). Finally upsert_link is taking a list of rows (as dicts) and inserting them.

These are pretty generic type signatures. For instance select_recent is returning typed data from sqlite; those dicts actually contain entries with types you could infer from the SQL schema. That’s a good deal more complicated to do automatically, though. It’d be awfully nice, but then my main goal here was just to shut up the red squiggly line and for that a more generic type is sufficient.

Having done all this it’s enough of a nuisance I probably won’t pursue this further. But I could imagine PugSQL emitting these .pyi files automatically, it could be pretty slick.

It’d be worth reviewing what SQLAlchemy is doing for static type checking. They have a similar problem and it looks like they’ve thought pretty carefully about a solution.