Changeset 748 for trunk/pg.py


Ignore:
Timestamp:
Jan 15, 2016, 9:25:31 AM (4 years ago)
Author:
cito
Message:

Add method truncate() to DB wrapper class

This methods can be used to quickly truncate tables.

Since this is pretty useful and will not break anything, I have
also back ported this addition to the 4.x branch.

Everything is well documented and tested, of course.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/pg.py

    r747 r748  
    578578            if param == 'all':
    579579                if value is not None:
    580                     raise ValueError(
    581                         "A value must ot be set when parameter is 'all'")
     580                    raise ValueError('A value must ot be specified'
     581                        " when parameter is 'all'")
    582582                params = {'all': None}
    583583                break
     
    10881088        return int(res)
    10891089
     1090    def truncate(self, table, restart=False, cascade=False, only=False):
     1091        """Empty a table or set of tables.
     1092
     1093        This method quickly removes all rows from the given table or set
     1094        of tables.  It has the same effect as an unqualified DELETE on each
     1095        table, but since it does not actually scan the tables it is faster.
     1096        Furthermore, it reclaims disk space immediately, rather than requiring
     1097        a subsequent VACUUM operation. This is most useful on large tables.
     1098
     1099        If restart is set to True, sequences owned by columns of the truncated
     1100        table(s) are automatically restarted.  If cascade is set to True, it
     1101        also truncates all tables that have foreign-key references to any of
     1102        the named tables.  If the parameter only is not set to True, all the
     1103        descendant tables (if any) will also be truncated. Optionally, a '*'
     1104        can be specified after the table name to explicitly indicate that
     1105        descendant tables are included.
     1106        """
     1107        if isinstance(table, basestring):
     1108            only = {table: only}
     1109            table = [table]
     1110        elif isinstance(table, (list, tuple)):
     1111            if isinstance(only, (list, tuple)):
     1112                only = dict(zip(table, only))
     1113            else:
     1114                only = dict.fromkeys(table, only)
     1115        elif isinstance(table, (set, frozenset)):
     1116            only = dict.fromkeys(table, only)
     1117        else:
     1118            raise TypeError('The table must be a string, list or set')
     1119        if not (restart is None or isinstance(restart, (bool, int))):
     1120            raise TypeError('Invalid type for the restart option')
     1121        if not (cascade is None or isinstance(cascade, (bool, int))):
     1122            raise TypeError('Invalid type for the cascade option')
     1123        tables = []
     1124        for t in table:
     1125            u = only.get(t)
     1126            if not (u is None or isinstance(u, (bool, int))):
     1127                raise TypeError('Invalid type for the only option')
     1128            if t.endswith('*'):
     1129                if u:
     1130                    raise ValueError(
     1131                        'Contradictory table name and only options')
     1132                t = t[:-1].rstrip()
     1133            t = self._escape_qualified_name(t)
     1134            if u:
     1135                t = 'ONLY %s' % t
     1136            tables.append(t)
     1137        q = ['TRUNCATE', ', '.join(tables)]
     1138        if restart:
     1139            q.append('RESTART IDENTITY')
     1140        if cascade:
     1141            q.append('CASCADE')
     1142        q = ' '.join(q)
     1143        self._do_debug(q)
     1144        return self.query(q)
     1145
    10901146    def notification_handler(self, event, callback, arg_dict={}, timeout=None):
    10911147        """Get notification handler that will run the given callback."""
Note: See TracChangeset for help on using the changeset viewer.