tsio.py 25.1 KB
Newer Older
1
from datetime import datetime
2
import logging
3
4
5

import pandas as pd

6
7
from sqlalchemy import Table, Column, Integer, ForeignKey, Index
from sqlalchemy.sql.elements import NONE_NAME
8
from sqlalchemy.engine.base import Engine
Aurélien Campéas's avatar
Aurélien Campéas committed
9
from sqlalchemy.sql.expression import select, func, desc
Aurélien Campéas's avatar
Aurélien Campéas committed
10
from sqlalchemy.dialects.postgresql import TIMESTAMP
11

12
from tshistory.schema import tsschema
13
from tshistory.util import (
14
    closed_overlaps,
15
16
    num2float,
    SeriesServices,
17
    start_end,
18
19
    tzaware_serie
)
20
from tshistory.snapshot import Snapshot, TABLES as SNAPTABLES
21

22
L = logging.getLogger('tshistory.tsio')
23
TABLES = {}
24
25


26
class TimeSerie(SeriesServices):
27
    namespace = 'tsh'
28
    schema = None
29
    metadatacache = None
30
31
32
33
34
35
36
37
    metakeys = {
        'tzaware',
        'index_type',
        'index_names',
        'index_dtype',
        'value_dtype',
        'value_type'
    }
38
    registry_map = None
39
    serie_tablename = None
40
    create_lock_id = None
41
42
43

    def __init__(self, namespace='tsh'):
        self.namespace = namespace
44
45
        self.schema = tsschema(namespace)
        self.schema.define()
46
        self.metadatacache = {}
47
        self.registry_map = {}
48
        self.serie_tablename = {}
49
        self.create_lock_id = sum(ord(c) for c in namespace)
50

51
52
53
54
55
56
    def _check_tx(self, cn):
        # safety belt to make sure important api points are tx-safe
        if isinstance(cn, Engine) or not cn.in_transaction():
            if not getattr(self, '_testing', False):
                raise TypeError('You must use a transaction object')

57
    def insert(self, cn, newts, seriename, author,
58
59
               metadata=None,
               _insertion_date=None):
60
        """Create a new revision of a given time series
61

62
        newts: pandas.Series with date index
63
        seriename: str unique identifier of the serie
64
        author: str free-form author name
65
        metadata: optional dict for changeset metadata
66
        """
67
        self._check_tx(cn)
68
69
70
71
        assert isinstance(newts, pd.Series), 'Not a pd.Series'
        assert isinstance(seriename, str), 'Name not a string'
        assert isinstance(author, str), 'Author not a string'
        assert metadata is None or isinstance(metadata, dict), 'Bad format for metadata'
72
73
        assert (_insertion_date is None or
                isinstance(_insertion_date, datetime)), 'Bad format for insertion date'
74
        assert not newts.index.duplicated().any(), 'There are some duplicates in the index'
75

76
        assert newts.index.notna().all(), 'The index contains NaT entries'
77
78
        if not newts.index.is_monotonic_increasing:
            newts = newts.sort_index()
79

80
        newts = num2float(newts)
81

82
        if not len(newts):
83
            return
84

85
        assert ('<M8[ns]' == newts.index.dtype or
86
                'datetime' in str(newts.index.dtype) and not
87
88
                isinstance(newts.index, pd.MultiIndex))

89
90
        newts.name = seriename
        table = self._get_ts_table(cn, seriename)
91

92
        if table is None:
93
            return self._create(cn, newts, seriename, author,
94
                                metadata, _insertion_date)
95

96
        return self._update(cn, table, newts, seriename, author,
97
                            metadata, _insertion_date)
98

99
    def get(self, cn, seriename, revision_date=None,
100
101
            from_value_date=None, to_value_date=None,
            _keep_nans=False):
102
103
104
105
106
        """Compute and return the serie of a given name

        revision_date: datetime filter to get previous versions of the
        serie

107
        """
108
        table = self._get_ts_table(cn, seriename)
109
110
        if table is None:
            return
111

112
        csetfilter = []
113
        if revision_date:
114
            csetfilter.append(lambda cset: cset.c.insertion_date <= revision_date)
115
        snap = Snapshot(cn, self, seriename)
116
        _, current = snap.find(csetfilter=csetfilter,
117
118
                               from_value_date=from_value_date,
                               to_value_date=to_value_date)
