|
| 1 | +# The API demands that the new_dataset_name be uniq within the schema it points to. |
| 2 | +# same behaviour as in the GUI |
| 3 | + |
| 4 | +module Superset |
| 5 | + module Dataset |
| 6 | + class Create < Superset::Request |
| 7 | + |
| 8 | + attr_reader :target_database_id, :new_dataset_name, :new_dataset_schema, :sql |
| 9 | + |
| 10 | + def initialize(target_database_id: , new_dataset_name: , new_dataset_schema: 'public', sql: ) |
| 11 | + @target_database_id = target_database_id |
| 12 | + @new_dataset_name = new_dataset_name |
| 13 | + @new_dataset_schema = new_dataset_schema |
| 14 | + @sql = sql |
| 15 | + end |
| 16 | + |
| 17 | + def perform |
| 18 | + raise "Error: target_database_id integer is required" unless target_database_id.present? && target_database_id.is_a?(Integer) |
| 19 | + raise "Error: new_dataset_name string is required" unless new_dataset_name.present? && new_dataset_name.is_a?(String) |
| 20 | + raise "Error: Dataset Name #{new_dataset_name} is already in use in the schema: #{new_dataset_schema}. Suggest you add (COPY) as a suffix to the name" if new_dataset_name_already_in_use? |
| 21 | + raise "Error: sql string is required" unless sql.present? && sql.is_a?(String) |
| 22 | + |
| 23 | + logger.info("Creating New Dataset #{new_dataset_name} in DB #{target_database_id} Schema #{new_dataset_schema}") |
| 24 | + |
| 25 | + response |
| 26 | + { id: response['id'], dataset_name: response['data']['datasource_name'] } |
| 27 | + end |
| 28 | + |
| 29 | + def response |
| 30 | + @response ||= client.post(route, params) |
| 31 | + end |
| 32 | + |
| 33 | + def params |
| 34 | + { |
| 35 | + "schema": new_dataset_schema, |
| 36 | + "sql": sql, |
| 37 | + "table_name": new_dataset_name, |
| 38 | + "database": target_database_id |
| 39 | + |
| 40 | + # Optional Params .. pulled straight from the GUI swagger example |
| 41 | + |
| 42 | + #"always_filter_main_dttm": false, |
| 43 | + #"external_url": "string", |
| 44 | + #"is_managed_externally": false, |
| 45 | + #"normalize_columns": false, |
| 46 | + # "owners": [ 0 ], |
| 47 | + } |
| 48 | + end |
| 49 | + |
| 50 | + private |
| 51 | + |
| 52 | + # The API demands that the new_dataset_name be uniq within the schema it points to. |
| 53 | + def new_dataset_name_already_in_use? |
| 54 | + Dataset::List.new(title_equals: new_dataset_name, schema_equals: new_dataset_schema, database_id_eq: target_database_id).result.any? |
| 55 | + end |
| 56 | + |
| 57 | + def route |
| 58 | + "dataset/" |
| 59 | + end |
| 60 | + end |
| 61 | + end |
| 62 | +end |
0 commit comments