0

I'm reading through the docs pertaining to SQLAlchemy's textual SQL and custom functions, and it's not clear to me how to combine the two.

For example, let's say I have the following code:

# relevant imports

def f(username):
    if len(username) < 5:
        return True
    else:
        return False

t = text("select * from users where f(username)")
db.session.execute(t)

I know that this particular example may not requred a user-defined function, but I would appreciate a general answer that will work for any user-define function.

0

1 Answer 1

1

I think you might be a bit confused about the meaning of those custom functions. They're referencing functions that are available in your SQL database, not functions that you've defined in Python. The docs give the example of NOW or CURRENT_TIMESTAMP; those are both functions that are usually provided by your database server software.

Many databases support "stored procedures"; for example, here are the docs for stored procedures in PostgreSQL. These are more similar to what you're describing: they're functions that can be evaluated during the query process. In your specific case, though, it's almost certainly easier to write your query to check the string length directly. For PostgreSQL or MySQL, that query would be:

select * from users where char_length(username) < 5
Sign up to request clarification or add additional context in comments.

2 Comments

Appreciate it. Do you know if MySQL has any built-in functions similar to re.search()?
Yup! You can use WHERE field REGEXP pattern: dev.mysql.com/doc/refman/8.0/en/regexp.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.