base.py 2.33 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# Copyright (c) 2016, Daniele Venzano
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Interface to PostgresQL for Zoe state."""

import logging

log = logging.getLogger(__name__)


23
class BaseRecord:
24 25 26 27 28 29 30 31 32 33 34 35 36
    """
    :type sql_manager: SQLManager
    """
    def __init__(self, d, sql_manager):
        """
        :type sql_manager: SQLManager
        """
        self.sql_manager = sql_manager
        self.id = d['id']

    def serialize(self):
        """Generates a dictionary that can be serialized in JSON."""
        raise NotImplementedError
37 38 39 40


class BaseTable:
    """Common abstraction for all tables."""
41
    def __init__(self, sql_manager, table_name):
42
        self.table_name = table_name
43 44
        self.sql_manager = sql_manager
        self.cursor = self.sql_manager.cursor()
45 46 47 48 49 50 51 52 53 54 55

    def create(self):
        """Create this table."""
        raise NotImplementedError

    def insert(self, **kwargs):
        """Create a new record."""
        raise NotImplementedError

    def delete(self, record_id):
        """Delete a record from this table."""
56
        query = 'DELETE FROM "{}" WHERE id = %s'.format(self.table_name)
57
        self.cursor.execute(query, (record_id,))
58
        self.sql_manager.commit()
59 60 61 62 63 64 65 66 67 68

    def update(self, record_id, **kwargs):
        """Update the state of an execution."""
        arg_list = []
        value_list = []
        for key, value in kwargs.items():
            arg_list.append('{} = %s'.format(key))
            value_list.append(value)
        set_q = ", ".join(arg_list)
        value_list.append(record_id)
69
        q_base = 'UPDATE "{}" SET '.format(self.table_name) + set_q + ' WHERE id=%s'
70 71
        query = self.cursor.mogrify(q_base, value_list)
        self.cursor.execute(query)
72
        self.sql_manager.commit()
73 74 75 76

    def select(self, only_one=False, limit=-1, **kwargs):
        """Select records."""
        raise NotImplementedError