-
-
Notifications
You must be signed in to change notification settings - Fork 35
/
_import.py
executable file
·1728 lines (1483 loc) · 59.3 KB
/
_import.py
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
#!/usr/bin/env python
# Copyright 2018 RethinkDB
#
# 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.
#
# This file incorporates work covered by the following copyright:
# Copyright 2010-2016 RethinkDB, all rights reserved.
"""`rethinkdb import` loads data into a RethinkDB cluster"""
from __future__ import print_function
import codecs
import collections
import csv
import ctypes
import json
import multiprocessing
import optparse
import os
import signal
import sys
import time
import traceback
from multiprocessing.queues import Queue, SimpleQueue
import six
from rethinkdb import ast, errors, query, utils_common
from rethinkdb.logger import default_logger
try:
unicode
except NameError:
unicode = str
try:
from Queue import Empty, Full
except ImportError:
from queue import Empty, Full
# json parameters
JSON_READ_CHUNK_SIZE = 128 * 1024
JSON_MAX_BUFFER_SIZE = 128 * 1024 * 1024
MAX_NESTING_DEPTH = 100
Error = collections.namedtuple("Error", ["message", "traceback", "file"])
class SourceFile(object):
format = None # set by subclasses
name = None
db = None
table = None
primary_key = None
indexes = None
write_hook = None
source_options = None
start_time = None
end_time = None
query_runner = None
_source = None # open filehandle for the source
# - internal synchronization variables
_bytes_size = None
_bytes_read = None # -1 until started
_total_rows = None # -1 until known
_rows_read = None
_rows_written = None
def __init__(
self,
source,
db,
table,
query_runner,
primary_key=None,
indexes=None,
write_hook=None,
source_options=None,
):
if self.format is None:
raise AssertionError(
"{class_name} must have a format".format(
class_name=self.__class__.__name__
)
)
if self.db == "rethinkdb":
raise AssertionError("Can not import tables into the system database")
# query_runner
if not isinstance(query_runner, utils_common.RetryQuery):
raise AssertionError("Query runner is not instance of RetryQuery")
self.query_runner = query_runner
# reporting information
self._bytes_size = multiprocessing.Value(ctypes.c_longlong, -1)
self._bytes_read = multiprocessing.Value(ctypes.c_longlong, -1)
self._total_rows = multiprocessing.Value(ctypes.c_longlong, -1)
self._rows_read = multiprocessing.Value(ctypes.c_longlong, 0)
self._rows_written = multiprocessing.Value(ctypes.c_longlong, 0)
# source
if hasattr(source, "read"):
if unicode != str or "b" in source.mode:
# Python2.x or binary file, assume utf-8 encoding
self._source = codecs.getreader("utf-8")(source)
else:
# assume that it has the right encoding on it
self._source = source
else:
try:
self._source = codecs.open(source, mode="r", encoding="utf-8")
except IOError as exc:
default_logger.exception(exc)
raise ValueError(
'Unable to open source file "%s": %s' % (str(source), str(exc))
)
if (
hasattr(self._source, "name")
and self._source.name
and os.path.isfile(self._source.name)
):
self._bytes_size.value = os.path.getsize(source)
if self._bytes_size.value == 0:
raise ValueError("Source is zero-length: %s" % source)
# table info
self.db = db
self.table = table
self.primary_key = primary_key
self.indexes = indexes or []
self.write_hook = write_hook or []
# options
self.source_options = source_options or {
"create_args": {"primary_key": self.primary_key}
}
# name
if hasattr(self._source, "name") and self._source.name:
self.name = os.path.basename(self._source.name)
else:
self.name = "%s.%s" % (self.db, self.table)
def __hash__(self):
return hash((self.db, self.table))
def get_line(self):
"""Returns a single line from the file"""
raise NotImplementedError(
"This needs to be implemented on the %s subclass" % self.format
)
# - bytes
@property
def bytes_size(self):
return self._bytes_size.value
@bytes_size.setter
def bytes_size(self, value):
self._bytes_size.value = value
@property
def bytes_read(self):
return self._bytes_read.value
@bytes_read.setter
def bytes_read(self, value):
self._bytes_read.value = value
# - rows
@property
def total_rows(self):
return self._total_rows.value
@total_rows.setter
def total_rows(self, value):
self._total_rows.value = value
@property
def rows_read(self):
return self._rows_read.value
@rows_read.setter
def rows_read(self, value):
self._rows_read.value = value
@property
def rows_written(self):
return self._rows_written.value
def add_rows_written(self, increment): # we have multiple writers to coordinate
with self._rows_written.get_lock():
self._rows_written.value += increment
# - percent done
@property
def percent_done(self):
"""return a float between 0 and 1 for a reasonable guess of percentage complete"""
# assume that reading takes 50% of the time and writing the other 50%
completed = 0.0 # of 2.0
# - add read percentage
if (
self._bytes_size.value <= 0
or self._bytes_size.value <= self._bytes_read.value
):
completed += 1.0
elif self._bytes_read.value < 0 and self._total_rows.value >= 0:
# done by rows read
if self._rows_read > 0:
completed += float(self._rows_read) / float(self._total_rows.value)
else:
# done by bytes read
if self._bytes_read.value > 0:
completed += float(self._bytes_read.value) / float(
self._bytes_size.value
)
# - add written percentage
if self._rows_read.value or self._rows_written.value:
total_rows = float(self._total_rows.value)
if total_rows == 0:
completed += 1.0
elif total_rows < 0:
# a guesstimate
per_row_size = float(self._bytes_read.value) / float(
self._rows_read.value
)
total_rows = float(self._rows_read.value) + (
float(self._bytes_size.value - self._bytes_read.value)
/ per_row_size
)
completed += float(self._rows_written.value) / total_rows
else:
# accurate count
completed += float(self._rows_written.value) / total_rows
# - return the value
return completed * 0.5
def setup_table(self):
"""Ensure that the db, table, and indexes exist and are correct"""
# - ensure the table exists and is ready
self.query_runner(
"create table: %s.%s" % (self.db, self.table),
ast.expr([self.table])
.set_difference(query.db(self.db).table_list())
.for_each(
query.db(self.db).table_create(
query.row,
**self.source_options["create_args"]
if "create_args" in self.source_options
else {}
)
),
)
self.query_runner(
"wait for %s.%s" % (self.db, self.table),
query.db(self.db).table(self.table).wait(timeout=30),
)
# - ensure that the primary key on the table is correct
primary_key = self.query_runner(
"primary key %s.%s" % (self.db, self.table),
query.db(self.db).table(self.table).info()["primary_key"],
)
if self.primary_key is None:
self.primary_key = primary_key
elif primary_key != self.primary_key:
raise RuntimeError(
"Error: table %s.%s primary key was `%s` rather than the expected: %s"
% (self.db, self.table, primary_key, self.primary_key)
)
def restore_indexes(self, warning_queue):
# recreate secondary indexes - dropping existing on the assumption they are wrong
if self.indexes:
existing_indexes = self.query_runner(
"indexes from: %s.%s" % (self.db, self.table),
query.db(self.db).table(self.table).index_list(),
)
try:
created_indexes = []
for index in self.indexes:
if index["index"] in existing_indexes: # drop existing versions
self.query_runner(
"drop index: %s.%s:%s"
% (self.db, self.table, index["index"]),
query.db(self.db)
.table(self.table)
.index_drop(index["index"]),
)
self.query_runner(
"create index: %s.%s:%s"
% (self.db, self.table, index["index"]),
query.db(self.db)
.table(self.table)
.index_create(index["index"], index["function"]),
)
created_indexes.append(index["index"])
# wait for all of the created indexes to build
self.query_runner(
"waiting for indexes on %s.%s" % (self.db, self.table),
query.db(self.db)
.table(self.table)
.index_wait(query.args(created_indexes)),
)
except RuntimeError:
exception_type, exception_class, trcback = sys.exc_info()
warning_queue.put(
(
exception_type,
exception_class,
traceback.extract_tb(trcback),
self._source.name,
)
)
if self.write_hook:
self.query_runner(
"Write hook from: %s.%s" % (self.db, self.table),
query.db(self.db).table(self.table).get_write_hook(),
)
try:
self.query_runner(
"drop hook: %s.%s" % (self.db, self.table),
query.db(self.db).table(self.table).set_write_hook(None),
)
self.query_runner(
"create hook: %s.%s:%s" % (self.db, self.table, self.write_hook),
query.db(self.db)
.table(self.table)
.set_write_hook(self.write_hook["function"]),
)
except RuntimeError:
exception_type, exception_class, trcback = sys.exc_info()
warning_queue.put(
(
exception_type,
exception_class,
traceback.extract_tb(trcback),
self._source.name,
)
)
def batches(self, batch_size=None, warning_queue=None):
# setup table
self.setup_table()
# default batch_size
if batch_size is None:
batch_size = utils_common.default_batch_size
else:
batch_size = int(batch_size)
if batch_size <= 0:
raise AssertionError("Batch size can not be less than one")
# setup
self.setup_file(warning_queue=warning_queue)
# - yield batches
batch = []
try:
need_more_data = False
while True:
if need_more_data:
self.fill_buffer()
need_more_data = False
while len(batch) < batch_size:
try:
row = self.get_line()
# ToDo: validate the line
batch.append(row)
except NeedMoreData:
need_more_data = True
break
else:
yield batch
batch = []
except StopIteration as e:
# yield any final batch
if batch:
yield batch
# - check the end of the file
self.teardown()
# - rebuild indexes
if self.indexes:
self.restore_indexes(warning_queue)
def setup_file(self, warning_queue=None):
raise NotImplementedError("Subclasses need to implement this")
def teardown(self):
pass
def read_to_queue(
self,
work_queue,
exit_event,
error_queue,
warning_queue,
timing_queue,
fields=None,
ignore_signals=True,
batch_size=None,
):
if (
ignore_signals
): # ToDo: work out when we are in a worker process automatically
signal.signal(signal.SIGINT, signal.SIG_IGN) # workers should ignore these
if batch_size is None:
batch_size = utils_common.default_batch_size
self.start_time = time.time()
try:
timePoint = time.time()
for batch in self.batches(warning_queue=warning_queue):
timing_queue.put(("reader_work", time.time() - timePoint))
timePoint = time.time()
# apply the fields filter
if fields:
for row in batch:
for key in [x for x in row.keys() if x not in fields]:
del row[key]
while not exit_event.is_set():
try:
work_queue.put((self.db, self.table, batch), timeout=0.1)
self._rows_read.value += len(batch)
break
except Full:
pass
else:
break
timing_queue.put(("reader_wait", time.time() - timePoint))
timePoint = time.time()
# - report relevant errors
except Exception as exc:
default_logger.exception(exc)
error_queue.put(Error(str(exc), traceback.format_exc(), self.name))
exit_event.set()
raise
finally:
self.end_time = time.time()
class NeedMoreData(Exception):
pass
class JsonSourceFile(SourceFile):
format = "json"
decoder = json.JSONDecoder()
json_array = None
found_first = False
_buffer_size = JSON_READ_CHUNK_SIZE
_buffer_str = None
_buffer_pos = None
_buffer_end = None
def fill_buffer(self):
if self._buffer_str is None:
self._buffer_str = ""
self._buffer_pos = 0
self._buffer_end = 0
elif self._buffer_pos == 0:
# double the buffer under the assumption that the documents are too large to fit
if self._buffer_size == JSON_MAX_BUFFER_SIZE:
raise Exception(
"Error: JSON max buffer size exceeded on file %s (from position %d). Use '--max-document-size' to "
"extend your buffer." % (self.name, self.bytes_processed)
)
self._buffer_size = min(self._buffer_size * 2, JSON_MAX_BUFFER_SIZE)
# add more data
read_target = self._buffer_size - self._buffer_end + self._buffer_pos
if read_target < 1:
raise AssertionError("Can not set the read target and full the buffer")
new_chunk = self._source.read(read_target)
if len(new_chunk) == 0:
raise StopIteration() # file ended
self._buffer_str = self._buffer_str[self._buffer_pos :] + new_chunk
self._bytes_read.value += len(new_chunk)
# reset markers
self._buffer_pos = 0
self._buffer_end = len(self._buffer_str) - 1
def get_line(self):
"""Return a line from the current _buffer_str, or raise NeedMoreData trying"""
# advance over any whitespace
self._buffer_pos = json.decoder.WHITESPACE.match(
self._buffer_str, self._buffer_pos
).end()
if self._buffer_pos >= self._buffer_end:
raise NeedMoreData()
# read over a comma if we are not the first item in a json_array
if (
self.json_array
and self.found_first
and self._buffer_str[self._buffer_pos] == ","
):
self._buffer_pos += 1
if self._buffer_pos >= self._buffer_end:
raise NeedMoreData()
# advance over any post-comma whitespace
self._buffer_pos = json.decoder.WHITESPACE.match(
self._buffer_str, self._buffer_pos
).end()
if self._buffer_pos >= self._buffer_end:
raise NeedMoreData()
# parse and return an object
try:
row, self._buffer_pos = self.decoder.raw_decode(
self._buffer_str, idx=self._buffer_pos
)
self.found_first = True
return row
except (ValueError, IndexError):
raise NeedMoreData()
def setup_file(self, warning_queue=None):
# - move to the first record
# advance through any leading whitespace
while True:
self.fill_buffer()
self._buffer_pos = json.decoder.WHITESPACE.match(self._buffer_str, 0).end()
if self._buffer_pos == 0:
break
# check the first character
try:
if self._buffer_str[0] == "[":
self.json_array = True
self._buffer_pos = 1
elif self._buffer_str[0] == "{":
self.json_array = False
else:
raise ValueError(
"Error: JSON format not recognized - file does not begin with an object or array"
)
except IndexError:
raise ValueError("Error: JSON file was empty of content")
def teardown(self):
# - check the end of the file
# note: fill_buffer should have guaranteed that we have only the data in the end
# advance through any leading whitespace
self._buffer_pos = json.decoder.WHITESPACE.match(
self._buffer_str, self._buffer_pos
).end()
# check the end of the array if we have it
if self.json_array:
if self._buffer_str[self._buffer_pos] != "]":
snippit = self._buffer_str[self._buffer_pos :]
extra = (
""
if len(snippit) <= 100
else " and %d more characters" % (len(snippit) - 100)
)
raise ValueError(
"Error: JSON array did not end cleanly, rather with: <<%s>>%s"
% (snippit[:100], extra)
)
self._buffer_pos += 1
# advance through any trailing whitespace
self._buffer_pos = json.decoder.WHITESPACE.match(
self._buffer_str, self._buffer_pos
).end()
snippit = self._buffer_str[self._buffer_pos :]
if len(snippit) > 0:
extra = (
""
if len(snippit) <= 100
else " and %d more characters" % (len(snippit) - 100)
)
raise ValueError(
"Error: extra data after JSON data: <<%s>>%s" % (snippit[:100], extra)
)
class CsvSourceFile(SourceFile):
format = "csv"
no_header_row = False
custom_header = None
_reader = None # instance of csv.reader
_columns = None # name of the columns
def __init__(self, *args, **kwargs):
if "source_options" in kwargs and isinstance(kwargs["source_options"], dict):
if "no_header_row" in kwargs["source_options"]:
self.no_header_row = kwargs["source_options"]["no_header_row"]
if "custom_header" in kwargs["source_options"]:
self.custom_header = kwargs["source_options"]["custom_header"]
super(CsvSourceFile, self).__init__(*args, **kwargs)
def byte_counter(self):
"""Generator for getting a byte count on a file being used"""
for line in self._source:
self._bytes_read.value += len(line)
if unicode != str:
yield line.encode(
"utf-8"
) # Python2.x csv module does not really handle unicode
else:
yield line
def setup_file(self, warning_queue=None):
# - setup csv.reader with a byte counter wrapper
self._reader = csv.reader(self.byte_counter())
# - get the header information for column names
if not self.no_header_row:
self._columns = next(self._reader)
# field names may override fields from the header
if self.custom_header is not None:
if not self.no_header_row:
warning_queue.put(
"Ignoring header row on %s: %s" % (self.name, str(self._columns))
)
self._columns = self.custom_header
elif self.no_header_row:
raise ValueError("Error: No field name information available")
def get_line(self):
raw_row = next(self._reader)
if len(self._columns) != len(raw_row):
raise Exception(
"Error: '%s' line %d has an inconsistent number of columns: %s"
% (self.name, self._reader.line_num, str(raw_row))
)
row = {}
for key, value in zip(
self._columns, raw_row
): # note: we import all csv fields as strings
# treat empty fields as no entry rather than empty string
if value == "":
continue
row[key] = value if str == unicode else unicode(value, encoding="utf-8")
return row
# ==
usage = """rethinkdb import -d DIR [-c HOST:PORT] [--tls-cert FILENAME] [-p] [--password-file FILENAME]
[--force] [-i (DB | DB.TABLE)] [--clients NUM]
[--shards NUM_SHARDS] [--replicas NUM_REPLICAS]
rethinkdb import -f FILE --table DB.TABLE [-c HOST:PORT] [--tls-cert FILENAME] [-p] [--password-file FILENAME]
[--force] [--clients NUM] [--format (csv | json)] [--pkey PRIMARY_KEY]
[--shards NUM_SHARDS] [--replicas NUM_REPLICAS]
[--delimiter CHARACTER] [--custom-header FIELD,FIELD... [--no-header]]"""
help_epilog = """
EXAMPLES:
rethinkdb import -d rdb_export -c mnemosyne:39500 --clients 128
Import data into a cluster running on host 'mnemosyne' with a client port at 39500,
using 128 client connections and the named export directory.
rethinkdb import -f site_history.csv --format csv --table test.history --pkey count
Import data into a local cluster and the table 'history' in the 'test' database,
using the named CSV file, and using the 'count' field as the primary key.
rethinkdb import -d rdb_export -c hades -p -i test
Import data into a cluster running on host 'hades' which requires a password,
using only the database 'test' from the named export directory.
rethinkdb import -f subscriber_info.json --fields id,name,hashtag --force
Import data into a local cluster using the named JSON file, and only the fields
'id', 'name', and 'hashtag', overwriting any existing rows with the same primary key.
rethinkdb import -f user_data.csv --delimiter ';' --no-header --custom-header id,name,number
Import data into a local cluster using the named CSV file with no header and instead
use the fields 'id', 'name', and 'number', the delimiter is a semicolon (rather than
a comma).
"""
def parse_options(argv, prog=None):
parser = utils_common.CommonOptionsParser(
usage=usage, epilog=help_epilog, prog=prog
)
parser.add_option(
"--clients",
dest="clients",
metavar="CLIENTS",
default=8,
help="client connections to use (default: 8)",
type="pos_int",
)
parser.add_option(
"--hard-durability",
dest="durability",
action="store_const",
default="soft",
help="use hard durability writes (slower, uses less memory)",
const="hard",
)
parser.add_option(
"--force",
dest="force",
action="store_true",
default=False,
help="import even if a table already exists, overwriting duplicate primary keys",
)
parser.add_option(
"--batch-size",
dest="batch_size",
default=utils_common.default_batch_size,
help=optparse.SUPPRESS_HELP,
type="pos_int",
)
# Replication settings
replication_options_group = optparse.OptionGroup(parser, "Replication Options")
replication_options_group.add_option(
"--shards",
dest="create_args",
metavar="SHARDS",
help="shards to setup on created tables (default: 1)",
type="pos_int",
action="add_key",
)
replication_options_group.add_option(
"--replicas",
dest="create_args",
metavar="REPLICAS",
help="replicas to setup on created tables (default: 1)",
type="pos_int",
action="add_key",
)
parser.add_option_group(replication_options_group)
# Directory import options
dir_import_group = optparse.OptionGroup(parser, "Directory Import Options")
dir_import_group.add_option(
"-d",
"--directory",
dest="directory",
metavar="DIRECTORY",
default=None,
help="directory to import data from",
)
dir_import_group.add_option(
"-i",
"--import",
dest="db_tables",
metavar="DB|DB.TABLE",
default=[],
help="restore only the given database or table (may be specified multiple times)",
action="append",
type="db_table",
)
dir_import_group.add_option(
"--no-secondary-indexes",
dest="indexes",
action="store_false",
default=None,
help="do not create secondary indexes",
)
parser.add_option_group(dir_import_group)
# File import options
file_import_group = optparse.OptionGroup(parser, "File Import Options")
file_import_group.add_option(
"-f",
"--file",
dest="file",
metavar="FILE",
default=None,
help="file to import data from",
type="file",
)
file_import_group.add_option(
"--table",
dest="import_table",
metavar="DB.TABLE",
default=None,
help="table to import the data into",
)
file_import_group.add_option(
"--fields",
dest="fields",
metavar="FIELD,...",
default=None,
help="limit which fields to use when importing one table",
)
file_import_group.add_option(
"--format",
dest="format",
metavar="json|csv",
default=None,
help="format of the file (default: json, accepts newline delimited json)",
type="choice",
choices=["json", "csv"],
)
file_import_group.add_option(
"--pkey",
dest="create_args",
metavar="PRIMARY_KEY",
default=None,
help="field to use as the primary key in the table",
action="add_key",
)
parser.add_option_group(file_import_group)
# CSV import options
csv_import_group = optparse.OptionGroup(parser, "CSV Options")
csv_import_group.add_option(
"--delimiter",
dest="delimiter",
metavar="CHARACTER",
default=None,
help="character separating fields, or '\\t' for tab",
)
csv_import_group.add_option(
"--no-header",
dest="no_header",
action="store_true",
default=None,
help="do not read in a header of field names",
)
csv_import_group.add_option(
"--custom-header",
dest="custom_header",
metavar="FIELD,...",
default=None,
help="header to use (overriding file header), must be specified if --no-header",
)
parser.add_option_group(csv_import_group)
# JSON import options
json_options_group = optparse.OptionGroup(parser, "JSON Options")
json_options_group.add_option(
"--max-document-size",
dest="max_document_size",
metavar="MAX_SIZE",
default=0,
help="maximum allowed size (bytes) for a single JSON document (default: 128MiB)",
type="pos_int",
)
json_options_group.add_option(
"--max-nesting-depth",
dest="max_nesting_depth",
metavar="MAX_DEPTH",
default=0,
help="maximum depth of the JSON documents (default: 100)",
type="pos_int",
)
parser.add_option_group(json_options_group)
options, args = parser.parse_args(argv)
# Check validity of arguments
if len(args) != 0:
raise parser.error(
"No positional arguments supported. Unrecognized option(s): %s" % args
)
# - create_args
if options.create_args is None:
options.create_args = {}
# - options based on file/directory import
if options.directory and options.file:
parser.error("-f/--file and -d/--directory can not be used together")
elif options.directory:
if not os.path.exists(options.directory):
parser.error("-d/--directory does not exist: %s" % options.directory)
if not os.path.isdir(options.directory):
parser.error("-d/--directory is not a directory: %s" % options.directory)
options.directory = os.path.realpath(options.directory)
# disallow invalid options
if options.import_table:
parser.error("--table option is not valid when importing a directory")
if options.fields:
parser.error("--fields option is not valid when importing a directory")
if options.format:
parser.error("--format option is not valid when importing a directory")
if options.create_args:
parser.error("--pkey option is not valid when importing a directory")
if options.delimiter:
parser.error("--delimiter option is not valid when importing a directory")
if options.no_header:
parser.error("--no-header option is not valid when importing a directory")
if options.custom_header:
parser.error(
"table create options are not valid when importing a directory: %s"
% ", ".join(
[x.lower().replace("_", " ") for x in options.custom_header.keys()]
)
)
# check valid options
if not os.path.isdir(options.directory):
parser.error("Directory to import does not exist: %s" % options.directory)
if options.fields and (
len(options.db_tables) > 1 or options.db_tables[0].table is None
):
parser.error(
"--fields option can only be used when importing a single table"
)
elif options.file:
if not os.path.exists(options.file):
parser.error("-f/--file does not exist: %s" % options.file)
if not os.path.isfile(options.file):
parser.error("-f/--file is not a file: %s" % options.file)
options.file = os.path.realpath(options.file)
# format
if options.format is None:
options.format = os.path.splitext(options.file)[1].lstrip(".")
# import_table
if options.import_table:
res = utils_common._tableNameRegex.match(options.import_table)
if res and res.group("table"):
options.import_table = utils_common.DbTable(
res.group("db"), res.group("table")
)
else:
parser.error("Invalid --table option: %s" % options.import_table)
else:
parser.error("A value is required for --table when importing from a file")
# fields