-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathSessionDataSet.cs
More file actions
385 lines (349 loc) · 13.7 KB
/
SessionDataSet.cs
File metadata and controls
385 lines (349 loc) · 13.7 KB
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
/*
* 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Thrift;
namespace Apache.IoTDB.DataStructure
{
public class SessionDataSet : System.IDisposable
{
private readonly long _queryId;
private readonly long _statementId;
private readonly string _sql;
private readonly List<string> _columnNames;
private readonly Dictionary<string, int> _columnNameIndexMap;
private readonly Dictionary<int, int> _duplicateLocation;
private readonly List<string> _columnTypeLst;
private TSQueryDataSet _queryDataset;
private readonly byte[] _currentBitmap;
private readonly int _columnSize;
private List<ByteBuffer> _valueBufferLst, _bitmapBufferLst;
private ByteBuffer _timeBuffer;
private readonly ConcurrentClientQueue _clientQueue;
private Client _client;
private int _rowIndex;
private bool _hasCatchedResult;
private RowRecord _cachedRowRecord;
private bool _isClosed = false;
private bool disposedValue;
private string TimestampStr => "Time";
private int StartIndex => 2;
private int Flag => 0x80;
private int DefaultTimeout => 10000;
public int FetchSize { get; set; }
/// <summary>
/// Gets the number of rows in the current fetched batch.
/// Note: This is NOT the total row count of the query result. Use HasNext() to check for more data.
/// </summary>
/// <returns>The number of rows in the current batch.</returns>
public int CurrentBatchRowCount() => _currentBatchRowCount;
/// <summary>
/// Gets the number of rows in the current fetched batch.
/// </summary>
/// <returns>The number of rows in the current batch.</returns>
[Obsolete("Use CurrentBatchRowCount() instead. This property returns batch size, not total row count.")]
public int RowCount { get; set; }
private int _currentBatchRowCount;
public SessionDataSet(string sql, TSExecuteStatementResp resp, Client client, ConcurrentClientQueue clientQueue, long statementId)
{
_clientQueue = clientQueue;
_client = client;
_sql = sql;
_queryDataset = resp.QueryDataSet;
_queryId = resp.QueryId;
_statementId = statementId;
_columnSize = resp.Columns.Count;
_currentBitmap = new byte[_columnSize];
_columnNames = new List<string>();
_timeBuffer = new ByteBuffer(_queryDataset.Time);
// column name -> column location
_columnNameIndexMap = new Dictionary<string, int>();
_columnTypeLst = new List<string>();
_duplicateLocation = new Dictionary<int, int>();
_valueBufferLst = new List<ByteBuffer>();
_bitmapBufferLst = new List<ByteBuffer>();
// some internal variable
_hasCatchedResult = false;
_rowIndex = 0;
_currentBatchRowCount = _queryDataset.Time.Length / sizeof(long);
RowCount = _currentBatchRowCount;
_columnNames = resp.Columns;
_columnTypeLst = resp.DataTypeList;
int deduplicateIdx = 0;
Dictionary<string, int> columnToFirstIndexMap = new Dictionary<string, int>();
for (var i = 0; i < _columnSize; i++)
{
var columnName = _columnNames[i];
if (_columnNameIndexMap.ContainsKey(columnName))
{
_duplicateLocation[i] = columnToFirstIndexMap[columnName];
}
else
{
columnToFirstIndexMap[columnName] = i;
if (resp.ColumnNameIndexMap != null)
{
int valueIndex = resp.ColumnNameIndexMap[columnName];
_columnNameIndexMap[columnName] = valueIndex;
_valueBufferLst.Add(new ByteBuffer(_queryDataset.ValueList[valueIndex]));
_bitmapBufferLst.Add(new ByteBuffer(_queryDataset.BitmapList[valueIndex]));
}
else
{
_columnNameIndexMap[columnName] = deduplicateIdx;
_valueBufferLst.Add(new ByteBuffer(_queryDataset.ValueList[deduplicateIdx]));
_bitmapBufferLst.Add(new ByteBuffer(_queryDataset.BitmapList[deduplicateIdx]));
}
deduplicateIdx++;
}
}
}
public List<string> ColumnNames => _columnNames;
private List<string> GetColumnNames()
{
var lst = new List<string>
{
"timestamp"
};
lst.AddRange(_columnNames);
return lst;
}
public void ShowTableNames()
{
var str = GetColumnNames()
.Aggregate("", (current, name) => current + (name + "\t\t"));
Console.WriteLine(str);
}
public bool HasNext()
{
if (_hasCatchedResult)
{
return true;
}
// we have consumed all current data, fetch some more
if (!_timeBuffer.HasRemaining())
{
if (!FetchResults())
{
return false;
}
}
ConstructOneRow();
_hasCatchedResult = true;
return true;
}
public RowRecord Next()
{
if (!_hasCatchedResult)
{
if (!HasNext())
{
return null;
}
}
_hasCatchedResult = false;
return _cachedRowRecord;
}
public RowRecord GetRow()
{
return _cachedRowRecord;
}
private TSDataType GetDataTypeFromStr(string str)
{
return str switch
{
"BOOLEAN" => TSDataType.BOOLEAN,
"INT32" => TSDataType.INT32,
"INT64" => TSDataType.INT64,
"FLOAT" => TSDataType.FLOAT,
"DOUBLE" => TSDataType.DOUBLE,
"TEXT" => TSDataType.TEXT,
"NULLTYPE" => TSDataType.NONE,
"TIMESTAMP" => TSDataType.TIMESTAMP,
"DATE" => TSDataType.DATE,
"BLOB" => TSDataType.BLOB,
"STRING" => TSDataType.STRING,
_ => TSDataType.STRING
};
}
private void ConstructOneRow()
{
List<object> fieldLst = new List<Object>();
for (int i = 0; i < _columnSize; i++)
{
if (_duplicateLocation.ContainsKey(i))
{
var field = fieldLst[_duplicateLocation[i]];
fieldLst.Add(field);
}
else
{
var columnValueBuffer = _valueBufferLst[i];
var columnBitmapBuffer = _bitmapBufferLst[i];
if (_rowIndex % 8 == 0)
{
_currentBitmap[i] = columnBitmapBuffer.GetByte();
}
object localField;
if (!IsNull(i, _rowIndex))
{
var columnDataType = GetDataTypeFromStr(_columnTypeLst[i]);
switch (columnDataType)
{
case TSDataType.BOOLEAN:
localField = columnValueBuffer.GetBool();
break;
case TSDataType.INT32:
// case TSDataType.DATE:
localField = columnValueBuffer.GetInt();
break;
case TSDataType.DATE:
localField = Utils.ParseIntToDate(columnValueBuffer.GetInt());
break;
case TSDataType.INT64:
case TSDataType.TIMESTAMP:
localField = columnValueBuffer.GetLong();
break;
case TSDataType.FLOAT:
localField = columnValueBuffer.GetFloat();
break;
case TSDataType.DOUBLE:
localField = columnValueBuffer.GetDouble();
break;
case TSDataType.TEXT:
case TSDataType.STRING:
// case TSDataType.BLOB:
localField = columnValueBuffer.GetStr();
break;
case TSDataType.BLOB:
localField = columnValueBuffer.GetBinary();
break;
// TODO
default:
string err_msg = "value format not supported";
throw new TException(err_msg, null);
}
fieldLst.Add(localField);
}
else
{
localField = null;
fieldLst.Add(DBNull.Value);
}
}
}
long timestamp = _timeBuffer.GetLong();
_rowIndex += 1;
_cachedRowRecord = new RowRecord(timestamp, fieldLst, _columnNames);
}
private bool IsNull(int loc, int row_index)
{
byte bitmap = _currentBitmap[loc];
int shift = row_index % 8;
return ((Flag >> shift) & bitmap) == 0;
}
private bool FetchResults()
{
_rowIndex = 0;
var req = new TSFetchResultsReq(_client.SessionId, _sql, FetchSize, _queryId, true)
{
Timeout = DefaultTimeout
};
try
{
var task = _client.ServiceClient.fetchResultsAsync(req);
var resp = task.ConfigureAwait(false).GetAwaiter().GetResult();
if (resp.HasResultSet)
{
_queryDataset = resp.QueryDataSet;
// reset buffer
_timeBuffer = new ByteBuffer(resp.QueryDataSet.Time);
_valueBufferLst = new List<ByteBuffer>();
_bitmapBufferLst = new List<ByteBuffer>();
for (int index = 0; index < _queryDataset.ValueList.Count; index++)
{
string columnName = _columnNames[index];
int valueIndex = _columnNameIndexMap[columnName];
_valueBufferLst.Add(new ByteBuffer(_queryDataset.ValueList[valueIndex]));
_bitmapBufferLst.Add(new ByteBuffer(_queryDataset.BitmapList[valueIndex]));
}
// reset row index
_rowIndex = 0;
}
return resp.HasResultSet;
}
catch (TException e)
{
throw new TException("Cannot fetch result from server, because of network connection", e);
}
}
public async Task Close()
{
if (!_isClosed)
{
var req = new TSCloseOperationReq(_client.SessionId)
{
QueryId = _queryId,
StatementId = _statementId
};
try
{
var status = await _client.ServiceClient.closeOperationAsync(req);
}
catch (TException e)
{
throw new TException("Operation Handle Close Failed", e);
}
finally
{
_clientQueue.Add(_client);
_client = null;
}
}
}
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
try
{
this.Close().Wait();
}
catch
{
}
}
_queryDataset = null;
_timeBuffer = null;
_valueBufferLst = null;
_bitmapBufferLst = null;
disposedValue = true;
}
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}