tsio.py 27.6 KB
Newer Older
1
from datetime import datetime
2
import logging
3
4
import hashlib
import uuid
5
from threading import Lock
6
7
import json
from pathlib import Path
8
9
10

import pandas as pd

11
12
from deprecated import deprecated

13
from tshistory.schema import tsschema
14
from tshistory.util import (
15
    closed_overlaps,
16
17
    num2float,
    SeriesServices,
18
    start_end,
19
    sqlfile,
20
    tx,
21
22
    tzaware_serie
)
23
from tshistory.snapshot import Snapshot
24

25
L = logging.getLogger('tshistory.tsio')
26
SERIESSCHEMA = Path(__file__).parent / 'series.sql'
27
28


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

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

54
    @tx
55
    def insert(self, cn, newts, seriename, author,
56
57
               metadata=None,
               _insertion_date=None):
58
        """Create a new revision of a given time series
59

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

73
        assert newts.index.notna().all(), 'The index contains NaT entries'
74
75
        if not newts.index.is_monotonic_increasing:
            newts = newts.sort_index()
76

77
        newts = num2float(newts)
78

79
        if not len(newts):
80
            return
81

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

86
        newts.name = seriename
87
        tablename = self._serie_to_tablename(cn, seriename)
88

89
        if tablename is None:
90
            return self._create(cn, newts, seriename, author,
91
                                metadata, _insertion_date)
92

93
        return self._update(cn, tablename, newts, seriename, author,
94
                            metadata, _insertion_date)
95

96
97
98
99
100
101
    def list_series(self, cn):
        """Return the list of all primary series"""
        sql = f'select seriename from "{self.namespace}".registry '
        return [row.seriename for row in cn.execute(sql)]


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

        revision_date: datetime filter to get previous versions of the
        serie

110
        """
Aurélien Campéas's avatar
Aurélien Campéas committed
111
        if not self.exists(cn, seriename):
112
            return
113

114
        csetfilter = []
115
        if revision_date:
116
117
118
            csetfilter.append(
                f'cset.insertion_date <= \'{revision_date.isoformat()}\''
            )
119
        snap = Snapshot(cn, self, seriename)
120
        _, current = snap.find(csetfilter=csetfilter,
121
122
                               from_value_date=from_value_date,
                               to_value_date=to_value_date)
123

124
        if current is not None and not _keep_nans:
125
            current.name = seriename
126
            current = current[~current.isnull()]
127
        return current
128

129
    def metadata(self, cn, seriename):
130
        """Return metadata dict of timeserie."""
131
132
        if seriename in self.metadatacache:
            return self.metadatacache[seriename]
133
134
135
        sql = (f'select metadata from {self.namespace}.registry '
               'where seriename = %(seriename)s')
        meta = cn.execute(sql, seriename=seriename).scalar()
136
137
        if meta is not None:
            self.metadatacache[seriename] = meta
138
139
        return meta

140
    @tx
141
    def update_metadata(self, cn, seriename, metadata, internal=False):
142
        assert isinstance(metadata, dict)
143
        assert internal or not set(metadata.keys()) & self.metakeys
144
        meta = self.metadata(cn, seriename)
145
        # remove al but internal stuff
146
147
148
149
150
        newmeta = {
            key: meta[key]
            for key in self.metakeys
            if meta.get(key) is not None
        }
151
        newmeta.update(metadata)
152
153
154
        sql = (f'update "{self.namespace}".registry as reg '
               'set metadata = %(metadata)s '
               'where reg.seriename = %(seriename)s')
155
        self.metadatacache.pop(seriename)
156
157
158
159
160
        cn.execute(
            sql,
            metadata=json.dumps(newmeta),
            seriename=seriename
        )
161

162
    def changeset_metadata(self, cn, csid):
163
164
165
        assert isinstance(csid, int)
        sql = (f'select metadata from "{self.namespace}".changeset '
               f'where id = {csid}')
166
167
        return cn.execute(sql).scalar()

168
169
170
    def type(self, cn, name):
        return 'primary'

171
    @tx
172
173
174
175
176
177
178
179
180
    def history(self, cn, seriename,
                from_insertion_date=None,
                to_insertion_date=None,
                from_value_date=None,
                to_value_date=None,
                deltabefore=None,
                deltaafter=None,
                diffmode=False,
                _keep_nans=False):
