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
    metakeys = {
        'tzaware',
        'index_type',
        'index_dtype',
        'value_dtype',
        'value_type'
    }
39
    registry_map = None
40
    serie_tablename = None
41
    create_lock_id = None
42
    cachelock = Lock()
43
44
45

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

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

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

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

74
        newts = num2float(newts)
75

76
        if not len(newts):
77
            return
78

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

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

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

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

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

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

        revision_date: datetime filter to get previous versions of the
        serie

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

275
        return dict(series)
276

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

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

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

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

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

323
324
    def insertion_dates(self, cn, seriename,
                        fromdate=None, todate=None):
325
        tablename = self._serie_to_tablename(cn, seriename)
326
        q = select(
327
            'insertion_date'
328
        ).table(
329
330
331
332
            f'"{self.namespace}".changeset as cset',
            f'"{self.namespace}.timeserie"."{tablename}" as tstable'
        ).where(
            'cset.id = tstable.cset'
333
        ).order('cset.id')
334

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

528
529
    # /API
    # Helpers
530

531
532
    # creation / update

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

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

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

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

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

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

608
    # serie table handling
609

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

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

627
        return tablename
628

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

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

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

662
    def _series_initial_meta(self, cn, name, ts):
663
        index = ts.index
664
        return {
665
666
667
668
669
            'tzaware': tzaware_serie(ts),
            'index_type': index.dtype.name,
            'index_dtype': index.dtype.str,
            'value_dtype': ts.dtypes.str,
            'value_type': ts.dtypes.name
670
671
672
673
674
675
676
677
678
679
680
        }

    def _register_serie(self, cn, seriename, ts):
        sql = (f'insert into "{self.namespace}".registry '
               '(seriename, table_name, metadata) '
               'values (%s, %s, %s) '
               'returning id')
        table_name = self._make_tablename(cn, seriename)
        metadata = json.dumps(
            self._series_initial_meta(cn, seriename, ts)
        )
681
682
683
684
685
686
        regid = cn.execute(
            sql,
            seriename,
            table_name,
            metadata
        ).scalar()
687
        self.registry_map[seriename] = regid
688

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

694
695
    # changeset handling

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

715
    def _changeset_series(self, cn, csid):
716
        q = select(
717
            'seriename'
718
        ).table(
719
720
721
722
723
724
            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
        )
725

726
        return q.do(cn).scalar()
727

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

735
736
    # insertion handling

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

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

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

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

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



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

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