Custom Compilation

9 views
Skip to first unread message

Soumaya Mauthoor

unread,
Mar 18, 2020, 1:23:51 PM3/18/20
to sqlal...@googlegroups.com
Hello

I have two uses cases:

(1) drop cascade as option
I know I can use custom compilation to add cascade for postgres databases using this example:
Is it possible to use custom compilation to add cascade as an optional keyword argument to drop()? 

(2) overwriting func functions
Is it possible to overwrite func.greatest to return func.max for SQLite?

I'm trying to learn more about custom compilation in general. This page is very helpful:  

Are there other resources you recommend?

Soumaya

Mike Bayer

unread,
Mar 18, 2020, 1:53:07 PM3/18/20
to noreply-spamdigest via sqlalchemy


On Wed, Mar 18, 2020, at 1:23 PM, Soumaya Mauthoor wrote:
Hello

I have two uses cases:

(1) drop cascade as option
I know I can use custom compilation to add cascade for postgres databases using this example:
Is it possible to use custom compilation to add cascade as an optional keyword argument to drop()? 


drop() doesn't accept any optional keyword arguments so you're best off making your own subclass of DropTable  called DropTableCascade and just executing it:   conn.execute(DropTableCascade(mytable))



(2) overwriting func functions
Is it possible to overwrite func.greatest to return func.max for SQLite?

generic functions are used for this.  Since "max" is a multiple-typed function you can use a helper class called ReturnTypeFromArgs:

from sqlalchemy.sql.functions import ReturnTypeFromArgs
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql import literal_column
from sqlalchemy.sql import func

from sqlalchemy.dialects import sqlite


class greatest(ReturnTypeFromArgs):
    pass


@compiles(greatest, "sqlite")
def _render_max(elem, compiler, **kw):
    return "max(%s)" % compiler.process(elem.clauses)


print(func.greatest(literal_column("foo")))
print(func.greatest(literal_column("foo")).compile(dialect=sqlite.dialect()))






I'm trying to learn more about custom compilation in general. This page is very helpful:  

Are there other resources you recommend?

Soumaya


--
SQLAlchemy -
The Python SQL Toolkit and Object Relational Mapper
 
 
To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description.
---
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+...@googlegroups.com.

sumau

unread,
Mar 19, 2020, 8:00:44 PM3/19/20
to sqlalchemy
Thanks Mike that worked perfectly :-)
Reply all
Reply to author
Forward
0 new messages