181
182
        tablename = self._serie_to_tablename(cn, seriename)
        if tablename is None:
183
184
            return

185
186
187
188
189
190
        revsql = [
            'select cset.id, cset.insertion_date '
            f'from "{self.namespace}".changeset as cset, '
            f'     "{self.namespace}.timeserie"."{tablename}" as ts '
            'where ts.cset = cset.id '
        ]
191
192

        if from_insertion_date:
193
            revsql.append('and cset.insertion_date >= %(from_idate)s ')
194
        if to_insertion_date:
195
            revsql.append('and cset.insertion_date <= %(to_idate)s ')
196

197
        if from_value_date or to_value_date:
198
199
            revsql.append(
                'and ' + closed_overlaps(from_value_date, to_value_date)
200
201
            )

202
203
204
        revsql.append('order by cset.id')
        revsql = ''.join(revsql)

205
        revs = cn.execute(
206
207
208
209
210
211
            revsql, {
                'fromdate': from_value_date,
                'todate': to_value_date,
                'from_idate': from_insertion_date,
                'to_idate': to_insertion_date
            }
212
        ).fetchall()
213
        if not revs:
214
            return {}
215

216
217
218
219
220
221
        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))

222
        snapshot = Snapshot(cn, self, seriename)
223
        series = []
224
225
        if (deltabefore, deltaafter) != (None, None):
            for csid, idate in revs:
226
227
                from_date = None
                to_date = None
228
                if deltabefore is not None:
229
                    from_date = idate - deltabefore
230
                if deltaafter is not None:
231
                    to_date = idate + deltaafter
232
233
                series.append((
                    idate,
234
                    snapshot.find(csetfilter=[f'cset.id = {csid}'],
235
236
                                  from_value_date=from_date,
                                  to_value_date=to_date)[1]
237
238
239
240
241
242
                ))
        else:
            series = snapshot.findall(revs,
                                      from_value_date,
                                      to_value_date
            )
243

244
245
        if diffmode:
            diffs = []
Aurélien Campéas's avatar
Aurélien Campéas committed
246
            for (_revdate_a, serie_a), (revdate_b, serie_b) in zip(series, series[1:]):
247
248
249
250
251
252
253
                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
254
255
        else:
            series = [
256
                (idate, ts if _keep_nans else ts.dropna() )
257
258
                 for idate, ts in series
            ]
259

260
        return {
261
            pd.Timestamp(idate).astimezone('UTC'): serie
262
263
            for idate, serie in series
        }
264

265
    @tx
266
    def staircase(self, cn, seriename, delta,
267
268
                  from_value_date=None,
                  to_value_date=None):
269
270
271
272
        """ compute a series whose value dates are bounded to be
        `delta` time after the insertion dates and where we
        keep the most recent ones
        """
273
        histo = self.history(
274
275
            cn, seriename, deltabefore=-delta,
            from_value_date=from_value_date,
276
277
            to_value_date=to_value_date,
            _keep_nans=True
278
        )
279
280
        if histo is None:
            return None
281

282
283
284
285
286
287
288
289
        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

290
        ts = pd.Series(vvmap).sort_index().loc[from_value_date:to_value_date]
291
        ts.name = seriename
292
        return ts.dropna()
293

294
    def exists(self, cn, seriename):
295
        return self._serie_to_tablename(cn, seriename) is not None
296

297
    def latest_insertion_date(self, cn, seriename):
298
299
300
301
302
        tablename = self._serie_to_tablename(cn, seriename)
        sql = ('select max(insertion_date) '
               f'from "{self.namespace}".changeset as cset, '
               f'     "{self.namespace}.timeserie"."{tablename}" as tstable '
               'where cset.id = tstable.cset')
303
304
305
        return pd.Timestamp(
            cn.execute(sql).scalar()
        ).astimezone('UTC')
306

307
308
    def insertion_dates(self, cn, seriename,
                        fromdate=None, todate=None):
309
310
        tablename = self._serie_to_tablename(cn, seriename)
        fromclause, toclause = '', ''
311
        if fromdate:
312
            fromclause = ' and cset.insertion_date >= %(fromdate)s '
