Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using a Saved Question, which has a filter to implicit/explicit table, causes wrong aliasing in subsequent nesting #20809

Closed
flamber opened this issue Mar 2, 2022 · 3 comments · Fixed by #24167
Assignees
Labels
.Backend Priority:P2 Average run of the mill bug Querying/Nested Queries Questions based on other saved questions .Regression Bugs that were previously fixed and/or bugs unintentionally shipped with new features. .Reproduced Issues reproduced in test (usually Cypress) Type:Bug Product defects
Milestone

Comments

@flamber
Copy link
Contributor

flamber commented Mar 2, 2022

Describe the bug
Using a Saved Question, which has a filter to implicit/explicit table, causes wrong aliasing in subsequent nesting.
Similar to #18512, just with another nesting, which was also noted in #20519.
Regression since 0.42.0

Happens to all databases, but if the fix needs special tweaking for BigQuery, then that needs to be taken into account too #20772.

To Reproduce

  1. Question > Sample > Reviews - filter by Products.Category, summarize Count group by Reviews.Product_ID - save as "Q1"
    image
  2. Question > Sample > Orders - join "Q1" on Orders.Product_ID=Q1.Product_ID
    image
  3. Add Custom Column 1 + 1 as "CC" - fails with Cannot determine the source table or query for Field clause [:field 107 {:source-field 110, :join-alias "PRODUCTS__via__PRODUCT_ID", :metabase.query-processor.util.add-alias-info/source-table "PRODUCTS__via__PRODUCT_ID", :metabase.query-processor.util.add-alias-info/source-alias "CATEGORY"}]

It doesn't show the full SQL in the stacktrace, which would be helpful.

Full stacktrace
2022-03-02 15:32:18,848 INFO middleware.fetch-source-query :: Fetched source query from Card 847: 
 {:source-table 13,
 :aggregation [[:count]],
 :breakout [[:field 110 nil]],
 :filter [:= [:field 107 {:source-field 110}] "Doohickey"]}

2022-03-02 15:32:18,860 INFO middleware.fetch-source-query :: Fetched source query from Card 847: 
 {:source-table 13,
 :aggregation [[:count]],
 :breakout [[:field 110 nil]],
 :filter [:= [:field 107 {:source-field 110}] "Doohickey"]}

