Browse Source

ecn-robots: refactored pgdb to use only one psql process per object.

master
Nagy Karoly Gabriel 14 years ago
parent
commit
6a94187ceb
1 changed files with 20 additions and 11 deletions
  1. +20
    -11
      pgdb.py

+ 20
- 11
pgdb.py

@ -2,12 +2,13 @@ r'''Python interface to PostgreSQL for managing database nodes.
'''
from subprocess import Popen, PIPE
import time
class Db(object):
def __init__(self,name):
self._name = name
self._p = Popen('/usr/bin/psql -Aqt -U postgres', stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
def _run(self, command,args=[]):
execfn = [command] + list(args)
try:
@ -19,8 +20,15 @@ class Db(object):
def _runsql(self, sql, db='postgres'):
given_sql = sql
out,error = self._run('/usr/bin/psql', ['-Aqt','-U','postgres','-d', db, '-c', given_sql])
return out.strip()
sql = sql +'\echo this is the end' +'\n'
self._p.stdout.flush()
self._p.stdin.write(str(sql))
out = ""
out = self._p.stdout.readline()
while out.find("this is the end") == -1:
out = out +self._p.stdout.readline()
lout = out.replace('this is the end','')
return lout.strip()
def _get_owner(self):
sql = "SELECT pg_get_userbyid(datdba) FROM pg_database WHERE datname ='"+self._name+"';"
@ -43,10 +51,9 @@ class Db(object):
@property
def info(self):
information = {'size':'', 'encoding':'', 'collation':'','ctype':''}
information['size'] = self._runsql("SELECT pg_size_pretty(pg_database_size('"+self._name+"'));").strip()
information['size'] = self._runsql("SELECT pg_size_pretty(pg_database_size('"+self._name+"'));")
information['encoding'], information['collation'], \
information['ctype'] = self._runsql("""SELECT pg_encoding_to_char(encoding),
datcollate, datctype FROM pg_database WHERE datname='"""+self._name+"';").split('|')
information['ctype'] = self._runsql("SELECT pg_encoding_to_char(encoding), datcollate, datctype FROM pg_database WHERE datname='"+self._name+"';").split('|')
return information
@property
@ -103,16 +110,18 @@ class Db(object):
def dblist(self):
sql = "SELECT datname FROM pg_database WHERE datname NOT IN ('template0', 'template1', 'postgres');"
dblist = self._runsql(sql)
return dblist
dbl = self._runsql(sql)
return dbl
def usrlist(self):
sql = "SELECT rolname FROM pg_authid WHERE rolcanlogin=true;"
usrlist = self._runsql(sql)
return usrlist
usrl = self._runsql(sql)
return usrl
def _test():
test = Db(u'postgres')
print test.dblist()
print test.usrlist()
print test.info['encoding'], test.info['collation'], test.info['ctype']
#print test.owner
#print test.connections

Loading…
Cancel
Save