313
        if todate:
314
315
316
317
318
319
320
            toclause = ' and cset.insertion_date <= %(todate)s '
        sql = ('select insertion_date '
               f'from "{self.namespace}".changeset as cset, '
               f'     "{self.namespace}.timeserie"."{tablename}" as tstable '
               'where cset.id = tstable.cset '
               f'{fromclause} {toclause}'
               'order by cset.id')
321

322
323
        return [
            pd.Timestamp(idate).astimezone('UTC')
324
325
326
            for idate, in cn.execute(
                    sql, fromdate=fromdate, todate=todate
            ).fetchall()
327
328
        ]

329
330
331
332
    def last_id(self, cn, seriename):
        snapshot = Snapshot(cn, self, seriename)
        return snapshot.last_id()

333
    def changeset_at(self, cn, seriename, revdate, mode='strict'):
334
335
336
337
338
339
340
341
342
343
344
345
346
        operators = {
            'strict': '=',
            'before': '<=',
            'after': '>='
        }
        tablename = self._serie_to_tablename(cn, seriename)
        assert mode in operators
        sql = ('select cset '
               f'from "{self.namespace}.timeserie"."{tablename}" as tstable, '
               f'      "{self.namespace}".changeset as cset '
               f'where cset.id = tstable.cset '
               f'and   cset.insertion_date {operators[mode]} %(revdate)s')
        return cn.execute(sql, revdate=revdate).scalar()
347

348
349
    @tx
    def rename(self, cn, oldname, newname):
350
351
352
353
        sql = (f'update "{self.namespace}".registry '
               'set seriename = %(newname)s '
               'where seriename = %(oldname)s')
        cn.execute(sql, oldname=oldname, newname=newname)
354
355
        self._resetcaches()

356
    @tx
357
    def delete(self, cn, seriename):
358
359
        tablename = self._serie_to_tablename(cn, seriename)
        if tablename is None:
360
361
            print('not deleting unknown series', seriename, self.namespace)
            return
362
        # changeset will keep ghost entries
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
        # whose cleanup is costly
        # we will mark them as from a deleted series
        # update changeset.metadata
        msg = f'belonged to deleted series `{seriename}`'
        csetsql = f'select cset from "{self.namespace}.timeserie"."{tablename}"'
        for csid, in cn.execute(csetsql):
            metadata = self.changeset_metadata(cn, csid) or {}
            metadata['tshistory.info'] = msg
            cn.execute(
                f'update "{self.namespace}".changeset '
                'set metadata = %(metadata)s '
                'where id = %(csid)s',
                csid=csid,
                metadata=json.dumps(metadata)
            )

379
        rid, tablename = cn.execute(
380
381
            f'select id, table_name from "{self.namespace}".registry '
            'where seriename = %(seriename)s',
382
383
384
385
            seriename=seriename
        ).fetchone()
        # drop series tables
        cn.execute(
386
            f'drop table "{self.namespace}.timeserie"."{tablename}" cascade'
387
388
        )
        cn.execute(
389
            f'drop table "{self.namespace}.snapshot"."{tablename}" cascade'
390
        )
391
392
        cn.execute(f'delete from "{self.namespace}".registry '
                   'where id = %(rid)s',
393
394
395
396
                   rid=rid)
        # -> this will transitively cleanup state changeset_series entries
        self._resetcaches()

397
    @tx
398
399
400
401
402
403
404
    def strip(self, cn, seriename, csid):
        logs = self.log(cn, fromrev=csid, names=(seriename,))
        assert logs

        # put stripping info in the metadata
        for log in logs:
            # update changeset.metadata
405
            metadata = self.changeset_metadata(cn, log['rev']) or {}
406
            metadata['tshistory.info'] = f'got stripped from {csid}'
407
408
409
410
            sql = (f'update "{self.namespace}".changeset '
                   'set metadata = %(metadata)s '
                   'where id = %(id)s')
            cn.execute(sql, id=log['rev'], metadata=json.dumps(metadata))
411
            # delete changset_serie item
412
413
414
415
416
417
418
            sql = (f'delete from "{self.namespace}".changeset_series as css '
                   'where css.cset = %(rev)s '
                   'and   css.serie = %(name)s')
            cn.execute(
                sql,
                rev=log['rev'],
                name=self._name_to_regid(cn, seriename)
419
420
421
            )

        # wipe the diffs