2022-03-02 15:32:20,109 ERROR middleware.catch-exceptions :: Error processing query: null
{:database_id 4,
 :started_at #t "2022-03-02T15:32:18.832986+01:00[Europe/Copenhagen]",
 :error_type :invalid-query,
 :json_query
 {:database 4,
  :query
  {:source-table 11,
   :joins
   [{:fields "all",
     :source-table "card__847",
     :condition ["=" ["field" 82 nil] ["field" 110 {:join-alias "Question 847"}]],
     :alias "Question 847"}],
   :expressions {:CC ["+" 1 1]}},
  :type "query",
  :parameters [],
  :middleware {:js-int-to-string? true, :add-default-userland-constraints? true}},
 :native nil,
 :status :failed,
 :class clojure.lang.ExceptionInfo,
 :stacktrace
 ["--> query_processor.util.add_alias_info$field_source_table_alias.invokeStatic(add_alias_info.clj:182)"
  "query_processor.util.add_alias_info$field_source_table_alias.invoke(add_alias_info.clj:171)"
  "query_processor.util.add_alias_info$fn__43108.invokeStatic(add_alias_info.clj:301)"
  "query_processor.util.add_alias_info$fn__43108.invoke(add_alias_info.clj:298)"
  "query_processor.util.add_alias_info$add_alias_info_STAR_$replace_43144__43145$fn__43152$fn__43153.invoke(add_alias_info.clj:355)"
  "query_processor.util.add_alias_info$add_alias_info_STAR_$replace_43144__43145$fn__43152.invoke(add_alias_info.clj:355)"
  "query_processor.util.add_alias_info$add_alias_info_STAR_$replace_43144__43145.invoke(add_alias_info.clj:355)"
  "mbql.util.match.impl$replace_in_collection.invokeStatic(impl.cljc:47)"
  "mbql.util.match.impl$replace_in_collection.invoke(impl.cljc:38)"
  "query_processor.util.add_alias_info$add_alias_info_STAR_$replace_43144__43145$fn__43152.invoke(add_alias_info.clj:355)"
  "query_processor.util.add_alias_info$add_alias_info_STAR_$replace_43144__43145.invoke(add_alias_info.clj:355)"
  "mbql.util.match.impl$replace_in_collection$iter__27400__27404$fn__27405.invoke(impl.cljc:44)"
  "mbql.util.match.impl$replace_in_collection.invokeStatic(impl.cljc:43)"
  "mbql.util.match.impl$replace_in_collection.invoke(impl.cljc:38)"
  "query_processor.util.add_alias_info$add_alias_info_STAR_$replace_43144__43145$fn__43152.invoke(add_alias_info.clj:355)"
  "query_processor.util.add_alias_info$add_alias_info_STAR_$replace_43144__43145.invoke(add_alias_info.clj:355)"
  "query_processor.util.add_alias_info$add_alias_info_STAR_.invokeStatic(add_alias_info.clj:355)"
  "query_processor.util.add_alias_info$add_alias_info_STAR_.invoke(add_alias_info.clj:352)"
  "query_processor.util.add_alias_info$add_alias_info$fn__43162.invoke(add_alias_info.clj:399)"
  "query_processor.util.add_alias_info$add_alias_info.invokeStatic(add_alias_info.clj:394)"
  "query_processor.util.add_alias_info$add_alias_info.invoke(add_alias_info.clj:365)"
  "query_processor.util.nest_query$nest_expressions.invokeStatic(nest_query.clj:110)"
  "query_processor.util.nest_query$nest_expressions.invoke(nest_query.clj:100)"
  "driver.sql.query_processor$fn__45560.invokeStatic(query_processor.clj:918)"
  "driver.sql.query_processor$fn__45560.invoke(query_processor.clj:916)"
  "driver.sql.query_processor$mbql__GT_honeysql.invokeStatic(query_processor.clj:923)"
  "driver.sql.query_processor$mbql__GT_honeysql.invoke(query_processor.clj:920)"
  "driver.sql.query_processor$mbql__GT_native.invokeStatic(query_processor.clj:934)"
  "driver.sql.query_processor$mbql__GT_native.invoke(query_processor.clj:930)"
  "driver.sql$fn__78595.invokeStatic(sql.clj:40)"
  "driver.sql$fn__78595.invoke(sql.clj:38)"
  "query_processor.middleware.mbql_to_native$query__GT_native_form.invokeStatic(mbql_to_native.clj:14)"
  "query_processor.middleware.mbql_to_native$query__GT_native_form.invoke(mbql_to_native.clj:9)"
  "query_processor.middleware.mbql_to_native$mbql__GT_native$fn__49655.invoke(mbql_to_native.clj:22)"
  "query_processor.middleware.check_features$check_features$fn__50401.invoke(check_features.clj:42)"
  "query_processor.middleware.limit$limit$fn__47991.invoke(limit.clj:37)"
  "query_processor.middleware.cache$maybe_return_cached_results$fn__50784.invoke(cache.clj:204)"
  "query_processor.middleware.optimize_temporal_filters$optimize_temporal_filters$fn__51848.invoke(optimize_temporal_filters.clj:204)"
  "query_processor.middleware.validate_temporal_bucketing$validate_temporal_bucketing$fn__51892.invoke(validate_temporal_bucketing.clj:50)"
  "query_processor.middleware.auto_parse_filter_values$auto_parse_filter_values$fn__49712.invoke(auto_parse_filter_values.clj:43)"
  "query_processor.middleware.wrap_value_literals$wrap_value_literals$fn__39780.invoke(wrap_value_literals.clj:161)"
  "query_processor.middleware.annotate$add_column_info$fn__44546.invoke(annotate.clj:659)"
  "query_processor.middleware.permissions$check_query_permissions$fn__46288.invoke(permissions.clj:108)"
  "query_processor.middleware.pre_alias_aggregations$pre_alias_aggregations$fn__51006.invoke(pre_alias_aggregations.clj:40)"
  "query_processor.middleware.cumulative_aggregations$handle_cumulative_aggregations$fn__46684.invoke(cumulative_aggregations.clj:60)"
  "query_processor.middleware.visualization_settings$update_viz_settings$fn__46622.invoke(visualization_settings.clj:63)"
  "query_processor.middleware.escape_join_aliases$escape_join_aliases_middleware$fn__48032.invoke(escape_join_aliases.clj:64)"
  "query_processor.middleware.fix_bad_references$fix_bad_references_middleware$fn__50971.invoke(fix_bad_references.clj:91)"
  "query_processor.middleware.resolve_joined_fields$resolve_joined_fields$fn__47569.invoke(resolve_joined_fields.clj:111)"
  "query_processor.middleware.resolve_joins$resolve_joins$fn__51618.invoke(resolve_joins.clj:178)"
  "query_processor.middleware.add_implicit_joins$add_implicit_joins$fn__51160.invoke(add_implicit_joins.clj:246)"
  "query_processor.middleware.large_int_id$convert_id_to_string$fn__47588.invoke(large_int_id.clj:59)"
  "query_processor.middleware.format_rows$format_rows$fn__51212.invoke(format_rows.clj:74)"
  "query_processor.middleware.add_default_temporal_unit$add_default_temporal_unit$fn__46956.invoke(add_default_temporal_unit.clj:23)"
  "query_processor.middleware.desugar$desugar$fn__46595.invoke(desugar.clj:21)"
  "query_processor.middleware.binning$update_binning_strategy$fn__39509.invoke(binning.clj:229)"
  "query_processor.middleware.resolve_fields$resolve_fields$fn__45930.invoke(resolve_fields.clj:34)"
  "query_processor.middleware.add_dimension_projections$add_remapping$fn__50338.invoke(add_dimension_projections.clj:487)"
  "query_processor.middleware.add_implicit_clauses$add_implicit_clauses$fn__50632.invoke(add_implicit_clauses.clj:164)"
  "query_processor.middleware.upgrade_field_literals$upgrade_field_literals$fn__47976.invoke(upgrade_field_literals.clj:117)"
  "query_processor.middleware.add_source_metadata$add_source_metadata_for_source_queries$fn__47333.invoke(add_source_metadata.clj:125)"
  "query_processor.middleware.reconcile_breakout_and_order_by_bucketing$reconcile_breakout_and_order_by_bucketing$fn__50883.invoke(reconcile_breakout_and_order_by_bucketing.clj:100)"
  "query_processor.middleware.auto_bucket_datetimes$auto_bucket_datetimes$fn__48970.invoke(auto_bucket_datetimes.clj:147)"
  "query_processor.middleware.resolve_source_table$resolve_source_tables$fn__45911.invoke(resolve_source_table.clj:45)"
  "query_processor.middleware.parameters$substitute_parameters$fn__48624.invoke(parameters.clj:109)"
  "query_processor.middleware.resolve_referenced$resolve_referenced_card_resources$fn__45984.invoke(resolve_referenced.clj:79)"
  "query_processor.middleware.expand_macros$expand_macros$fn__52276.invoke(expand_macros.clj:184)"
  "query_processor.middleware.add_timezone_info$add_timezone_info$fn__48404.invoke(add_timezone_info.clj:15)"
  "query_processor.middleware.splice_params_in_response$splice_params_in_response$fn__51227.invoke(splice_params_in_response.clj:32)"
  "query_processor.middleware.resolve_database_and_driver$resolve_database_and_driver$fn__50643$fn__50648.invoke(resolve_database_and_driver.clj:35)"
  "driver$do_with_driver.invokeStatic(driver.clj:60)"
  "driver$do_with_driver.invoke(driver.clj:56)"
  "query_processor.middleware.resolve_database_and_driver$resolve_database_and_driver$fn__50643.invoke(resolve_database_and_driver.clj:34)"
  "query_processor.middleware.fetch_source_query$resolve_card_id_source_tables$fn__46530.invoke(fetch_source_query.clj:286)"
  "query_processor.middleware.store$initialize_store$fn__46721$fn__46722.invoke(store.clj:11)"
  "query_processor.store$do_with_store.invokeStatic(store.clj:44)"
  "query_processor.store$do_with_store.invoke(store.clj:38)"
  "query_processor.middleware.store$initialize_store$fn__46721.invoke(store.clj:10)"
  "query_processor.middleware.validate$validate_query$fn__50978.invoke(validate.clj:10)"
  "query_processor.middleware.normalize_query$normalize$fn__50985.invoke(normalize_query.clj:22)"
  "query_processor.middleware.add_rows_truncated$add_rows_truncated$fn__48350.invoke(add_rows_truncated.clj:35)"
  "query_processor.middleware.results_metadata$record_and_return_metadata_BANG_$fn__49641.invoke(results_metadata.clj:82)"
  "query_processor.middleware.constraints$add_default_userland_constraints$fn__48368.invoke(constraints.clj:42)"
  "query_processor.middleware.process_userland_query$process_userland_query$fn__50919.invoke(process_userland_query.clj:146)"
  "query_processor.middleware.catch_exceptions$catch_exceptions$fn__51307.invoke(catch_exceptions.clj:169)"
  "query_processor.reducible$async_qp$qp_STAR___43282$thunk__43283.invoke(reducible.clj:103)"
  "query_processor.reducible$async_qp$qp_STAR___43282.invoke(reducible.clj:109)"
  "query_processor.reducible$sync_qp$qp_STAR___43291$fn__43294.invoke(reducible.clj:135)"
  "query_processor.reducible$sync_qp$qp_STAR___43291.invoke(reducible.clj:134)"
  "query_processor$process_userland_query.invokeStatic(query_processor.clj:247)"
  "query_processor$process_userland_query.doInvoke(query_processor.clj:243)"
  "query_processor$fn__52324$process_query_and_save_execution_BANG___52333$fn__52336.invoke(query_processor.clj:258)"
  "query_processor$fn__52324$process_query_and_save_execution_BANG___52333.invoke(query_processor.clj:251)"
  "query_processor$fn__52368$process_query_and_save_with_max_results_constraints_BANG___52377$fn__52380.invoke(query_processor.clj:270)"
  "query_processor$fn__52368$process_query_and_save_with_max_results_constraints_BANG___52377.invoke(query_processor.clj:263)"
  "api.dataset$run_query_async$fn__65303.invoke(dataset.clj:69)"
  "query_processor.streaming$streaming_response_STAR_$fn__38418$fn__38419.invoke(streaming.clj:162)"
  "query_processor.streaming$streaming_response_STAR_$fn__38418.invoke(streaming.clj:161)"
  "async.streaming_response$do_f_STAR_.invokeStatic(streaming_response.clj:65)"
  "async.streaming_response$do_f_STAR_.invoke(streaming_response.clj:63)"
  "async.streaming_response$do_f_async$task__26888.invoke(streaming_response.clj:84)"],
 :card_id nil,
 :context :ad-hoc,
 :error
 "Cannot determine the source table or query for Field clause [:field 107 {:source-field 110, :join-alias \"PRODUCTS__via__PRODUCT_ID\", :metabase.query-processor.util.add-alias-info/source-table \"PRODUCTS__via__PRODUCT_ID\", :metabase.query-processor.util.add-alias-info/source-alias \"CATEGORY\"}]",
 :row_count 0,
 :running_time 0,
 :preprocessed
 {:database 4,
  :query
  {:source-table 11,
   :expressions {:CC [:+ 1 1]},
   :fields
   [[:field 83 nil]
    [:field 80 nil]
    [:field 82 nil]
    [:field 84 nil]
    [:field 87 nil]
    [:field 88 nil]
    [:field 81 nil]
    [:field 86 {:temporal-unit :default}]
    [:field 85 nil]
    [:expression "CC"]
    [:field 110 {:join-alias "Question 847"}]
    [:field "count" {:base-type :type/BigInteger, :join-alias "Question 847"}]],
   :joins
   [{:alias "Question 847",
     :strategy :left-join,
     :fields
     [[:field 110 {:join-alias "Question 847"}]
      [:field "count" {:base-type :type/BigInteger, :join-alias "Question 847"}]],
     :condition [:= [:field 82 nil] [:field 110 {:join-alias "Question 847"}]],
     :source-card-id 847,
     :source-query
     {:source-table 13,
      :aggregation [[:aggregation-options [:count] {:name "count"}]],
      :breakout [[:field 110 nil]],
      :filter
      [:=
       [:field 107 {:source-field 110, :join-alias "PRODUCTS__via__PRODUCT_ID"}]
       [:value
        "Doohickey"
        {:base_type :type/Text,
         :effective_type :type/Text,
         :coercion_strategy nil,
         :semantic_type :type/Category,
         :database_type "VARCHAR",
         :name "CATEGORY"}]],
      :order-by [[:asc [:field 110 nil]]],
      :joins
      [{:alias "PRODUCTS__via__PRODUCT_ID",
        :strategy :left-join,
        :condition [:= [:field 110 nil] [:field 105 {:join-alias "PRODUCTS__via__PRODUCT_ID"}]],
        :source-table 10,
        :fk-field-id 110}]},
     :source-metadata
     [{:description "The product the review was for",
       :semantic_type :type/FK,
       :table_id 13,
       :coercion_strategy nil,
       :name "PRODUCT_ID",
       :settings nil,
       :source :breakout,
       :field_ref [:field 110 nil],
       :effective_type :type/Integer,
       :parent_id nil,
       :id 110,
       :visibility_type :normal,
       :display_name "Product ID",
       :fingerprint {:global {:distinct-count 176, :nil% 0.0}},
       :base_type :type/Integer}
      {:base_type :type/BigInteger,
       :semantic_type :type/Quantity,
       :name "count",
       :display_name "Count",
       :source :aggregation,
       :field_ref [:aggregation 0]}]}],
   :limit 2000},
  :type :query,
  :middleware {:js-int-to-string? true, :add-default-userland-constraints? true},
  :info
  {:executed-by 1,
   :context :ad-hoc,
   :nested? false,
   :query-hash
   [-25, -117, 4, -9, 53, 100, -52, -46, 65, 58, 111, 70, -112, 67, 16, 90, 107, 69, 82, -119, -75, -41, 102, 56, 100,
    -15, -6, -120, 5, -63, 7, 91]},
  :constraints {:max-results 10000, :max-results-bare-rows 2000}},
 :ex-data
 {:type :invalid-query,
  :clause
  [:field
   107
   {:source-field 110,
    :join-alias "PRODUCTS__via__PRODUCT_ID",
    :metabase.query-processor.util.add-alias-info/source-table "PRODUCTS__via__PRODUCT_ID",
    :metabase.query-processor.util.add-alias-info/source-alias "CATEGORY"}],
  :query
  {:source-table 11,
   :expressions {:CC [:+ 1 1]},
   :fields
   ([:field
     83
     {:metabase.query-processor.util.add-alias-info/source-table 11,
      :metabase.query-processor.util.add-alias-info/source-alias "ID",
      :metabase.query-processor.util.add-alias-info/desired-alias "ID",
      :metabase.query-processor.util.add-alias-info/position 0}]
    [:field
     80
     {:metabase.query-processor.util.add-alias-info/source-table 11,
      :metabase.query-processor.util.add-alias-info/source-alias "USER_ID",
      :metabase.query-processor.util.add-alias-info/desired-alias "USER_ID",
      :metabase.query-processor.util.add-alias-info/position 1}]
    [:field
     82
     {:metabase.query-processor.util.add-alias-info/source-table 11,
      :metabase.query-processor.util.add-alias-info/source-alias "PRODUCT_ID",
      :metabase.query-processor.util.add-alias-info/desired-alias "PRODUCT_ID",
      :metabase.query-processor.util.add-alias-info/position 2}]
    [:field
     84
     {:metabase.query-processor.util.add-alias-info/source-table 11,
      :metabase.query-processor.util.add-alias-info/source-alias "SUBTOTAL",
      :metabase.query-processor.util.add-alias-info/desired-alias "SUBTOTAL",
      :metabase.query-processor.util.add-alias-info/position 3}]
    [:field
     87
     {:metabase.query-processor.util.add-alias-info/source-table 11,
      :metabase.query-processor.util.add-alias-info/source-alias "TAX",
      :metabase.query-processor.util.add-alias-info/desired-alias "TAX",
      :metabase.query-processor.util.add-alias-info/position 4}]
    [:field
     88
     {:metabase.query-processor.util.add-alias-info/source-table 11,
      :metabase.query-processor.util.add-alias-info/source-alias "TOTAL",
      :metabase.query-processor.util.add-alias-info/desired-alias "TOTAL",
      :metabase.query-processor.util.add-alias-info/position 5}]
    [:field
     81
     {:metabase.query-processor.util.add-alias-info/source-table 11,
      :metabase.query-processor.util.add-alias-info/source-alias "DISCOUNT",
      :metabase.query-processor.util.add-alias-info/desired-alias "DISCOUNT",
      :metabase.query-processor.util.add-alias-info/position 6}]
    [:field
     86
     {:temporal-unit :default,
      :metabase.query-processor.util.add-alias-info/source-table 11,
      :metabase.query-processor.util.add-alias-info/source-alias "CREATED_AT",
      :metabase.query-processor.util.add-alias-info/desired-alias "CREATED_AT",
      :metabase.query-processor.util.add-alias-info/position 7}]
    [:field
     85
     {:metabase.query-processor.util.add-alias-info/source-table 11,
      :metabase.query-processor.util.add-alias-info/source-alias "QUANTITY",
      :metabase.query-processor.util.add-alias-info/desired-alias "QUANTITY",
      :metabase.query-processor.util.add-alias-info/position 8}]
    [:expression
     "CC"
     {:metabase.query-processor.util.add-alias-info/desired-alias "CC",
      :metabase.query-processor.util.add-alias-info/position 9}]
    [:field
     110
     {:join-alias "Question 847",
      :metabase.query-processor.util.add-alias-info/source-table "Question 847",
      :metabase.query-processor.util.add-alias-info/source-alias "PRODUCT_ID",
      :metabase.query-processor.util.add-alias-info/desired-alias "Question 847__PRODUCT_ID",
      :metabase.query-processor.util.add-alias-info/position 10}]
    [:field
     "count"
     {:base-type :type/BigInteger,
      :join-alias "Question 847",
      :metabase.query-processor.util.add-alias-info/source-table "Question 847",
      :metabase.query-processor.util.add-alias-info/source-alias "count",
      :metabase.query-processor.util.add-alias-info/desired-alias "Question 847__count",
      :metabase.query-processor.util.add-alias-info/position 11}]
    [:field
     107
     {:source-field 110,
      :join-alias "PRODUCTS__via__PRODUCT_ID",
      :metabase.query-processor.util.add-alias-info/source-table "PRODUCTS__via__PRODUCT_ID",
      :metabase.query-processor.util.add-alias-info/source-alias "CATEGORY"}]
    [:field
     105
     {:join-alias "PRODUCTS__via__PRODUCT_ID",
      :metabase.query-processor.util.add-alias-info/source-table "PRODUCTS__via__PRODUCT_ID",
      :metabase.query-processor.util.add-alias-info/source-alias "ID"}]),
   :joins
   [{:alias "Question 847",
     :strategy :left-join,
     :fields
     [[:field
       110
       {:join-alias "Question 847",
        :metabase.query-processor.util.add-alias-info/source-table "Question 847",
        :metabase.query-processor.util.add-alias-info/source-alias "PRODUCT_ID",
        :metabase.query-processor.util.add-alias-info/desired-alias "Question 847__PRODUCT_ID",
        :metabase.query-processor.util.add-alias-info/position 10}]
      [:field
       "count"
       {:base-type :type/BigInteger,
        :join-alias "Question 847",
        :metabase.query-processor.util.add-alias-info/source-table "Question 847",
        :metabase.query-processor.util.add-alias-info/source-alias "count",
        :metabase.query-processor.util.add-alias-info/desired-alias "Question 847__count",
        :metabase.query-processor.util.add-alias-info/position 11}]],
     :condition
     [:=
      [:field
       82
       {:metabase.query-processor.util.add-alias-info/source-table 11,
        :metabase.query-processor.util.add-alias-info/source-alias "PRODUCT_ID",
        :metabase.query-processor.util.add-alias-info/desired-alias "PRODUCT_ID",
        :metabase.query-processor.util.add-alias-info/position 2}]
      [:field
       110
       {:join-alias "Question 847",
        :metabase.query-processor.util.add-alias-info/source-table "Question 847",
        :metabase.query-processor.util.add-alias-info/source-alias "PRODUCT_ID",
        :metabase.query-processor.util.add-alias-info/desired-alias "Question 847__PRODUCT_ID",
        :metabase.query-processor.util.add-alias-info/position 10}]],
     :source-card-id 847,
     :source-query
     {:source-table 13,
      :aggregation
      [[:aggregation-options
        [:count]
        {:name "count",
         :metabase.query-processor.util.add-alias-info/position 1,
         :metabase.query-processor.util.add-alias-info/desired-alias "count"}]],
      :breakout
      [[:field
        110
        {:metabase.query-processor.util.add-alias-info/source-table 13,
         :metabase.query-processor.util.add-alias-info/source-alias "PRODUCT_ID",
         :metabase.query-processor.util.add-alias-info/desired-alias "PRODUCT_ID",
         :metabase.query-processor.util.add-alias-info/position 0}]],
      :filter
      [:=
       [:field
        107
        {:source-field 110,
         :join-alias "PRODUCTS__via__PRODUCT_ID",
         :metabase.query-processor.util.add-alias-info/source-table "PRODUCTS__via__PRODUCT_ID",
         :metabase.query-processor.util.add-alias-info/source-alias "CATEGORY"}]
       [:value
        "Doohickey"
        {:base-type :type/Text,
         :effective-type :type/Text,
         :semantic-type :type/Category,
         :database-type "VARCHAR",
         :name "CATEGORY"}]],
      :order-by
      [[:asc
        [:field
         110
         {:metabase.query-processor.util.add-alias-info/source-table 13,
          :metabase.query-processor.util.add-alias-info/source-alias "PRODUCT_ID",
          :metabase.query-processor.util.add-alias-info/desired-alias "PRODUCT_ID",
          :metabase.query-processor.util.add-alias-info/position 0}]]],
      :joins
      [{:alias "PRODUCTS__via__PRODUCT_ID",
        :strategy :left-join,
        :condition
        [:=
         [:field
          110
          {:metabase.query-processor.util.add-alias-info/source-table 13,
           :metabase.query-processor.util.add-alias-info/source-alias "PRODUCT_ID",
           :metabase.query-processor.util.add-alias-info/desired-alias "PRODUCT_ID",
           :metabase.query-processor.util.add-alias-info/position 0}]
         [:field
          105
          {:join-alias "PRODUCTS__via__PRODUCT_ID",
           :metabase.query-processor.util.add-alias-info/source-table "PRODUCTS__via__PRODUCT_ID",
           :metabase.query-processor.util.add-alias-info/source-alias "ID"}]],
        :source-table 10,
        :fk-field-id 110}]},
     :source-metadata
     [{:description "The product the review was for",
       :semantic_type :type/FK,
       :table_id 13,
       :name "PRODUCT_ID",
       :source :breakout,
       :field_ref [:field 110 nil],
       :effective_type :type/Integer,
       :id 110,
       :visibility_type :normal,
       :display_name "Product ID",
       :fingerprint {:global {:distinct-count 176, :nil% 0.0}},
       :base_type :type/Integer}
      {:base_type :type/BigInteger,
       :semantic_type :type/Quantity,
       :name "count",
       :display_name "Count",
       :source :aggregation,
       :field_ref [:aggregation 0]}]}]}},
 :data {:rows [], :cols []}}