119

120
        if current is not None and not _keep_nans:
121
            current.name = seriename
122
            current = current[~current.isnull()]
123
        return current
124

125
    def metadata(self, cn, seriename):
126
        """Return metadata dict of timeserie."""
127
128
        if seriename in self.metadatacache:
            return self.metadatacache[seriename]
129
130
        reg = self.schema.registry
        sql = select([reg.c.metadata]).where(
131
            reg.c.seriename == seriename
132
133
        )
        meta = cn.execute(sql).scalar()
134
        self.metadatacache[seriename] = meta
135
136
        return meta

137
    def update_metadata(self, cn, seriename, metadata):
138
        self._check_tx(cn)
139
        assert isinstance(metadata, dict)
140
        assert not set(metadata.keys()) & self.metakeys
141
        meta = self.metadata(cn, seriename)
142
143
144
        # remove al but internal stuff
        newmeta = {key: meta[key] for key in self.metakeys}
        newmeta.update(metadata)
145
146
        reg = self.schema.registry
        sql = reg.update().where(
147
            reg.c.seriename == seriename
148
        ).values(metadata=newmeta)
149
        self.metadatacache.pop(seriename)
150
151
        cn.execute(sql)

152
153
154
155
156
157
158
    def changeset_metadata(self, cn, csid):
        sql = 'select metadata from "{ns}".changeset where id = {id}'.format(
            ns=self.namespace,
            id=csid
        )
        return cn.execute(sql).scalar()

159
    def get_history(self, cn, seriename,
160
                    from_insertion_date=None,
161
162
                    to_insertion_date=None,
                    from_value_date=None,
163
                    to_value_date=None,
164
                    deltabefore=None,
165
166
                    deltaafter=None,
                    diffmode=False):
167
        table = self._get_ts_table(cn, seriename)
168
169
170
        if table is None:
            return

171
        cset = self.schema.changeset
172
173
174
175
176
177
178
179
180
181
182
183
        revsql = select(
            [cset.c.id, cset.c.insertion_date]
        ).order_by(
            cset.c.id
        ).where(
            table.c.cset == cset.c.id
        )

        if from_insertion_date:
            revsql = revsql.where(cset.c.insertion_date >= from_insertion_date)
        if to_insertion_date:
            revsql = revsql.where(cset.c.insertion_date <= to_insertion_date)
184

185
186
187
188
189
190
191
192
193
        if from_value_date or to_value_date:
            revsql = revsql.where(
                closed_overlaps(from_value_date, to_value_date)
            )

        revs = cn.execute(
            revsql,
            {'fromdate': from_value_date, 'todate': to_value_date}
        ).fetchall()
194
        if not revs:
195
            return {}
196

197
198
199
200
201
202
        if diffmode:
            # compute the previous serie value
            first_csid = revs[0][0]
            previous_csid = self._previous_cset(cn, seriename, first_csid)
            revs.insert(0, (previous_csid, None))

203
        snapshot = Snapshot(cn, self, seriename)
204
        series = []
205
206
        if (deltabefore, deltaafter) != (None, None):
            for csid, idate in revs:
207
208
                from_date = None
                to_date = None
209
                if deltabefore is not None:
210
                    from_date = idate - deltabefore
211
                if deltaafter is not None:
212
                    to_date = idate + deltaafter
213
214
215
                series.append((
                    idate,
                    snapshot.find(csetfilter=[lambda cset: cset.c.id == csid],
216
217
                                  from_value_date=from_date,
                                  to_value_date=to_date)[1]
218
219
220
221
222
223
                ))
        else:
            series = snapshot.findall(revs,
                                      from_value_date,
                                      to_value_date
            )
224

225
226
        if diffmode:
            diffs = []
Aurélien Campéas's avatar
Aurélien Campéas committed
227
            for (_revdate_a, serie_a), (revdate_b, serie_b) in zip(series, series[1:]):
228
229
230
231
232
233
234
                if serie_a is None:
                    # when we scan the entirety of the history: there exists no "previous" serie
                    # we therefore consider the first serie as a diff to the "null" serie
                    diffs.append((revdate_b, serie_b))
                else:
                    diffs.append((revdate_b, self.diff(serie_a, serie_b)))
            series = diffs
235
236
237
238
239
        else:
            series = [
                (idate, ts.dropna())
                 for idate, ts in series
            ]