422
423
424
425
        tablename = self._serie_to_tablename(cn, seriename)
        sql = (f'delete from "{self.namespace}.timeserie"."{tablename}" '
               'where cset >= %(csid)s')
        cn.execute(sql, csid=csid)
426

427
    def info(self, cn):
428
429
        """Gather global statistics on the current tshistory repository
        """
430
        sql = f'select count(*) from "{self.namespace}".registry'
431
        stats = {'series count': cn.execute(sql).scalar()}
432
        sql = f'select max(id) from "{self.namespace}".changeset'
433
        stats['changeset count'] = cn.execute(sql).scalar()
434
435
        sql = (f'select distinct seriename from "{self.namespace}".registry '
               'order by seriename')
436
        stats['serie names'] = [row for row, in cn.execute(sql).fetchall()]
437
438
        return stats

439
    def log(self, cn, limit=0, names=None, authors=None,
440
            stripped=False,
441
442
            fromrev=None, torev=None,
            fromdate=None, todate=None):
443
444
445
446
        """Build a structure showing the history of all the series in the db,
        per changeset, in chronological order.
        """
        log = []
447

448
449
450
451
452
453
454
455
456
457
458
459
460
        sql = [
            'select distinct cset.id, cset.author, cset.insertion_date, cset.metadata '
            f'from "{self.namespace}".changeset as cset, '
            f'     "{self.namespace}".registry as reg, '
            f'     "{self.namespace}".changeset_series as css '
        ]
        wheres = []
        if stripped:
            sql.append(f'left join "{self.namespace}".changeset as cset2 '
                       'on (cset2.id = css.cset) ')
        else:
            wheres.append('cset.id = css.cset and '
                          'css.serie = reg.id ')
461

462
        if names:
463
464
465
466
            # XXX check names exist
            wheres.append('reg.seriename in (%s)' % ','.join(
                repr(name) for name in names)
            )
467
        if authors:
468
469
470
            wheres.append('cset.author in (%s)' % ','.join(
                repr(auth) for auth in authors)
            )
471
        if fromrev:
472
            wheres.append('cset.id >= %(fromrev)s')
473
        if torev:
474
            wheres.append('cset.id <= %(torev)s')
475
        if fromdate:
476
            wheres.append('cset.insertion_date >= %(fromdate)s')
477
        if todate:
478
479
480
481
482
483
484
485
            wheres.append('cset.insertion_date <= %(todate)s')

        sql.append('where ' + ' and '.join(wheres))
        if limit:
            sql.append('limit %(limit)s ')
        sql.append('order by cset.id desc')

        sql = ''.join(sql)
486

487
488
489
490
491
492
        rset = cn.execute(sql, {
            'fromdate': fromdate,
            'todate': todate,
            'fromrev': fromrev,
            'torev': torev
        })
493
        for csetid, author, revdate, meta in rset.fetchall():
494
495
            log.append({'rev': csetid, 'author': author,
                        'date': pd.Timestamp(revdate, tz='utc'),
496
                        'meta': meta or {},
497
                        'names': self._changeset_series(cn, csetid)})
498

499
        log.sort(key=lambda rev: rev['rev'])
500
501
        return log

502
    def interval(self, cn, seriename, notz=False):
503
504
505
        tablename = self._serie_to_tablename(cn, seriename)
        if tablename is None:
            raise ValueError(f'no such serie: {seriename}')
506
        sql = (f'select tsstart, tsend '
507
508
509
               f'from "{self.namespace}.timeserie"."{tablename}" '
               f'order by cset desc limit 1')
        res = cn.execute(sql).fetchone()
510
        start, end = res.tsstart, res.tsend
511
        if self.metadata(cn, seriename).get('tzaware') and not notz:
512
513
514
            start, end = pd.Timestamp(start, tz='UTC'), pd.Timestamp(end, tz='UTC')
        return pd.Interval(left=start, right=end, closed='both')

515
516
    # /API
    # Helpers
517

518
519
    # creation / update

520
    def _create(self, cn, newts, seriename, author,
521
                metadata=None, insertion_date=None):