2022-03-02 15:32:20,118 DEBUG middleware.log :: POST /api/dataset 202 [ASYNC: completed] 1.3 s (28 DB calls) App DB connections: 0/7 Jetty threads: 3/50 (2 idle, 0 queued) (54 total active threads) Queries in flight: 1 (0 queued)

Information about your Metabase Installation:
Tested 0.41.6 thru 0.42.2

@flamber flamber added Type:Bug Product defects Priority:P2 Average run of the mill bug Querying/Nested Queries Questions based on other saved questions .Backend .Regression Bugs that were previously fixed and/or bugs unintentionally shipped with new features. labels Mar 2, 2022
@camsaul camsaul self-assigned this Mar 7, 2022
@igorkova
Copy link

Hi @camsaul 👋
Our company's BI efforts are basically in "freeze" state for the last 6 months. We have been hit previously by: #16656 (comment) with hopes that 0.42 will unblock us.

Unfortunately, we are again hit by (we think) this aliasing issue.

While we do understand that you have a lot of things on your plate, we'd just like to understand do you see this issue being solved short-term by any chance?
Alternatively, is there another tier of Metabase (pro/enterprise) which is not affected by these bugs?

@flamber
Copy link
Contributor Author

flamber commented Mar 19, 2022

@igorkova All versions of Metabase behave the same. There's just more functionality on Pro/Enterprise.
We are trying to address the issue, but nested queries becomes complex, so it's difficult to fix things without causing regressions.

