Skip to content
Advertisement

Writing a hybrid method using pathlib (accessing properties)

I’m trying to do some path-checking logic on some values in a database. I’m having trouble implementing the class level expression for the hybrid method.

Here is some stripped down code:

JavaScript

I’m getting the error: Neither 'Function' object nor 'Comparator' object has an attribute 'parents' So I have to create a SQL expression for this function, but I’m not sure how, or if it’s even possible with accessing the parents property on the Path object.

Advertisement

Answer

SQLite can’t handle Python instances, and SQLAlchemy Function support doesn’t cover instance methods either.

First of all, you can’t use Path() objects as a SQLite function, as explained in the sqlite3.Connection.create_function documentation:

The callable must return a type natively supported by SQLite.

The natively supported types are None, float, int, str or bytes values.

The error you see comes from your attempt to use b.parents in your expression; b is the Function object, the func.Path(...) call, and SQLAlchemy expects a function to return a SQL type, not a Path() object.

Instead of trying to shoehorn Path() objects into SQLite, you’ll need to find another way to test if a path is a parent folder. You could use Column.startswith() here, provided you first ensure the paths don’t end with /, by using the standard RTRIM() function:

JavaScript

This will produce a SQL expression like this:

JavaScript
Advertisement