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
from deprecated import deprecated
12
from sqlhelp import sqlfile, select
13

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

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


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

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

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

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

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

75
        newts = num2float(newts)
76

77
        if not len(newts):
78
            return
79

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

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

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

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

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

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
            csetfilter.append(
117
                lambda q: q.where(
118
119
                    f'cset.insertion_date <= %(idate)s', idate=revision_date
                )
120
            )
121
        snap = Snapshot(cn, self, seriename)
122
        _, current = snap.find(csetfilter=csetfilter,
123
124
                               from_value_date=from_value_date,
                               to_value_date=to_value_date)
125

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

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

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

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

175
176
177
    def type(self, cn, name):
        return 'primary'

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

192
        q = select(
193
            'cset.id', 'cset.insertion_date'
194
        ).table(
195
196
197
198
            f'"{self.namespace}.timeserie"."{tablename}" as ts'
        ).join(
            f'"{self.namespace}".changeset as cset on cset.id = ts.cset'
        )
199
200

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

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

218
        q.order('cset.id')
219
        revs = q.do(cn).fetchall()
220
        if not revs:
221
            return {}
222

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

228
229
230
231
232
233
        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))

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

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

276
        return dict(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
        q = select(
313
            'max(insertion_date)'
314
        ).table(
315
316
317
318
319
            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
        q = select(
328
            'insertion_date'
329
        ).table(
330
331
332
333
            f'"{self.namespace}".changeset as cset',
            f'"{self.namespace}.timeserie"."{tablename}" as tstable'
        ).where(
            'cset.id = tstable.cset'
334
        ).order('cset.id')
335

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

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

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

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

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

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

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

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

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

450
451
452
        snapshot = Snapshot(cn, self, seriename)
        snapshot.reclaim()

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

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

473
        q = select(
474
475
            'cset.id', 'cset.author', 'cset.insertion_date', 'cset.metadata',
            opt='distinct'
476
        ).table(
477
478
479
480
481
            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'
        )
482

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

502
        q.order('cset.id', 'desc')
503
        if limit:
504
            q.limit(int(limit))
505

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

513
        log.sort(key=lambda rev: rev['rev'])
514
515
        return log

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

529
530
    # /API
    # Helpers
531

532
533
    # creation / update

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

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

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

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

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

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

609
    # serie table handling
610

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

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

628
        return tablename
629

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
        q = select(
715
            'seriename'
716
        ).table(
717
718
719
720
721
722
            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
        )
723

724
        return q.do(cn).scalar()
725

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

733
734
    # insertion handling

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

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

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

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

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



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

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