522
        start, end = start_end(newts, notz=False)
523
524
525
526
        if start is None:
            assert end is None
            # this is just full of nans
            return None
527
528
529
530
531
        # chop off unwanted nans
        newts = newts.loc[start:end]
        if len(newts) == 0:
            return None

532
533
534
        # at creation time we take an exclusive lock to avoid
        # a deadlock on created tables against the changeset-series fk
        cn.execute(
535
            f'select pg_advisory_xact_lock({self.create_lock_id})'
536
        )
537
        self._register_serie(cn, seriename, newts)
538
        snapshot = Snapshot(cn, self, seriename)
539
        csid = self._newchangeset(cn, author, insertion_date, metadata)
540
        head = snapshot.create(newts)
541
        start, end = start_end(newts)
542
543
544
545
546
547
        tablename = self._make_ts_table(cn, seriename)
        sql = (f'insert into "{self.namespace}.timeserie"."{tablename}" '
               '(cset, snapshot, tsstart, tsend) '
               f'values (%s, %s, %s, %s)')
        cn.execute(sql, csid, head,
                   start.to_pydatetime(), end.to_pydatetime())
548
        self._finalize_insertion(cn, csid, seriename)
549
        L.info('first insertion of %s (size=%s) by %s',
550
               seriename, len(newts), author)
551
552
        return newts

553
    def _update(self, cn, tablename, newts, seriename, author,
554
                metadata=None, insertion_date=None):
555
556
        self._validate(cn, newts, seriename)
        snapshot = Snapshot(cn, self, seriename)
557
558
559
        diff = self.diff(snapshot.last(newts.index.min(),
                                       newts.index.max()),
                         newts)
560
561
        if not len(diff):
            L.info('no difference in %s by %s (for ts of size %s)',
562
                   seriename, author, len(newts))
563
564
            return

565
        # compute series start/end stamps
566
        tsstart, tsend = start_end(newts)
567
568
569
        ival = self.interval(cn, seriename, notz=True)
        start = min(tsstart or ival.left, ival.left)
        end = max(tsend or ival.right, ival.right)
570
571
572
573
574
575
576
577
578
579
580
581
582
583

        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)
584
        head = snapshot.update(diff)
585
586
587
588
        sql = (f'insert into "{self.namespace}.timeserie"."{tablename}" '
               '(cset, snapshot, tsstart, tsend) '
               'values (%s, %s, %s, %s)')
        cn.execute(sql, csid, head, start, end)
589
        self._finalize_insertion(cn, csid, seriename)
590
591

        L.info('inserted diff (size=%s) for ts %s by %s',
592
               len(diff), seriename, author)
593
594
        return diff

595
    # serie table handling
596

597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
    def _make_tablename(self, cn, seriename):
        """ compute the unqualified (no namespace) table name
        from a serie name, to allow arbitrary serie names
        """
        # postgresql table names are limited to 63 chars.
        if len(seriename) > 63:
            seriename = hashlib.sha1(seriename.encode('utf-8')).hexdigest()

        # collision detection (collision can happen after a rename)
        if cn.execute(f'select table_name '
                      f'from "{self.namespace}".registry '
                      f'where table_name = %(seriename)s',
                      seriename=seriename).scalar():
            return str(uuid.uuid4())

        return seriename

614
615
616
617
    def _serie_to_tablename(self, cn, seriename):
        tablename = self.serie_tablename.get(seriename)
        if tablename is not None:
            return tablename
618

619
620
621
622
623
        tablename = cn.execute(
            f'select table_name from "{self.namespace}".registry '
            f'where seriename = %(seriename)s',
            seriename=seriename
        ).scalar()
624
625
626
627
628
629
630
631
632
633
        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
Aurélien Campéas's avatar
Aurélien Campéas committed
634
            tablename = self._make_tablename(cn, seriename)
635
636
637
638
639
640
        table = sqlfile(
            SERIESSCHEMA,
            namespace=self.namespace,
            tablename=tablename
        )
        return table, tablename
641

Aurélien Campéas's avatar
Aurélien Campéas committed
642
    def _make_ts_table(self, cn, seriename):
643
644
645
        table, tablename = self._table_definition_for(cn, seriename)
        cn.execute(table)
        return tablename
