-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathsession.go
1300 lines (1177 loc) · 39.9 KB
/
session.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package client
import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"log"
"net"
"reflect"
"sort"
"strings"
"time"
"github.com/apache/iotdb-client-go/common"
"github.com/apache/iotdb-client-go/rpc"
"github.com/apache/thrift/lib/go/thrift"
)
const (
DefaultTimeZone = "Asia/Shanghai"
DefaultFetchSize = 1024
DefaultConnectRetryMax = 3
TreeSqlDialect = "tree"
TableSqlDialect = "table"
)
type Version string
const (
V_0_12 = Version("V_0_12")
V_0_13 = Version("V_0_13")
V_1_0 = Version("V_1_0")
DEFAULT_VERSION = V_1_0
)
var errLength = errors.New("deviceIds, times, measurementsList and valuesList's size should be equal")
type Config struct {
Host string
Port string
UserName string
Password string
FetchSize int32
TimeZone string
ConnectRetryMax int
sqlDialect string
Version Version
Database string
}
type Session struct {
config *Config
client *rpc.IClientRPCServiceClient
sessionId int64
trans thrift.TTransport
requestStatementId int64
protocolFactory thrift.TProtocolFactory
endPointList []endPoint
}
type endPoint struct {
Host string
Port string
}
func (s *Session) Open(enableRPCCompression bool, connectionTimeoutInMs int) error {
if s.config.FetchSize <= 0 {
s.config.FetchSize = DefaultFetchSize
}
if s.config.TimeZone == "" {
s.config.TimeZone = DefaultTimeZone
}
if s.config.ConnectRetryMax <= 0 {
s.config.ConnectRetryMax = DefaultConnectRetryMax
}
var err error
// in thrift 0.14.1, this func returns two values; in thrift 0.15.0, it returns one.
s.trans = thrift.NewTSocketConf(net.JoinHostPort(s.config.Host, s.config.Port), &thrift.TConfiguration{
ConnectTimeout: time.Duration(connectionTimeoutInMs) * time.Millisecond, // Use 0 for no timeout
})
// s.trans = thrift.NewTFramedTransport(s.trans) // deprecated
tmp_conf := thrift.TConfiguration{MaxFrameSize: thrift.DEFAULT_MAX_FRAME_SIZE}
s.trans = thrift.NewTFramedTransportConf(s.trans, &tmp_conf)
if !s.trans.IsOpen() {
err = s.trans.Open()
if err != nil {
return err
}
}
s.protocolFactory = getProtocolFactory(enableRPCCompression)
iprot := s.protocolFactory.GetProtocol(s.trans)
oprot := s.protocolFactory.GetProtocol(s.trans)
s.client = rpc.NewIClientRPCServiceClient(thrift.NewTStandardClient(iprot, oprot))
req := rpc.TSOpenSessionReq{
ClientProtocol: rpc.TSProtocolVersion_IOTDB_SERVICE_PROTOCOL_V3, ZoneId: s.config.TimeZone, Username: s.config.UserName,
Password: &s.config.Password,
}
req.Configuration = make(map[string]string)
req.Configuration["sql_dialect"] = s.config.sqlDialect
if s.config.Version == "" {
req.Configuration["version"] = string(DEFAULT_VERSION)
} else {
req.Configuration["version"] = string(s.config.Version)
}
if s.config.Database != "" {
req.Configuration["db"] = s.config.Database
}
resp, err := s.client.OpenSession(context.Background(), &req)
if err != nil {
return err
}
s.sessionId = resp.GetSessionId()
s.requestStatementId, err = s.client.RequestStatementId(context.Background(), s.sessionId)
return err
}
type ClusterConfig struct {
NodeUrls []string //ip:port
UserName string
Password string
FetchSize int32
TimeZone string
ConnectRetryMax int
sqlDialect string
Database string
}
func (s *Session) OpenCluster(enableRPCCompression bool) error {
if s.config.FetchSize <= 0 {
s.config.FetchSize = DefaultFetchSize
}
if s.config.TimeZone == "" {
s.config.TimeZone = DefaultTimeZone
}
if s.config.ConnectRetryMax <= 0 {
s.config.ConnectRetryMax = DefaultConnectRetryMax
}
var err error
s.protocolFactory = getProtocolFactory(enableRPCCompression)
iprot := s.protocolFactory.GetProtocol(s.trans)
oprot := s.protocolFactory.GetProtocol(s.trans)
s.client = rpc.NewIClientRPCServiceClient(thrift.NewTStandardClient(iprot, oprot))
req := rpc.TSOpenSessionReq{
ClientProtocol: rpc.TSProtocolVersion_IOTDB_SERVICE_PROTOCOL_V3, ZoneId: s.config.TimeZone, Username: s.config.UserName,
Password: &s.config.Password,
}
req.Configuration = make(map[string]string)
req.Configuration["sql_dialect"] = s.config.sqlDialect
if s.config.Version == "" {
req.Configuration["version"] = string(DEFAULT_VERSION)
} else {
req.Configuration["version"] = string(s.config.Version)
}
if s.config.Database != "" {
req.Configuration["db"] = s.config.Database
}
resp, err := s.client.OpenSession(context.Background(), &req)
if err != nil {
return err
}
s.sessionId = resp.GetSessionId()
s.requestStatementId, err = s.client.RequestStatementId(context.Background(), s.sessionId)
return err
}
func getProtocolFactory(enableRPCCompression bool) thrift.TProtocolFactory {
if enableRPCCompression {
return thrift.NewTCompactProtocolFactoryConf(&thrift.TConfiguration{})
} else {
return thrift.NewTBinaryProtocolFactoryConf(&thrift.TConfiguration{})
}
}
func (s *Session) Close() error {
req := rpc.NewTSCloseSessionReq()
req.SessionId = s.sessionId
_, err := s.client.CloseSession(context.Background(), req)
if err != nil {
return err
}
return s.trans.Close()
}
/*
*set one storage group
*param
*storageGroupId: string, storage group name (starts from root)
*return
*error: correctness of operation
*/
func (s *Session) SetStorageGroup(storageGroupId string) (r *common.TSStatus, err error) {
r, err = s.client.SetStorageGroup(context.Background(), s.sessionId, storageGroupId)
if err != nil && r == nil {
if s.reconnect() {
r, err = s.client.SetStorageGroup(context.Background(), s.sessionId, storageGroupId)
}
}
return r, err
}
/*
*delete one storage group
*param
*storageGroupId: string, storage group name (starts from root)
*return
*error: correctness of operation
*/
func (s *Session) DeleteStorageGroup(storageGroupId string) (r *common.TSStatus, err error) {
r, err = s.client.DeleteStorageGroups(context.Background(), s.sessionId, []string{storageGroupId})
if err != nil && r == nil {
if s.reconnect() {
r, err = s.client.DeleteStorageGroups(context.Background(), s.sessionId, []string{storageGroupId})
}
}
return r, err
}
/*
*delete multiple storage group
*param
*storageGroupIds: []string, paths of the target storage groups
*return
*error: correctness of operation
*/
func (s *Session) DeleteStorageGroups(storageGroupIds ...string) (r *common.TSStatus, err error) {
r, err = s.client.DeleteStorageGroups(context.Background(), s.sessionId, storageGroupIds)
if err != nil && r == nil {
if s.reconnect() {
r, err = s.client.DeleteStorageGroups(context.Background(), s.sessionId, storageGroupIds)
}
}
return r, err
}
/*
*create single time series
*params
*path: string, complete time series path (starts from root)
*dataType: int32, data type for this time series
*encoding: int32, data type for this time series
*compressor: int32, compressing type for this time series
*return
*error: correctness of operation
*/
func (s *Session) CreateTimeseries(path string, dataType TSDataType, encoding TSEncoding, compressor TSCompressionType, attributes map[string]string, tags map[string]string) (r *common.TSStatus, err error) {
request := rpc.TSCreateTimeseriesReq{
SessionId: s.sessionId, Path: path, DataType: int32(dataType), Encoding: int32(encoding),
Compressor: int32(compressor), Attributes: attributes, Tags: tags,
}
status, err := s.client.CreateTimeseries(context.Background(), &request)
if err != nil && status == nil {
if s.reconnect() {
request.SessionId = s.sessionId
status, err = s.client.CreateTimeseries(context.Background(), &request)
}
}
return status, err
}
/*
*create single aligned time series
*params
*prefixPath: string, time series prefix path (starts from root)
*measurements: []string, sensor names
*dataTypes: []int32, data types for time series
*encodings: []int32, encodings for time series
*compressors: []int32, compressing types for time series
*measurementAlias: []string, sensor names alias
*return
*error: correctness of operation
*/
func (s *Session) CreateAlignedTimeseries(prefixPath string, measurements []string, dataTypes []TSDataType, encodings []TSEncoding, compressors []TSCompressionType, measurementAlias []string) (r *common.TSStatus, err error) {
destTypes := make([]int32, len(dataTypes))
for i, t := range dataTypes {
destTypes[i] = int32(t)
}
destEncodings := make([]int32, len(encodings))
for i, e := range encodings {
destEncodings[i] = int32(e)
}
destCompressions := make([]int32, len(compressors))
for i, e := range compressors {
destCompressions[i] = int32(e)
}
request := rpc.TSCreateAlignedTimeseriesReq{
SessionId: s.sessionId,
PrefixPath: prefixPath,
Measurements: measurements,
DataTypes: destTypes,
Encodings: destEncodings,
Compressors: destCompressions,
MeasurementAlias: measurementAlias,
}
status, err := s.client.CreateAlignedTimeseries(context.Background(), &request)
if err != nil && status == nil {
if s.reconnect() {
request.SessionId = s.sessionId
status, err = s.client.CreateAlignedTimeseries(context.Background(), &request)
}
}
return status, err
}
/*
*create multiple time series
*params
*paths: []string, complete time series paths (starts from root)
*dataTypes: []int32, data types for time series
*encodings: []int32, encodings for time series
*compressors: []int32, compressing types for time series
*return
*error: correctness of operation
*/
func (s *Session) CreateMultiTimeseries(paths []string, dataTypes []TSDataType, encodings []TSEncoding, compressors []TSCompressionType) (r *common.TSStatus, err error) {
destTypes := make([]int32, len(dataTypes))
for i, t := range dataTypes {
destTypes[i] = int32(t)
}
destEncodings := make([]int32, len(encodings))
for i, e := range encodings {
destEncodings[i] = int32(e)
}
destCompressions := make([]int32, len(compressors))
for i, e := range compressors {
destCompressions[i] = int32(e)
}
request := rpc.TSCreateMultiTimeseriesReq{
SessionId: s.sessionId, Paths: paths, DataTypes: destTypes,
Encodings: destEncodings, Compressors: destCompressions,
}
r, err = s.client.CreateMultiTimeseries(context.Background(), &request)
if err != nil && r == nil {
if s.reconnect() {
request.SessionId = s.sessionId
r, err = s.client.CreateMultiTimeseries(context.Background(), &request)
}
}
return r, err
}
/*
*delete multiple time series, including data and schema
*params
*paths: []string, time series paths, which should be complete (starts from root)
*return
*error: correctness of operation
*/
func (s *Session) DeleteTimeseries(paths []string) (r *common.TSStatus, err error) {
r, err = s.client.DeleteTimeseries(context.Background(), s.sessionId, paths)
if err != nil && r == nil {
if s.reconnect() {
r, err = s.client.DeleteTimeseries(context.Background(), s.sessionId, paths)
}
}
return r, err
}
/*
*delete all startTime <= data <= endTime in multiple time series
*params
*paths: []string, time series array that the data in
*startTime: int64, start time of deletion range
*endTime: int64, end time of deletion range
*return
*error: correctness of operation
*/
func (s *Session) DeleteData(paths []string, startTime int64, endTime int64) (r *common.TSStatus, err error) {
request := rpc.TSDeleteDataReq{SessionId: s.sessionId, Paths: paths, StartTime: startTime, EndTime: endTime}
r, err = s.client.DeleteData(context.Background(), &request)
if err != nil && r == nil {
if s.reconnect() {
request.SessionId = s.sessionId
r, err = s.client.DeleteData(context.Background(), &request)
}
}
return r, err
}
/*
*special case for inserting one row of String (TEXT) value
*params
*deviceId: string, time series path for device
*measurements: []string, sensor names
*values: []string, values to be inserted, for each sensor
*timestamp: int64, indicate the timestamp of the row of data
*return
*error: correctness of operation
*/
func (s *Session) InsertStringRecord(deviceId string, measurements []string, values []string, timestamp int64) (r *common.TSStatus, err error) {
request := rpc.TSInsertStringRecordReq{
SessionId: s.sessionId, PrefixPath: deviceId, Measurements: measurements,
Values: values, Timestamp: timestamp,
}
r, err = s.client.InsertStringRecord(context.Background(), &request)
if err != nil && r == nil {
if s.reconnect() {
request.SessionId = s.sessionId
r, err = s.client.InsertStringRecord(context.Background(), &request)
}
}
return r, err
}
func (s *Session) GetTimeZone() (string, error) {
resp, err := s.client.GetTimeZone(context.Background(), s.sessionId)
if err != nil {
return DefaultTimeZone, err
}
return resp.TimeZone, nil
}
func (s *Session) SetTimeZone(timeZone string) (r *common.TSStatus, err error) {
request := rpc.TSSetTimeZoneReq{SessionId: s.sessionId, TimeZone: timeZone}
r, err = s.client.SetTimeZone(context.Background(), &request)
s.config.TimeZone = timeZone
return r, err
}
func (s *Session) ExecuteStatementWithContext(ctx context.Context, sql string) (*SessionDataSet, error) {
request := rpc.TSExecuteStatementReq{
SessionId: s.sessionId,
Statement: sql,
StatementId: s.requestStatementId,
FetchSize: &s.config.FetchSize,
}
resp, err := s.client.ExecuteStatement(ctx, &request)
if err != nil && resp == nil {
if s.reconnect() {
request.SessionId = s.sessionId
request.StatementId = s.requestStatementId
resp, err = s.client.ExecuteStatement(ctx, &request)
}
}
if statusErr := VerifySuccess(resp.Status); statusErr != nil {
return nil, statusErr
}
return s.genDataSet(sql, resp), err
}
func (s *Session) ExecuteStatement(sql string) (*SessionDataSet, error) {
return s.ExecuteStatementWithContext(context.Background(), sql)
}
func (s *Session) ExecuteNonQueryStatement(sql string) (r *common.TSStatus, err error) {
request := rpc.TSExecuteStatementReq{
SessionId: s.sessionId,
Statement: sql,
StatementId: s.requestStatementId,
FetchSize: &s.config.FetchSize,
}
resp, err := s.client.ExecuteStatement(context.Background(), &request)
if err != nil && resp == nil {
if s.reconnect() {
request.SessionId = s.sessionId
request.StatementId = s.requestStatementId
resp, err = s.client.ExecuteStatement(context.Background(), &request)
}
}
if resp.IsSetDatabase() {
s.changeDatabase(*resp.Database)
}
return resp.Status, err
}
func (s *Session) changeDatabase(database string) {
s.config.Database = database
}
func (s *Session) ExecuteQueryStatement(sql string, timeoutMs *int64) (*SessionDataSet, error) {
request := rpc.TSExecuteStatementReq{
SessionId: s.sessionId, Statement: sql, StatementId: s.requestStatementId,
FetchSize: &s.config.FetchSize, Timeout: timeoutMs,
}
if resp, err := s.client.ExecuteQueryStatement(context.Background(), &request); err == nil {
if statusErr := VerifySuccess(resp.Status); statusErr == nil {
return NewSessionDataSet(sql, resp.Columns, resp.DataTypeList, resp.ColumnNameIndexMap, *resp.QueryId, s.client, s.sessionId, resp.QueryDataSet, resp.IgnoreTimeStamp != nil && *resp.IgnoreTimeStamp, s.config.FetchSize, timeoutMs), err
} else {
return nil, statusErr
}
} else {
if s.reconnect() {
request.SessionId = s.sessionId
request.StatementId = s.requestStatementId
resp, err = s.client.ExecuteQueryStatement(context.Background(), &request)
if statusErr := VerifySuccess(resp.Status); statusErr == nil {
return NewSessionDataSet(sql, resp.Columns, resp.DataTypeList, resp.ColumnNameIndexMap, *resp.QueryId, s.client, s.sessionId, resp.QueryDataSet, resp.IgnoreTimeStamp != nil && *resp.IgnoreTimeStamp, s.config.FetchSize, timeoutMs), err
} else {
return nil, statusErr
}
}
return nil, err
}
}
func (s *Session) ExecuteAggregationQuery(paths []string, aggregations []common.TAggregationType,
startTime *int64, endTime *int64, interval *int64,
timeoutMs *int64,
) (*SessionDataSet, error) {
request := rpc.TSAggregationQueryReq{
SessionId: s.sessionId, StatementId: s.requestStatementId, Paths: paths,
Aggregations: aggregations, StartTime: startTime, EndTime: endTime, Interval: interval, FetchSize: &s.config.FetchSize, Timeout: timeoutMs,
}
if resp, err := s.client.ExecuteAggregationQuery(context.Background(), &request); err == nil {
if statusErr := VerifySuccess(resp.Status); statusErr == nil {
return NewSessionDataSet("", resp.Columns, resp.DataTypeList, resp.ColumnNameIndexMap, *resp.QueryId, s.client, s.sessionId, resp.QueryDataSet, resp.IgnoreTimeStamp != nil && *resp.IgnoreTimeStamp, s.config.FetchSize, timeoutMs), err
} else {
return nil, statusErr
}
} else {
if s.reconnect() {
request.SessionId = s.sessionId
resp, err = s.client.ExecuteAggregationQuery(context.Background(), &request)
if statusErr := VerifySuccess(resp.Status); statusErr == nil {
return NewSessionDataSet("", resp.Columns, resp.DataTypeList, resp.ColumnNameIndexMap, *resp.QueryId, s.client, s.sessionId, resp.QueryDataSet, resp.IgnoreTimeStamp != nil && *resp.IgnoreTimeStamp, s.config.FetchSize, timeoutMs), err
} else {
return nil, statusErr
}
}
return nil, err
}
}
func (s *Session) ExecuteAggregationQueryWithLegalNodes(paths []string, aggregations []common.TAggregationType,
startTime *int64, endTime *int64, interval *int64,
timeoutMs *int64, legalNodes *bool,
) (*SessionDataSet, error) {
request := rpc.TSAggregationQueryReq{
SessionId: s.sessionId, StatementId: s.requestStatementId, Paths: paths,
Aggregations: aggregations, StartTime: startTime, EndTime: endTime, Interval: interval, FetchSize: &s.config.FetchSize,
Timeout: timeoutMs, LegalPathNodes: legalNodes,
}
if resp, err := s.client.ExecuteAggregationQuery(context.Background(), &request); err == nil {
if statusErr := VerifySuccess(resp.Status); statusErr == nil {
return NewSessionDataSet("", resp.Columns, resp.DataTypeList, resp.ColumnNameIndexMap, *resp.QueryId, s.client, s.sessionId, resp.QueryDataSet, resp.IgnoreTimeStamp != nil && *resp.IgnoreTimeStamp, s.config.FetchSize, timeoutMs), err
} else {
return nil, statusErr
}
} else {
if s.reconnect() {
request.SessionId = s.sessionId
resp, err = s.client.ExecuteAggregationQuery(context.Background(), &request)
if statusErr := VerifySuccess(resp.Status); statusErr == nil {
return NewSessionDataSet("", resp.Columns, resp.DataTypeList, resp.ColumnNameIndexMap, *resp.QueryId, s.client, s.sessionId, resp.QueryDataSet, resp.IgnoreTimeStamp != nil && *resp.IgnoreTimeStamp, s.config.FetchSize, timeoutMs), err
} else {
return nil, statusErr
}
}
return nil, err
}
}
func (s *Session) genTSInsertRecordReq(deviceId string, time int64,
measurements []string,
types []TSDataType,
values []interface{},
isAligned bool,
) (*rpc.TSInsertRecordReq, error) {
request := &rpc.TSInsertRecordReq{}
request.SessionId = s.sessionId
request.PrefixPath = deviceId
request.Timestamp = time
request.Measurements = measurements
request.IsAligned = &isAligned
if bys, err := valuesToBytes(types, values); err == nil {
request.Values = bys
} else {
return nil, err
}
return request, nil
}
func (s *Session) InsertRecord(deviceId string, measurements []string, dataTypes []TSDataType, values []interface{}, timestamp int64) (r *common.TSStatus, err error) {
request, err := s.genTSInsertRecordReq(deviceId, timestamp, measurements, dataTypes, values, false)
if err != nil {
return nil, err
}
r, err = s.client.InsertRecord(context.Background(), request)
if err != nil && r == nil {
if s.reconnect() {
request.SessionId = s.sessionId
r, err = s.client.InsertRecord(context.Background(), request)
}
}
return r, err
}
func (s *Session) InsertAlignedRecord(deviceId string, measurements []string, dataTypes []TSDataType, values []interface{}, timestamp int64) (r *common.TSStatus, err error) {
request, err := s.genTSInsertRecordReq(deviceId, timestamp, measurements, dataTypes, values, true)
if err != nil {
return nil, err
}
r, err = s.client.InsertRecord(context.Background(), request)
if err != nil && r == nil {
if s.reconnect() {
request.SessionId = s.sessionId
r, err = s.client.InsertRecord(context.Background(), request)
}
}
return r, err
}
type deviceData struct {
timestamps []int64
measurementsSlice [][]string
dataTypesSlice [][]TSDataType
valuesSlice [][]interface{}
isAligned bool
}
func (d *deviceData) Len() int {
return len(d.timestamps)
}
func (d *deviceData) Less(i, j int) bool {
return d.timestamps[i] < d.timestamps[j]
}
func (d *deviceData) Swap(i, j int) {
d.timestamps[i], d.timestamps[j] = d.timestamps[j], d.timestamps[i]
d.measurementsSlice[i], d.measurementsSlice[j] = d.measurementsSlice[j], d.measurementsSlice[i]
d.dataTypesSlice[i], d.dataTypesSlice[j] = d.dataTypesSlice[j], d.dataTypesSlice[i]
d.valuesSlice[i], d.valuesSlice[j] = d.valuesSlice[j], d.valuesSlice[i]
}
// InsertRecordsOfOneDevice Insert multiple rows, which can reduce the overhead of network. This method is just like jdbc
// executeBatch, we pack some insert request in batch and send them to server. If you want improve
// your performance, please see insertTablet method
// Each row is independent, which could have different insertTargetName, time, number of measurements
func (s *Session) InsertRecordsOfOneDevice(deviceId string, timestamps []int64, measurementsSlice [][]string, dataTypesSlice [][]TSDataType, valuesSlice [][]interface{}, sorted bool) (r *common.TSStatus, err error) {
length := len(timestamps)
if len(measurementsSlice) != length || len(dataTypesSlice) != length || len(valuesSlice) != length {
return nil, errors.New("timestamps, measurementsSlice and valuesSlice's size should be equal")
}
if !sorted {
sort.Sort(&deviceData{
timestamps: timestamps,
measurementsSlice: measurementsSlice,
dataTypesSlice: dataTypesSlice,
valuesSlice: valuesSlice,
})
}
valuesList := make([][]byte, length)
for i := 0; i < length; i++ {
if valuesList[i], err = valuesToBytes(dataTypesSlice[i], valuesSlice[i]); err != nil {
return nil, err
}
}
request := &rpc.TSInsertRecordsOfOneDeviceReq{
SessionId: s.sessionId,
PrefixPath: deviceId,
Timestamps: timestamps,
MeasurementsList: measurementsSlice,
ValuesList: valuesList,
}
r, err = s.client.InsertRecordsOfOneDevice(context.Background(), request)
if err != nil && r == nil {
if s.reconnect() {
request.SessionId = s.sessionId
r, err = s.client.InsertRecordsOfOneDevice(context.Background(), request)
}
}
return r, err
}
func (s *Session) InsertAlignedRecordsOfOneDevice(deviceId string, timestamps []int64, measurementsSlice [][]string, dataTypesSlice [][]TSDataType, valuesSlice [][]interface{}, sorted bool) (r *common.TSStatus, err error) {
length := len(timestamps)
if len(measurementsSlice) != length || len(dataTypesSlice) != length || len(valuesSlice) != length {
return nil, errors.New("timestamps, measurementsSlice and valuesSlice's size should be equal")
}
if !sorted {
sort.Sort(&deviceData{
timestamps: timestamps,
measurementsSlice: measurementsSlice,
dataTypesSlice: dataTypesSlice,
valuesSlice: valuesSlice,
})
}
valuesList := make([][]byte, length)
for i := 0; i < length; i++ {
if valuesList[i], err = valuesToBytes(dataTypesSlice[i], valuesSlice[i]); err != nil {
return nil, err
}
}
isAligned := true
request := &rpc.TSInsertRecordsOfOneDeviceReq{
SessionId: s.sessionId,
PrefixPath: deviceId,
Timestamps: timestamps,
MeasurementsList: measurementsSlice,
ValuesList: valuesList,
IsAligned: &isAligned,
}
r, err = s.client.InsertRecordsOfOneDevice(context.Background(), request)
if err != nil && r == nil {
if s.reconnect() {
request.SessionId = s.sessionId
r, err = s.client.InsertRecordsOfOneDevice(context.Background(), request)
}
}
return r, err
}
/*
*insert multiple rows of data, records are independent to each other, in other words, there's no relationship
*between those records
*
*params
*deviceIds: []string, time series paths for device
*measurements: [][]string, each element of outer list indicates measurements of a device
*dataTypes: [][]int32, each element of outer list indicates sensor data types of a device
*values: [][]interface{}, values to be inserted, for each device
*timestamps: []int64, timestamps for records
*
*/
func (s *Session) InsertRecords(deviceIds []string, measurements [][]string, dataTypes [][]TSDataType, values [][]interface{},
timestamps []int64,
) (r *common.TSStatus, err error) {
request, err := s.genInsertRecordsReq(deviceIds, measurements, dataTypes, values, timestamps, false)
if err != nil {
return nil, err
} else {
r, err = s.client.InsertRecords(context.Background(), request)
if err != nil && r == nil {
if s.reconnect() {
request.SessionId = s.sessionId
r, err = s.client.InsertRecords(context.Background(), request)
}
}
return r, err
}
}
func (s *Session) InsertAlignedRecords(deviceIds []string, measurements [][]string, dataTypes [][]TSDataType, values [][]interface{},
timestamps []int64,
) (r *common.TSStatus, err error) {
request, err := s.genInsertRecordsReq(deviceIds, measurements, dataTypes, values, timestamps, true)
if err != nil {
return nil, err
} else {
r, err = s.client.InsertRecords(context.Background(), request)
if err != nil && r == nil {
if s.reconnect() {
request.SessionId = s.sessionId
r, err = s.client.InsertRecords(context.Background(), request)
}
}
return r, err
}
}
/*
* InsertTablets insert multiple tablets, tablets are independent to each other
*params
*tablets: []*client.Tablet, list of tablets
*/
func (s *Session) InsertTablets(tablets []*Tablet, sorted bool) (r *common.TSStatus, err error) {
if !sorted {
for _, t := range tablets {
if err := t.Sort(); err != nil {
return nil, err
}
}
}
request, err := s.genInsertTabletsReq(tablets, false)
if err != nil {
return nil, err
}
r, err = s.client.InsertTablets(context.Background(), request)
if err != nil && r == nil {
if s.reconnect() {
request.SessionId = s.sessionId
r, err = s.client.InsertTablets(context.Background(), request)
}
}
return r, err
}
func (s *Session) InsertAlignedTablets(tablets []*Tablet, sorted bool) (r *common.TSStatus, err error) {
if !sorted {
for _, t := range tablets {
if err := t.Sort(); err != nil {
return nil, err
}
}
}
request, err := s.genInsertTabletsReq(tablets, true)
if err != nil {
return nil, err
}
r, err = s.client.InsertTablets(context.Background(), request)
if err != nil && r == nil {
if s.reconnect() {
request.SessionId = s.sessionId
r, err = s.client.InsertTablets(context.Background(), request)
}
}
return r, err
}
func (s *Session) ExecuteBatchStatement(inserts []string) (r *common.TSStatus, err error) {
request := rpc.TSExecuteBatchStatementReq{
SessionId: s.sessionId,
Statements: inserts,
}
r, err = s.client.ExecuteBatchStatement(context.Background(), &request)
if err != nil && r == nil {
if s.reconnect() {
request.SessionId = s.sessionId
r, err = s.client.ExecuteBatchStatement(context.Background(), &request)
}
}
return r, err
}
func (s *Session) ExecuteRawDataQuery(paths []string, startTime int64, endTime int64) (*SessionDataSet, error) {
request := rpc.TSRawDataQueryReq{
SessionId: s.sessionId,
Paths: paths,
FetchSize: &s.config.FetchSize,
StartTime: startTime,
EndTime: endTime,
StatementId: s.requestStatementId,
}
resp, err := s.client.ExecuteRawDataQuery(context.Background(), &request)
if err != nil && resp == nil {
if s.reconnect() {
request.SessionId = s.sessionId
request.StatementId = s.requestStatementId
resp, err = s.client.ExecuteRawDataQuery(context.Background(), &request)
}
}
return s.genDataSet("", resp), err
}
func (s *Session) ExecuteUpdateStatement(sql string) (*SessionDataSet, error) {
request := rpc.TSExecuteStatementReq{
SessionId: s.sessionId,
Statement: sql,
StatementId: s.requestStatementId,
FetchSize: &s.config.FetchSize,
}
resp, err := s.client.ExecuteUpdateStatement(context.Background(), &request)
if err != nil && resp == nil {
if s.reconnect() {
request.SessionId = s.sessionId
request.StatementId = s.requestStatementId
resp, err = s.client.ExecuteUpdateStatement(context.Background(), &request)
}
}
return s.genDataSet(sql, resp), err
}
func (s *Session) genDataSet(sql string, resp *rpc.TSExecuteStatementResp) *SessionDataSet {
var queryId int64
if resp.QueryId == nil {
queryId = 0
} else {
queryId = *resp.QueryId
}
return NewSessionDataSet(sql, resp.Columns, resp.DataTypeList, resp.ColumnNameIndexMap,
queryId, s.client, s.sessionId, resp.QueryDataSet, resp.IgnoreTimeStamp != nil && *resp.IgnoreTimeStamp, s.config.FetchSize, nil)
}
func (s *Session) genInsertTabletsReq(tablets []*Tablet, isAligned bool) (*rpc.TSInsertTabletsReq, error) {
var (
length = len(tablets)
deviceIds = make([]string, length)
measurementsList = make([][]string, length)
valuesList = make([][]byte, length)
timestampsList = make([][]byte, length)
typesList = make([][]int32, length)
sizeList = make([]int32, length)
)
for index, tablet := range tablets {
deviceIds[index] = tablet.insertTargetName
measurementsList[index] = tablet.GetMeasurements()
values, err := tablet.getValuesBytes()
if err != nil {
return nil, err
}
valuesList[index] = values
timestampsList[index] = tablet.GetTimestampBytes()
typesList[index] = tablet.getDataTypes()
sizeList[index] = int32(tablet.RowSize)
}
request := rpc.TSInsertTabletsReq{
SessionId: s.sessionId,
PrefixPaths: deviceIds,
TypesList: typesList,
MeasurementsList: measurementsList,
ValuesList: valuesList,
TimestampsList: timestampsList,
SizeList: sizeList,
IsAligned: &isAligned,
}
return &request, nil
}
func (s *Session) genInsertRecordsReq(deviceIds []string, measurements [][]string, dataTypes [][]TSDataType, values [][]interface{},
timestamps []int64, isAligned bool,
) (*rpc.TSInsertRecordsReq, error) {
length := len(deviceIds)
if length != len(timestamps) || length != len(measurements) || length != len(values) {
return nil, errLength
}
request := rpc.TSInsertRecordsReq{
SessionId: s.sessionId,
PrefixPaths: deviceIds,
MeasurementsList: measurements,
Timestamps: timestamps,
IsAligned: &isAligned,
}
v := make([][]byte, length)
for i := 0; i < len(measurements); i++ {
if bys, err := valuesToBytes(dataTypes[i], values[i]); err == nil {
v[i] = bys
} else {
return nil, err
}
}
request.ValuesList = v
return &request, nil
}
func valuesToBytes(dataTypes []TSDataType, values []interface{}) ([]byte, error) {
buff := &bytes.Buffer{}
for i, t := range dataTypes {
binary.Write(buff, binary.BigEndian, byte(t))
v := values[i]
if v == nil {
return nil, fmt.Errorf("values[%d] can't be nil", i)
}
switch t {
case BOOLEAN:
switch v.(type) {
case bool:
binary.Write(buff, binary.BigEndian, v)