240

241
        return {
242
            pd.Timestamp(idate).astimezone('UTC'): serie
243
244
            for idate, serie in series
        }
245

246
247
248
    def get_delta(self, cn, seriename, delta,
                  from_value_date=None,
                  to_value_date=None):
249
250
251
252
        """ compute a series whose value dates are bounded to be
        `delta` time after the insertion dates and where we
        keep the most recent ones
        """
253
        histo = self.get_history(
254
255
256
            cn, seriename, deltabefore=-delta,
            from_value_date=from_value_date,
            to_value_date=to_value_date
257
        )
258
259
        if histo is None:
            return None
260

261
262
263
264
265
266
267
268
        vimap = {}
        vvmap = {}
        for idate, series in histo.items():
            for vdate, value in series.iteritems():
                if vdate not in vimap or vimap[vdate] < idate:
                    vimap[vdate] = idate
                    vvmap[vdate] = value

269
        ts = pd.Series(vvmap).sort_index().loc[from_value_date:to_value_date]
270
271
        ts.name = seriename
        return ts
272

273
274
    def exists(self, cn, seriename):
        return self._get_ts_table(cn, seriename) is not None
275

276
    def latest_insertion_date(self, cn, seriename):
277
        cset = self.schema.changeset
278
        tstable = self._get_ts_table(cn, seriename)
279
280
281
282
283
284
285
286
        sql = select(
            [func.max(cset.c.insertion_date)]
        ).where(
            tstable.c.cset == cset.c.id
        )
        return pd.Timestamp(
            cn.execute(sql).scalar()
        ).astimezone('UTC')
287

288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
    def insertion_dates(self, cn, seriename):
        cset = self.schema.changeset
        tstable = self._get_ts_table(cn, seriename)
        sql = select(
            [cset.c.insertion_date]
        ).where(
            tstable.c.cset == cset.c.id
        ).order_by(
            cset.c.id
        )
        return [
            pd.Timestamp(idate).astimezone('UTC')
            for idate, in cn.execute(sql).fetchall()
        ]

303
304
305
306
    def last_id(self, cn, seriename):
        snapshot = Snapshot(cn, self, seriename)
        return snapshot.last_id()

307
308
309
    def changeset_at(self, cn, seriename, revdate, mode='strict'):
        assert mode in ('strict', 'before', 'after')
        cset = self.schema.changeset
310
        table = self._table_definition_for(cn, seriename)
311
312
        sql = select([table.c.cset]).where(
            table.c.cset == cset.c.id
313
314
315
316
317
318
319
320
321
        )
        if mode == 'strict':
            sql = sql.where(cset.c.insertion_date == revdate)
        elif mode == 'before':
            sql = sql.where(cset.c.insertion_date <= revdate)
        else:
            sql = sql.where(cset.c.insertion_date >= revdate)
        return cn.execute(sql).scalar()

322
    def delete(self, cn, seriename):
323
        self._check_tx(cn)
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
        assert not isinstance(cn, Engine), 'use a transaction object'
        assert self.exists(cn, seriename)
        # changeset will keep ghost entries
        # we cleanup changeset series, then registry
        # then we drop the two remaining tables
        # cn *must* be a transaction scope
        rid, tablename = cn.execute(
            'select id, table_name from "{}".registry '
            'where seriename = %(seriename)s'.format(self.namespace),
            seriename=seriename
        ).fetchone()
        # drop series tables
        cn.execute(
            'drop table "{}.timeserie"."{}" cascade'.format(self.namespace, tablename)
        )
        cn.execute(
            'drop table "{}.snapshot"."{}" cascade'.format(self.namespace, tablename)
        )
        # cleanup changesets table
        cn.execute('with csets as ('
                   ' select cset from "{ns}".changeset_series '
                   ' where serie = %(rid)s'
                   ') '
                   'delete from "{ns}".changeset as cset using csets '
                   'where cset.id = csets.cset'.format(ns=self.namespace),
                   rid=rid
        )
        cn.execute('delete from "{}".registry '
                   'where id = %(rid)s'.format(self.namespace),
                   rid=rid)
        # -> this will transitively cleanup state changeset_series entries
        self._resetcaches()

357
    def strip(self, cn, seriename, csid):
358
        self._check_tx(cn)