Since you're unsure if you are seeing this issue, then please use the forum for questions and troubleshooting: https://discourse.metabase.com/

@attaxia

This comment was marked as duplicate.

nemanjaglumac added a commit that referenced this issue Jun 28, 2022
nemanjaglumac added a commit that referenced this issue Jun 28, 2022
github-actions bot pushed a commit that referenced this issue Jun 28, 2022
nemanjaglumac added a commit that referenced this issue Jun 29, 2022
Co-authored-by: Nemanja Glumac <31325167+nemanjaglumac@users.noreply.github.com>
@nemanjaglumac nemanjaglumac added the .Reproduced Issues reproduced in test (usually Cypress) label Jun 29, 2022
dpsutton added a commit that referenced this issue Jul 25, 2022
This test is essentially the repro from the ticket
#20809

```clojure
debug-qp=> (to-mbql-shorthand (:dataset_query (metabase.models/Card 4919)))
(mt/mbql-query
 orders
 {:joins [{:source-table "card__4918",
           :alias "Question 4918",
           :condition [:=
                       $product_id
                       [:field
                        %reviews.product_id
                        {:join-alias "Question 4918"}]],
           :fields :all}],
  :expressions {"CC" [:+ 1 1]}})
debug-qp=> (to-mbql-shorthand (:dataset_query (metabase.models/Card 4918)))
(mt/mbql-query
 reviews
 {:breakout [$product_id],
  :aggregation [[:count]],
  :filter [:= $product_id->products.category "Doohickey"]})
```

