tsio.py 27.4 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.util import (
14
    closed_overlaps,
15
16
    num2float,
    SeriesServices,
17
    start_end,
18
    sqlfile,
19
    sqlp,
20
    sqlq,
21
    tx,
22
23
    tzaware_serie
)
24
from tshistory.snapshot import Snapshot
25

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


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

    def __init__(self, namespace='tsh'):
        self.namespace = namespace
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
    def list_series(self, cn):
97
        """Return the mapping of all series to their type"""
98
        sql = f'select seriename from "{self.namespace}".registry '
99
100
101
102
        return {
            row.seriename: 'primary'
            for row in cn.execute(sql)
        }
103

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

        revision_date: datetime filter to get previous versions of the
        serie

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

116
        csetfilter = []
117
        if revision_date:
118
            csetfilter.append(
119
120
121
                sqlp(
                    f'cset.insertion_date <= %(idate)s', idate=revision_date
                )
122
            )
123
        snap = Snapshot(cn, self, seriename)
124
        _, current = snap.find(csetfilter=csetfilter,
125
126
                               from_value_date=from_value_date,
                               to_value_date=to_value_date)
127

128
        if current is not None and not _keep_nans:
129
            current.name = seriename
130
            current = current[~current.isnull()]
131
        return current
132

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

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

166
    def changeset_metadata(self, cn, csid):
167
        assert isinstance(csid, int)
168
169
170
171
172
173
174
175
        q = sqlq(
            'metadata'
        ).relation(
            f'"{self.namespace}".changeset'
        ).where(
            f'id = %(csid)s', csid=csid
        )
        return q.do(cn).scalar()
176

177
178
179
    def type(self, cn, name):
        return 'primary'

180
    @tx
181
182
183
184
185
186
187
188
189
    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):
190
191
        tablename = self._serie_to_tablename(cn, seriename)
        if tablename is None:
192
193
            return

194
195
196
197
198
199
200
        q = sqlq(
            'cset.id', 'cset.insertion_date'
        ).relation(
            f'"{self.namespace}.timeserie"."{tablename}" as ts'
        ).join(
            f'"{self.namespace}".changeset as cset on cset.id = ts.cset'
        )
201
202

        if from_insertion_date:
203
204
205
206
            q.where(
                'cset.insertion_date >= %(from_idate)s',
                from_idate=from_insertion_date
            )
207
        if to_insertion_date:
208
209
210
211
            q.where(
                'cset.insertion_date <= %(to_idate)s ',
                to_idate=to_insertion_date
            )
212

213
        if from_value_date or to_value_date:
214
215
216
217
            q.where(
                closed_overlaps(from_value_date, to_value_date),
                fromdate=from_value_date,
                todate=to_value_date
218
219
            )

220
221
        q.option('order by cset.id')
        revs = q.do(cn).fetchall()
222
        if not revs:
223
            return {}
224

225
226
227
228
229
        revs = [
            (csid, pd.Timestamp(idate).astimezone('UTC'))
            for csid, idate in revs
        ]

230
231
232
233
234
235
        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))

236
        snapshot = Snapshot(cn, self, seriename)
237
        series = []
238
239
        if (deltabefore, deltaafter) != (None, None):
            for csid, idate in revs:
240
241
                from_date = None
                to_date = None
242
                if deltabefore is not None:
243
                    from_date = idate - deltabefore
244
                if deltaafter is not None:
245
                    to_date = idate + deltaafter
246
247
                series.append((
                    idate,
248
249
250
251
252
253
254
255
                    snapshot.find(
                        csetfilter=[
                            sqlp('cset.id = %(csid)s', csid=csid)
                        ],
                        from_value_date=from_date,
                        to_value_date=to_date)[1]
                    )
                )
256
257
258
259
260
        else:
            series = snapshot.findall(revs,
                                      from_value_date,
                                      to_value_date
            )
261

262
263
        if diffmode:
            diffs = []
Aurélien Campéas's avatar
Aurélien Campéas committed
264
            for (_revdate_a, serie_a), (revdate_b, serie_b) in zip(series, series[1:]):
265
266
267
268
269
270
271
                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