359
360
361
362
363
364
365
366
        logs = self.log(cn, fromrev=csid, names=(seriename,))
        assert logs

        # put stripping info in the metadata
        cset = self.schema.changeset
        cset_serie = self.schema.changeset_series
        for log in logs:
            # update changeset.metadata
367
            metadata = self.changeset_metadata(cn, log['rev']) or {}
368
369
370
371
372
373
            metadata['tshistory.info'] = 'got stripped from {}'.format(csid)
            sql = cset.update().where(cset.c.id == log['rev']
            ).values(metadata=metadata)
            cn.execute(sql)
            # delete changset_serie item
            sql = cset_serie.delete().where(
374
                cset_serie.c.cset == log['rev']
375
            ).where(
376
                cset_serie.c.serie == self._name_to_regid(cn, seriename)
377
378
379
380
            )
            cn.execute(sql)

        # wipe the diffs
381
        table = self._table_definition_for(cn, seriename)
382
        cn.execute(table.delete().where(table.c.cset >= csid))
383

384
    def info(self, cn):
385
386
        """Gather global statistics on the current tshistory repository
        """
387
        sql = 'select count(*) from "{}".registry'.format(self.namespace)
388
        stats = {'series count': cn.execute(sql).scalar()}
389
        sql = 'select max(id) from "{}".changeset'.format(self.namespace)
390
        stats['changeset count'] = cn.execute(sql).scalar()
391
392
393
        sql = 'select distinct seriename from "{}".registry order by seriename'.format(
            self.namespace
        )
394
        stats['serie names'] = [row for row, in cn.execute(sql).fetchall()]
395
396
        return stats

397
    def log(self, cn, limit=0, names=None, authors=None,
398
            stripped=False,
399
400
            fromrev=None, torev=None,
            fromdate=None, todate=None):
401
402
403
404
        """Build a structure showing the history of all the series in the db,
        per changeset, in chronological order.
        """
        log = []
405
406
407
408
409
        cset, cset_series, reg = (
            self.schema.changeset,
            self.schema.changeset_series,
            self.schema.registry
        )
410

411
        sql = select([cset.c.id, cset.c.author, cset.c.insertion_date, cset.c.metadata]
412
        ).distinct().order_by(desc(cset.c.id))
413
414
415

        if limit:
            sql = sql.limit(limit)
416
        if names:
417
            sql = sql.where(reg.c.seriename.in_(names))
418
419
        if authors:
            sql = sql.where(cset.c.author.in_(authors))
420
421
422
423
        if fromrev:
            sql = sql.where(cset.c.id >= fromrev)
        if torev:
            sql = sql.where(cset.c.id <= torev)
424
425
426
427
        if fromdate:
            sql = sql.where(cset.c.insertion_date >= fromdate)
        if todate:
            sql = sql.where(cset.c.insertion_date <= todate)
428
429
430
431
        if stripped:
            # outerjoin to show dead things
            sql = sql.select_from(cset.outerjoin(cset_series))
        else:
432
            sql = sql.where(cset.c.id == cset_series.c.cset
433
            ).where(cset_series.c.serie == reg.c.id)
434

435
        rset = cn.execute(sql)
436
        for csetid, author, revdate, meta in rset.fetchall():
437
438
            log.append({'rev': csetid, 'author': author,
                        'date': pd.Timestamp(revdate, tz='utc'),
439
                        'meta': meta or {},
440
                        'names': self._changeset_series(cn, csetid)})
441

442
        log.sort(key=lambda rev: rev['rev'])
443
444
        return log

445
    def interval(self, cn, seriename, notz=False):
446
447
448
449
450
451
452
453
        tablename = self._serie_to_tablename(cn, seriename)
        if tablename is None:
            raise ValueError(f'no such serie: {seriename}')
        sql = (f'select start, "end" '
               f'from "{self.namespace}.timeserie"."{tablename}" '
               f'order by cset desc limit 1')
        res = cn.execute(sql).fetchone()
        start, end = res.start, res.end
454
        if self.metadata(cn, seriename).get('tzaware') and not notz:
455
456
457
            start, end = pd.Timestamp(start, tz='UTC'), pd.Timestamp(end, tz='UTC')
        return pd.Interval(left=start, right=end, closed='both')

458
459
    # /API
    # Helpers
460

461
462
    # creation / update

463
    def _create(self, cn, newts, seriename, author,
464
                metadata=None, insertion_date=None):
