summaryrefslogtreecommitdiff
path: root/lib/ansible/modules/cloud/google/gcp_bigquery_table.py
blob: 4a4f8804e62deeaa1429f38610c7a36001a0c174 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
#     ***     AUTO GENERATED CODE    ***    AUTO GENERATED CODE     ***
#
# ----------------------------------------------------------------------------
#
#     This file is automatically generated by Magic Modules and manual
#     changes will be clobbered when the file is regenerated.
#
#     Please read more about how to change this file at
#     https://www.github.com/GoogleCloudPlatform/magic-modules
#
# ----------------------------------------------------------------------------

from __future__ import absolute_import, division, print_function

__metaclass__ = type

################################################################################
# Documentation
################################################################################

ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'}

DOCUMENTATION = '''
---
module: gcp_bigquery_table
description:
- A Table that belongs to a Dataset .
short_description: Creates a GCP Table
version_added: '2.8'
author: Google Inc. (@googlecloudplatform)
requirements:
- python >= 2.6
- requests >= 2.18.4
- google-auth >= 1.3.0
options:
  state:
    description:
    - Whether the given object should exist in GCP
    choices:
    - present
    - absent
    default: present
    type: str
  table_reference:
    description:
    - Reference describing the ID of this table.
    required: false
    type: dict
    suboptions:
      dataset_id:
        description:
        - The ID of the dataset containing this table.
        required: false
        type: str
      project_id:
        description:
        - The ID of the project containing this table.
        required: false
        type: str
      table_id:
        description:
        - The ID of the table.
        required: false
        type: str
  clustering:
    description:
    - One or more fields on which data should be clustered. Only top-level, non-repeated,
      simple-type fields are supported. When you cluster a table using multiple columns,
      the order of columns you specify is important. The order of the specified columns
      determines the sort order of the data.
    required: false
    type: list
    version_added: '2.9'
  description:
    description:
    - A user-friendly description of the dataset.
    required: false
    type: str
  friendly_name:
    description:
    - A descriptive name for this table.
    required: false
    type: str
  labels:
    description:
    - The labels associated with this dataset. You can use these to organize and group
      your datasets .
    required: false
    type: dict
  name:
    description:
    - Name of the table.
    required: false
    type: str
  num_rows:
    description:
    - The number of rows of data in this table, excluding any data in the streaming
      buffer.
    required: false
    type: int
    version_added: '2.9'
  view:
    description:
    - The view definition.
    required: false
    type: dict
    suboptions:
      use_legacy_sql:
        description:
        - Specifies whether to use BigQuery's legacy SQL for this view .
        required: false
        type: bool
      user_defined_function_resources:
        description:
        - Describes user-defined function resources used in the query.
        required: false
        type: list
        suboptions:
          inline_code:
            description:
            - An inline resource that contains code for a user-defined function (UDF).
              Providing a inline code resource is equivalent to providing a URI for
              a file containing the same code.
            required: false
            type: str
          resource_uri:
            description:
            - A code resource to load from a Google Cloud Storage URI (gs://bucket/path).
            required: false
            type: str
  time_partitioning:
    description:
    - If specified, configures time-based partitioning for this table.
    required: false
    type: dict
    suboptions:
      expiration_ms:
        description:
        - Number of milliseconds for which to keep the storage for a partition.
        required: false
        type: int
      field:
        description:
        - If not set, the table is partitioned by pseudo column, referenced via either
          '_PARTITIONTIME' as TIMESTAMP type, or '_PARTITIONDATE' as DATE type. If
          field is specified, the table is instead partitioned by this field. The
          field must be a top-level TIMESTAMP or DATE field. Its mode must be NULLABLE
          or REQUIRED.
        required: false
        type: str
        version_added: '2.9'
      type:
        description:
        - The only type supported is DAY, which will generate one partition per day.
        - 'Some valid choices include: "DAY"'
        required: false
        type: str
  schema:
    description:
    - Describes the schema of this table.
    required: false
    type: dict
    suboptions:
      fields:
        description:
        - Describes the fields in a table.
        required: false
        type: list
        suboptions:
          description:
            description:
            - The field description. The maximum length is 1,024 characters.
            required: false
            type: str
          fields:
            description:
            - Describes the nested schema fields if the type property is set to RECORD.
            required: false
            type: list
          mode:
            description:
            - The field mode.
            - 'Some valid choices include: "NULLABLE", "REQUIRED", "REPEATED"'
            required: false
            type: str
          name:
            description:
            - The field name.
            required: false
            type: str
          type:
            description:
            - The field data type.
            - 'Some valid choices include: "STRING", "BYTES", "INTEGER", "FLOAT",
              "TIMESTAMP", "DATE", "TIME", "DATETIME", "RECORD"'
            required: false
            type: str
  encryption_configuration:
    description:
    - Custom encryption configuration.
    required: false
    type: dict
    suboptions:
      kms_key_name:
        description:
        - Describes the Cloud KMS encryption key that will be used to protect destination
          BigQuery table. The BigQuery Service Account associated with your project
          requires access to this encryption key.
        required: false
        type: str
  expiration_time:
    description:
    - The time when this table expires, in milliseconds since the epoch. If not present,
      the table will persist indefinitely.
    required: false
    type: int
  external_data_configuration:
    description:
    - Describes the data format, location, and other properties of a table stored
      outside of BigQuery. By defining these properties, the data source can then
      be queried as if it were a standard BigQuery table.
    required: false
    type: dict
    suboptions:
      autodetect:
        description:
        - Try to detect schema and format options automatically. Any option specified
          explicitly will be honored.
        required: false
        type: bool
      compression:
        description:
        - The compression type of the data source.
        - 'Some valid choices include: "GZIP", "NONE"'
        required: false
        type: str
      ignore_unknown_values:
        description:
        - Indicates if BigQuery should allow extra values that are not represented
          in the table schema .
        required: false
        type: bool
      max_bad_records:
        description:
        - The maximum number of bad records that BigQuery can ignore when reading
          data .
        required: false
        default: '0'
        type: int
      source_format:
        description:
        - The data format.
        - 'Some valid choices include: "CSV", "GOOGLE_SHEETS", "NEWLINE_DELIMITED_JSON",
          "AVRO", "DATASTORE_BACKUP", "BIGTABLE"'
        required: false
        type: str
      source_uris:
        description:
        - The fully-qualified URIs that point to your data in Google Cloud.
        - 'For Google Cloud Storage URIs: Each URI can contain one ''*'' wildcard
          character and it must come after the ''bucket'' name. Size limits related
          to load jobs apply to external data sources. For Google Cloud Bigtable URIs:
          Exactly one URI can be specified and it has be a fully specified and valid
          HTTPS URL for a Google Cloud Bigtable table. For Google Cloud Datastore
          backups, exactly one URI can be specified. Also, the ''*'' wildcard character
          is not allowed.'
        required: false
        type: list
      schema:
        description:
        - The schema for the data. Schema is required for CSV and JSON formats.
        required: false
        type: dict
        suboptions:
          fields:
            description:
            - Describes the fields in a table.
            required: false
            type: list
            suboptions:
              description:
                description:
                - The field description.
                required: false
                type: str
              fields:
                description:
                - Describes the nested schema fields if the type property is set to
                  RECORD .
                required: false
                type: list
              mode:
                description:
                - Field mode.
                - 'Some valid choices include: "NULLABLE", "REQUIRED", "REPEATED"'
                required: false
                type: str
              name:
                description:
                - Field name.
                required: false
                type: str
              type:
                description:
                - Field data type.
                - 'Some valid choices include: "STRING", "BYTES", "INTEGER", "FLOAT",
                  "TIMESTAMP", "DATE", "TIME", "DATETIME", "RECORD"'
                required: false
                type: str
      google_sheets_options:
        description:
        - Additional options if sourceFormat is set to GOOGLE_SHEETS.
        required: false
        type: dict
        suboptions:
          skip_leading_rows:
            description:
            - The number of rows at the top of a Google Sheet that BigQuery will skip
              when reading the data.
            required: false
            default: '0'
            type: int
      csv_options:
        description:
        - Additional properties to set if sourceFormat is set to CSV.
        required: false
        type: dict
        suboptions:
          allow_jagged_rows:
            description:
            - Indicates if BigQuery should accept rows that are missing trailing optional
              columns .
            required: false
            type: bool
          allow_quoted_newlines:
            description:
            - Indicates if BigQuery should allow quoted data sections that contain
              newline characters in a CSV file .
            required: false
            type: bool
          encoding:
            description:
            - The character encoding of the data.
            - 'Some valid choices include: "UTF-8", "ISO-8859-1"'
            required: false
            type: str
          field_delimiter:
            description:
            - The separator for fields in a CSV file.
            required: false
            type: str
          quote:
            description:
            - The value that is used to quote data sections in a CSV file.
            required: false
            type: str
          skip_leading_rows:
            description:
            - The number of rows at the top of a CSV file that BigQuery will skip
              when reading the data.
            required: false
            default: '0'
            type: int
      bigtable_options:
        description:
        - Additional options if sourceFormat is set to BIGTABLE.
        required: false
        type: dict
        suboptions:
          ignore_unspecified_column_families:
            description:
            - If field is true, then the column families that are not specified in
              columnFamilies list are not exposed in the table schema .
            required: false
            type: bool
          read_rowkey_as_string:
            description:
            - If field is true, then the rowkey column families will be read and converted
              to string.
            required: false
            type: bool
          column_families:
            description:
            - List of column families to expose in the table schema along with their
              types.
            required: false
            type: list
            suboptions:
              columns:
                description:
                - Lists of columns that should be exposed as individual fields as
                  opposed to a list of (column name, value) pairs.
                required: false
                type: list
                suboptions:
                  encoding:
                    description:
                    - The encoding of the values when the type is not STRING.
                    - 'Some valid choices include: "TEXT", "BINARY"'
                    required: false
                    type: str
                  field_name:
                    description:
                    - If the qualifier is not a valid BigQuery field identifier, a
                      valid identifier must be provided as the column field name and
                      is used as field name in queries.
                    required: false
                    type: str
                  only_read_latest:
                    description:
                    - If this is set, only the latest version of value in this column
                      are exposed .
                    required: false
                    type: bool
                  qualifier_string:
                    description:
                    - Qualifier of the column.
                    required: true
                    type: str
                  type:
                    description:
                    - The type to convert the value in cells of this column.
                    - 'Some valid choices include: "BYTES", "STRING", "INTEGER", "FLOAT",
                      "BOOLEAN"'
                    required: false
                    type: str
              encoding:
                description:
                - The encoding of the values when the type is not STRING.
                - 'Some valid choices include: "TEXT", "BINARY"'
                required: false
                type: str
              family_id:
                description:
                - Identifier of the column family.
                required: false
                type: str
              only_read_latest:
                description:
                - If this is set only the latest version of value are exposed for
                  all columns in this column family .
                required: false
                type: bool
              type:
                description:
                - The type to convert the value in cells of this column family.
                - 'Some valid choices include: "BYTES", "STRING", "INTEGER", "FLOAT",
                  "BOOLEAN"'
                required: false
                type: str
  dataset:
    description:
    - Name of the dataset.
    required: false
    type: str
  project:
    description:
    - The Google Cloud Platform project to use.
    type: str
  auth_kind:
    description:
    - The type of credential used.
    type: str
    required: true
    choices:
    - application
    - machineaccount
    - serviceaccount
  service_account_contents:
    description:
    - The contents of a Service Account JSON file, either in a dictionary or as a
      JSON string that represents it.
    type: jsonarg
  service_account_file:
    description:
    - The path of a Service Account JSON file if serviceaccount is selected as type.
    type: path
  service_account_email:
    description:
    - An optional service account email address if machineaccount is selected and
      the user does not wish to use the default email.
    type: str
  scopes:
    description:
    - Array of scopes to be used
    type: list
  env_type:
    description:
    - Specifies which Ansible environment you're running this module within.
    - This should not be set unless you know what you're doing.
    - This only alters the User Agent string for any API requests.
    type: str
'''