272
273
        else:
            series = [
274
                (idate, ts if _keep_nans else ts.dropna() )
275
276
                 for idate, ts in series
            ]
277

278
        return dict(series)
279

280
    @tx
281
    def staircase(self, cn, seriename, delta,
282
283
                  from_value_date=None,
                  to_value_date=None):
284
285
286
287
        """ compute a series whose value dates are bounded to be
        `delta` time after the insertion dates and where we
        keep the most recent ones
        """
288
        histo = self.history(
289
290
            cn, seriename, deltabefore=-delta,
            from_value_date=from_value_date,
291
292
            to_value_date=to_value_date,
            _keep_nans=True
293
        )
294
295
        if histo is None:
            return None
296

297
298
299
300
301
302
303
304
        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

305
        ts = pd.Series(vvmap).sort_index().loc[from_value_date:to_value_date]
306
        ts.name = seriename
307
        return ts.dropna()
308

309
    def exists(self, cn, seriename):
310
        return self._serie_to_tablename(cn, seriename) is not None
311

312
    def latest_insertion_date(self, cn, seriename):
313
        tablename = self._serie_to_tablename(cn, seriename)
314
315
316
317
318
319
320
321
        q = sqlq(
            'max(insertion_date)'
        ).relation(
            f'"{self.namespace}".changeset as cset',
            f'"{self.namespace}.timeserie"."{tablename}" as tstable'
        ).where(
               'cset.id = tstable.cset'
        )
322
        return pd.Timestamp(
323
            q.do(cn).scalar()
324
        ).astimezone('UTC')
325

326
327
    def insertion_dates(self, cn, seriename,
                        fromdate=None, todate=None):
328
        tablename = self._serie_to_tablename(cn, seriename)
329
330
331
332
333
334
335
336
337
338
339
        q = sqlq(
            'insertion_date'
        ).relation(
            f'"{self.namespace}".changeset as cset',
            f'"{self.namespace}.timeserie"."{tablename}" as tstable'
        ).where(
            'cset.id = tstable.cset'
        ).option(
            'order by cset.id'
        )

340
        if fromdate:
341
342
343
344
            q.where(
                'cset.insertion_date >= %(fromdate)s',
                fromdate=fromdate
            )
345
        if todate:
346
347
348
349
            q.where(
                'cset.insertion_date <= %(todate)s',
                todate=todate
            )
350

351
352
        return [
            pd.Timestamp(idate).astimezone('UTC')
353
            for idate, in q.do(cn).fetchall()
354
355
        ]

356
357
358
359
    def last_id(self, cn, seriename):
        snapshot = Snapshot(cn, self, seriename)
        return snapshot.last_id()

360
    def changeset_at(self, cn, seriename, revdate, mode='strict'):
361
362
363
364
365
366
367
        operators = {
            'strict': '=',
            'before': '<=',
            'after': '>='
        }
        tablename = self._serie_to_tablename(cn, seriename)
        assert mode in operators
368
369
370
371
372
373
374
375
376
377
378
        q = sqlq(
            'cset'
        ).relation(
            f'"{self.namespace}.timeserie"."{tablename}" as tstable',
            f'"{self.namespace}".changeset as cset '
        ).where(
            'cset.id = tstable.cset',
            f'cset.insertion_date {operators[mode]} %(revdate)s',
            revdate=revdate
        )
        return q.do(cn).scalar()
379

380
381
    @tx
    def rename(self, cn, oldname, newname):
382
383
384
385
        sql = (f'update "{self.namespace}".registry '
               'set seriename = %(newname)s '
               'where seriename = %(oldname)s')
        cn.execute(sql, oldname=oldname, newname=newname)
386
387
        self._resetcaches()

388
    @tx
389
    def delete(self, cn, seriename):
390
391
        tablename = self._serie_to_tablename(cn, seriename)
        if tablename is None:
392
393
            print('not deleting unknown series', seriename, self.namespace)
            return
394
        # changeset will keep ghost entries
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
        # 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)
            )

