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
    num2float,
16
    subset,
17
    SeriesServices,
18
    start_end,
19
20
    tzaware_serie
)
21
from tshistory.snapshot import Snapshot, TABLES as SNAPTABLES
22

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


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

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

52
53
54
55
56
57
    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')

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

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

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

81
        newts = num2float(newts)
82

83
        if not len(newts):
84
            return
85

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

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

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

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

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

        revision_date: datetime filter to get previous versions of the
        serie

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

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

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

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

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

153
154
155
156
157
158
159
    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()

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

172
        cset = self.schema.changeset
173
174
175
176
177
178
179
180
181
182
183
184
        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)
185

186
187
188
189
190
191
192
193
194
        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()
195
        if not revs:
196
            return {}
197

198
199
200
201
202
203
        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))

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

226
227
        if diffmode:
            diffs = []
Aurélien Campéas's avatar
Aurélien Campéas committed
228
            for (_revdate_a, serie_a), (revdate_b, serie_b) in zip(series, series[1:]):
229
230
231
232
233
234
235
                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
236
237
238
239
240
        else:
            series = [
                (idate, ts.dropna())
                 for idate, ts in series
            ]
241

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

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

262
263
264
265
266
267
268
269
        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

270
        ts = subset(pd.Series(vvmap).sort_index(), from_value_date, to_value_date)
271
272
        ts.name = seriename
        return ts
273

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

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

289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
    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()
        ]

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

308
309
310
    def changeset_at(self, cn, seriename, revdate, mode='strict'):
        assert mode in ('strict', 'before', 'after')
        cset = self.schema.changeset
311
        table = self._table_definition_for(cn, seriename)
312
313
        sql = select([table.c.cset]).where(
            table.c.cset == cset.c.id
314
315
316
317
318
319
320
321
322
        )
        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()

323
    def delete(self, cn, seriename):
324
        self._check_tx(cn)
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
357
        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()

358
    def strip(self, cn, seriename, csid):
359
        self._check_tx(cn)
360
361
362
363
364
365
366
367
        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
368
            metadata = self.changeset_metadata(cn, log['rev']) or {}
369
370
371
372
373
374
            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(
375
                cset_serie.c.cset == log['rev']
376
            ).where(
377
                cset_serie.c.serie == self._name_to_regid(cn, seriename)
378
379
380
381
            )
            cn.execute(sql)

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

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

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

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

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

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

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

446
    def interval(self, cn, seriename, notz=False):
447
448
449
450
451
452
453
454
        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
455
        if self.metadata(cn, seriename).get('tzaware') and not notz:
456
457
458
            start, end = pd.Timestamp(start, tz='UTC'), pd.Timestamp(end, tz='UTC')
        return pd.Interval(left=start, right=end, closed='both')

459
460
    # /API
    # Helpers
461

462
463
    # creation / update

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

476
477
478
479
480
        # 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)
        )
481
        self._register_serie(cn, seriename, newts)
482
        snapshot = Snapshot(cn, self, seriename)
483
        csid = self._newchangeset(cn, author, insertion_date, metadata)
484
        head = snapshot.create(newts)
485
        start, end = start_end(newts)
486
487
        value = {
            'cset': csid,
488
489
490
            'snapshot': head,
            'start': start,
            'end': end
491
        }
Aurélien Campéas's avatar
Aurélien Campéas committed
492
        table = self._make_ts_table(cn, seriename)
493
        cn.execute(table.insert().values(value))
494
        self._finalize_insertion(cn, csid, seriename)
495
        L.info('first insertion of %s (size=%s) by %s',
496
               seriename, len(newts), author)
497
498
        return newts

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

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

        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)
530
531
532
        head = snapshot.update(diff)
        value = {
            'cset': csid,
533
534
535
            'snapshot': head,
            'start': start,
            'end': end
536
537
        }
        cn.execute(table.insert().values(value))
538
        self._finalize_insertion(cn, csid, seriename)
539
540

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

544
    # serie table handling
545

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

551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
        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)
567
        if table is None:
568
569
            TABLES[fq_tablename] = table = Table(
                tablename, self.schema.meta,
570
571
572
                Column('id', Integer, primary_key=True),
                Column('cset', Integer,
                       ForeignKey('{}.changeset.id'.format(self.namespace)),
573
                       nullable=False),
574
575
                Column('start', TIMESTAMP, nullable=False),
                Column('end', TIMESTAMP, nullable=False),
576
577
578
                Column('snapshot', Integer,
                       ForeignKey('{}.snapshot.{}.id'.format(
                           self.namespace,
579
580
581
                           tablename))),
                Index(NONE_NAME, 'cset'),
                Index(NONE_NAME, 'snapshot'),
582
583
                Index(NONE_NAME, 'start'),
                Index(NONE_NAME, 'end'),
584
                schema='{}.timeserie'.format(self.namespace),
585
                keep_existing=True
586
587
            )
        return table
588

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

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

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

617
618
    # changeset handling

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

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

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

643
644
645
646
647
648
649
    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()

650
651
    # insertion handling

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

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

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

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

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