EXAMPLES = '''
- name: create a dataset
  gcp_bigquery_dataset:
    name: example_dataset
    dataset_reference:
      dataset_id: example_dataset
    project: "{{ gcp_project }}"
    auth_kind: "{{ gcp_cred_kind }}"
    service_account_file: "{{ gcp_cred_file }}"
    state: present
  register: dataset

- name: create a table
  gcp_bigquery_table:
    name: example_table
    dataset: example_dataset
    table_reference:
      dataset_id: example_dataset
      project_id: test_project
      table_id: example_table
    project: test_project
    auth_kind: serviceaccount
    service_account_file: "/tmp/auth.pem"
    state: present
'''

RETURN = '''
tableReference:
  description:
  - Reference describing the ID of this table.
  returned: success
  type: complex
  contains:
    datasetId:
      description:
      - The ID of the dataset containing this table.
      returned: success
      type: str
    projectId:
      description:
      - The ID of the project containing this table.
      returned: success
      type: str
    tableId:
      description:
      - The ID of the table.
      returned: success
      type: str
clustering:
  description:
  - One or more fields on which data should be clustered. Only top-level, non-repeated,
    simple-type fields are supported. When you cluster a table using multiple columns,
    the order of columns you specify is important. The order of the specified columns
    determines the sort order of the data.
  returned: success
  type: list
creationTime:
  description:
  - The time when this dataset was created, in milliseconds since the epoch.
  returned: success
  type: int
description:
  description:
  - A user-friendly description of the dataset.
  returned: success
  type: str
friendlyName:
  description:
  - A descriptive name for this table.
  returned: success
  type: str
id:
  description:
  - An opaque ID uniquely identifying the table.
  returned: success
  type: str
labels:
  description:
  - The labels associated with this dataset. You can use these to organize and group
    your datasets .
  returned: success
  type: dict
lastModifiedTime:
  description:
  - The time when this table was last modified, in milliseconds since the epoch.
  returned: success
  type: int
location:
  description:
  - The geographic location where the table resides. This value is inherited from
    the dataset.
  returned: success
  type: str
name:
  description:
  - Name of the table.
  returned: success
  type: str
numBytes:
  description:
  - The size of this table in bytes, excluding any data in the streaming buffer.
  returned: success
  type: int
numLongTermBytes:
  description:
  - The number of bytes in the table that are considered "long-term storage".
  returned: success
  type: int
numRows:
  description:
  - The number of rows of data in this table, excluding any data in the streaming
    buffer.
  returned: success
  type: int
requirePartitionFilter:
  description:
  - If set to true, queries over this table require a partition filter that can be
    used for partition elimination to be specified.
  returned: success
  type: bool
type:
  description:
  - Describes the table type.
  returned: success
  type: str
view:
  description:
  - The view definition.
  returned: success
  type: complex
  contains:
    useLegacySql:
      description:
      - Specifies whether to use BigQuery's legacy SQL for this view .
      returned: success
      type: bool
    userDefinedFunctionResources:
      description:
      - Describes user-defined function resources used in the query.
      returned: success
      type: complex
      contains:
        inlineCode:
          description:
          - An inline resource that contains code for a user-defined function (UDF).
            Providing a inline code resource is equivalent to providing a URI for
            a file containing the same code.
          returned: success
          type: str
        resourceUri:
          description:
          - A code resource to load from a Google Cloud Storage URI (gs://bucket/path).
          returned: success
          type: str
timePartitioning:
  description:
  - If specified, configures time-based partitioning for this table.
  returned: success
  type: complex
  contains:
    expirationMs:
      description:
      - Number of milliseconds for which to keep the storage for a partition.
      returned: success
      type: int
    field:
      description:
      - If not set, the table is partitioned by pseudo column, referenced via either
        '_PARTITIONTIME' as TIMESTAMP type, or '_PARTITIONDATE' as DATE type. If field
        is specified, the table is instead partitioned by this field. The field must
        be a top-level TIMESTAMP or DATE field. Its mode must be NULLABLE or REQUIRED.
      returned: success
      type: str
    type:
      description:
      - The only type supported is DAY, which will generate one partition per day.
      returned: success
      type: str
streamingBuffer:
  description:
  - Contains information regarding this table's streaming buffer, if one is present.
    This field will be absent if the table is not being streamed to or if there is
    no data in the streaming buffer.
  returned: success
  type: complex
  contains:
    estimatedBytes:
      description:
      - A lower-bound estimate of the number of bytes currently in the streaming buffer.
      returned: success
      type: int
    estimatedRows:
      description:
      - A lower-bound estimate of the number of rows currently in the streaming buffer.
      returned: success
      type: int
    oldestEntryTime:
      description:
      - Contains the timestamp of the oldest entry in the streaming buffer, in milliseconds
        since the epoch, if the streaming buffer is available.
      returned: success
      type: int
schema:
  description:
  - Describes the schema of this table.
  returned: success
  type: complex
  contains:
    fields:
      description:
      - Describes the fields in a table.
      returned: success
      type: complex
      contains:
        description:
          description:
          - The field description. The maximum length is 1,024 characters.
          returned: success
          type: str
        fields:
          description:
          - Describes the nested schema fields if the type property is set to RECORD.
          returned: success
          type: list
        mode:
          description:
          - The field mode.
          returned: success
          type: str
        name:
          description:
          - The field name.
          returned: success
          type: str
        type:
          description:
          - The field data type.
          returned: success
          type: str
encryptionConfiguration:
  description:
  - Custom encryption configuration.
  returned: success
  type: complex
  contains:
    kmsKeyName:
      description:
      - Describes the Cloud KMS encryption key that will be used to protect destination
        BigQuery table. The BigQuery Service Account associated with your project
        requires access to this encryption key.
      returned: success
      type: str
expirationTime:
  description:
  - The time when this table expires, in milliseconds since the epoch. If not present,
    the table will persist indefinitely.
  returned: success
  type: int
externalDataConfiguration:
  description:
  - Describes the data format, location, and other properties of a table stored outside
    of BigQuery. By defining these properties, the data source can then be queried
    as if it were a standard BigQuery table.
  returned: success
  type: complex
  contains:
    autodetect:
      description:
      - Try to detect schema and format options automatically. Any option specified
        explicitly will be honored.
      returned: success
      type: bool
    compression:
      description:
      - The compression type of the data source.
      returned: success
      type: str
    ignoreUnknownValues:
      description:
      - Indicates if BigQuery should allow extra values that are not represented in
        the table schema .
      returned: success
      type: bool
    maxBadRecords:
      description:
      - The maximum number of bad records that BigQuery can ignore when reading data
        .
      returned: success
      type: int
    sourceFormat:
      description:
      - The data format.
      returned: success
      type: str
    sourceUris:
      description:
      - The fully-qualified URIs that point to your data in Google Cloud.
      - 'For Google Cloud Storage URIs: Each URI can contain one ''*'' wildcard character
        and it must come after the ''bucket'' name. Size limits related to load jobs
        apply to external data sources. For Google Cloud Bigtable URIs: Exactly one
        URI can be specified and it has be a fully specified and valid HTTPS URL for
        a Google Cloud Bigtable table. For Google Cloud Datastore backups, exactly
        one URI can be specified. Also, the ''*'' wildcard character is not allowed.'
      returned: success
      type: list
    schema:
      description:
      - The schema for the data. Schema is required for CSV and JSON formats.
      returned: success
      type: complex
      contains:
        fields:
          description:
          - Describes the fields in a table.
          returned: success
          type: complex
          contains:
            description:
              description:
              - The field description.
              returned: success
              type: str
            fields:
              description:
              - Describes the nested schema fields if the type property is set to
                RECORD .
              returned: success
              type: list
            mode:
              description:
              - Field mode.
              returned: success
              type: str
            name:
              description:
              - Field name.
              returned: success
              type: str
            type:
              description:
              - Field data type.
              returned: success
              type: str
    googleSheetsOptions:
      description:
      - Additional options if sourceFormat is set to GOOGLE_SHEETS.
      returned: success
      type: complex
      contains:
        skipLeadingRows:
          description:
          - The number of rows at the top of a Google Sheet that BigQuery will skip
            when reading the data.
          returned: success
          type: int
    csvOptions:
      description:
      - Additional properties to set if sourceFormat is set to CSV.
      returned: success
      type: complex
      contains:
        allowJaggedRows:
          description:
          - Indicates if BigQuery should accept rows that are missing trailing optional
            columns .
          returned: success
          type: bool
        allowQuotedNewlines:
          description:
          - Indicates if BigQuery should allow quoted data sections that contain newline
            characters in a CSV file .
          returned: success
          type: bool
        encoding:
          description:
          - The character encoding of the data.
          returned: success
          type: str
        fieldDelimiter:
          description:
          - The separator for fields in a CSV file.
          returned: success
          type: str
        quote:
          description:
          - The value that is used to quote data sections in a CSV file.
          returned: success
          type: str
        skipLeadingRows:
          description:
          - The number of rows at the top of a CSV file that BigQuery will skip when
            reading the data.
          returned: success
          type: int
    bigtableOptions:
      description:
      - Additional options if sourceFormat is set to BIGTABLE.
      returned: success
      type: complex
      contains:
        ignoreUnspecifiedColumnFamilies:
          description:
          - If field is true, then the column families that are not specified in columnFamilies
            list are not exposed in the table schema .
          returned: success
          type: bool
        readRowkeyAsString:
          description:
          - If field is true, then the rowkey column families will be read and converted
            to string.
          returned: success
          type: bool
        columnFamilies:
          description:
          - List of column families to expose in the table schema along with their
            types.
          returned: success
          type: complex
          contains:
            columns:
              description:
              - Lists of columns that should be exposed as individual fields as opposed
                to a list of (column name, value) pairs.
              returned: success
              type: complex
              contains:
                encoding:
                  description:
                  - The encoding of the values when the type is not STRING.
                  returned: success
                  type: str
                fieldName:
                  description:
                  - If the qualifier is not a valid BigQuery field identifier, a valid
                    identifier must be provided as the column field name and is used
                    as field name in queries.
                  returned: success
                  type: str
                onlyReadLatest:
                  description:
                  - If this is set, only the latest version of value in this column
                    are exposed .
                  returned: success
                  type: bool
                qualifierString:
                  description:
                  - Qualifier of the column.
                  returned: success
                  type: str
                type:
                  description:
                  - The type to convert the value in cells of this column.
                  returned: success
                  type: str
            encoding:
              description:
              - The encoding of the values when the type is not STRING.
              returned: success
              type: str
            familyId:
              description:
              - Identifier of the column family.
              returned: success
              type: str
            onlyReadLatest:
              description:
              - If this is set only the latest version of value are exposed for all
                columns in this column family .
              returned: success
              type: bool
            type:
              description:
              - The type to convert the value in cells of this column family.
              returned: success
              type: str
dataset:
  description:
  - Name of the dataset.
  returned: success
  type: str
'''

