<commit_before>from psycopg2.extras import DictCursor

__all__ = ['PgPyTable', 'PgPyDict']

def column_value_pairs(d, join_str=', '):
    """
    Create a string of SQL that will instruct a Psycopg2 DictCursor to
    interpolate the dictionary's keys into a SELECT or UPDATE SQL query.

    Example:
        d = {'id':10, 'person':'Dave'}

        becomes

        id=%(id)s, person=%(person)s
    """
    return join_str.join([str(k)+'=%('+k+')s' for k in d.keys()])


def insert_column_value_pairs(d):
    """
    Create a string of SQL that will instruct a Psycopg2 DictCursor to
    interpolate the dictionary's keys into a INSERT SQL query.

    Example:
        d = {'id':10, 'person':'Dave'}

        becomes

        (id, person) VALUES (%(id)s, %(person)s)
    """
    return '({}) VALUES ({})'.format(
            ', '.join(d),
            ', '.join(['%('+k+')s' for k in d]),
            )


class PgPyTable(object):
    """
    I am used to specify how a Psycopg2 table is constructed.  My init'd object
    can later be called to insert objects into that table.

    Example 1:
        Postgresql Table:
            >>> CREATE TABLE my_table (id SERIAL PRIMARY KEY, foo TEXT)

        Python:
            >>> conn = psycopg2.connect(**db_config)
            >>> curs = conn.cursor(cursor_factory=DictCursor)
            >>> MyTable = PgPyTable('my_table', curs, ('id',))
            >>> MyTable
            PgPyTable(my_table, ('id',))

            >>> row1 = MyTable({'foo':'bar',})
            {'id':1, 'foo':'bar'}

            >>> row2 = MyTable({'foo':'baz',})
            {'id':2, 'foo':'baz'}

            >>> row2_copy = MyTable.getByPrimary(2)
            >>> row2 == row2__copy
            True
    """

    def __init__(self, table, psycopg2_cursor, primary_keys):
        self.table = table
        self.curs = psycopg2_cursor
        self.pks = primary_keys
        self.ref_info = {}


    def __repr__(self):
        return 'PgPyTable({}, {})'.format(self.table, self.pks)


    def _execute(self, *a, **kw):
        return self.curs.execute(*a, **kw)


    def _initPgPyDict(self, d):
        # Create the PgPyDict before appending references because dictcursor
        # will not allow columns to be added.
        d = PgPyDict(d, self.table, self.curs, self.pks,
                self.ref_info)
        d = self._appendReferences(d)
        return d


    def __call__(self, *a, **kw):
        """
        Insert a new row using the provided dictionary.
        """
        d = dict(*a, **kw)
        keys = d.keys()
        if keys:
            self._execute('INSERT INTO {} {} RETURNING *'.format(
                        self.table, insert_column_value_pairs(keys)),
                    d)
        else:
            # Handle an empty call
            self._execute('INSERT INTO {} DEFAULT VALUES RETURNING *'.format(
                self.table))
        return self._initPgPyDict(self.curs.fetchone())


    def getByPrimary(self, primary):
        """
        Get a row from the table that matches the primary keys specified
        during this instance's creation.

        Single Primary Key:
            t = PgPyTable('some_table', curs, ('id',))
            row = t.getByPrimary(42)

        Multiple Primary Keys:
            t = PgPyTable('some_table', curs, ('id', 'group_id'))
            row = t.getByPrimary({'id':8, 'group_id':12})
        """
        try:
            if type(primary) != dict:
                primary = {self.pks[0]:primary,}
            return self._initPgPyDict(self.getWhere(primary))
        except IndexError:
            if not self.pks:
                raise ValueError('No primary keys specified, use getWhere')
            else:
                raise ValueError('Primary does not match primary keys specified during table creation.')


    def getWhere(self, where):
        self._execute('SELECT * FROM {} WHERE {}'.format(
                self.table,
                column_value_pairs(where, join_str=' AND ')
                ),
            where)
        return self.curs.fetchone()


    def _appendReferences(self, d):
        for ref_column in self.ref_info:
            table, pk, key_name = self.ref_info[ref_column]
            d[key_name] = table.getWhere({pk:d[ref_column],})
        return d


    def addReference(self, pgpytable, primary_key, ref_column, key_name):
        """
        When getting this table's row, get another table's row which is
        referenced by the provided parameters.
        """
        self.ref_info[ref_column] = (pgpytable, primary_key, key_name)



