/
datasource.py
1345 lines (1123 loc) · 55.3 KB
/
datasource.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
import datetime
import enum
import importlib
import json
import logging
import os
import sys
import platform
import uuid
import click
import great_expectations.exceptions as ge_exceptions
from great_expectations.util import verify_dynamic_loading_support
from great_expectations import DataContext, rtd_url_ge_version
from great_expectations.cli.docs import build_docs
from great_expectations.cli.init_messages import NO_DATASOURCES_FOUND
from great_expectations.cli.util import cli_message
from great_expectations.core import ExpectationSuite
from great_expectations.data_context.types.resource_identifiers import (
ValidationResultIdentifier,
)
from great_expectations.datasource import (
PandasDatasource,
SparkDFDatasource,
SqlAlchemyDatasource,
)
from great_expectations.datasource.generator import ManualBatchKwargsGenerator
from great_expectations.datasource.generator.table_generator import (
TableBatchKwargsGenerator,
)
from great_expectations.exceptions import (
BatchKwargsError,
DatasourceInitializationError,
)
from great_expectations.profile.sample_expectations_dataset_profiler import (
SampleExpectationsDatasetProfiler,
)
from great_expectations.validator.validator import Validator
logger = logging.getLogger(__name__)
# FIXME: This prevents us from seeing a huge stack of these messages in python 2. We'll need to fix that later.
# tests/test_cli.py::test_cli_profile_with_datasource_arg
# /Users/abe/Documents/superconductive/tools/great_expectations/tests/test_cli.py:294: Warning: Click detected the use of the unicode_literals __future__ import. This is heavily discouraged because it can introduce subtle bugs in your code. You should instead use explicit u"" literals for your unicode strings. For more information see https://click.palletsprojects.com/python3/
# cli, ["profile", "my_datasource", "-d", project_root_dir])
click.disable_unicode_literals_warning = True
class DatasourceTypes(enum.Enum):
PANDAS = "pandas"
SQL = "sql"
SPARK = "spark"
# TODO DBT = "dbt"
DATASOURCE_TYPE_BY_DATASOURCE_CLASS = {
"PandasDatasource": DatasourceTypes.PANDAS,
"SparkDFDatasource": DatasourceTypes.SPARK,
"SqlAlchemyDatasource": DatasourceTypes.SQL,
}
MANUAL_GENERATOR_CLASSES = (ManualBatchKwargsGenerator)
class SupportedDatabases(enum.Enum):
MYSQL = 'MySQL'
POSTGRES = 'Postgres'
REDSHIFT = 'Redshift'
SNOWFLAKE = 'Snowflake'
OTHER = 'other - Do you have a working SQLAlchemy connection string?'
# TODO MSSQL
# TODO BigQuery
@click.group()
def datasource():
"""datasource operations"""
pass
@datasource.command(name="new")
@click.option(
'--directory',
'-d',
default=None,
help="The project's great_expectations directory."
)
def datasource_new(directory):
"""Add a new datasource to the data context."""
try:
context = DataContext(directory)
except ge_exceptions.ConfigNotFoundError as err:
cli_message("<red>{}</red>".format(err.message))
return
datasource_name, data_source_type = add_datasource(context)
if datasource_name:
cli_message("A new datasource '{}' was added to your project.".format(datasource_name))
else: # no datasource was created
sys.exit(1)
@datasource.command(name="list")
@click.option(
'--directory',
'-d',
default=None,
help="The project's great_expectations directory."
)
def datasource_list(directory):
"""List known datasources."""
try:
context = DataContext(directory)
datasources = context.list_datasources()
# TODO Pretty up this console output
cli_message(str([d for d in datasources]))
except ge_exceptions.ConfigNotFoundError as err:
cli_message("<red>{}</red>".format(err.message))
return
@datasource.command(name="profile")
@click.argument('datasource', default=None, required=False)
@click.option(
"--generator-name",
"-g",
default=None,
help="The name of the batch kwarg generator configured in the datasource. The generator will list data assets in the datasource"
)
@click.option('--data-assets', '-l', default=None,
help='Comma-separated list of the names of data assets that should be profiled. Requires datasource specified.')
@click.option('--profile_all_data_assets', '-A', is_flag=True, default=False,
help='Profile ALL data assets within the target data source. '
'If True, this will override --max_data_assets.')
@click.option(
"--directory",
"-d",
default=None,
help="The project's great_expectations directory."
)
@click.option(
"--view/--no-view",
help="By default open in browser unless you specify the --no-view flag",
default=True
)
@click.option('--additional-batch-kwargs', default=None,
help='Additional keyword arguments to be provided to get_batch when loading the data asset. Must be a valid JSON dictionary')
def datasource_profile(datasource, generator_name, data_assets, profile_all_data_assets, directory, view, additional_batch_kwargs):
"""
Profile a datasource (Beta)
If the optional data_assets and profile_all_data_assets arguments are not specified, the profiler will check
if the number of data assets in the datasource exceeds the internally defined limit. If it does, it will
prompt the user to either specify the list of data assets to profile or to profile all.
If the limit is not exceeded, the profiler will profile all data assets in the datasource.
"""
cli_message("<yellow>Warning - this is a BETA feature.</yellow>")
try:
context = DataContext(directory)
except ge_exceptions.ConfigNotFoundError as err:
cli_message("<red>{}</red>".format(err.message))
return
if additional_batch_kwargs is not None:
# TODO refactor out json load check in suite edit and add here
additional_batch_kwargs = json.loads(additional_batch_kwargs)
# TODO refactor batch load check in suite edit and add here
if datasource is None:
datasources = [_datasource["name"] for _datasource in context.list_datasources()]
if not datasources:
cli_message(NO_DATASOURCES_FOUND)
sys.exit(1)
elif len(datasources) > 1:
cli_message(
"<red>Error: please specify the datasource to profile. "\
"Available datasources: " + ", ".join(datasources) + "</red>"
)
sys.exit(1)
else:
profile_datasource(
context,
datasources[0],
generator_name=generator_name,
data_assets=data_assets,
profile_all_data_assets=profile_all_data_assets,
open_docs=view,
additional_batch_kwargs=additional_batch_kwargs
)
else:
profile_datasource(
context,
datasource,
generator_name=generator_name,
data_assets=data_assets,
profile_all_data_assets=profile_all_data_assets,
open_docs=view,
additional_batch_kwargs=additional_batch_kwargs
)
def add_datasource(context, choose_one_data_asset=False):
"""
Interactive flow for adding a datasource to an existing context.
:param context:
:param choose_one_data_asset: optional - if True, this signals the method that the intent
is to let user choose just one data asset (e.g., a file) and there is no need
to configure a generator that comprehensively scans the datasource for data assets
:return: a tuple: datasource_name, data_source_type
"""
msg_prompt_where_is_your_data = """
What data would you like Great Expectations to connect to?
1. Files on a filesystem (for processing with Pandas or Spark)
2. Relational database (SQL)
"""
msg_prompt_files_compute_engine = """
What are you processing your files with?
1. Pandas
2. PySpark
"""
data_source_location_selection = click.prompt(
msg_prompt_where_is_your_data,
type=click.Choice(["1", "2"]),
show_choices=False
)
datasource_name = None
data_source_type = None
if data_source_location_selection == "1":
data_source_compute_selection = click.prompt(
msg_prompt_files_compute_engine,
type=click.Choice(["1", "2"]),
show_choices=False
)
if data_source_compute_selection == "1": # pandas
data_source_type = DatasourceTypes.PANDAS
datasource_name = _add_pandas_datasource(context, passthrough_generator_only=choose_one_data_asset)
elif data_source_compute_selection == "2": # Spark
data_source_type = DatasourceTypes.SPARK
datasource_name = _add_spark_datasource(context, passthrough_generator_only=choose_one_data_asset)
else:
data_source_type = DatasourceTypes.SQL
datasource_name = _add_sqlalchemy_datasource(context, prompt_for_datasource_name=True)
return datasource_name, data_source_type
def _add_pandas_datasource(context, passthrough_generator_only=True, prompt_for_datasource_name=True):
if passthrough_generator_only:
datasource_name = "files_datasource"
configuration = PandasDatasource.build_configuration()
else:
path = click.prompt(
msg_prompt_filesys_enter_base_path,
type=click.Path(
exists=True,
file_okay=False,
dir_okay=True,
readable=True
),
show_default=True
)
if path.startswith("./"):
path = path[2:]
if path.endswith("/"):
basenamepath = path[:-1]
else:
basenamepath = path
datasource_name = os.path.basename(basenamepath) + "__dir"
if prompt_for_datasource_name:
datasource_name = click.prompt(
msg_prompt_datasource_name,
default=datasource_name,
show_default=True
)
configuration = PandasDatasource.build_configuration(
generators={
"subdir_reader": {
"class_name": "SubdirReaderBatchKwargsGenerator",
"base_directory": os.path.join("..", path),
}
}
)
context.add_datasource(name=datasource_name, class_name='PandasDatasource', **configuration)
return datasource_name
def load_library(library_name, install_instructions_string=None):
"""
Dynamically load a module from strings or raise a helpful error.
:param library_name: name of the library to load
:param install_instructions_string: optional - used when the install instructions
are different from 'pip install library_name'
:return: True if the library was loaded successfully, False otherwise
"""
try:
loaded_module = importlib.import_module(library_name)
return True
except ModuleNotFoundError as e:
if install_instructions_string:
cli_message("""<red>ERROR: Great Expectations relies on the library `{}` to connect to your data.</red>
- Please `{}` before trying again.""".format(library_name, install_instructions_string))
else:
cli_message("""<red>ERROR: Great Expectations relies on the library `{}` to connect to your data.</red>
- Please `pip install {}` before trying again.""".format(library_name, library_name))
return False
def _add_sqlalchemy_datasource(context, prompt_for_datasource_name=True):
msg_success_database = "\n<green>Great Expectations connected to your database!</green>"
if not load_library("sqlalchemy"):
return None
db_choices = [str(x) for x in list(range(1, 1 + len(SupportedDatabases)))]
selected_database = int(
click.prompt(
msg_prompt_choose_database,
type=click.Choice(db_choices),
show_choices=False
)
) - 1 # don't show user a zero index list :)
selected_database = list(SupportedDatabases)[selected_database]
datasource_name = "my_{}_db".format(selected_database.value.lower())
if selected_database == SupportedDatabases.OTHER:
datasource_name = "my_database"
if prompt_for_datasource_name:
datasource_name = click.prompt(
msg_prompt_datasource_name,
default=datasource_name,
show_default=True
)
credentials = {}
# Since we don't want to save the database credentials in the config file that will be
# committed in the repo, we will use our Variable Substitution feature to store the credentials
# in the credentials file (that will not be committed, since it is in the uncommitted directory)
# with the datasource's name as the variable name.
# The value of the datasource's "credentials" key in the config file (great_expectations.yml) will
# be ${datasource name}.
# GE will replace the ${datasource name} with the value from the credentials file in runtime.
while True:
cli_message(msg_db_config.format(datasource_name))
if selected_database == SupportedDatabases.MYSQL:
if not load_library("pymysql"):
return None
credentials = _collect_mysql_credentials(default_credentials=credentials)
elif selected_database == SupportedDatabases.POSTGRES:
if not load_library("psycopg2"):
return None
credentials = _collect_postgres_credentials(default_credentials=credentials)
elif selected_database == SupportedDatabases.REDSHIFT:
if not load_library("psycopg2"):
return None
credentials = _collect_redshift_credentials(default_credentials=credentials)
elif selected_database == SupportedDatabases.SNOWFLAKE:
if not load_library("snowflake", install_instructions_string="pip install snowflake-sqlalchemy"):
return None
credentials = _collect_snowflake_credentials(default_credentials=credentials)
elif selected_database == SupportedDatabases.OTHER:
sqlalchemy_url = click.prompt(
"""What is the url/connection string for the sqlalchemy connection?
(reference: https://docs.sqlalchemy.org/en/latest/core/engines.html#database-urls)
""",
show_default=False).strip()
credentials = {
"url": sqlalchemy_url
}
context.save_config_variable(datasource_name, credentials)
message = """
<red>Cannot connect to the database.</red>
- Please check your environment and the configuration you provided.
- Database Error: {0:s}"""
try:
cli_message("<cyan>Attempting to connect to your database. This may take a moment...</cyan>")
configuration = SqlAlchemyDatasource.build_configuration(credentials="${" + datasource_name + "}")
context.add_datasource(name=datasource_name, class_name='SqlAlchemyDatasource', **configuration)
cli_message(msg_success_database)
break
except ModuleNotFoundError as de:
cli_message(message.format(str(de)))
return None
except DatasourceInitializationError as de:
cli_message(message.format(str(de)))
if not click.confirm(
"Enter the credentials again?".format(str(de)),
default=True
):
context.add_datasource(datasource_name,
initialize=False,
module_name="great_expectations.datasource",
class_name="SqlAlchemyDatasource",
data_asset_type={
"class_name": "SqlAlchemyDataset"},
credentials="${" + datasource_name + "}",
)
# TODO this message about continuing may not be accurate
cli_message(
"""
We saved datasource {0:s} in {1:s} and the credentials you entered in {2:s}.
Since we could not connect to the database, you can complete troubleshooting in the configuration files documented here:
<blue>https://docs.greatexpectations.io/en/latest/tutorials/add-sqlalchemy-datasource.html?utm_source=cli&utm_medium=init&utm_campaign={3:s}#{4:s}</blue> .
After you connect to the datasource, run great_expectations init to continue.
""".format(datasource_name, DataContext.GE_YML, context.get_config()["config_variables_file_path"], rtd_url_ge_version, selected_database.value.lower()))
return None
return datasource_name
def _should_hide_input():
"""
This is a workaround to help identify Windows and adjust the prompts accordingly
since hidden prompts may freeze in certain Windows terminals
"""
if 'windows' in platform.platform().lower():
return False
return True
def _collect_postgres_credentials(default_credentials={}):
credentials = {
"drivername": "postgres"
}
credentials["host"] = click.prompt("What is the host for the postgres connection?",
default=default_credentials.get("host", "localhost"),
show_default=True).strip()
credentials["port"] = click.prompt("What is the port for the postgres connection?",
default=default_credentials.get("port", "5432"),
show_default=True).strip()
credentials["username"] = click.prompt("What is the username for the postgres connection?",
default=default_credentials.get("username", "postgres"),
show_default=True).strip()
# This is a minimal workaround we're doing to deal with hidden input problems using Git Bash on Windows
# TODO: Revisit this if we decide to fully support Windows and identify if there is a better solution
credentials["password"] = click.prompt("What is the password for the postgres connection?",
default="",
show_default=False, hide_input=_should_hide_input())
credentials["database"] = click.prompt("What is the database name for the postgres connection?",
default=default_credentials.get("database", "postgres"),
show_default=True).strip()
return credentials
def _collect_snowflake_credentials(default_credentials={}):
credentials = {
"drivername": "snowflake"
}
# required
credentials["username"] = click.prompt("What is the user login name for the snowflake connection?",
default=default_credentials.get("username", ""),
show_default=True).strip()
credentials["password"] = click.prompt("What is the password for the snowflake connection?",
default="",
show_default=False, hide_input=True)
credentials["host"] = click.prompt("What is the account name for the snowflake connection (include region -- ex "
"'ABCD.us-east-1')?",
default=default_credentials.get("host", ""),
show_default=True).strip()
# optional
database = click.prompt("What is database name for the snowflake connection? (optional -- leave blank for none)",
default=default_credentials.get("database", ""),
show_default=True).strip()
if len(database) > 0:
credentials["database"] = database
credentials["query"] = {}
schema = click.prompt("What is schema name for the snowflake connection? (optional -- leave "
"blank for none)",
default=default_credentials.get("schema_name", ""),
show_default=True).strip()
if len(schema) > 0:
credentials["query"]["schema"] = schema
warehouse = click.prompt("What is warehouse name for the snowflake connection? (optional "
"-- leave blank for none)",
default=default_credentials.get("warehouse", ""),
show_default=True).strip()
if len(warehouse) > 0:
credentials["query"]["warehouse"] = warehouse
role = click.prompt("What is role name for the snowflake connection? (optional -- leave blank for none)",
default=default_credentials.get("role", ""), show_default=True).strip()
if len(role) > 0:
credentials["query"]["role"] = role
return credentials
def _collect_mysql_credentials(default_credentials={}):
# We are insisting on pymysql driver when adding a MySQL datasource through the CLI
# to avoid overcomplication of this flow.
# If user wants to use another driver, they must create the sqlalchemy connection
# URL by themselves in config_variables.yml
credentials = {
"drivername": "mysql+pymysql"
}
credentials["host"] = click.prompt("What is the host for the MySQL connection?",
default=default_credentials.get("host", "localhost"),
show_default=True).strip()
credentials["port"] = click.prompt("What is the port for the MySQL connection?",
default=default_credentials.get("port", "3306"),
show_default=True).strip()
credentials["username"] = click.prompt("What is the username for the MySQL connection?",
default=default_credentials.get("username", ""),
show_default=True).strip()
credentials["password"] = click.prompt("What is the password for the MySQL connection?",
default="",
show_default=False, hide_input=True)
credentials["database"] = click.prompt("What is the database name for the MySQL connection?",
default=default_credentials.get("database", ""),
show_default=True).strip()
return credentials
def _collect_redshift_credentials(default_credentials={}):
# We are insisting on psycopg2 driver when adding a Redshift datasource through the CLI
# to avoid overcomplication of this flow.
# If user wants to use another driver, they must create the sqlalchemy connection
# URL by themselves in config_variables.yml
credentials = {
"drivername": "postgresql+psycopg2"
}
# required
credentials["host"] = click.prompt("What is the host for the Redshift connection?",
default=default_credentials.get("host", ""),
show_default=True).strip()
credentials["port"] = click.prompt("What is the port for the Redshift connection?",
default=default_credentials.get("port", "5439"),
show_default=True).strip()
credentials["username"] = click.prompt("What is the username for the Redshift connection?",
default=default_credentials.get("username", ""),
show_default=True).strip()
# This is a minimal workaround we're doing to deal with hidden input problems using Git Bash on Windows
# TODO: Revisit this if we decide to fully support Windows and identify if there is a better solution
credentials["password"] = click.prompt("What is the password for the Redshift connection?",
default="",
show_default=False, hide_input=_should_hide_input())
credentials["database"] = click.prompt("What is the database name for the Redshift connection?",
default=default_credentials.get("database", ""),
show_default=True).strip()
# optional
credentials["query"] = {}
credentials["query"]["sslmode"] = click.prompt("What is sslmode name for the Redshift connection?",
default=default_credentials.get("sslmode", "prefer"),
show_default=True)
return credentials
def _add_spark_datasource(context, passthrough_generator_only=True, prompt_for_datasource_name=True):
if not load_library("pyspark"):
return None
if passthrough_generator_only:
datasource_name = "files_spark_datasource"
# configuration = SparkDFDatasource.build_configuration(generators={
# "default": {
# "class_name": "PassthroughGenerator",
# }
# }
# )
configuration = SparkDFDatasource.build_configuration()
else:
path = click.prompt(
msg_prompt_filesys_enter_base_path,
# default='/data/',
type=click.Path(
exists=True,
file_okay=False,
dir_okay=True,
readable=True
),
show_default=True
).strip()
if path.startswith("./"):
path = path[2:]
if path.endswith("/"):
basenamepath = path[:-1]
else:
basenamepath = path
datasource_name = os.path.basename(basenamepath) + "__dir"
if prompt_for_datasource_name:
datasource_name = click.prompt(
msg_prompt_datasource_name,
default=datasource_name,
show_default=True
)
configuration = SparkDFDatasource.build_configuration(generators={
"subdir_reader": {
"class_name": "SubdirReaderBatchKwargsGenerator",
"base_directory": os.path.join("..", path)
}
}
)
context.add_datasource(name=datasource_name, class_name='SparkDFDatasource', **configuration)
return datasource_name
def select_datasource(context, datasource_name=None):
msg_prompt_select_data_source = "Select a datasource"
msg_no_datasources_configured = "<red>No datasources found in the context. To add a datasource, run `great_expectations datasource new`</red>"
data_source = None
if datasource_name is None:
data_sources = sorted(context.list_datasources(), key=lambda x: x["name"])
if len(data_sources) == 0:
cli_message(msg_no_datasources_configured)
elif len(data_sources) ==1:
datasource_name = data_sources[0]["name"]
else:
choices = "\n".join([" {}. {}".format(i, data_source["name"]) for i, data_source in enumerate(data_sources, 1)])
option_selection = click.prompt(
msg_prompt_select_data_source + "\n" + choices + "\n",
type=click.Choice([str(i) for i, data_source in enumerate(data_sources, 1)]),
show_choices=False
)
datasource_name = data_sources[int(option_selection)-1]["name"]
if datasource_name is not None:
data_source = context.get_datasource(datasource_name)
return data_source
def select_generator(context, datasource_name, available_data_assets_dict=None):
msg_prompt_select_generator = "Select generator"
if available_data_assets_dict is None:
available_data_assets_dict = context.get_available_data_asset_names(datasource_names=datasource_name)
available_data_asset_names_by_generator = {}
for key, value in available_data_assets_dict[datasource_name].items():
if len(value["names"]) > 0:
available_data_asset_names_by_generator[key] = value["names"]
if len(available_data_asset_names_by_generator.keys()) == 0:
return None
elif len(available_data_asset_names_by_generator.keys()) == 1:
return list(available_data_asset_names_by_generator.keys())[0]
else: # multiple generators
generator_names = list(available_data_asset_names_by_generator.keys())
choices = "\n".join([" {}. {}".format(i, generator_name) for i, generator_name in enumerate(generator_names, 1)])
option_selection = click.prompt(
msg_prompt_select_generator + "\n" + choices,
type=click.Choice([str(i) for i, generator_name in enumerate(generator_names, 1)]),
show_choices=False
)
generator_name = generator_names[int(option_selection)-1]
return generator_name
# TODO this method needs testing
def get_batch_kwargs(context,
datasource_name=None,
generator_name=None,
generator_asset=None,
additional_batch_kwargs=None):
"""
This method manages the interaction with user necessary to obtain batch_kwargs for a batch of a data asset.
In order to get batch_kwargs this method needs datasource_name, generator_name and generator_asset
to combine them into a fully qualified data asset identifier(datasource_name/generator_name/generator_asset).
All three arguments are optional. If they are present, the method uses their values. Otherwise, the method
prompts user to enter them interactively. Since it is possible for any of these three components to be
passed to this method as empty values and to get their values after interacting with user, this method
returns these components' values in case they changed.
If the datasource has generators that can list available data asset names, the method lets user choose a name
from that list (note: if there are multiple generators, user has to choose one first). If a name known to
the chosen generator is selected, the generator will be able to yield batch_kwargs. The method also gives user
an alternative to selecting the data asset name from the generator's list - user can type in a name for their
data asset. In this case a passthrough batch kwargs generator will be used to construct a fully qualified data asset
identifier (note: if the datasource has no passthrough generator configured, the method will exist with a failure).
Since no generator can yield batch_kwargs for this data asset name, the method prompts user to specify batch_kwargs
by choosing a file (if the datasource is pandas or spark) or by writing a SQL query (if the datasource points
to a database).
:param context:
:param datasource_name:
:param generator_name:
:param generator_asset:
:param additional_batch_kwargs:
:return: a tuple: (datasource_name, generator_name, generator_asset, batch_kwargs). The components
of the tuple were passed into the methods as optional arguments, but their values might
have changed after this method's execution. If the returned batch_kwargs is None, it means
that the generator will know to yield batch_kwargs when called.
"""
try:
available_data_assets_dict = context.get_available_data_asset_names(datasource_names=datasource_name)
except ValueError:
# the datasource has no generators
available_data_assets_dict = {datasource_name: {}}
data_source = select_datasource(context, datasource_name=datasource_name)
datasource_name = data_source.name
if generator_name is None:
generator_name = select_generator(context, datasource_name,
available_data_assets_dict=available_data_assets_dict)
# if the user provided us with the generator name and the generator asset, we have everything we need -
# let's ask the generator to build batch kwargs for this asset - we are done.
if generator_name is not None and generator_asset is not None:
generator = datasource.get_generator(generator_name)
batch_kwargs = generator.build_batch_kwargs(generator_asset, **additional_batch_kwargs)
return batch_kwargs
if isinstance(context.get_datasource(datasource_name), (PandasDatasource, SparkDFDatasource)):
generator_asset, batch_kwargs = _get_batch_kwargs_from_generator_or_from_file_path(
context,
datasource_name,
generator_name=generator_name,
)
elif isinstance(context.get_datasource(datasource_name), SqlAlchemyDatasource):
generator_asset, batch_kwargs = _get_batch_kwargs_for_sqlalchemy_datasource(context,
datasource_name,
additional_batch_kwargs=additional_batch_kwargs)
else:
raise ge_exceptions.DataContextError("Datasource {0:s} is expected to be a PandasDatasource or SparkDFDatasource, but is {1:s}".format(datasource_name, str(type(context.get_datasource(datasource_name)))))
return (datasource_name, generator_name, generator_asset, batch_kwargs)
def create_expectation_suite(
context,
datasource_name=None,
generator_name=None,
generator_asset=None,
batch_kwargs=None,
expectation_suite_name=None,
additional_batch_kwargs=None,
empty_suite=False,
show_intro_message=False,
open_docs=False
):
"""
Create a new expectation suite.
:return: a tuple: (success, suite name)
"""
msg_intro = "\n<cyan>========== Create sample Expectations ==========</cyan>\n\n"
msg_some_data_assets_not_found = """Some of the data assets you specified were not found: {0:s}
"""
msg_prompt_what_will_profiler_do = """
Great Expectations will choose a couple of columns and generate expectations about them
to demonstrate some examples of assertions you can make about your data.
Press Enter to continue
"""
msg_prompt_expectation_suite_name = """
Name the new expectation suite"""
msg_suite_already_exists = "<red>An expectation suite named `{}` already exists. If you intend to edit the suite please use `great_expectations suite edit {}`.</red>"
if show_intro_message and not empty_suite:
cli_message(msg_intro)
data_source = select_datasource(context, datasource_name=datasource_name)
if data_source is None:
# select_datasource takes care of displaying an error message, so all is left here is to exit.
sys.exit(1)
datasource_name = data_source.name
existing_suite_names = [expectation_suite_id.expectation_suite_name for expectation_suite_id in context.list_expectation_suites()]
if expectation_suite_name in existing_suite_names:
cli_message(
msg_suite_already_exists.format(
expectation_suite_name,
expectation_suite_name
)
)
sys.exit(1)
if generator_name is None or generator_asset is None or batch_kwargs is None:
datasource_name, generator_name, generator_asset, batch_kwargs = get_batch_kwargs(
context,
datasource_name=datasource_name,
generator_name=generator_name,
generator_asset=generator_asset,
additional_batch_kwargs=additional_batch_kwargs)
# In this case, we have "consumed" the additional_batch_kwargs
additional_batch_kwargs = {}
if expectation_suite_name is None:
if generator_asset:
default_expectation_suite_name = "{}.warning".format(generator_asset)
elif "query" in batch_kwargs:
default_expectation_suite_name = "query.warning"
elif "path" in batch_kwargs:
try:
# Try guessing a filename
filename = os.path.split(os.path.normpath(batch_kwargs["path"]))[1]
# Take all but the last part after the period
filename = ".".join(filename.split(".")[:-1])
default_expectation_suite_name = str(filename) + ".warning"
except (OSError, IndexError):
default_expectation_suite_name = "warning"
else:
default_expectation_suite_name = "warning"
while True:
expectation_suite_name = click.prompt(msg_prompt_expectation_suite_name, default=default_expectation_suite_name, show_default=True)
if expectation_suite_name in existing_suite_names:
cli_message(
msg_suite_already_exists.format(
expectation_suite_name,
expectation_suite_name
)
)
else:
break
if empty_suite:
suite = context.create_expectation_suite(expectation_suite_name, overwrite_existing=False)
suite.add_citation(comment="New suite added via CLI", batch_kwargs=batch_kwargs)
context.save_expectation_suite(suite, expectation_suite_name)
return True, expectation_suite_name
profiler = SampleExpectationsDatasetProfiler
click.prompt(msg_prompt_what_will_profiler_do, default=True, show_default=False)
cli_message("\nGenerating example Expectation Suite...")
run_id = datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%S.%fZ")
profiling_results = context.profile_data_asset(
datasource_name,
generator_name=generator_name,
data_asset_name=generator_asset,
batch_kwargs=batch_kwargs,
profiler=profiler,
expectation_suite_name=expectation_suite_name,
run_id=run_id,
additional_batch_kwargs=additional_batch_kwargs
)
if profiling_results['success']:
build_docs(context, view=False)
if open_docs: # This is mostly to keep tests from spawning windows
try:
# TODO this is really brittle and not covered in tests
validation_result = profiling_results["results"][0][1]
validation_result_identifier = ValidationResultIdentifier.from_object(validation_result)
context.open_data_docs(resource_identifier=validation_result_identifier)
except (KeyError, IndexError):
context.open_data_docs()
return True, expectation_suite_name
if profiling_results['error']['code'] == DataContext.PROFILING_ERROR_CODE_SPECIFIED_DATA_ASSETS_NOT_FOUND:
raise ge_exceptions.DataContextError(msg_some_data_assets_not_found.format(",".join(profiling_results['error']['not_found_data_assets'])))
if not profiling_results['success']: # unknown error
raise ge_exceptions.DataContextError("Unknown profiling error code: " + profiling_results['error']['code'])
def _get_batch_kwargs_from_generator_or_from_file_path(context, datasource_name,
generator_name=None,
additional_batch_kwargs={}):
msg_prompt_generator_or_file_path = """
Would you like to:
1. choose from a list of data assets in this datasource
2. enter the path of a data file
"""
msg_prompt_file_path = """
Enter the path (relative or absolute) of a data file
"""
msg_prompt_enter_data_asset_name = "\nWhich data would you like to use?\n"
msg_prompt_enter_data_asset_name_suffix = " Don't see the name of the data asset in the list above? Just type it\n"
msg_prompt_file_type = """
We could not determine the format of the file. What is it?
1. CSV
2. Parquet
3. Excel
4. JSON
"""
reader_method_file_extensions = {
"1": "csv",
"2": "parquet",
"3": "xlsx",
"4": "json",
}
generator_asset = None
datasource = context.get_datasource(datasource_name)
if generator_name is not None:
generator = datasource.get_generator(generator_name)
option_selection = click.prompt(
msg_prompt_generator_or_file_path,
type=click.Choice(["1", "2"]),
show_choices=False
)
if option_selection == "1":
available_data_asset_names = sorted(generator.get_available_data_asset_names()["names"], key=lambda x: x[0])
available_data_asset_names_str = ["{} ({})".format(name[0], name[1]) for name in
available_data_asset_names]
data_asset_names_to_display = available_data_asset_names_str[:50]
choices = "\n".join([" {}. {}".format(i, name) for i, name in enumerate(data_asset_names_to_display, 1)])
prompt = msg_prompt_enter_data_asset_name + choices + "\n" + msg_prompt_enter_data_asset_name_suffix.format(
len(data_asset_names_to_display))
generator_asset_selection = click.prompt(prompt, default=None, show_default=False)
generator_asset_selection = generator_asset_selection.strip()
try:
data_asset_index = int(generator_asset_selection) - 1
try:
generator_asset = \
[name[0] for name in available_data_asset_names][data_asset_index]
except IndexError:
pass
except ValueError:
generator_asset = generator_asset_selection
batch_kwargs = generator.build_batch_kwargs(generator_asset, **additional_batch_kwargs)
return (generator_asset, batch_kwargs)
# No generator name was passed or the user chose to enter a file path
# We should allow a directory for Spark, but not for Pandas
dir_okay = isinstance(datasource, SparkDFDatasource)
path = None
while True:
path = click.prompt(
msg_prompt_file_path,
type=click.Path(
exists=True,
file_okay=True,
dir_okay=dir_okay,
readable=True
),
show_default=True,
default=path
)
path = os.path.abspath(path)
batch_kwargs = {