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
230
        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))

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

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

273
        return {
274
            pd.Timestamp(idate).astimezone('UTC'): serie
275
276
            for idate, serie in series
        }
277

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

295
296
297
298
299
300
301
302
        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

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

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

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

324
325
    def insertion_dates(self, cn, seriename,
                        fromdate=None, todate=None):
326
        tablename = self._serie_to_tablename(cn, seriename)
327
328
329
330
331
332
333
334
335
336
337
        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'
        )

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

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

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

358
    def changeset_at(self, cn, seriename, revdate, mode='strict'):
359
360
361
362
363
364
365
        operators = {
            'strict': '=',
            'before': '<=',
            'after': '>='
        }
        tablename = self._serie_to_tablename(cn, seriename)
        assert mode in operators
366
367
368
369
370
371
372
373
374
375
376
        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()
377

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

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

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

427
    @tx
428
    def strip(self, cn, seriename, csid):
429
430
431
432
433
434
        # 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)

435
436
437
        logs = self.log(cn, fromrev=csid, names=(seriename,))
        assert logs
        for log in logs:
438
439
440
441
            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 {}
442
            metadata['tshistory.info'] = f'got stripped from {csid}'
443
444
            sql = (f'update "{self.namespace}".changeset '
                   'set metadata = %(metadata)s '
445
446
                   'where id = %(csid)s')
            cn.execute(sql, csid=csid, metadata=json.dumps(metadata))
447
            # delete changset_serie item
448
            sql = (f'delete from "{self.namespace}".changeset_series as css '
449
450
                   'where css.cset = %(csid)s')
            cn.execute(sql, csid=csid)
451

452
453
454
        snapshot = Snapshot(cn, self, seriename)
        snapshot.reclaim()

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

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

475
476
477
478
479
480
481
482
483
        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'
        )
484

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

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

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

515
        log.sort(key=lambda rev: rev['rev'])
516
517
        return log

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

531
532
    # /API
    # Helpers
533

534
535
    # creation / update

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

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

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

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

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

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

611
    # serie table handling
612

613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
    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

630
631
632
633
    def _serie_to_tablename(self, cn, seriename):
        tablename = self.serie_tablename.get(seriename)
        if tablename is not None:
            return tablename
634

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

Aurélien Campéas's avatar
Aurélien Campéas committed
658
    def _make_ts_table(self, cn, seriename):
659
660
661
        table, tablename = self._table_definition_for(cn, seriename)
        cn.execute(table)
        return tablename
662
663

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

687
    def _get_ts_table(self, cn, seriename):
688
689
        tablename = self._serie_to_tablename(cn, seriename)
        if tablename:
Aurélien Campéas's avatar
Aurélien Campéas committed
690
            return self._table_definition_for(cn, seriename)
691

692
693
    # changeset handling

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

713
    def _changeset_series(self, cn, csid):
714
715
716
717
718
        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')
719

720
        return [
721
            row.seriename
722
            for row in cn.execute(sql, csid=csid).fetchall()
723
        ]
724

725
726
    def _previous_cset(self, cn, seriename, csid):
        tablename = self._serie_to_tablename(cn, seriename)
727
        sql = (f'select cset from "{self.namespace}.timeserie"."{tablename}" '
728
               'where cset < %(csid)s '
729
               'order by cset desc limit 1')
730
731
        return cn.execute(sql, csid=csid).scalar()

732
733
    # insertion handling

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

747
748
    def _name_to_regid(self, cn, seriename):
        regid = self.registry_map.get(seriename)
749
750
751
        if regid is not None:
            return regid

752
753
754
755
756
757
758
        sql = ('select id '
               f'from "{self.namespace}".registry '
               'where seriename = %(seriename)s')
        regid = self.registry_map[seriename] = cn.execute(
            sql,
            seriename=seriename
        ).scalar()
759
760
        return regid

761
    def _finalize_insertion(self, cn, csid, seriename):
762
763
764
765
        sql = (f'insert into "{self.namespace}".changeset_series '
               '(cset, serie) '
               'values (%s, %s)')
        cn.execute(sql, csid, self._name_to_regid(cn, seriename))
766

767
    def _resetcaches(self):
768
769
770
771
        with self.cachelock:
            self.metadatacache.clear()
            self.registry_map.clear()
            self.serie_tablename.clear()
772
773
774
775
776
777
778
779



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

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