Thanks to @Cam for providing such a lovely tool
dpsutton added a commit that referenced this issue Jul 25, 2022
* Ignore fields in joins when hoisting joined fields

Need to understand two sides of mbql to understand this.

```clojure
(defn nest-expressions
  "Pushes the `:source-table`/`:source-query`, `:expressions`, and `:joins` in the top-level of the query into a
  `:source-query` and updates `:expression` references and `:field` clauses with `:join-alias`es accordingly. See
  tests for examples. This is used by the SQL QP to make sure expressions happen in a subselect."
  ...)
```

Make a query against the orders table joined to the people table and
select order id, order total, and the person's email:

```sql
 SELECT "PUBLIC"."orders"."id"    AS "ID",
       "PUBLIC"."orders"."total" AS "TOTAL",
       "People - User"."email"   AS "People - User__EMAIL"
FROM   "PUBLIC"."orders"
       LEFT JOIN "PUBLIC"."people" "People - User"
              ON "PUBLIC"."orders"."user_id" = "People - User"."id"
LIMIT  1048575
```

Now add a custom column called adjective, which is 'expensive' when
total > 100 else 'cheap'
```sql
 SELECT "source"."id"                   AS "ID",
       "source"."total"                AS "TOTAL",
       "source"."adjective"            AS "adjective",
       "source"."people - user__email" AS "People - User__EMAIL"
FROM   (SELECT "PUBLIC"."orders"."id"         AS "ID",
               "PUBLIC"."orders"."user_id"    AS "USER_ID",
               "PUBLIC"."orders"."product_id" AS "PRODUCT_ID",
               "PUBLIC"."orders"."subtotal"   AS "SUBTOTAL",
               "PUBLIC"."orders"."tax"        AS "TAX",
               "PUBLIC"."orders"."total"      AS "TOTAL",
               "PUBLIC"."orders"."discount"   AS "DISCOUNT",
               "PUBLIC"."orders"."created_at" AS "CREATED_AT",
               "PUBLIC"."orders"."quantity"   AS "QUANTITY",
               CASE
                 WHEN "PUBLIC"."orders"."total" > 50 THEN 'expensive'
                 ELSE 'cheap'
               end                            AS "adjective",
               "People - User"."email"        AS "People - User__EMAIL",
               "People - User"."id"           AS "People - User__ID"
        FROM   "PUBLIC"."orders"
               LEFT JOIN "PUBLIC"."people" "People - User"
                      ON "PUBLIC"."orders"."user_id" = "People - User"."id")
       "source"
LIMIT  1048575
```

We put the "work" in a nested query and then just update the outer
select to select `source.total` instead of `orders.total`. But the way
this figured out which joins to hoist up was a bit broken. It walked all
over the inner query, finding fields it was interested in. However, it
also got fields it shouldn't have, by descending into join information
that should be opaque at this level.