################################################################################
# Imports
################################################################################

from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest, remove_nones_from_dict, replace_resource_dict
import json

################################################################################
# Main
################################################################################


def main():
    """Main function"""

    module = GcpModule(
        argument_spec=dict(
            state=dict(default='present', choices=['present', 'absent'], type='str'),
            table_reference=dict(type='dict', options=dict(dataset_id=dict(type='str'), project_id=dict(type='str'), table_id=dict(type='str'))),
            clustering=dict(type='list', elements='str'),
            description=dict(type='str'),
            friendly_name=dict(type='str'),
            labels=dict(type='dict'),
            name=dict(type='str'),
            num_rows=dict(type='int'),
            view=dict(
                type='dict',
                options=dict(
                    use_legacy_sql=dict(type='bool'),
                    user_defined_function_resources=dict(
                        type='list', elements='dict', options=dict(inline_code=dict(type='str'), resource_uri=dict(type='str'))
                    ),
                ),
            ),
            time_partitioning=dict(type='dict', options=dict(expiration_ms=dict(type='int'), field=dict(type='str'), type=dict(type='str'))),
            schema=dict(
                type='dict',
                options=dict(
                    fields=dict(
                        type='list',
                        elements='dict',
                        options=dict(
                            description=dict(type='str'),
                            fields=dict(type='list', elements='str'),
                            mode=dict(type='str'),
                            name=dict(type='str'),
                            type=dict(type='str'),
                        ),
                    )
                ),
            ),
            encryption_configuration=dict(type='dict', options=dict(kms_key_name=dict(type='str'))),
            expiration_time=dict(type='int'),
            external_data_configuration=dict(
                type='dict',
                options=dict(
                    autodetect=dict(type='bool'),
                    compression=dict(type='str'),
                    ignore_unknown_values=dict(type='bool'),
                    max_bad_records=dict(default=0, type='int'),
                    source_format=dict(type='str'),
                    source_uris=dict(type='list', elements='str'),
                    schema=dict(
                        type='dict',
                        options=dict(
                            fields=dict(
                                type='list',
                                elements='dict',
                                options=dict(
                                    description=dict(type='str'),
                                    fields=dict(type='list', elements='str'),
                                    mode=dict(type='str'),
                                    name=dict(type='str'),
                                    type=dict(type='str'),
                                ),
                            )
                        ),
                    ),
                    google_sheets_options=dict(type='dict', options=dict(skip_leading_rows=dict(default=0, type='int'))),
                    csv_options=dict(
                        type='dict',
                        options=dict(
                            allow_jagged_rows=dict(type='bool'),
                            allow_quoted_newlines=dict(type='bool'),
                            encoding=dict(type='str'),
                            field_delimiter=dict(type='str'),
                            quote=dict(type='str'),
                            skip_leading_rows=dict(default=0, type='int'),
                        ),
                    ),
                    bigtable_options=dict(
                        type='dict',
                        options=dict(
                            ignore_unspecified_column_families=dict(type='bool'),
                            read_rowkey_as_string=dict(type='bool'),
                            column_families=dict(
                                type='list',
                                elements='dict',
                                options=dict(
                                    columns=dict(
                                        type='list',
                                        elements='dict',
                                        options=dict(
                                            encoding=dict(type='str'),
                                            field_name=dict(type='str'),
                                            only_read_latest=dict(type='bool'),
                                            qualifier_string=dict(required=True, type='str'),
                                            type=dict(type='str'),
                                        ),
                                    ),
                                    encoding=dict(type='str'),
                                    family_id=dict(type='str'),
                                    only_read_latest=dict(type='bool'),
                                    type=dict(type='str'),
                                ),
                            ),
                        ),
                    ),
                ),
            ),
            dataset=dict(type='str'),
        )
    )

    if not module.params['scopes']:
        module.params['scopes'] = ['https://www.googleapis.com/auth/bigquery']

    state = module.params['state']
    kind = 'bigquery#table'

    fetch = fetch_resource(module, self_link(module), kind)
    changed = False

    if fetch:
        if state == 'present':
            if is_different(module, fetch):
                update(module, self_link(module), kind)
                fetch = fetch_resource(module, self_link(module), kind)
                changed = True
        else:
            delete(module, self_link(module), kind)
            fetch = {}
            changed = True
    else:
        if state == 'present':
            fetch = create(module, collection(module), kind)
            changed = True
        else:
            fetch = {}

    fetch.update({'changed': changed})

    module.exit_json(**fetch)


