tsio.py 27.5 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
    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
        self.metadatacache = {}
49
        self.registry_map = {}
50
        self.serie_tablename = {}
51
        self.create_lock_id = sum(ord(c) for c in namespace)
52

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

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

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

76
        newts = num2float(newts)
77

78
        if not len(newts):
79
            return
80

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

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

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

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

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

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

        revision_date: datetime filter to get previous versions of the
        serie

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

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

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

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

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

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

171
172
173
    def type(self, cn, name):
        return 'primary'

174
    @tx
175
176
177
178
179
180
181
182
183
    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):
184
185
        tablename = self._serie_to_tablename(cn, seriename)
        if tablename is None:
186
187
            return

188
189
190
191
192
193
        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 '
        ]
194
195

        if from_insertion_date:
196
            revsql.append('and cset.insertion_date >= %(from_idate)s ')
197
        if to_insertion_date:
198
            revsql.append('and cset.insertion_date <= %(to_idate)s ')
199

200
        if from_value_date or to_value_date:
201
202
            revsql.append(
                'and ' + closed_overlaps(from_value_date, to_value_date)
203
204
            )

205
206
207
        revsql.append('order by cset.id')
        revsql = ''.join(revsql)

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

219
220
221
222
223
224
        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))

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

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

267
        return {
268
            pd.Timestamp(idate).astimezone('UTC'): serie
269
270
            for idate, serie in series
        }
271

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

289
290
291
292
293
294
295
296
        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

297
        ts = pd.Series(vvmap).sort_index().loc[from_value_date:to_value_date]
298
        ts.name = seriename
299
        return ts.dropna()
300

301
    def exists(self, cn, seriename):
302
        return self._serie_to_tablename(cn, seriename) is not None
303

304
    def latest_insertion_date(self, cn, seriename):
305
306
307
308
309
        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')
310
311
312
        return pd.Timestamp(
            cn.execute(sql).scalar()
        ).astimezone('UTC')
313

314
315
    def insertion_dates(self, cn, seriename,
                        fromdate=None, todate=None):
316
317
        tablename = self._serie_to_tablename(cn, seriename)
        fromclause, toclause = '', ''
318
        if fromdate:
319
            fromclause = ' and cset.insertion_date >= %(fromdate)s '
320
        if todate:
321
322
323
324
325
326
327
            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')
328

329
330
        return [
            pd.Timestamp(idate).astimezone('UTC')
331
332
333
            for idate, in cn.execute(
                    sql, fromdate=fromdate, todate=todate
            ).fetchall()
334
335
        ]

336
337
338
339
    def last_id(self, cn, seriename):
        snapshot = Snapshot(cn, self, seriename)
        return snapshot.last_id()

340
    def changeset_at(self, cn, seriename, revdate, mode='strict'):
341
342
343
344
345
346
347
348
349
350
351
352
353
        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()
354

355
356
    @tx
    def rename(self, cn, oldname, newname):
357
358
359
360
        sql = (f'update "{self.namespace}".registry '
               'set seriename = %(newname)s '
               'where seriename = %(oldname)s')
        cn.execute(sql, oldname=oldname, newname=newname)
361
362
        self._resetcaches()

363
    @tx
364
    def delete(self, cn, seriename):
365
366
        tablename = self._serie_to_tablename(cn, seriename)
        if tablename is None:
367
368
            print('not deleting unknown series', seriename, self.namespace)
            return
369
        # changeset will keep ghost entries
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
        # 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)
            )

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

404
    @tx
405
    def strip(self, cn, seriename, csid):
406
407
408
409
410
411
        # 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)

412
413
414
        logs = self.log(cn, fromrev=csid, names=(seriename,))
        assert logs
        for log in logs:
415
416
417
418
            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 {}
419
            metadata['tshistory.info'] = f'got stripped from {csid}'
420
421
            sql = (f'update "{self.namespace}".changeset '
                   'set metadata = %(metadata)s '
422
423
                   'where id = %(csid)s')
            cn.execute(sql, csid=csid, metadata=json.dumps(metadata))
424
            # delete changset_serie item
425
            sql = (f'delete from "{self.namespace}".changeset_series as css '
426
427
                   'where css.cset = %(csid)s')
            cn.execute(sql, csid=csid)
428

429
430
431
        snapshot = Snapshot(cn, self, seriename)
        snapshot.reclaim()

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

444
    def log(self, cn, limit=0, names=None, authors=None,
445
446
            fromrev=None, torev=None,
            fromdate=None, todate=None):
447
448
449
450
        """Build a structure showing the history of all the series in the db,
        per changeset, in chronological order.
        """
        log = []
451

452
453
        sql = [
            'select distinct cset.id, cset.author, cset.insertion_date, cset.metadata '
454
455
456
            f'from "{self.namespace}".changeset as cset '
            f'join "{self.namespace}".changeset_series as css on css.cset = cset.id '
            f'join "{self.namespace}".registry as reg on reg.id = css.serie '
457
458
        ]
        wheres = []
459

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

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

497
        log.sort(key=lambda rev: rev['rev'])
498
499
        return log

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

513
514
    # /API
    # Helpers
515

516
517
    # creation / update

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

530
531
532
        # at creation time we take an exclusive lock to avoid
        # a deadlock on created tables against the changeset-series fk
        cn.execute(
533
            f'select pg_advisory_xact_lock({self.create_lock_id})'
534
        )
535
        self._register_serie(cn, seriename, newts)
536
        snapshot = Snapshot(cn, self, seriename)
537
        csid = self._newchangeset(cn, author, insertion_date, metadata)
538
        head = snapshot.create(newts)
539
        start, end = start_end(newts)
540
541
542
543
544
545
        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())
546
        self._finalize_insertion(cn, csid, seriename)
547
        L.info('first insertion of %s (size=%s) by %s',
548
               seriename, len(newts), author)
549
550
        return newts

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

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

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

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

593
    # serie table handling
594

595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
    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

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

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

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

    def _register_serie(self, cn, seriename, ts):
646
647
        index = ts.index
        inames = [name for name in index.names if name]
648
        sql = (f'insert into "{self.namespace}".registry '
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
               '(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()
667
        self.registry_map[seriename] = regid
668

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

674
675
    # changeset handling

676
677
678
    def _newchangeset(self, cn, author, insertion_date=None, metadata=None):
        if insertion_date is not None:
            assert insertion_date.tzinfo is not None
679
680
681
            idate = pd.Timestamp(insertion_date)
        else:
            idate = pd.Timestamp(datetime.utcnow(), tz='UTC')
682
        sql = (f'insert into "{self.namespace}".changeset '
683
684
685
686
687
688
689
690
691
692
693
               '(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)