-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathgriddb_python.py
More file actions
2448 lines (1945 loc) · 102 KB
/
griddb_python.py
File metadata and controls
2448 lines (1945 loc) · 102 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
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
'''
Copyright (c) 2024 TOSHIBA Digital Solutions Corporation
Licensed 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.
'''
import jpype
import sys
import traceback
import ipaddress
if not jpype.isJVMStarted():
jpype.startJVM()
import jpype.imports
from java.util import Properties
from java.util import ArrayList
from java.util import HashMap
from java.sql import Timestamp
from java.util import Collections
from org.apache.arrow.memory import RootAllocator
from org.apache.arrow import c
import pyarrow
import pyarrow.jvm
from enum import IntEnum
from functools import singledispatchmethod
from datetime import datetime
from datetime import timedelta
from datetime import timezone
from java.util import Date as JDate
from java.lang import Integer as JInteger
from java.lang import Long as JLong
from java.lang import String as JString
from javax.sql.rowset.serial import SerialBlob
from com.toshiba.mwcloud.gs.arrow.adapter import JavaAPIToArrow
from com.toshiba.mwcloud.gs.arrow.adapter import JavaAPIParameterBinder
from com.toshiba.mwcloud.gs.arrow.adapter import JavaAPIToArrowConfigBuilder
from com.toshiba.mwcloud.gs.arrow.adapter import MultiGetWrapper
from com.toshiba.mwcloud.gs.arrow.adapter import MultiPutWrapper
from com.toshiba.mwcloud.gs import GridStoreFactory as SF
from com.toshiba.mwcloud.gs import GridStore as JStore
from com.toshiba.mwcloud.gs import ContainerInfo as JContainerInfo
from com.toshiba.mwcloud.gs import ColumnInfo as JColumnInfo
from com.toshiba.mwcloud.gs import TimeSeriesProperties as JTimeSeriesProperties
from com.toshiba.mwcloud.gs import Row as JRow
from com.toshiba.mwcloud.gs import GSType as JType
from com.toshiba.mwcloud.gs import IndexInfo as JIndexInfo
from com.toshiba.mwcloud.gs import IndexType as JIndexType
from com.toshiba.mwcloud.gs import Container as JContainer
from com.toshiba.mwcloud.gs import ContainerType as JContainerType
from com.toshiba.mwcloud.gs import AggregationResult as JAggregationResult
from com.toshiba.mwcloud.gs import QueryAnalysisEntry as JQueryAnalysisEntry
from com.toshiba.mwcloud.gs import RowKeyPredicate as JRowKeyPredicate
from com.toshiba.mwcloud.gs import TimestampUtils as JTimestampUtils
from com.toshiba.mwcloud.gs import TimeUnit as JTimeUnit
from com.toshiba.mwcloud.gs import FetchOption as JFetchOption
from com.toshiba.mwcloud.gs import Geometry as JGeometry
CLIENT_VERSION = "Python Client for GridDB V5.8"
import warnings
warnings.filterwarnings(action="ignore", message=r"datetime.datetime.utcfromtimestamp")
JException = jpype.JClass('java.lang.Exception')
JGsException = jpype.JClass('com.toshiba.mwcloud.gs.GSException')
JGsTimeException = jpype.JClass('com.toshiba.mwcloud.gs.GSTimeoutException')
class Type(IntEnum):
"""_summary_
Args:
Enum (_type_): _description_
Returns:
_type_: _description_
"""
STRING = 0
"""STRING型
"""
BOOL = 1
"""BOOL型
"""
BYTE = 2
"""BYTE型
"""
SHORT = 3
"""SHORT型
"""
INTEGER = 4
"""INTEGER型
"""
LONG = 5
"""LONG型
"""
FLOAT = 6
"""FLOAT型
"""
DOUBLE = 7
"""DOUBLE型
"""
TIMESTAMP = 8
"""TIMESTAMP型
"""
GEOMETRY = 9
"""GEOMETRY型
"""
BLOB = 10
"""BLOB型
"""
@classmethod
def _convert_to_java(self, ptype:object)->object:
jtype = None
if ptype == self.STRING:
jtype = JType.STRING
elif ptype == self.BOOL:
jtype = JType.BOOL
elif ptype == self.BYTE:
jtype = JType.BYTE
elif ptype == self.SHORT:
jtype = JType.SHORT
elif ptype == self.INTEGER:
jtype = JType.INTEGER
elif ptype == self.LONG:
jtype = JType.LONG
elif ptype == self.FLOAT:
jtype = JType.FLOAT
elif ptype == self.DOUBLE:
jtype = JType.DOUBLE
elif ptype == self.TIMESTAMP:
jtype = JType.TIMESTAMP
elif ptype == self.GEOMETRY:
jtype = JType.GEOMETRY
elif ptype == self.BLOB:
jtype = JType.BLOB
return jtype
@classmethod
def _convert_to_python(self, jtype:object)->object:
pytype = None
if jtype == JType.STRING:
pytype = self.STRING
elif jtype == JType.BOOL:
pytype = self.BOOL
elif jtype == JType.BYTE:
pytype = self.BYTE
elif jtype == JType.SHORT:
pytype = self.SHORT
elif jtype == JType.INTEGER:
pytype = self.INTEGER
elif jtype == JType.LONG:
pytype = self.LONG
elif jtype == JType.FLOAT:
pytype = self.FLOAT
elif jtype == JType.DOUBLE:
pytype = self.DOUBLE
elif jtype == JType.TIMESTAMP:
pytype = self.TIMESTAMP
elif jtype == JType.GEOMETRY:
pytype = self.GEOMETRY
elif jtype == JType.BLOB:
pytype = self.BLOB
return pytype
class TypeOption(IntEnum):
"""NOT NULL制約を示します。
"""
NULLABLE = 2
"""NOT NULL制約を持たないカラムであることを示します。
"""
NOT_NULL = 4
"""NOT NULL制約を持つカラムであることを示します。
"""
class IndexType(IntEnum):
"""Containerに設定する索引の種別を示します。
DEFAULTが指定された場合、以下の基準に従い、デフォルト種別の索引が選択されます。
.. csv-table::
:header: "カラム型", "コレクションコンテナ", "時系列コンテナ"
STRING, TREE, TREE
BOOL, TREE, TREE
Numeric type, TREE, TREE
TIMESTAMP, TREE, TREE
GEOMETRY, SPATIAL, 設定不可
BLOB, 設定不可, 設定不可
"""
DEFAULT = -1
"""デフォルトの索引種別を示します。
"""
TREE = 1
"""ツリー索引を示します。この索引種別は、時系列におけるロウキーと対応するカラムを除く任意の種別のコンテナにおける、STRING/BOOL/BYTE/SHORT/INTEGER/LONG/FLOAT/DOUBLE/TIMESTAMPの型のカラムに対して使用できます。
"""
SPATIAL = 4
"""空間索引を示します。この索引種別は、コレクションにおけるGEOMETRY型のカラムに対してのみ使用できます。時系列コンテナに対して設定することはできません。
"""
@classmethod
def _convert_to_java(self, index_type:object)->JIndexType:
jix_type = None
if index_type == IndexType.DEFAULT:
jix_type = JIndexType.DEFAULT
elif index_type == IndexType.TREE:
jix_type = JIndexType.TREE
elif index_type == IndexType.SPATIAL:
jix_type = JIndexType.SPATIAL
return jix_type
@classmethod
def _convert_to_python(self, jindex_type:object)->object:
pyix_type = None
if jindex_type == JIndexType.DEFAULT:
pyix_type = IndexType.DEFAULT
elif jindex_type == JIndexType.TREE:
pyix_type = IndexType.TREE
elif jindex_type == JIndexType.SPATIAL:
pyix_type = IndexType.SPATIAL
return pyix_type
class ContainerType(IntEnum):
"""コンテナの種別を表します。
"""
COLLECTION = 0
"""コレクションコンテナ
"""
TIME_SERIES = 1
"""時系列コンテナ
"""
@classmethod
def _convert_to_java(self, pytype:object)->JContainerType:
jcon_type = None
if pytype == self.COLLECTION:
jcon_type = JContainerType.COLLECTION
elif pytype == self.TIME_SERIES:
jcon_type = JContainerType.TIME_SERIES
return jcon_type
@classmethod
def _convert_to_python(self, jtype:object)->object:
con_type = None
if jtype == JContainerType.COLLECTION:
con_type = self.COLLECTION
elif jtype == JContainerType.TIME_SERIES:
con_type = self.TIME_SERIES
return con_type
class util(object):
""" 内部処理用クラス
"""
@classmethod
def _conavert_to_python(self, jtype:object, value:any, time_unit:object)->any:
rc = None
if value is None:
rc = None
elif jtype == JType.BLOB:
rc = bytearray(value.getBytes(1, jpype.types.JInt(value.length())))
elif jtype == JType.BOOL:
rc = bool(value)
elif jtype == JType.BYTE:
rc = int(value)
elif jtype == JType.DOUBLE:
rc = float(value)
elif jtype == JType.FLOAT:
rc = float(value)
elif jtype == JType.GEOMETRY:
rc = str(value.toString())
elif jtype == JType.INTEGER:
rc = int(value)
elif jtype == JType.LONG:
rc = int(value)
elif jtype == JType.SHORT:
rc = int(value)
elif jtype == JType.STRING:
rc = str(value)
elif jtype == JType.TIMESTAMP:
if time_unit == JTimeUnit.MICROSECOND:
sec = value.getTime() // 1000
usec = value.getNanos() //1000
rc = datetime.utcfromtimestamp(sec) + timedelta(microseconds=usec)
elif time_unit == JTimeUnit.NANOSECOND:
rc = value
else:
rc = datetime.utcfromtimestamp(value.getTime() /1000)
elif jtype in [
JType.BOOL_ARRAY,
JType.BYTE_ARRAY,
JType.DOUBLE_ARRAY,
JType.FLOAT_ARRAY,
JType.INTEGER_ARRAY,
JType.LONG_ARRAY,
JType.SHORT_ARRAY,
JType.STRING_ARRAY,
JType.TIMESTAMP_ARRAY,
]:
rc = None
else:
raise GSException(f"Unsupported data type. GSType:{jtype}")
return rc
@classmethod
def get_list(self, jrow:object)->list:
jcon_info = jrow.getSchema()
rc_list = []
for col_no in range(jcon_info.getColumnCount()):
jcol_info = jcon_info.getColumnInfo(col_no)
jtype = jcol_info.getType()
value = jrow.getValue(col_no)
time_unit = None
if jtype == JType.TIMESTAMP:
time_unit = jcol_info.getTimePrecision()
rc = self._conavert_to_python(jtype, value, time_unit)
rc_list.append(rc)
return rc_list
@classmethod
def get_list_predicate(self, jrkp:object, data_list:list)->list:
jcon_info = jrkp.getKeySchema()
rc_list = []
for col_no in range(jcon_info.getColumnCount()):
jcol_info = jcon_info.getColumnInfo(col_no)
jtype = jcol_info.getType()
value = data_list[col_no]
time_unit = None
if jtype == JType.TIMESTAMP:
time_unit = jcol_info.getTimePrecision()
rc = self._conavert_to_python(jtype, value, time_unit)
rc_list.append(rc)
return rc_list
@classmethod
def get_key_list(self, jcon_info:object, key_list:list)->list:
rc_list = []
if len(key_list) > jcon_info.getColumnCount():
raise GSException("The number of entries in the specified list is exceeded.")
for col_no, value in enumerate(key_list):
jcol_info = jcon_info.getColumnInfo(col_no)
jtype = jcol_info.getType()
time_unit = None
if jtype == JType.TIMESTAMP:
time_unit = jcol_info.getTimePrecision()
rc = self._conavert_to_python(jtype, value, time_unit)
rc_list.append(rc)
return rc_list
@classmethod
def convert_data(self, jcon_info:JContainerInfo, col_no:int, value:any)->object:
jcol_info = jcon_info.getColumnInfo(col_no)
gs_type = jcol_info.getType()
rc = None
if value is None:
rc = None
elif gs_type == JType.BLOB:
if isinstance(value, bytearray):
rc = SerialBlob(jpype.JArray(jpype.types.JByte)(value))
else:
raise GSException(f"Unsupported data type. GSType:{gs_type} specifiedType:{type(value)}")
elif gs_type == JType.BOOL:
if isinstance(value, bool):
rc = jpype.types.JBoolean(value)
else:
raise GSException(f"Unsupported data type. GSType:{gs_type} specifiedType:{type(value)}")
elif gs_type == JType.BYTE:
if type(value) == int:
rc = jpype.types.JByte(value)
else:
raise GSException(f"Unsupported data type. GSType:{gs_type} specifiedType:{type(value)}")
elif gs_type == JType.SHORT:
if type(value) == int:
rc = jpype.types.JShort(value)
else:
raise GSException(f"Unsupported data type. GSType:{gs_type} specifiedType:{type(value)}")
elif gs_type == JType.INTEGER:
if type(value) == int:
rc = jpype.types.JInt(value)
else:
raise GSException(f"Unsupported data type. GSType:{gs_type} specifiedType:{type(value)}")
elif gs_type == JType.LONG:
if type(value) == int:
rc = jpype.types.JLong(value)
else:
raise GSException(f"Unsupported data type. GSType:{gs_type} specifiedType:{type(value)}")
elif gs_type == JType.FLOAT:
if isinstance(value, float):
rc = jpype.types.JFloat(value)
elif type(value) == int:
rc = jpype.types.JFloat(value)
else:
raise GSException(f"Unsupported data type. GSType:{gs_type} specifiedType:{type(value)}")
elif gs_type == JType.DOUBLE:
if isinstance(value, float):
rc = jpype.types.JDouble(value)
elif type(value) == int:
rc = jpype.types.JDouble(value)
else:
raise GSException(f"Unsupported data type. GSType:{gs_type} specifiedType:{type(value)}")
elif gs_type == JType.TIMESTAMP:
time_unit = jcol_info.getTimePrecision()
if time_unit in [JTimeUnit.MICROSECOND, JTimeUnit.NANOSECOND]:
if isinstance(value, Timestamp):
rc = value
elif isinstance(value, datetime):
msec = int(value.timestamp() * 1000)
timestamp = Timestamp(msec)
if time_unit == JTimeUnit.MICROSECOND:
usec = value.microsecond
timestamp.setNanos(usec * 1000)
elif time_unit == JTimeUnit.NANOSECOND:
nano = int(value.timestamp() * 1e9)
timestamp.setNanos(nano % 1000000000)
rc = timestamp
else:
raise GSException(f"Unsupported data type. GSType:{gs_type} specifiedType:{type(value)}")
else:
if isinstance(value, datetime):
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
rc = JDate(int(value.timestamp() * 1000))
elif isinstance(value, Timestamp):
rc = value
elif isinstance(value, JDate):
rc = datetime.utcfromtimestamp(value.getTime() / 1000)
else:
raise GSException(f"Unsupported data type. GSType:{gs_type} specifiedType:{type(value)}")
elif gs_type == JType.STRING:
if isinstance(value, str):
rc = value
elif isinstance(value, JString):
rc = str(value)
else:
raise GSException(f"Unsupported data type. GSType:{gs_type} specifiedType:{type(value)}")
elif gs_type == JType.GEOMETRY:
if isinstance(value, str):
rc = JGeometry.valueOf(value)
else:
raise GSException(f"Unsupported data type. GSType:{gs_type} specifiedType:{type(value)}")
else:
raise GSException(f"Unsupported data type. GSType:{gs_type} specifiedType:{type(value)}")
return rc
@classmethod
def check_type(self, value:any, actual_type_list:any):
if value is not None:
safe = False
if isinstance(actual_type_list, list):
for actual_type in actual_type_list:
if actual_type == int:
if type(value) == actual_type:
safe = True
break
else:
if isinstance(value, actual_type):
safe = True
break
else:
if actual_type_list == int:
if type(value) == actual_type_list:
safe = True
else:
if isinstance(value, actual_type_list):
safe = True
if not safe:
specified_type = type(value)
raise GSException(f"Specified type unmatched (specifiedType={specified_type}, actualType={actual_type_list})")
class AggregationResult(object):
"""集計演算の結果を保持します。
保持する型は、集計演算の種別や集計対象のカラムの型によって決定されます。具体的な規則はTQLの仕様を参照してください。
取り出しできる型は、保持されている型によって決まります。保持されている型が数値型の場合はfloat型またはint型、TIMESTAMP型の場合はdatetime型またはTimestamp型の値としてのみ取り出しできます。
"""
def __init__(self, jaggregationResult:object, jcontainer_info):
"""_summary_
Args:
jaggregationResult (_type_): _description_
"""
self._jar = jaggregationResult
self._jcon_info = jcontainer_info
def get(self, type:object)->any:
"""指定した型で集計値を取得します。
指定可能な型はLONG、DOUBLE、TIMESTAMP。
TIMESTAMP型でナノ秒精度の場合はdatatime型ではなく、Timestamp型で返します。
パラメータ:
type (Type): カラム型
返り値:
集計値
"""
rc = None
try:
if type == Type.DOUBLE:
rc = self._jar.getDouble()
elif type == Type.LONG:
rc = self._jar.getLong()
elif type == Type.TIMESTAMP:
jcol_info = self._jcon_info.getColumnInfo(0)
if jcol_info.getTimePrecision() in [JTimeUnit.MICROSECOND, JTimeUnit.NANOSECOND]:
rc = self._jar.getPreciseTimestamp()
else:
rc = self._jar.getTimestamp()
return rc
except Exception as ex:
raise GSException("An exception occurred in GridDB python API", ex)
class IndexInfo(object):
"""索引に関する情報を表します。
"""
def __init__(self, column_name_list:list=None, name:str=None, type=IndexType.DEFAULT):
"""コンストラクタ
パラメータ:
column_name_list (list[str]): カラム名の一覧
name (str): 索引名
type (IndexType): 索引種別
"""
util.check_type(column_name_list, list)
util.check_type(name, str)
util.check_type(type, IndexType)
try:
jcol_list = ArrayList()
for column_name in column_name_list:
jcol_list.add(column_name)
self._jix_info = JIndexInfo.createByColumnList(jcol_list, IndexType._convert_to_java(type))
if name is not None:
self._jix_info.setName(name)
except Exception as ex:
raise GSException("An exception occurred in GridDB python API", ex)
@property
def column_name_list(self)->list:
"""カラム名の一覧
"""
try:
if self._jix_info is None:
return None
else:
rc_list = []
for col in self._jix_info.getColumnNameList():
rc_list.append(col)
return rc_list
except Exception as ex:
raise GSException("An exception occurred in GridDB python API", ex)
@property
def name(self)->str:
"""索引名
"""
try:
if self._jix_info is None:
return None
else:
return_name = self._jix_info.getName()
if return_name is None:
return return_name
else:
return str(return_name)
except Exception as ex:
raise GSException("An exception occurred in GridDB python API", ex)
@property
def type(self)->object:
"""索引種別
"""
try:
if self._jix_info is None:
return None
else:
return IndexType._convert_to_python(self._jix_info.getType())
except Exception as ex:
raise GSException("An exception occurred in GridDB python API", ex)
class Container(object):
"""同一タイプのロウ集合からなるGridDBの構成要素に対しての、管理機能を提供します。
GridDB上のスキーマを構成する各カラムは、ロウオブジェクト内のフィールドやメソッド定義と対応関係を持ちます。 1つのコンテナは1つ以上のカラムにより構成されます。
カラム名の文字種や長さ、カラム数には制限があります。
また、フィールドの値の表現範囲やサイズにも制限があります。
詳細は機能リファレンスの「システムの制限値」をご覧ください。
GridDB上のロウにおけるNULLは、NOT NULL制約が設定されていない限り保持することができます。
PythonではNoneとして入出力できます。
トランザクション処理では、デフォルトで自動コミットモードが有効になっています。自動コミットモードでは、変更操作は逐次確定し、明示的に取り消すことができません。手動コミットモードにおいて、このオブジェクトを介した操作によりクラスタノード上でエラーが検出されGSExceptionが送出された場合、コミット前の更新操作はすべて取り消されます。トランザクション分離レベルはREAD COMMITTEDのみをサポートします。ロック粒度は、コンテナの種別によって異なります。
このContainerの生成後またはトランザクション終了後、最初にロウの更新・追加・削除、ならびに更新用ロック獲得が行われた時点で、新たなトランザクションが開始されます。
"""
def __init__(self, jstore:object, jcon:object):
"""_summary_
Args:
container (object): _description_
"""
self._jstore = jstore
self._jcon = jcon
def abort(self):
"""手動コミットモードにおいて、現在のトランザクションの操作結果を元に戻し、トランザクションを終了します。
"""
try:
self._jcon.abort()
except Exception as ex:
raise GSException("An exception occurred in GridDB python API", ex)
def close(self):
"""クローズします。
"""
try:
self._jcon.close()
except Exception as ex:
raise GSException("An exception occurred in GridDB python API", ex)
def commit(self):
"""手動コミットモードにおいて、現在のトランザクションにおける操作結果を確定させ、トランザクションを終了します。
"""
try:
self._jcon.commit()
except Exception as ex:
raise GSException("An exception occurred in GridDB python API", ex)
@singledispatchmethod
def create_index(self, arg, index_type, name):
"""索引を作成します。
argにカラム名、index_typeに索引種別、nameに索引名を指定することで単一カラムの索引を作成します。
argに索引情報(IndexInfoオブジェクト)を指定することで複合索引を作成します。
時系列のロウキー(TIMESTAMP型)には索引を設定できません。
第一パラメータ(arg)にキーワードパラメータを使うことはできません。
パラメータ:
arg (str, IndexInfo): カラム名もしくは索引情報
index_type (IndexType): 索引種別
name (str): 索引名
"""
raise GSException("arg is invalid.")
@create_index.register
def _(self, arg:str,
index_type:IndexType=IndexType.DEFAULT,
name:str=None):
""" インデックス名を指定したcreate_index()
"""
# argのインスタンスをチェックする。
util.check_type(arg, str)
util.check_type(index_type, IndexType)
util.check_type(name, str)
try:
jix_info = JIndexInfo.createByColumn(arg, IndexType._convert_to_java(index_type))
if name is not None:
jix_info.setName(name)
self._jcon.createIndex(jix_info)
except Exception as ex:
raise GSException("An exception occurred in GridDB python API", ex)
@create_index.register
def _(self, arg:IndexInfo,
index_type:IndexType=IndexType.DEFAULT,
name:str=None):
""" IndexInfoを指定したcreate_index()
"""
# argのインスタンスをチェックする。
util.check_type(arg, IndexInfo)
util.check_type(index_type, IndexType)
util.check_type(name, str)
jix_info = arg._jix_info
# 指定されたIndexInfoと指定されたIndexTypeの一致を確認
if IndexType._convert_to_python(jix_info.getType()) != index_type:
raise GSException("index_type does not match arg content.")
# 指定されたIndexInfoと指定されたnameの一致を確認
if (name is not None) and (str(jix_info.getName()) != name):
raise GSException("name does not match arg content.")
try:
self._jcon.createIndex(jix_info)
except Exception as ex:
raise GSException("An exception occurred in GridDB python API", ex)
@singledispatchmethod
def drop_index(self, arg=None,
index_type:object=IndexType.DEFAULT,
name:str=None):
"""索引を削除します。
argにカラム名、index_typeに索引種別、nameに索引名を指定することで単一カラムの索引を削除します。
argに索引情報(IndexInfoオブジェクト)を指定することで複合索引を削除します。
削除対象となる索引が一つも存在しない場合、索引の削除は行われません。
第一パラメータ(arg)にキーワードパラメータを使うことはできません。
パラメータ:
arg (str, IndexInfo): カラム名もしくは索引情報
index_type (IndexType): 索引種別
name (str): 索引名
"""
raise GSException("arg is invalid.")
@drop_index.register
def _(self, arg:str,
index_type:object=IndexType.DEFAULT,
name:str=None):
# argのインスタンスをチェックする。
util.check_type(arg, str)
util.check_type(index_type, IndexType)
util.check_type(name, str)
# カラム名とインデックスタイプを指定してdropIndexを発行
try:
jix_info = JIndexInfo.createByColumn(arg, IndexType._convert_to_java(index_type))
if name is not None:
jix_info.setName(name)
self._jcon.dropIndex(jix_info)
except Exception as ex:
raise GSException("An exception occurred in GridDB python API", ex)
@drop_index.register
def _(self, arg:object,
index_type:object=IndexType.DEFAULT,
name:str=None):
util.check_type(arg, IndexInfo)
util.check_type(index_type, IndexType)
util.check_type(name, str)
jix_info = arg._jix_info
try:
# 指定されたIndexInfoと指定されたnameの一致を確認
if name is not None and str(jix_info.getName()) != name:
raise GSException("name does not match arg content.")
self._jcon.dropIndex(jix_info)
except Exception as ex:
raise GSException("An exception occurred in GridDB python API", ex)
def flush(self):
"""これまでの更新結果をSSDなどの不揮発性記憶媒体に書き出し、すべてのクラスタノードが突然停止したとしても内容が失われないようにします。
通常より信頼性が要求される処理のために使用します。ただし、頻繁に実行すると性能低下を引き起こす可能性が高まります。
書き出し対象のクラスタノードの範囲など、挙動の詳細はGridDB上の設定によって変化します。
"""
try:
self._jcon.flush()
except Exception as ex:
raise GSException("An exception occurred in GridDB python API", ex)
def get(self, key:any)->list:
"""指定のロウキーに対応するロウの内容を取得します。
パラメータ:
key (int, str, datetime, Timestamp, RowKey): ロウキー
返り値:
ロウの内容と対応するlist形式のロウオブジェクト (list)
"""
try:
util.check_type(key, [int, str, datetime, Timestamp, RowKey])
if isinstance(key, RowKey):
jrow = self._jcon.get(key._jrk)
else:
con_jrow = self._jcon.createRow()
jcon_info = con_jrow.getSchema()
if not jcon_info.isRowKeyAssigned():
raise GSException("key is not defined correctly.")
jrow = self._jcon.get(util.convert_data(jcon_info, 0, key))
if jrow is None:
return None
else:
return util.get_list(jrow)
except Exception as ex:
raise GSException("An exception occurred in GridDB python API", ex)
@singledispatchmethod
def multi_put(self, row_list, row_allocator=None):
"""指定のロウオブジェクト集合(もしくはRecordBatchオブジェクト)に基づき、任意個数のロウをまとめて新規作成または更新します。
手動コミットモードの場合、対象のロウはロックされます。
row_listにArrow形式のRecordBatchオブジェクトを指定した場合はroot_allocatorにRootAllocatorオブジェクトを指定する必要があります。
第一パラメータ(row_list)にキーワードパラメータを使うことはできません。
パラメータ:
row_list (list, RecordBatch): list形式のロウオブジェクト、もしくはRecordBatchオブジェクト
root_allocator (RootAllocator): RootAllocatorオブジェクト
"""
raise GSException("row_list value specified is incorrect.")
@multi_put.register
def _(self, row_list:list, root_allocator:object=None):
""" row_listにlistを指定されたときのmulti_put()
"""
# row_listのデータ型をチェックする
util.check_type(row_list, list)
try:
jrow_list = ArrayList()
for row in row_list:
jrow = self._jcon.createRow()
jcon_info = jrow.getSchema()
for col_no, col in enumerate(row):
value = util.convert_data(jcon_info, col_no, col)
jrow.setValue(col_no, value)
jrow_list.add(jrow)
self._jcon.put(jrow_list)
except Exception as ex:
raise GSException("An exception occurred in GridDB python API", ex)
@multi_put.register
def _(self, row_list:object, root_allocator:object=None):
""" RecordBatchを指定されたときのmulti_put()
"""
# row_listのデータ型をチェックする
util.check_type(row_list, pyarrow.lib.RecordBatch)
util.check_type(root_allocator, RootAllocator)
if root_allocator is None:
raise GSException("Error in root_allocator specification.")
root = root_allocator
try:
c_schema = c.ArrowSchema.allocateNew(root_allocator)
c_array = c.ArrowArray.allocateNew(root_allocator)
row_list._export_to_c(c_array.memoryAddress(), c_schema.memoryAddress())
sc_root = c.Data.importVectorSchemaRoot(root_allocator, c_array, c_schema, None)
binder = JavaAPIParameterBinder.builder(self._jcon, sc_root).bindAll().build()
self._jcon.put(binder.getList())
except Exception as ex:
raise GSException("An exception occurred in GridDB python API", ex)
def put(self, row:list)->bool:
"""ロウを新規作成または更新します。
ロウキーに対応するカラムが存在する場合、ロウキーとコンテナの状態を基に、ロウを新規作成するか、更新するかを決定します。この際、対応するロウがコンテナ内に存在しない場合は新規作成、存在する場合は更新します。
ロウキーに対応するカラムを持たない場合、常に新規のロウを作成します。
手動コミットモードの場合、対象のロウがロックされます。
パラメータ:
row (list): 新規作成または更新するロウの内容と対応するlist形式のロウオブジェクト
返り値:
ロウキーと一致するロウが存在したかどうか (bool)
"""
# rowの値ををJavaのArrayList[Rowオブジェクト]に変換
util.check_type(row, list)
try:
jrow = self._jcon.createRow()
jcon_info = jrow.getSchema()
for col_no, col in enumerate(row):
value = util.convert_data(jcon_info, col_no, col)
jrow.setValue(col_no, value)
return self._jcon.put(jrow)
except Exception as ex:
raise GSException("An exception occurred in GridDB python API", ex)
def query(self, query_string:str)->object:
"""指定のTQL文を実行するためのクエリを作成します。
パラメータ:
query_string (str): TQL文
返り値:
Queryオブジェクト (Query)
"""
util.check_type(query_string, str)
try:
jquery = self._jcon.query(query_string, None)
return Query(jquery)
except Exception as ex:
raise GSException("An exception occurred in GridDB python API", ex)
def remove(self, key:object)->bool:
"""指定のロウキーに対応するロウを削除します。
手動コミットモードの場合、対象のロウはロックされます。
パラメータ:
key (int, str, datetime, Timestamp, RowKey): ロウキー
返り値:
対応するロウが存在したかどうか (bool)
"""
util.check_type(key, [int, str, datetime, Timestamp, RowKey])
try:
if isinstance(key, RowKey):
self._jcon.remove(key._jrow)
else:
con_jrow = self._jcon.createRow()
jcon_info = con_jrow.getSchema()
if not jcon_info.isRowKeyAssigned():
raise GSException("key is not defined correctly.")
return self._jcon.remove(util.convert_data(jcon_info, 0, key))
except Exception as ex:
raise GSException("An exception occurred in GridDB python API", ex)
def set_auto_commit(self, enabled:bool):
"""コミットモードの設定を変更します。
自動コミットモードでは、直接トランザクション状態を制御できず、変更操作が逐次コミットされます。自動コミットモードが有効でない場合、すなわち手動コミットモードの場合は、直接commit()を呼び出すかトランザクションがタイムアウトしない限り、このコンテナ内で同一のトランザクションが使用され続け、変更操作はコミットされません。
自動コミットモードが無効から有効に切り替わる際、未コミットの変更内容は暗黙的にコミットされます。コミットモードに変更がない場合、トランザクション状態は変更されません。