def create(module, link, kind):
    auth = GcpSession(module, 'bigquery')
    return return_if_object(module, auth.post(link, resource_to_request(module)), kind)


def update(module, link, kind):
    auth = GcpSession(module, 'bigquery')
    return return_if_object(module, auth.put(link, resource_to_request(module)), kind)


def delete(module, link, kind):
    auth = GcpSession(module, 'bigquery')
    return return_if_object(module, auth.delete(link), kind)


def resource_to_request(module):
    request = {
        u'kind': 'bigquery#table',
        u'tableReference': TableTablereference(module.params.get('table_reference', {}), module).to_request(),
        u'clustering': module.params.get('clustering'),
        u'description': module.params.get('description'),
        u'friendlyName': module.params.get('friendly_name'),
        u'labels': module.params.get('labels'),
        u'name': module.params.get('name'),
        u'numRows': module.params.get('num_rows'),
        u'view': TableView(module.params.get('view', {}), module).to_request(),
        u'timePartitioning': TableTimepartitioning(module.params.get('time_partitioning', {}), module).to_request(),
        u'schema': TableSchema(module.params.get('schema', {}), module).to_request(),
        u'encryptionConfiguration': TableEncryptionconfiguration(module.params.get('encryption_configuration', {}), module).to_request(),
        u'expirationTime': module.params.get('expiration_time'),
        u'externalDataConfiguration': TableExternaldataconfiguration(module.params.get('external_data_configuration', {}), module).to_request(),
    }
    return_vals = {}
    for k, v in request.items():
        if v or v is False:
            return_vals[k] = v

    return return_vals