411
        rid, tablename = cn.execute(
412
413
            f'select id, table_name from "{self.namespace}".registry '
            'where seriename = %(seriename)s',
414
415
416
417
            seriename=seriename
        ).fetchone()
        # drop series tables
        cn.execute(
418
            f'drop table "{self.namespace}.timeserie"."{tablename}" cascade'
419
420
        )
        cn.execute(
421
            f'drop table "{self.namespace}.snapshot"."{tablename}" cascade'
422
        )
423
424
        cn.execute(f'delete from "{self.namespace}".registry '
                   'where id = %(rid)s',
425
426
427
428
                   rid=rid)
        # -> this will transitively cleanup state changeset_series entries
        self._resetcaches()

429
    @tx
430
    def strip(self, cn, seriename, csid):
431
432
433
434
435
436
        # wipe the diffs
        tablename = self._serie_to_tablename(cn, seriename)
        sql = (f'delete from "{self.namespace}.timeserie"."{tablename}" '
               'where cset >= %(csid)s')
        cn.execute(sql, csid=csid)

437
438
439
        logs = self.log(cn, fromrev=csid, names=(seriename,))
        assert logs
        for log in logs:
440
441
442
443
            csid = log['rev']
            # set in metadata the fact that this changeset
            # has been stripped (hence is no longer being referenced)
            metadata = self.changeset_metadata(cn, csid) or {}
444
            metadata['tshistory.info'] = f'got stripped from {csid}'
445
446
            sql = (f'update "{self.namespace}".changeset '
                   'set metadata = %(metadata)s '
447
448
                   'where id = %(csid)s')
            cn.execute(sql, csid=csid, metadata=json.dumps(metadata))
449
            # delete changset_serie item
450
            sql = (f'delete from "{self.namespace}".changeset_series as css '
451
452
                   'where css.cset = %(csid)s')
            cn.execute(sql, csid=csid)
453

454
455
456
        snapshot = Snapshot(cn, self, seriename)
        snapshot.reclaim()

457
    def info(self, cn):
458
459
        """Gather global statistics on the current tshistory repository
        """
460
        sql = f'select count(*) from "{self.namespace}".registry'
461
        stats = {'series count': cn.execute(sql).scalar()}
462
        sql = f'select max(id) from "{self.namespace}".changeset'
463
        stats['changeset count'] = cn.execute(sql).scalar()
464
465
        sql = (f'select distinct seriename from "{self.namespace}".registry '
               'order by seriename')
466
        stats['serie names'] = [row for row, in cn.execute(sql).fetchall()]
467
468
        return stats

469
    def log(self, cn, limit=0, names=None, authors=None,
470
471
            fromrev=None, torev=None,
            fromdate=None, todate=None):
472
473
474
475
        """Build a structure showing the history of all the series in the db,
        per changeset, in chronological order.
        """
        log = []
476

477
478
479
480
481
482
483
484
485
        q = sqlq(
            'cset.id', 'cset.author', 'cset.insertion_date', 'cset.metadata',
            opt='distinct'
        ).relation(
            f'"{self.namespace}".changeset as cset'
        ).join(
            f'"{self.namespace}".changeset_series as css on css.cset = cset.id',
            f'"{self.namespace}".registry as reg on reg.id = css.serie'
        )
486

487
        if names:
488
489
490
            q.where(
                'reg.seriename in %(names)s',
                names=tuple(names)
491
            )
492
        if authors:
493
494
495
            q.where(
                'cset.author in %(authors)s',
                author=tuple(authors)
496
            )
497
        if fromrev:
498
            q.where('cset.id >= %(fromrev)s', fromrev=fromrev)
499
        if torev:
500
            q.where('cset.id <= %(torev)s', torev=torev)
501
        if fromdate:
502
            q.where('cset.insertion_date >= %(fromdate)s', fromdate=fromdate)
503
        if todate:
504
            q.where('cset.insertion_date <= %(todate)s', todate=todate)
505

506
        q.option('order by cset.id desc')
507
        if limit:
508
            q.option('limit %(limit)s', limit=limit)
509

510
        rset = q.do(cn)
511
        for csetid, author, revdate, meta in rset.fetchall():
512
            log.append({'rev': csetid, 'author': author,
513
                        'date': pd.Timestamp(revdate).tz_convert('utc'),
514
                        'meta': meta or {},
515
                        'name': self._changeset_series(cn, csetid)})
