tsio.py 27.3 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
312
313
314
315
        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')
316
317
318
        return pd.Timestamp(
            cn.execute(sql).scalar()
        ).astimezone('UTC')
319

320
321
    def insertion_dates(self, cn, seriename,
                        fromdate=None, todate=None):
322
323
        tablename = self._serie_to_tablename(cn, seriename)
        fromclause, toclause = '', ''
324
        if fromdate:
325
            fromclause = ' and cset.insertion_date >= %(fromdate)s '
326
        if todate:
327
328
329
330
331
332
333
            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')
334

335
336
        return [
            pd.Timestamp(idate).astimezone('UTC')
337
338
339
            for idate, in cn.execute(
                    sql, fromdate=fromdate, todate=todate
            ).fetchall()
340
341
        ]

342
343
344
345
    def last_id(self, cn, seriename):
        snapshot = Snapshot(cn, self, seriename)
        return snapshot.last_id()

346
    def changeset_at(self, cn, seriename, revdate, mode='strict'):
347
348
349
350
351
352
353
354
355
356
357
358
359
        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()
360

361
362
    @tx
    def rename(self, cn, oldname, newname):
363
364
365
366
        sql = (f'update "{self.namespace}".registry '
               'set seriename = %(newname)s '
               'where seriename = %(oldname)s')
        cn.execute(sql, oldname=oldname, newname=newname)
367
368
        self._resetcaches()

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

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

410
    @tx
411
    def strip(self, cn, seriename, csid):
412
413
414
415
416
417
        # 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)

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

435
436
437
        snapshot = Snapshot(cn, self, seriename)
        snapshot.reclaim()

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

450
    def log(self, cn, limit=0, names=None, authors=None,
451
452
            fromrev=None, torev=None,
            fromdate=None, todate=None):
453
454
455
456
        """Build a structure showing the history of all the series in the db,
        per changeset, in chronological order.
        """
        log = []
457

458
459
460
461
462
463
464
465
466
        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'
        )
467

468
        if names:
469
470
471
            q.where(
                'reg.seriename in %(names)s',
                names=tuple(names)
472
            )
473
        if authors:
474
475
476
            q.where(
                'cset.author in %(authors)s',
                author=tuple(authors)
477
            )
478
        if fromrev:
479
            q.where('cset.id >= %(fromrev)s', fromrev=fromrev)
480
        if torev:
481
            q.where('cset.id <= %(torev)s', torev=torev)
482
        if fromdate:
483
            q.where('cset.insertion_date >= %(fromdate)s', fromdate=fromdate)
484
        if todate:
485
            q.where('cset.insertion_date <= %(todate)s', todate=todate)
486
487

        if limit:
488
489
            q.option('limit %(limit)s', limit=limit)
        q.option('order by cset.id desc')
490

491
        rset = q.do(cn)
492
        for csetid, author, revdate, meta in rset.fetchall():
493
            log.append({'rev': csetid, 'author': author,
494
                        'date': pd.Timestamp(revdate).tz_convert('utc'),
495
                        'meta': meta or {},
496
                        'names': self._changeset_series(cn, csetid)})
497

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

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

514
515
    # /API
    # Helpers
516

517
518
    # creation / update

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

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

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

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

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

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

594
    # serie table handling
595

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

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

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

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

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

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

675
676
    # changeset handling

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

696
    def _changeset_series(self, cn, csid):
697
698
699
700
701
        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')
702

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

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

715
716
    # insertion handling

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

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

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

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

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



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

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