def fetch_resource(module, link, kind, allow_not_found=True):
    auth = GcpSession(module, 'bigquery')
    return return_if_object(module, auth.get(link), kind, allow_not_found)


def self_link(module):
    return "https://www.googleapis.com/bigquery/v2/projects/{project}/datasets/{dataset}/tables/{name}".format(**module.params)


def collection(module):
    return "https://www.googleapis.com/bigquery/v2/projects/{project}/datasets/{dataset}/tables".format(**module.params)


def return_if_object(module, response, kind, allow_not_found=False):
    # If not found, return nothing.
    if allow_not_found and response.status_code == 404:
        return None

    # If no content, return nothing.
    if response.status_code == 204:
        return None

    try:
        module.raise_for_status(response)
        result = response.json()
    except getattr(json.decoder, 'JSONDecodeError', ValueError):
        module.fail_json(msg="Invalid JSON response with error: %s" % response.text)

    if navigate_hash(result, ['error', 'errors']):
        module.fail_json(msg=navigate_hash(result, ['error', 'errors']))

    return result


def is_different(module, response):
    request = resource_to_request(module)
    response = response_to_hash(module, response)

    # Remove all output-only from response.
    response_vals = {}
    for k, v in response.items():
        if k in request:
            response_vals[k] = v

    request_vals = {}
    for k, v in request.items():
        if k in response:
            request_vals[k] = v

    return GcpRequest(request_vals) != GcpRequest(response_vals)


