blob: 09c7058c3b2aaf740ffaf884667cbc9aa6dc1c6c [file] [log] [blame]
Matt Hart76fb2542014-06-01 14:24:56 +01001#! /usr/bin/python
2
3# Copyright 2013 Linaro Limited
4# Author Matt Hart <matthew.hart@linaro.org>
5#
6# This program is free software; you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation; either version 2 of the License, or
9# (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program; if not, write to the Free Software
18# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19# MA 02110-1301, USA.
20
21import logging
22import psycopg2
23import time
24
25class DBHandler(object):
26 def __init__(self, config):
27 logging.debug("Creating new DBHandler: %s" % config["dbhost"])
28 logging.getLogger().name = "DBHandler"
29 self.conn = psycopg2.connect(database=config["dbname"], user=config["dbuser"],
30 password=config["dbpass"], host=config["dbhost"])
31 self.cursor = self.conn.cursor()
32
33 def do_sql(self, sql):
34 logging.debug("executing sql: %s" % sql)
35 self.cursor.execute(sql)
36 self.conn.commit()
37
38 def do_sql_with_fetch(self, sql):
39 logging.debug("executing sql: %s" % sql)
40 self.cursor.execute(sql)
41 row = self.cursor.fetchone()
42 self.conn.commit()
43 return row
44
45 def delete_row(self, row_id):
46 logging.debug("deleting row %i" % row_id)
47 self.do_sql("delete from pdu_queue where id=%i" % row_id)
48
49 def get_res(self, sql):
50 return self.cursor.execute(sql)
51
52 def get_next_job(self):
53 now = int(time.time())
Matt Hart132d43c2015-02-25 18:19:53 +000054 row = self.do_sql_with_fetch("select id,hostname,port,request from pdu_queue where (exectime < %i or exectime is null) order by id asc limit 1" % now)
Matt Hart76fb2542014-06-01 14:24:56 +010055 return row
56
57 def close(self):
58 logging.debug("Closing DBHandler")
59 self.cursor.close()
60 self.conn.close()