#!/usr/bin/env python

"""
Find out if we're running in a pypy session, in which case we need to
use the cffi version of psycopg2
"""
import platform
import json
pypy = "PyPy" == platform.python_implementation()

try:
    if pypy:
        from psycopg2cffi import compat
        compat.register()
        print("Psycopg2 CFFI registered")
except Exception, e:
    print("ERROR: Failed to register psycopg2cffi: %s" % (e,))
    raise

import psycopg2
import psycopg2.extras
import psycopg2.extensions
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)
from txpostgres import txpostgres
from txpostgres.reconnection import DeadConnectionDetector
from twisted.python.modules import getModule
from twisted.python import util
from twisted.internet import reactor, task, defer


def get_database_credentials(appname):
    filepath = getModule(__name__).filePath
    basedir = filepath.parent().parent().parent().parent()
    return json.loads(basedir.child("etc").child("database_credentials_%s.json" % (appname,)).getContent())


def Pool(appname):
    return PoolFactory.get(appname)


class PoolFactory(object):
    pools = {}
    @classmethod
    def get(cls, appname):
        if not appname in cls.pools:
            cls.pools[appname] = _Pool(appname)
        return cls.pools[appname]

class _Pool(txpostgres.ConnectionPool):

    def __init__(self, appname):
        self.status_df = None
        credentials = get_database_credentials(appname)
        app_credentials = credentials[appname]
        args = tuple()

        def connection_factory(self, *args, **kwargs):
            kwargs['detector'] = DeadConnectionDetector()
            return txpostgres.Connection(*args, **kwargs)

        txpostgres.ConnectionPool.connectionFactory = connection_factory
        txpostgres.ConnectionPool.__init__(self,
                                           None,
                                           *args,
                                           connection_factory=psycopg2.extras.NamedTupleConnection,
                                           **app_credentials)

    def start(self):
        if not self.status_df:
            self.status_df = txpostgres.ConnectionPool.start(self)

        """
        Everyone who calls 'start' gets their own deferred
        Probably not important, but it makes the code more
        predictable
        """
        df = defer.Deferred()

        def cb(result):
            df.callback(result)
            return result

        self.status_df.addCallback(cb)
        return df


class BookTown(object):

    def __init__(self):
        pass

def go(result, pool):
    query = """
        SELECT
            *
        FROM
            alternate_stock"""
    df = pool.runQuery(query)
    df.addCallback(dumpres)
    return df


def dumpres(result):
    print("RESULT: %s" % (result,))
    print(result[0].isbn)
    return result


def main(reactor):
    print("MAIN %s" % (reactor,))

    pool = Pool("booktown")
    df = pool.start()
    df.addCallback(go, pool)

    return df


if __name__ == "__main__":
    task.react(main)

@@ -871,27 +871,33 @@
 credentials(
-app
+database_
 name):%0A    f
@@ -1077,19 +1077,25 @@
 son%22 %25 (
-app
+database_
 name,)).
@@ -1115,27 +1115,33 @@
 %0A%0A%0Adef Pool(
-app
+database_
 name):%0A    r
@@ -1162,19 +1162,25 @@
 ory.get(
-app
+database_
 name)%0A%0A%0A
@@ -1255,19 +1255,25 @@
 et(cls, 
-app
+database_
 name):%0A 
@@ -1286,19 +1286,25 @@
  if not 
-app
+database_
 name in 
@@ -1332,27 +1332,33 @@
   cls.pools%5B
-app
+database_
 name%5D = _Poo
@@ -1359,19 +1359,25 @@
 = _Pool(
-app
+database_
 name)%0A  
@@ -1399,19 +1399,25 @@
 s.pools%5B
-app
+database_
 name%5D%0A%0Ac
@@ -1479,19 +1479,25 @@
 _(self, 
-app
+database_
 name):%0A 
@@ -1572,19 +1572,25 @@
 entials(
-app
+database_
 name)%0A  
@@ -1628,17 +1628,8 @@
 ials
-%5Bappname%5D
 %0A   

Add the database_name to the credentials filename. Drop it from the returned json structure