# Remove unnecessary properties from the response.
# This is for doing comparisons with Ansible's current parameters.
def response_to_hash(module, response):
    return {
        u'tableReference': TableTablereference(response.get(u'tableReference', {}), module).from_response(),
        u'clustering': response.get(u'clustering'),
        u'creationTime': response.get(u'creationTime'),
        u'description': response.get(u'description'),
        u'friendlyName': response.get(u'friendlyName'),
        u'id': response.get(u'id'),
        u'labels': response.get(u'labels'),
        u'lastModifiedTime': response.get(u'lastModifiedTime'),
        u'location': response.get(u'location'),
        u'name': response.get(u'name'),
        u'numBytes': response.get(u'numBytes'),
        u'numLongTermBytes': response.get(u'numLongTermBytes'),
        u'numRows': response.get(u'numRows'),
        u'requirePartitionFilter': response.get(u'requirePartitionFilter'),
        u'type': response.get(u'type'),
        u'view': TableView(response.get(u'view', {}), module).from_response(),
        u'timePartitioning': TableTimepartitioning(response.get(u'timePartitioning', {}), module).from_response(),
        u'streamingBuffer': TableStreamingbuffer(response.get(u'streamingBuffer', {}), module).from_response(),
        u'schema': TableSchema(response.get(u'schema', {}), module).from_response(),
        u'encryptionConfiguration': TableEncryptionconfiguration(response.get(u'encryptionConfiguration', {}), module).from_response(),
        u'expirationTime': response.get(u'expirationTime'),
        u'externalDataConfiguration': TableExternaldataconfiguration(response.get(u'externalDataConfiguration', {}), module).from_response(),
    }