646
647

    def _register_serie(self, cn, seriename, ts):
648
649
        index = ts.index
        inames = [name for name in index.names if name]
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
        sql = (f'insert into {self.namespace}.registry '
               '(seriename, table_name, metadata) '
               'values (%s, %s, %s) '
               'returning id')
        table_name = self._make_tablename(cn, seriename)
        metadata = json.dumps({
            'tzaware': tzaware_serie(ts),
            'index_type': index.dtype.name,
            'index_names': inames,
            'index_dtype': index.dtype.str,
            'value_dtype': ts.dtypes.str,
            'value_type': ts.dtypes.name
        })
        regid = cn.execute(
            sql,
            seriename,
            table_name,
            metadata
        ).scalar()
669
        self.registry_map[seriename] = regid
670

671
    def _get_ts_table(self, cn, seriename):
672
673
        tablename = self._serie_to_tablename(cn, seriename)
        if tablename:
Aurélien Campéas's avatar
Aurélien Campéas committed
674
            return self._table_definition_for(cn, seriename)
675

676
677
    # changeset handling

678
679
680
681
    def _newchangeset(self, cn, author, insertion_date=None, metadata=None):
        if insertion_date is not None:
            assert insertion_date.tzinfo is not None
        idate = pd.Timestamp(insertion_date or datetime.utcnow(), tz='UTC')
682
683
684
685
686
687
688
689
690
691
692
693
        sql = (f'insert into {self.namespace}.changeset '
               '(author, metadata, insertion_date) '
               'values (%s, %s, %s) '
               'returning id')
        if metadata:
            metadata = json.dumps(metadata)
        return cn.execute(
            sql,
            author,
            metadata,
            idate
        ).scalar()
694

695
    def _changeset_series(self, cn, csid):
696
697
698
699
700
        sql = ('select seriename '
               f'from "{self.namespace}".registry as reg, '
               f'     "{self.namespace}".changeset_series as css '
               'where css.serie = reg.id '
               'and   css.cset = %(csid)s')
701

702
        return [
703
            row.seriename
704
            for row in cn.execute(sql, csid=csid).fetchall()
705
        ]
706

707
708
    def _previous_cset(self, cn, seriename, csid):
        tablename = self._serie_to_tablename(cn, seriename)
709
        sql = (f'select cset from "{self.namespace}.timeserie"."{tablename}" '
710
               'where cset < %(csid)s '
711
               'order by cset desc limit 1')
712
713
        return cn.execute(sql, csid=csid).scalar()

714
715
    # insertion handling

716
    def _validate(self, cn, ts, seriename):
717
718
        if ts.isnull().all():
            # ts erasure
719
            return
720
        tstype = ts.dtype
721
        meta = self.metadata(cn, seriename)
722
        if tstype != meta['value_type']:
723
724
            m = (f'Type error when inserting {seriename}, '
                 f'new type is {tstype}, type in base is {meta["value_type"]}')
725
            raise Exception(m)
726
        if ts.index.dtype.name != meta['index_type']:
727
            raise Exception('Incompatible index types')
728

729
730
    def _name_to_regid(self, cn, seriename):
        regid = self.registry_map.get(seriename)
731
732
733
        if regid is not None:
            return regid

734
735
736
737
738
739
740
        sql = ('select id '
               f'from "{self.namespace}".registry '
               'where seriename = %(seriename)s')
        regid = self.registry_map[seriename] = cn.execute(
            sql,
            seriename=seriename
        ).scalar()
741
742
        return regid

743
    def _finalize_insertion(self, cn, csid, seriename):
744
745
746
747
        sql = (f'insert into "{self.namespace}".changeset_series '
               '(cset, serie) '
               'values (%s, %s)')
        cn.execute(sql, csid, self._name_to_regid(cn, seriename))
748

749
    def _resetcaches(self):
750
751
752
753
        with self.cachelock:
            self.metadatacache.clear()
            self.registry_map.clear()
            self.serie_tablename.clear()
754
755
756
757
758
759
760
761



@deprecated(reason='use the `timeseries` object instead')
class TimeSerie(timeseries):

    get_history = deprecated(timeseries.history)
    get_delta = deprecated(timeseries.staircase)