465
        start, end = start_end(newts, notz=False)
466
467
468
469
        if start is None:
            assert end is None
            # this is just full of nans
            return None
470
471
472
473
474
        # chop off unwanted nans
        newts = newts.loc[start:end]
        if len(newts) == 0:
            return None

475
476
477
478
479
        # at creation time we take an exclusive lock to avoid
        # a deadlock on created tables against the changeset-series fk
        cn.execute(
            'select pg_advisory_xact_lock({})'.format(self.create_lock_id)
        )
480
        self._register_serie(cn, seriename, newts)
481
        snapshot = Snapshot(cn, self, seriename)
482
        csid = self._newchangeset(cn, author, insertion_date, metadata)
483
        head = snapshot.create(newts)
484
        start, end = start_end(newts)
485
486
        value = {
            'cset': csid,
487
488
489
            'snapshot': head,
            'start': start,
            'end': end
490
        }
Aurélien Campéas's avatar
Aurélien Campéas committed
491
        table = self._make_ts_table(cn, seriename)
492
        cn.execute(table.insert().values(value))
493
        self._finalize_insertion(cn, csid, seriename)
494
        L.info('first insertion of %s (size=%s) by %s',
495
               seriename, len(newts), author)
496
497
        return newts

498
    def _update(self, cn, table, newts, seriename, author,
499
                metadata=None, insertion_date=None):
500
501
        self._validate(cn, newts, seriename)
        snapshot = Snapshot(cn, self, seriename)
502
503
504
        diff = self.diff(snapshot.last(newts.index.min(),
                                       newts.index.max()),
                         newts)
505
506
        if not len(diff):
            L.info('no difference in %s by %s (for ts of size %s)',
507
                   seriename, author, len(newts))
508
509
            return

510
        # compute series start/end stamps
511
        tsstart, tsend = start_end(newts)
512
513
514
        ival = self.interval(cn, seriename, notz=True)
        start = min(tsstart or ival.left, ival.left)
        end = max(tsend or ival.right, ival.right)
515
516
517
518
519
520
521
522
523
524
525
526
527
528

        if pd.isnull(diff[0]) or pd.isnull(diff[-1]):
            # we *might* be shrinking, let's look at the full series
            # and yes, shrinkers have a slow path
            last = snapshot.last()
            patched = self.patch(last, diff).dropna()
            if not len(patched):
                raise ValueError('complete erasure of a series is forbidden')
            if pd.isnull(diff[0]):
                start = patched.index[0]
            if pd.isnull(diff[-1]):
                end = patched.index[-1]

        csid = self._newchangeset(cn, author, insertion_date, metadata)
529
530
531
        head = snapshot.update(diff)
        value = {
            'cset': csid,
532
533
534
            'snapshot': head,
            'start': start,
            'end': end
535
536
        }
        cn.execute(table.insert().values(value))
537
        self._finalize_insertion(cn, csid, seriename)
538
539

        L.info('inserted diff (size=%s) for ts %s by %s',
540
               len(diff), seriename, author)
541
542
        return diff

543
    # serie table handling
544

545
546
547
548
    def _serie_to_tablename(self, cn, seriename):
        tablename = self.serie_tablename.get(seriename)
        if tablename is not None:
            return tablename
549

550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
        reg = self.schema.registry
        sql = select([reg.c.table_name]).where(reg.c.seriename == seriename)
        tablename = cn.execute(sql).scalar()
        if tablename is None:
            # creation time
            return
        self.serie_tablename[seriename] = tablename
        return tablename

    def _table_definition_for(self, cn, seriename):
        tablename = self._serie_to_tablename(cn, seriename)
        if tablename is None:
            # creation time
            tablename = self._make_tablename(seriename)
        fq_tablename = '{}.timeserie.{}'.format(self.namespace, tablename)
        table = TABLES.get(fq_tablename)
566
        if table is None:
567
568
            TABLES[fq_tablename] = table = Table(
                tablename, self.schema.meta,
569
570
571
                Column('id', Integer, primary_key=True),
                Column('cset', Integer,
                       ForeignKey('{}.changeset.id'.format(self.namespace)),
572
                       nullable=False),
573
574
                Column('start', TIMESTAMP, nullable=False),
                Column('end', TIMESTAMP, nullable=False),
575
576
577
                Column('snapshot', Integer,
                       ForeignKey('{}.snapshot.{}.id'.format(
                           self.namespace,
578
579
580
                           tablename))),
                Index(NONE_NAME, 'cset'),
                Index(NONE_NAME, 'snapshot'),
581
582
                Index(NONE_NAME, 'start'),
                Index(NONE_NAME, 'end'),
583
                schema='{}.timeserie'.format(self.namespace),
584
                keep_existing=True
585
586
            )
        return table
587

Aurélien Campéas's avatar
Aurélien Campéas committed
588
    def _make_ts_table(self, cn, seriename):
589
        table = self._table_definition_for(cn, seriename)
590
        table.create(cn)
591
592
593
        return table

    def _register_serie(self, cn, seriename, ts):
594
595
        index = ts.index
        inames = [name for name in index.names if name]
596
        sql = self.schema.registry.insert().values(
597
598
            seriename=seriename,
            table_name=self._make_tablename(seriename),
599
600
601
602
            metadata={
                'tzaware': tzaware_serie(ts),
                'index_type': index.dtype.name,
                'index_names': inames,
603
604
                'index_dtype': index.dtype.str,
                'value_dtype': ts.dtypes.str,
605
                'value_type': ts.dtypes.name
606
            }
607
        )
608
609
        regid = cn.execute(sql).inserted_primary_key[0]
        self.registry_map[seriename] = regid
610

611
    def _get_ts_table(self, cn, seriename):
612
613
614
        tablename = self._serie_to_tablename(cn, seriename)
        if tablename:
            return self._table_definition_for(cn, tablename)
615

616
617
    # changeset handling

618
    def _newchangeset(self, cn, author, insertion_date=None, metadata=None):
619
        table = self.schema.changeset
620
621
622
        if insertion_date is not None:
            assert insertion_date.tzinfo is not None
        idate = pd.Timestamp(insertion_date or datetime.utcnow(), tz='UTC')
623
624
        sql = table.insert().values(
            author=author,
625
            metadata=metadata,
626
            insertion_date=idate)
627
        return cn.execute(sql).inserted_primary_key[0]
628

629
    def _changeset_series(self, cn, csid):
630
        cset_serie = self.schema.changeset_series
631
632
        reg = self.schema.registry
        sql = select(
633
            [reg.c.seriename]
634
635
        ).where(cset_serie.c.cset == csid
        ).where(cset_serie.c.serie == reg.c.id)
636

637
        return [
638
            row.seriename
639
640
            for row in cn.execute(sql).fetchall()
        ]
641

642
643
644
645
646
647
648
    def _previous_cset(self, cn, seriename, csid):
        tablename = self._serie_to_tablename(cn, seriename)
        sql = ('select cset from "{}.timeserie"."{}" '
               'where cset < %(csid)s '
               'order by cset desc limit 1').format(self.namespace, tablename)
        return cn.execute(sql, csid=csid).scalar()

649
650
    # insertion handling

651
    def _validate(self, cn, ts, seriename):
652
653
        if ts.isnull().all():
            # ts erasure
654
            return
655
        tstype = ts.dtype
656
        meta = self.metadata(cn, seriename)
657
        if tstype != meta['value_type']:
658
            m = 'Type error when inserting {}, new type is {}, type in base is {}'.format(
659
                seriename, tstype, meta['value_type'])
660
            raise Exception(m)
661
        if ts.index.dtype.name != meta['index_type']:
662
            raise Exception('Incompatible index types')
663

664
665
    def _name_to_regid(self, cn, seriename):
        regid = self.registry_map.get(seriename)
666
667
668
669
        if regid is not None:
            return regid

        registry = self.schema.registry
670
        sql = select([registry.c.id]).where(registry.c.seriename == seriename)
671
        regid = self.registry_map[seriename] = cn.execute(sql).scalar()
672
673
        return regid

674
    def _finalize_insertion(self, cn, csid, seriename):
675
676
677
        table = self.schema.changeset_series
        sql = table.insert().values(
            cset=csid,
678
            serie=self._name_to_regid(cn, seriename)
679
680
        )
        cn.execute(sql)
681

682
683
684
    def _resetcaches(self):
        TABLES.clear()
        SNAPTABLES.clear()
685
686
687
        self.metadatacache.clear()
        self.registry_map.clear()
        self.serie_tablename.clear()