516

517
        log.sort(key=lambda rev: rev['rev'])
518
519
        return log

520
    def interval(self, cn, seriename, notz=False):
521
522
523
        tablename = self._serie_to_tablename(cn, seriename)
        if tablename is None:
            raise ValueError(f'no such serie: {seriename}')
524
        sql = (f'select tsstart, tsend '
525
526
527
               f'from "{self.namespace}.timeserie"."{tablename}" '
               f'order by cset desc limit 1')
        res = cn.execute(sql).fetchone()
528
        start, end = res.tsstart, res.tsend
529
        if self.metadata(cn, seriename).get('tzaware') and not notz:
530
531
532
            start, end = pd.Timestamp(start, tz='UTC'), pd.Timestamp(end, tz='UTC')
        return pd.Interval(left=start, right=end, closed='both')

533
534
    # /API
    # Helpers
535

536
537
    # creation / update

538
    def _create(self, cn, newts, seriename, author,
539
                metadata=None, insertion_date=None):
540
        start, end = start_end(newts, notz=False)
541
542
543
544
        if start is None:
            assert end is None
            # this is just full of nans
            return None
545
546
547
548
549
        # chop off unwanted nans
        newts = newts.loc[start:end]
        if len(newts) == 0:
            return None

550
551
552
        # at creation time we take an exclusive lock to avoid
        # a deadlock on created tables against the changeset-series fk
        cn.execute(
553
            f'select pg_advisory_xact_lock({self.create_lock_id})'
554
        )
555
        self._register_serie(cn, seriename, newts)
556
        snapshot = Snapshot(cn, self, seriename)
557
        csid = self._newchangeset(cn, author, insertion_date, metadata)
558
        head = snapshot.create(newts)
559
        start, end = start_end(newts)
560
561
562
563
564
565
        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())
566
        self._finalize_insertion(cn, csid, seriename)
567
        L.info('first insertion of %s (size=%s) by %s',
568
               seriename, len(newts), author)
569
570
        return newts

571
    def _update(self, cn, tablename, newts, seriename, author,
572
                metadata=None, insertion_date=None):
573
574
        self._validate(cn, newts, seriename)
        snapshot = Snapshot(cn, self, seriename)
575
576
577
        diff = self.diff(snapshot.last(newts.index.min(),
                                       newts.index.max()),
                         newts)
578
579
        if not len(diff):
            L.info('no difference in %s by %s (for ts of size %s)',
580
                   seriename, author, len(newts))
581
582
            return

583
        # compute series start/end stamps
584
        tsstart, tsend = start_end(newts)
585
586
587
        ival = self.interval(cn, seriename, notz=True)
        start = min(tsstart or ival.left, ival.left)
        end = max(tsend or ival.right, ival.right)
588
589
590
591
592
593
594
595
596
597
598
599
600
601

        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)
602
        head = snapshot.update(diff)
603
604
605
606
        sql = (f'insert into "{self.namespace}.timeserie"."{tablename}" '
               '(cset, snapshot, tsstart, tsend) '
               'values (%s, %s, %s, %s)')
        cn.execute(sql, csid, head, start, end)
607
        self._finalize_insertion(cn, csid, seriename)
608
609

        L.info('inserted diff (size=%s) for ts %s by %s',
610
               len(diff), seriename, author)
611
612
        return diff

613
    # serie table handling
614

615
616
617
618
    def _make_tablename(self, cn, seriename):
        """ compute the unqualified (no namespace) table name
        from a serie name, to allow arbitrary serie names
        """
619
620
        # default
        tablename = seriename
621
622
        # postgresql table names are limited to 63 chars.
        if len(seriename) > 63:
623
            tablename = hashlib.sha1(seriename.encode('utf-8')).hexdigest()
624
625
626
627
628
629

        # 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():
630
            tablename = str(uuid.uuid4())
631

632
        return tablename
633

634
635
636
637
    def _serie_to_tablename(self, cn, seriename):
        tablename = self.serie_tablename.get(seriename)
        if tablename is not None:
            return tablename
638

639
640
641
642
643
        tablename = cn.execute(
            f'select table_name from "{self.namespace}".registry '
            f'where seriename = %(seriename)s',
            seriename=seriename
        ).scalar()