In the repro for this, we make a card Q1, selecting product_id and
count, but with an implicit join to products and filtering where
category = doohickey.

```clojure
;; card Q1
{:type :query,
 :query {:source-table 4,     #_ reviews
         :filter [:= [:field 26 {:source-field 33}] "Doohickey"], #_ products.category
         :aggregation [[:count]],
         :breakout [[:field 33 nil]],  #_ reviews.product_id
         :limit 2},
 :database 1}
 ```

A second question Q2 queries the Orders table and joins to Q1 on
orders.product_id = q1.product_id, and adds a custom column `+ 1 1`.
```
;; card Q2, based on Q1
{:source-table 2,
 :expressions {"CC" [:+ 1 1]},
 :fields [[:field 9 nil]
          [:field 3 nil]
          [:field 5 nil]
          [:field 6 nil]
          [:field 8 nil]
          [:field 7 nil]
          [:field 1 nil]
          [:field 4 {:temporal-unit :default}]
          [:field 2 nil]
          [:expression
           "CC"
           {:metabase.query-processor.util.add-alias-info/desired-alias "CC",
            :metabase.query-processor.util.add-alias-info/position 9}]
          [:field 33 nil]
          [:field "count" {:base-type :type/BigInteger}]],
 :joins [{:alias "Question 4918",
          :strategy :left-join,
          :fields [[:field 33 nil]
                   [:field "count" {:base-type :type/BigInteger}]],
          :condition [:=
                      [:field 5 nil]
                      [:field 33 nil]],
          :source-card-id 4918,
          }]}
```

and this should yield the sql:

```sql
SELECT "source"."ID" AS "ID",
       "source"."PRODUCT_ID" AS "PRODUCT_ID",
       "source"."TOTAL" AS "TOTAL",
       "source"."CC" AS "CC",
       "source"."Question 4918__PRODUCT_ID" AS "Question 4918__PRODUCT_ID",
       "source"."Question 4918__count" AS "Question 4918__count"
FROM (
  SELECT "PUBLIC"."ORDERS"."ID" AS "ID",
         "PUBLIC"."ORDERS"."USER_ID" AS "USER_ID",
         "PUBLIC"."ORDERS"."PRODUCT_ID" AS "PRODUCT_ID",
         "PUBLIC"."ORDERS"."SUBTOTAL" AS "SUBTOTAL",
         "PUBLIC"."ORDERS"."TAX" AS "TAX",
         "PUBLIC"."ORDERS"."TOTAL" AS "TOTAL",
         "PUBLIC"."ORDERS"."DISCOUNT" AS "DISCOUNT",
         "PUBLIC"."ORDERS"."CREATED_AT" AS "CREATED_AT",
         "PUBLIC"."ORDERS"."QUANTITY" AS "QUANTITY",
         (1 + 1) AS "CC",
         "Question 4918"."PRODUCT_ID" AS "Question 4918__PRODUCT_ID",
         "Question 4918"."count" AS "Question 4918__count"
  FROM "PUBLIC"."ORDERS"
  LEFT JOIN (
    SELECT "PUBLIC"."REVIEWS"."PRODUCT_ID" AS "PRODUCT_ID",
           count(*) AS "count"
    FROM "PUBLIC"."REVIEWS"
    LEFT JOIN "PUBLIC"."PRODUCTS" "PRODUCTS__via__PRODUCT_ID"
      ON "PUBLIC"."REVIEWS"."PRODUCT_ID" = "PRODUCTS__via__PRODUCT_ID"."ID"
    WHERE "PRODUCTS__via__PRODUCT_ID"."CATEGORY" = 'Doohickey'
    GROUP BY "PUBLIC"."REVIEWS"."PRODUCT_ID"
    ORDER BY "PUBLIC"."REVIEWS"."PRODUCT_ID" ASC) "Question 4918"
  ON "PUBLIC"."ORDERS"."PRODUCT_ID" = "Question 4918"."PRODUCT_ID") "source"
LIMIT 1048575
```

But when it was looking through to see which fields to hoist top level,
it was also finding `"PRODUCTS__via__PRODUCT_ID"."ID"` and
`"PRODUCTS__via__PRODUCT_ID"."CATEGORY"` as fields it should hoist up
because it searched the whole tree underneath it which includes join
conditions and such.

But of course that doesn't matter, the only thing is really analyzing
what fields come out of a query, and those fields do not come out of the
nested query

```sql
    SELECT "PUBLIC"."REVIEWS"."PRODUCT_ID" AS "PRODUCT_ID",
           count(*) AS "count"
    FROM "PUBLIC"."REVIEWS"
    LEFT JOIN "PUBLIC"."PRODUCTS" "PRODUCTS__via__PRODUCT_ID"
      ON "PUBLIC"."REVIEWS"."PRODUCT_ID" = "PRODUCTS__via__PRODUCT_ID"."ID"
    WHERE "PRODUCTS__via__PRODUCT_ID"."CATEGORY" = 'Doohickey'
    GROUP BY "PUBLIC"."REVIEWS"."PRODUCT_ID"
    ORDER BY "PUBLIC"."REVIEWS"."PRODUCT_ID" ASC) "Question 4918"
```

that only returns product_id and count.

And this matches the error it was (helpfully) throwing:

```clojure
investigation=> (qp/compile nested-query)
Execution error (ExceptionInfo) at metabase.query-processor.util.add-alias-info/field-source-table-alias (add_alias_info.clj:182).
Cannot determine the source table or query for Field clause
[:field
 26 #_ products.category
 {:source-field 33, #_reviews.product_id
  :join-alias "PRODUCTS__via__PRODUCT_ID",
  :metabase.query-processor.util.add-alias-info/source-table "PRODUCTS__via__PRODUCT_ID",
  :metabase.query-processor.util.add-alias-info/source-alias "CATEGORY"}]
```