class TableTablereference(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = {}

    def to_request(self):
        return remove_nones_from_dict(
            {u'datasetId': self.request.get('dataset_id'), u'projectId': self.request.get('project_id'), u'tableId': self.request.get('table_id')}
        )

    def from_response(self):
        return remove_nones_from_dict(
            {u'datasetId': self.request.get(u'datasetId'), u'projectId': self.request.get(u'projectId'), u'tableId': self.request.get(u'tableId')}
        )


class TableView(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = {}

    def to_request(self):
        return remove_nones_from_dict(
            {
                u'useLegacySql': self.request.get('use_legacy_sql'),
                u'userDefinedFunctionResources': TableUserdefinedfunctionresourcesArray(
                    self.request.get('user_defined_function_resources', []), self.module
                ).to_request(),
            }
        )

    def from_response(self):
        return remove_nones_from_dict(
            {
                u'useLegacySql': self.request.get(u'useLegacySql'),
                u'userDefinedFunctionResources': TableUserdefinedfunctionresourcesArray(
                    self.request.get(u'userDefinedFunctionResources', []), self.module
                ).from_response(),
            }
        )


class TableUserdefinedfunctionresourcesArray(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = []

    def to_request(self):
        items = []
        for item in self.request:
            items.append(self._request_for_item(item))
        return items

    def from_response(self):
        items = []
        for item in self.request:
            items.append(self._response_from_item(item))
        return items

    def _request_for_item(self, item):
        return remove_nones_from_dict({u'inlineCode': item.get('inline_code'), u'resourceUri': item.get('resource_uri')})

    def _response_from_item(self, item):
        return remove_nones_from_dict({u'inlineCode': item.get(u'inlineCode'), u'resourceUri': item.get(u'resourceUri')})


class TableTimepartitioning(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = {}

    def to_request(self):
        return remove_nones_from_dict(
            {u'expirationMs': self.request.get('expiration_ms'), u'field': self.request.get('field'), u'type': self.request.get('type')}
        )

    def from_response(self):
        return remove_nones_from_dict(
            {u'expirationMs': self.request.get(u'expirationMs'), u'field': self.request.get(u'field'), u'type': self.request.get(u'type')}
        )


class TableStreamingbuffer(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = {}

    def to_request(self):
        return remove_nones_from_dict({})

    def from_response(self):
        return remove_nones_from_dict({})


class TableSchema(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = {}

    def to_request(self):
        return remove_nones_from_dict({u'fields': TableFieldsArray(self.request.get('fields', []), self.module).to_request()})

    def from_response(self):
        return remove_nones_from_dict({u'fields': TableFieldsArray(self.request.get(u'fields', []), self.module).from_response()})


class TableFieldsArray(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = []

    def to_request(self):
        items = []
        for item in self.request:
            items.append(self._request_for_item(item))
        return items

    def from_response(self):
        items = []
        for item in self.request:
            items.append(self._response_from_item(item))
        return items

    def _request_for_item(self, item):
        return remove_nones_from_dict(
            {
                u'description': item.get('description'),
                u'fields': item.get('fields'),
                u'mode': item.get('mode'),
                u'name': item.get('name'),
                u'type': item.get('type'),
            }
        )

    def _response_from_item(self, item):
        return remove_nones_from_dict(
            {
                u'description': item.get(u'description'),
                u'fields': item.get(u'fields'),
                u'mode': item.get(u'mode'),
                u'name': item.get(u'name'),
                u'type': item.get(u'type'),
            }
        )


class TableEncryptionconfiguration(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = {}

    def to_request(self):
        return remove_nones_from_dict({u'kmsKeyName': self.request.get('kms_key_name')})

    def from_response(self):
        return remove_nones_from_dict({u'kmsKeyName': self.request.get(u'kmsKeyName')})


class TableExternaldataconfiguration(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = {}

    def to_request(self):
        return remove_nones_from_dict(
            {
                u'autodetect': self.request.get('autodetect'),
                u'compression': self.request.get('compression'),
                u'ignoreUnknownValues': self.request.get('ignore_unknown_values'),
                u'maxBadRecords': self.request.get('max_bad_records'),
                u'sourceFormat': self.request.get('source_format'),
                u'sourceUris': self.request.get('source_uris'),
                u'schema': TableSchema(self.request.get('schema', {}), self.module).to_request(),
                u'googleSheetsOptions': TableGooglesheetsoptions(self.request.get('google_sheets_options', {}), self.module).to_request(),
                u'csvOptions': TableCsvoptions(self.request.get('csv_options', {}), self.module).to_request(),
                u'bigtableOptions': TableBigtableoptions(self.request.get('bigtable_options', {}), self.module).to_request(),
            }
        )

    def from_response(self):
        return remove_nones_from_dict(
            {
                u'autodetect': self.request.get(u'autodetect'),
                u'compression': self.request.get(u'compression'),
                u'ignoreUnknownValues': self.request.get(u'ignoreUnknownValues'),
                u'maxBadRecords': self.request.get(u'maxBadRecords'),
                u'sourceFormat': self.request.get(u'sourceFormat'),
                u'sourceUris': self.request.get(u'sourceUris'),
                u'schema': TableSchema(self.request.get(u'schema', {}), self.module).from_response(),
                u'googleSheetsOptions': TableGooglesheetsoptions(self.request.get(u'googleSheetsOptions', {}), self.module).from_response(),
                u'csvOptions': TableCsvoptions(self.request.get(u'csvOptions', {}), self.module).from_response(),
                u'bigtableOptions': TableBigtableoptions(self.request.get(u'bigtableOptions', {}), self.module).from_response(),
            }
        )


class TableSchema(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = {}

    def to_request(self):
        return remove_nones_from_dict({u'fields': TableFieldsArray(self.request.get('fields', []), self.module).to_request()})

    def from_response(self):
        return remove_nones_from_dict({u'fields': TableFieldsArray(self.request.get(u'fields', []), self.module).from_response()})


class TableFieldsArray(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = []

    def to_request(self):
        items = []
        for item in self.request:
            items.append(self._request_for_item(item))
        return items

    def from_response(self):
        items = []
        for item in self.request:
            items.append(self._response_from_item(item))
        return items

    def _request_for_item(self, item):
        return remove_nones_from_dict(
            {
                u'description': item.get('description'),
                u'fields': item.get('fields'),
                u'mode': item.get('mode'),
                u'name': item.get('name'),
                u'type': item.get('type'),
            }
        )

    def _response_from_item(self, item):
        return remove_nones_from_dict(
            {
                u'description': item.get(u'description'),
                u'fields': item.get(u'fields'),
                u'mode': item.get(u'mode'),
                u'name': item.get(u'name'),
                u'type': item.get(u'type'),
            }
        )


class TableGooglesheetsoptions(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = {}

    def to_request(self):
        return remove_nones_from_dict({u'skipLeadingRows': self.request.get('skip_leading_rows')})

    def from_response(self):
        return remove_nones_from_dict({u'skipLeadingRows': self.request.get(u'skipLeadingRows')})


class TableCsvoptions(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = {}

    def to_request(self):
        return remove_nones_from_dict(
            {
                u'allowJaggedRows': self.request.get('allow_jagged_rows'),
                u'allowQuotedNewlines': self.request.get('allow_quoted_newlines'),
                u'encoding': self.request.get('encoding'),
                u'fieldDelimiter': self.request.get('field_delimiter'),
                u'quote': self.request.get('quote'),
                u'skipLeadingRows': self.request.get('skip_leading_rows'),
            }
        )

    def from_response(self):
        return remove_nones_from_dict(
            {
                u'allowJaggedRows': self.request.get(u'allowJaggedRows'),
                u'allowQuotedNewlines': self.request.get(u'allowQuotedNewlines'),
                u'encoding': self.request.get(u'encoding'),
                u'fieldDelimiter': self.request.get(u'fieldDelimiter'),
                u'quote': self.request.get(u'quote'),
                u'skipLeadingRows': self.request.get(u'skipLeadingRows'),
            }
        )


class TableBigtableoptions(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = {}

    def to_request(self):
        return remove_nones_from_dict(
            {
                u'ignoreUnspecifiedColumnFamilies': self.request.get('ignore_unspecified_column_families'),
                u'readRowkeyAsString': self.request.get('read_rowkey_as_string'),
                u'columnFamilies': TableColumnfamiliesArray(self.request.get('column_families', []), self.module).to_request(),
            }
        )

    def from_response(self):
        return remove_nones_from_dict(
            {
                u'ignoreUnspecifiedColumnFamilies': self.request.get(u'ignoreUnspecifiedColumnFamilies'),
                u'readRowkeyAsString': self.request.get(u'readRowkeyAsString'),
                u'columnFamilies': TableColumnfamiliesArray(self.request.get(u'columnFamilies', []), self.module).from_response(),
            }
        )


class TableColumnfamiliesArray(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = []

    def to_request(self):
        items = []
        for item in self.request:
            items.append(self._request_for_item(item))
        return items

    def from_response(self):
        items = []
        for item in self.request:
            items.append(self._response_from_item(item))
        return items

    def _request_for_item(self, item):
        return remove_nones_from_dict(
            {
                u'columns': TableColumnsArray(item.get('columns', []), self.module).to_request(),
                u'encoding': item.get('encoding'),
                u'familyId': item.get('family_id'),
                u'onlyReadLatest': item.get('only_read_latest'),
                u'type': item.get('type'),
            }
        )

    def _response_from_item(self, item):
        return remove_nones_from_dict(
            {
                u'columns': TableColumnsArray(item.get(u'columns', []), self.module).from_response(),
                u'encoding': item.get(u'encoding'),
                u'familyId': item.get(u'familyId'),
                u'onlyReadLatest': item.get(u'onlyReadLatest'),
                u'type': item.get(u'type'),
            }
        )


class TableColumnsArray(object):
    def __init__(self, request, module):
        self.module = module
        if request:
            self.request = request
        else:
            self.request = []

    def to_request(self):
        items = []
        for item in self.request:
            items.append(self._request_for_item(item))
        return items

    def from_response(self):
        items = []
        for item in self.request:
            items.append(self._response_from_item(item))
        return items

    def _request_for_item(self, item):
        return remove_nones_from_dict(
            {
                u'encoding': item.get('encoding'),
                u'fieldName': item.get('field_name'),
                u'onlyReadLatest': item.get('only_read_latest'),
                u'qualifierString': item.get('qualifier_string'),
                u'type': item.get('type'),
            }
        )

    def _response_from_item(self, item):
        return remove_nones_from_dict(
            {
                u'encoding': item.get(u'encoding'),
                u'fieldName': item.get(u'fieldName'),
                u'onlyReadLatest': item.get(u'onlyReadLatest'),
                u'qualifierString': item.get(u'qualifierString'),
                u'type': item.get(u'type'),
            }
        )


if __name__ == '__main__':
    main()