644
645
646
647
648
649
650
651
652
653
        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
654
            tablename = self._make_tablename(cn, seriename)
655
656
657
658
659
660
        table = sqlfile(
            SERIESSCHEMA,
            namespace=self.namespace,
            tablename=tablename
        )
        return table, tablename
661

Aurélien Campéas's avatar
Aurélien Campéas committed
662
    def _make_ts_table(self, cn, seriename):
663
664
665
        table, tablename = self._table_definition_for(cn, seriename)
        cn.execute(table)
        return tablename
666
667

    def _register_serie(self, cn, seriename, ts):
668
669
        index = ts.index
        inames = [name for name in index.names if name]
670
        sql = (f'insert into "{self.namespace}".registry '
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
               '(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()
689
        self.registry_map[seriename] = regid
690

691
    def _get_ts_table(self, cn, seriename):
692
693
        tablename = self._serie_to_tablename(cn, seriename)
        if tablename:
Aurélien Campéas's avatar
Aurélien Campéas committed
694
            return self._table_definition_for(cn, seriename)
695

696
697
    # changeset handling

698
699
700
    def _newchangeset(self, cn, author, insertion_date=None, metadata=None):
        if insertion_date is not None:
            assert insertion_date.tzinfo is not None
701
702
703
            idate = pd.Timestamp(insertion_date)
        else:
            idate = pd.Timestamp(datetime.utcnow(), tz='UTC')
704
        sql = (f'insert into "{self.namespace}".changeset '
705
706
707
708
709
710
711
712
713
714
715
               '(author, metadata, insertion_date) '
               'values (%s, %s, %s) '
               'returning id')
        if metadata:
            metadata = json.dumps(metadata)
        return cn.execute(
            sql,
            author,
            metadata,
            idate
        ).scalar()
716

717
    def _changeset_series(self, cn, csid):
718
719
720
721
722
723
724
725
726
        q = sqlq(
            'seriename'
        ).relation(
            f'"{self.namespace}".registry as reg',
        ).join(
            f'"{self.namespace}".changeset_series as css on css.serie = reg.id'
        ).where(
            'css.cset = %(csid)s', csid=csid
        )
727

728
        return q.do(cn).scalar()
729

730
731
    def _previous_cset(self, cn, seriename, csid):
        tablename = self._serie_to_tablename(cn, seriename)
732
        sql = (f'select cset from "{self.namespace}.timeserie"."{tablename}" '
733
               'where cset < %(csid)s '
734
               'order by cset desc limit 1')
735
736
        return cn.execute(sql, csid=csid).scalar()

737
738
    # insertion handling

739
    def _validate(self, cn, ts, seriename):
740
741
        if ts.isnull().all():
            # ts erasure
742
            return
743
        tstype = ts.dtype
744
        meta = self.metadata(cn, seriename)
745
        if tstype != meta['value_type']:
746
747
            m = (f'Type error when inserting {seriename}, '
                 f'new type is {tstype}, type in base is {meta["value_type"]}')
748
            raise Exception(m)
749
        if ts.index.dtype.name != meta['index_type']:
750
            raise Exception('Incompatible index types')
751

752
753
    def _name_to_regid(self, cn, seriename):
        regid = self.registry_map.get(seriename)
754
755
756
        if regid is not None:
            return regid

757
758
759
760
761
762
763
        sql = ('select id '
               f'from "{self.namespace}".registry '
               'where seriename = %(seriename)s')
        regid = self.registry_map[seriename] = cn.execute(
            sql,
            seriename=seriename
        ).scalar()
764
765
        return regid

766
    def _finalize_insertion(self, cn, csid, seriename):
767
768
769
770
        sql = (f'insert into "{self.namespace}".changeset_series '
               '(cset, serie) '
               'values (%s, %s)')
        cn.execute(sql, csid, self._name_to_regid(cn, seriename))
771

772
    def _resetcaches(self):
773
774
775
776
        with self.cachelock:
            self.metadatacache.clear()
            self.registry_map.clear()
            self.serie_tablename.clear()
777
778
779
780
781
782
783
784



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

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