If you benefit from web2py hope you feel encouraged to pay it forward by contributing back to society in whatever form you choose!

I need to interact with a legacy database where boolean are mapped like this:

TRUE = -1

FALSE = 0

The way to achieve that is to write a custom adapter.

Create web2py/site-packages/custom_adapter.py like this:

# -*- coding: utf-8 -*-/

from gluon.dal import ADAPTERS, PostgreSQLAdapter

class BoolAsIntPostgreSQLAdapter(PostgreSQLAdapter):

    # specify a diver to use
    drivers = ('psycopg2','pg8000')
    TRUE = -1
    FALSE = 0

    types = {
        'boolean': 'smallint',
        'string': 'VARCHAR(%(length)s)',
        'text': 'TEXT',
        'json': 'TEXT',
        'password': 'VARCHAR(%(length)s)',
        'blob': 'BYTEA',
        'upload': 'VARCHAR(%(length)s)',
        'integer': 'INTEGER',
        'bigint': 'BIGINT',
        'float': 'FLOAT',
        'double': 'FLOAT8',
        'decimal': 'NUMERIC(%(precision)s,%(scale)s)',
        'date': 'DATE',
        'time': 'TIME',
        'datetime': 'TIMESTAMP',
        'id': 'SERIAL PRIMARY KEY',
        'reference': 'INTEGER REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s',
        'list:integer': 'TEXT',
        'list:string': 'TEXT',
        'list:reference': 'TEXT',
        'geometry': 'GEOMETRY',
        'geography': 'GEOGRAPHY',
        'big-id': 'BIGSERIAL PRIMARY KEY',
        'big-reference': 'BIGINT REFERENCES %(foreign_key)s ON DELETE %(on_delete_action)s',
        }
    def parse_boolean(self, value, field_type):
        return value == self.TRUE or False 
    

ADAPTERS.update( {
    'custompgsql': BoolAsIntPostgreSQLAdapter
})

Now in your db.py you can use your adapter:

import custom_adapter
db = DAL('custompgsql://user:pass@host/database')

Many thanks to Niphlod.

References:

https://groups.google.com/forum/#!msg/web2py/1gSdmZ601f4/BIBsR4PWYRQJ

 

Related slices

Comments (1)

  • Login to post



  • 1
    simone-niphlod-11079 11 years ago

    to be extremely sure, please use a parse_boolean that returns either True or False, not "None".

    def parse_boolean(self, value, field_type):
        return value == self.TRUE or False

     


Hosting graciously provided by:
Python Anywhere