class PgPyDict(dict):
    """
    A Python dictionary wrapped so that it's contents are flushed to the<commit_msg>Condition may never be met.<commit_after>from psycopg2.extras import DictCursor

__all__ = ['PgPyTable', 'PgPyDict']

def column_value_pairs(d, join_str=', '):
    """
    Create a string of SQL that will instruct a Psycopg2 DictCursor to
    interpolate the dictionary's keys into a SELECT or UPDATE SQL query.

    Example:
        d = {'id':10, 'person':'Dave'}

        becomes

        id=%(id)s, person=%(person)s
    """
    return join_str.join([str(k)+'=%('+k+')s' for k in d.keys()])


def insert_column_value_pairs(d):
    """
    Create a string of SQL that will instruct a Psycopg2 DictCursor to
    interpolate the dictionary's keys into a INSERT SQL query.

    Example:
        d = {'id':10, 'person':'Dave'}

        becomes

        (id, person) VALUES (%(id)s, %(person)s)
    """
    return '({}) VALUES ({})'.format(
            ', '.join(d),
            ', '.join(['%('+k+')s' for k in d]),
            )


class PgPyTable(object):
    """
    I am used to specify how a Psycopg2 table is constructed.  My init'd object
    can later be called to insert objects into that table.

    Example 1:
        Postgresql Table:
            >>> CREATE TABLE my_table (id SERIAL PRIMARY KEY, foo TEXT)

        Python:
            >>> conn = psycopg2.connect(**db_config)
            >>> curs = conn.cursor(cursor_factory=DictCursor)
            >>> MyTable = PgPyTable('my_table', curs, ('id',))
            >>> MyTable
            PgPyTable(my_table, ('id',))

            >>> row1 = MyTable({'foo':'bar',})
            {'id':1, 'foo':'bar'}

            >>> row2 = MyTable({'foo':'baz',})
            {'id':2, 'foo':'baz'}

            >>> row2_copy = MyTable.getByPrimary(2)
            >>> row2 == row2__copy
            True
    """

    def __init__(self, table, psycopg2_cursor, primary_keys):
        self.table = table
        self.curs = psycopg2_cursor
        self.pks = primary_keys
        self.ref_info = {}


    def __repr__(self):
        return 'PgPyTable({}, {})'.format(self.table, self.pks)


    def _execute(self, *a, **kw):
        return self.curs.execute(*a, **kw)


    def _initPgPyDict(self, d):
        # Create the PgPyDict before appending references because dictcursor
        # will not allow columns to be added.
        d = PgPyDict(d, self.table, self.curs, self.pks,
                self.ref_info)
        d = self._appendReferences(d)
        return d


    def __call__(self, *a, **kw):
        """
        Insert a new row using the provided dictionary.
        """
        d = dict(*a, **kw)
        keys = d.keys()
        if keys:
            self._execute('INSERT INTO {} {} RETURNING *'.format(
                        self.table, insert_column_value_pairs(keys)),
                    d)
        else:
            # Handle an empty call
            self._execute('INSERT INTO {} DEFAULT VALUES RETURNING *'.format(
                self.table))
        return self._initPgPyDict(self.curs.fetchone())


    def getByPrimary(self, primary):
        """
        Get a row from the table that matches the primary keys specified
        during this instance's creation.

        Single Primary Key:
            t = PgPyTable('some_table', curs, ('id',))
            row = t.getByPrimary(42)

        Multiple Primary Keys:
            t = PgPyTable('some_table', curs, ('id', 'group_id'))
            row = t.getByPrimary({'id':8, 'group_id':12})
        """
        try:
            if type(primary) != dict:
                primary = {self.pks[0]:primary,}
            return self._initPgPyDict(self.getWhere(primary))
        except IndexError:
            raise ValueError('No primary keys specified, use getWhere')


    def getWhere(self, where):
        self._execute('SELECT * FROM {} WHERE {}'.format(
                self.table,
                column_value_pairs(where, join_str=' AND ')
                ),
            where)
        return self.curs.fetchone()


    def _appendReferences(self, d):
        for ref_column in self.ref_info:
            table, pk, key_name = self.ref_info[ref_column]
            d[key_name] = table.getWhere({pk:d[ref_column],})
        return d


    def addReference(self, pgpytable, primary_key, ref_column, key_name):
        """
        When getting this table's row, get another table's row which is
        referenced by the provided parameters.
        """
        self.ref_info[ref_column] = (pgpytable, primary_key, key_name)



class PgPyDict(dict):
    """
    A Python dictionary wrapped so that it's contents are flushed to the
{'fraction_non_alphanumeric': 0.12627357468025147, 'fraction_numerical': 0.0056362453934532845, 'mean_word_length': 2.046219874546055, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 57, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2840945', 'n_tokens_mistral': 2887, 'n_tokens_neox': 2729, 'n_words': 758}