#!/usr/bin/env python

"""
Database utilities.

Copyright (C) 2016 Paul Boddie <paul@boddie.org.uk>

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any later
version.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
details.

You should have received a copy of the GNU General Public License along with
this program.  If not, see <http://www.gnu.org/licenses/>.
"""

import re

class DatabaseOperations:

    "Special database-related operations."

    def __init__(self, column_names=None, filter_values=None, paramstyle=None):
        self.column_names = column_names
        self.filter_values = filter_values
        self.paramstyle = paramstyle

    def get_query(self, query, columns=None, values=None, setcolumns=None,
                  setvalues=None):

        """
        Return 'query' parameterised with condition clauses indicated by
        ":condition" in 'query' that are themselves populated using the given
        'columns' and 'values' together with any conditions provided when
        initialising this class.

        If 'setcolumns' and 'setvalues' are given, such column details and
        values will be used to parameterise ":set" clauses in the query.
        """

        columns = self.merge_default_columns(columns)
        values = self.merge_default_values(values)

        condition = self.get_condition(columns)
        columnlist = self.columnlist(columns)
        placeholders = self.placeholders(values)
        setters = self.get_setters(setcolumns)

        setvalues = setvalues or []

        # Obtain the placeholder markers in order.

        parts = re.split("(:(?:condition|set|columns|values)(?=[^a-zA-Z]|$))", query)

        l = [parts[0]]
        is_placeholder = True
        all_values = []

        for part in parts[1:]:
            if is_placeholder:

                # Replace ":condition", replicating the given values.

                if part == ":condition":
                    all_values += values
                    l.append(condition)

                # Replace ":set", replicating the given values.

                elif part == ":set":
                    all_values += setvalues
                    l.append(setters)

                # Replace ":columns", providing a column list.

                elif part == ":columns":
                    l.append(columnlist)

                # Replace ":values", replicating the given values.

                elif part == ":values":
                    all_values += values
                    l.append(placeholders)

                else:
                    l.append(part)
            else:
                l.append(part)

            is_placeholder = not is_placeholder

        query = "".join(l)
        return query, all_values

    def get_condition(self, columns=None):

        "Return a condition clause featuring the given 'columns'."

        l = self._get_columns(columns)
        return "where %s" % " and ".join(l)

    def get_setters(self, columns=None):

        "Return set operations featuring the given 'columns'."

        l = self._get_columns(columns)
        return "set %s" % ", ".join(l)

    def _get_columns(self, columns=None):

        "Return a list of statements or tests involving 'columns'."

        l = []

        if columns:
            for column in columns:
                if " " in column:
                    column_name, remaining = column.split(" ", 1)
                    l.append("%s %s" % (self._quote(column_name), remaining.replace("?", self._param())))
                else:
                    l.append("%s = %s" % (self._quote(column), self._param()))

        return l

    def _quote(self, column):
        return '"%s"' % column

    def merge_default_columns(self, columns=None):
        return list(self.column_names or []) + list(columns or [])

    def merge_default_values(self, values=None):
        return list(self.filter_values or []) + list(values or [])

    def columnlist(self, columns=None):
        return ", ".join([self._quote(column) for column in columns])

    def placeholders(self, values=None):
        return ", ".join([self._param()] * len(values))

    def _param(self):

        # NOTE: To be expanded.

        if self.paramstyle == "pyformat":
            return "%s"
        else:
            return "?"

# vim: tabstop=4 expandtab shiftwidth=4
