wiki:ViewsInSqlObject
Warning: Can't synchronize with repository "(default)" (Unsupported version control system "svn": No module named svn). Look in the Trac log for more information.

Version 1 (modified by jerub, 13 years ago) (diff)

Demonstrate how to create a view in sqlobject.

This is not a real example, my use-case for a view had left-joins on 6 tables, not just one, but it's a good template to work from. Note that you always have to have an 'id' column come back, and it has to be a valid primary key for the view, otherwise SQLObjet magic blows up.

This will only work on databases that support views, obviously. You should be able to put this straight into model.py, modify to actually work with your SQL database, and then do tg-admin sql create. After that, you can treat it like a normal SQLObject table.

class MyView(SQLObject):
    name_one = StringCol()
    name_two = StringCol()
    somebool = BoolCol()

    @classmethod
    def createTable(cls, ifNotExists=False, createJoinTables=True,
                    createIndexes=True, applyConstraints=True,
                    connection=None):
        conn = connection or cls._connection
        if ifNotExists and conn.tableExists(cls.sqlmeta.table):
            return

        sql, constraints = cls.createTableSQL()

        # Treat the view like a constraint, only create it
        # after all the other tables have been created.
        return [sql]

    @classmethod
    def createTableSQL(cls, createJoinTables=True, createIndexes=True,
                       connection=None):
        return """CREATE VIEW %s as (
        SELECT table_one.id as id,
               table_one.some_name as name_one,
               table_two.some_name as name_two,
               SOMEFUNC(table_one.foo + table_two.bar) as somebool
        FROM 
            table_one 
            LEFT JOIN table_two ON (table_one.foo_id = table_one.id)
        ) """ % (cls.sqlmeta.table,), []