And here's the query it was analyzing when determining which fields it
needed to hoist (looking for ones with `:join-alias` (which is also in
the nest_query_test.clj file):

```clojure
;; removed some cruft and extra field information for brevity
{:source-table 2,
 :expressions  {"CC" [:+ 1 1]},
 :fields       [[:field 33 {:join-alias "Question 4918",}]
                [:field "count" {:join-alias "Question 4918"}]]
 :joins        [{:alias           "Question 4918",
                 :strategy        :left-join,
                 :fields          [[:field 33 {:join-alias "Question 4918"}]
                                   [:field
                                    "count"
                                    {:join-alias "Question 4918"}]]
                 :condition       [:=
                                   [:field 5 nil]
                                   [:field 33 {:join-alias "Question 4918",}]],
                 :source-card-id  4918,
                 :source-query    {:source-table 4,
                                   ;; nested query has filter values with join-alias that should not
                                   ;; be selected
                                   :filter       [:=
                                                  [:field 26 {:join-alias "PRODUCTS__via__PRODUCT_ID"}]
                                                  [:value "Doohickey" {}]],
                                   :aggregation  [[:aggregation-options
                                                   [:count]
                                                   {:name "count"}]],
                                   :breakout     [[:field 33 nil]],
                                   :limit        2,
                                   :order-by     [[:asc
                                                   [:field 33 nil]]],
                                   ;; nested query has an implicit join with conditions that should
                                   ;; not be selected
                                   :joins        [{:alias        "PRODUCTS__via__PRODUCT_ID",
                                                   :strategy     :left-join,
                                                   :condition    [:=
                                                                  [:field 33 nil]
                                                                  [:field
                                                                   30
                                                                   {:join-alias "PRODUCTS__via__PRODUCT_ID"}]]
                                                   :source-table 1,
                                                   :fk-field-id  33}]},
                 :source-metadata [{:field_ref [:field 33 nil]}
                                   {:field_ref [:aggregation 0]}]}]}
```

* Add round-trip test through qp

This test is essentially the repro from the ticket
#20809

```clojure
debug-qp=> (to-mbql-shorthand (:dataset_query (metabase.models/Card 4919)))
(mt/mbql-query
 orders
 {:joins [{:source-table "card__4918",
           :alias "Question 4918",
           :condition [:=
                       $product_id
                       [:field
                        %reviews.product_id
                        {:join-alias "Question 4918"}]],
           :fields :all}],
  :expressions {"CC" [:+ 1 1]}})
debug-qp=> (to-mbql-shorthand (:dataset_query (metabase.models/Card 4918)))
(mt/mbql-query
 reviews
 {:breakout [$product_id],
  :aggregation [[:count]],
  :filter [:= $product_id->products.category "Doohickey"]})
```

Thanks to @Cam for providing such a lovely tool
@flamber flamber added this to the 0.44 milestone Jul 25, 2022
github-actions bot pushed a commit that referenced this issue Jul 25, 2022
* Ignore fields in joins when hoisting joined fields

Need to understand two sides of mbql to understand this.

```clojure
(defn nest-expressions
  "Pushes the `:source-table`/`:source-query`, `:expressions`, and `:joins` in the top-level of the query into a
  `:source-query` and updates `:expression` references and `:field` clauses with `:join-alias`es accordingly. See
  tests for examples. This is used by the SQL QP to make sure expressions happen in a subselect."
  ...)
```

Make a query against the orders table joined to the people table and
select order id, order total, and the person's email:

```sql
 SELECT "PUBLIC"."orders"."id"    AS "ID",
       "PUBLIC"."orders"."total" AS "TOTAL",
       "People - User"."email"   AS "People - User__EMAIL"
FROM   "PUBLIC"."orders"
       LEFT JOIN "PUBLIC"."people" "People - User"
              ON "PUBLIC"."orders"."user_id" = "People - User"."id"
LIMIT  1048575
```

Now add a custom column called adjective, which is 'expensive' when
total > 100 else 'cheap'
```sql
 SELECT "source"."id"                   AS "ID",
       "source"."total"                AS "TOTAL",
       "source"."adjective"            AS "adjective",
       "source"."people - user__email" AS "People - User__EMAIL"
FROM   (SELECT "PUBLIC"."orders"."id"         AS "ID",
               "PUBLIC"."orders"."user_id"    AS "USER_ID",
               "PUBLIC"."orders"."product_id" AS "PRODUCT_ID",
               "PUBLIC"."orders"."subtotal"   AS "SUBTOTAL",
               "PUBLIC"."orders"."tax"        AS "TAX",
               "PUBLIC"."orders"."total"      AS "TOTAL",
               "PUBLIC"."orders"."discount"   AS "DISCOUNT",
               "PUBLIC"."orders"."created_at" AS "CREATED_AT",
               "PUBLIC"."orders"."quantity"   AS "QUANTITY",
               CASE
                 WHEN "PUBLIC"."orders"."total" > 50 THEN 'expensive'
                 ELSE 'cheap'
               end                            AS "adjective",
               "People - User"."email"        AS "People - User__EMAIL",
               "People - User"."id"           AS "People - User__ID"
        FROM   "PUBLIC"."orders"
               LEFT JOIN "PUBLIC"."people" "People - User"
                      ON "PUBLIC"."orders"."user_id" = "People - User"."id")
       "source"
LIMIT  1048575
```

We put the "work" in a nested query and then just update the outer
select to select `source.total` instead of `orders.total`. But the way
this figured out which joins to hoist up was a bit broken. It walked all
over the inner query, finding fields it was interested in. However, it
also got fields it shouldn't have, by descending into join information
that should be opaque at this level.

In the repro for this, we make a card Q1, selecting product_id and
count, but with an implicit join to products and filtering where
category = doohickey.

```clojure
;; card Q1
{:type :query,
 :query {:source-table 4,     #_ reviews
         :filter [:= [:field 26 {:source-field 33}] "Doohickey"], #_ products.category
         :aggregation [[:count]],
         :breakout [[:field 33 nil]],  #_ reviews.product_id
         :limit 2},
 :database 1}
 ```

A second question Q2 queries the Orders table and joins to Q1 on
orders.product_id = q1.product_id, and adds a custom column `+ 1 1`.
```
;; card Q2, based on Q1
{:source-table 2,
 :expressions {"CC" [:+ 1 1]},
 :fields [[:field 9 nil]
          [:field 3 nil]
          [:field 5 nil]
          [:field 6 nil]
          [:field 8 nil]
          [:field 7 nil]
          [:field 1 nil]
          [:field 4 {:temporal-unit :default}]
          [:field 2 nil]
          [:expression
           "CC"
           {:metabase.query-processor.util.add-alias-info/desired-alias "CC",
            :metabase.query-processor.util.add-alias-info/position 9}]
          [:field 33 nil]
          [:field "count" {:base-type :type/BigInteger}]],
 :joins [{:alias "Question 4918",
          :strategy :left-join,
          :fields [[:field 33 nil]
                   [:field "count" {:base-type :type/BigInteger}]],
          :condition [:=
                      [:field 5 nil]
                      [:field 33 nil]],
          :source-card-id 4918,
          }]}
```

and this should yield the sql:

```sql
SELECT "source"."ID" AS "ID",
       "source"."PRODUCT_ID" AS "PRODUCT_ID",
       "source"."TOTAL" AS "TOTAL",
       "source"."CC" AS "CC",
       "source"."Question 4918__PRODUCT_ID" AS "Question 4918__PRODUCT_ID",
       "source"."Question 4918__count" AS "Question 4918__count"
FROM (
  SELECT "PUBLIC"."ORDERS"."ID" AS "ID",
         "PUBLIC"."ORDERS"."USER_ID" AS "USER_ID",
         "PUBLIC"."ORDERS"."PRODUCT_ID" AS "PRODUCT_ID",
         "PUBLIC"."ORDERS"."SUBTOTAL" AS "SUBTOTAL",
         "PUBLIC"."ORDERS"."TAX" AS "TAX",
         "PUBLIC"."ORDERS"."TOTAL" AS "TOTAL",
         "PUBLIC"."ORDERS"."DISCOUNT" AS "DISCOUNT",
         "PUBLIC"."ORDERS"."CREATED_AT" AS "CREATED_AT",
         "PUBLIC"."ORDERS"."QUANTITY" AS "QUANTITY",
         (1 + 1) AS "CC",
         "Question 4918"."PRODUCT_ID" AS "Question 4918__PRODUCT_ID",
         "Question 4918"."count" AS "Question 4918__count"
  FROM "PUBLIC"."ORDERS"
  LEFT JOIN (
    SELECT "PUBLIC"."REVIEWS"."PRODUCT_ID" AS "PRODUCT_ID",
           count(*) AS "count"
    FROM "PUBLIC"."REVIEWS"
    LEFT JOIN "PUBLIC"."PRODUCTS" "PRODUCTS__via__PRODUCT_ID"
      ON "PUBLIC"."REVIEWS"."PRODUCT_ID" = "PRODUCTS__via__PRODUCT_ID"."ID"
    WHERE "PRODUCTS__via__PRODUCT_ID"."CATEGORY" = 'Doohickey'
    GROUP BY "PUBLIC"."REVIEWS"."PRODUCT_ID"
    ORDER BY "PUBLIC"."REVIEWS"."PRODUCT_ID" ASC) "Question 4918"
  ON "PUBLIC"."ORDERS"."PRODUCT_ID" = "Question 4918"."PRODUCT_ID") "source"
LIMIT 1048575
```

But when it was looking through to see which fields to hoist top level,
it was also finding `"PRODUCTS__via__PRODUCT_ID"."ID"` and
`"PRODUCTS__via__PRODUCT_ID"."CATEGORY"` as fields it should hoist up
because it searched the whole tree underneath it which includes join
conditions and such.

But of course that doesn't matter, the only thing is really analyzing
what fields come out of a query, and those fields do not come out of the
nested query

```sql
    SELECT "PUBLIC"."REVIEWS"."PRODUCT_ID" AS "PRODUCT_ID",
           count(*) AS "count"
    FROM "PUBLIC"."REVIEWS"
    LEFT JOIN "PUBLIC"."PRODUCTS" "PRODUCTS__via__PRODUCT_ID"
      ON "PUBLIC"."REVIEWS"."PRODUCT_ID" = "PRODUCTS__via__PRODUCT_ID"."ID"
    WHERE "PRODUCTS__via__PRODUCT_ID"."CATEGORY" = 'Doohickey'
    GROUP BY "PUBLIC"."REVIEWS"."PRODUCT_ID"
    ORDER BY "PUBLIC"."REVIEWS"."PRODUCT_ID" ASC) "Question 4918"
```

that only returns product_id and count.

And this matches the error it was (helpfully) throwing:

```clojure
investigation=> (qp/compile nested-query)
Execution error (ExceptionInfo) at metabase.query-processor.util.add-alias-info/field-source-table-alias (add_alias_info.clj:182).
Cannot determine the source table or query for Field clause
[:field
 26 #_ products.category
 {:source-field 33, #_reviews.product_id
  :join-alias "PRODUCTS__via__PRODUCT_ID",
  :metabase.query-processor.util.add-alias-info/source-table "PRODUCTS__via__PRODUCT_ID",
  :metabase.query-processor.util.add-alias-info/source-alias "CATEGORY"}]
```

And here's the query it was analyzing when determining which fields it
needed to hoist (looking for ones with `:join-alias` (which is also in
the nest_query_test.clj file):

```clojure
;; removed some cruft and extra field information for brevity
{:source-table 2,
 :expressions  {"CC" [:+ 1 1]},
 :fields       [[:field 33 {:join-alias "Question 4918",}]
                [:field "count" {:join-alias "Question 4918"}]]
 :joins        [{:alias           "Question 4918",
                 :strategy        :left-join,
                 :fields          [[:field 33 {:join-alias "Question 4918"}]
                                   [:field
                                    "count"
                                    {:join-alias "Question 4918"}]]
                 :condition       [:=
                                   [:field 5 nil]
                                   [:field 33 {:join-alias "Question 4918",}]],
                 :source-card-id  4918,
                 :source-query    {:source-table 4,
                                   ;; nested query has filter values with join-alias that should not
                                   ;; be selected
                                   :filter       [:=
                                                  [:field 26 {:join-alias "PRODUCTS__via__PRODUCT_ID"}]
                                                  [:value "Doohickey" {}]],
                                   :aggregation  [[:aggregation-options
                                                   [:count]
                                                   {:name "count"}]],
                                   :breakout     [[:field 33 nil]],
                                   :limit        2,
                                   :order-by     [[:asc
                                                   [:field 33 nil]]],
                                   ;; nested query has an implicit join with conditions that should
                                   ;; not be selected
                                   :joins        [{:alias        "PRODUCTS__via__PRODUCT_ID",
                                                   :strategy     :left-join,
                                                   :condition    [:=
                                                                  [:field 33 nil]
                                                                  [:field
                                                                   30
                                                                   {:join-alias "PRODUCTS__via__PRODUCT_ID"}]]
                                                   :source-table 1,
                                                   :fk-field-id  33}]},
                 :source-metadata [{:field_ref [:field 33 nil]}
                                   {:field_ref [:aggregation 0]}]}]}
```

* Add round-trip test through qp

This test is essentially the repro from the ticket
#20809

```clojure
debug-qp=> (to-mbql-shorthand (:dataset_query (metabase.models/Card 4919)))
(mt/mbql-query
 orders
 {:joins [{:source-table "card__4918",
           :alias "Question 4918",
           :condition [:=
                       $product_id
                       [:field
                        %reviews.product_id
                        {:join-alias "Question 4918"}]],
           :fields :all}],
  :expressions {"CC" [:+ 1 1]}})
debug-qp=> (to-mbql-shorthand (:dataset_query (metabase.models/Card 4918)))
(mt/mbql-query
 reviews
 {:breakout [$product_id],
  :aggregation [[:count]],
  :filter [:= $product_id->products.category "Doohickey"]})
```

Thanks to @Cam for providing such a lovely tool
This was referenced Feb 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
.Backend Priority:P2 Average run of the mill bug Querying/Nested Queries Questions based on other saved questions .Regression Bugs that were previously fixed and/or bugs unintentionally shipped with new features. .Reproduced Issues reproduced in test (usually Cypress) Type:Bug Product defects
Projects
None yet
Development

Successfully merging a pull request may close this issue.

6 participants