@@ -776,6 +776,54 @@ def test_unnest(engine, bigquery_dataset):
776776 assert sorted (r [0 ] for r in conn .execute (query )) == ["a" , "b" , "c" , "x" , "y" ]
777777
778778
779+ @pytest .mark .skipif (
780+ packaging .version .parse (sqlalchemy .__version__ ) < packaging .version .parse ("1.4" ),
781+ reason = "unnest (and other table-valued-function) support required version 1.4" ,
782+ )
783+ def test_unnest_with_cte (engine , bigquery_dataset ):
784+ from sqlalchemy import select , func , String
785+ from sqlalchemy_bigquery import ARRAY
786+
787+ conn = engine .connect ()
788+ metadata = MetaData ()
789+ table_name = "test_unnest_with_cte"
790+ table = Table (
791+ f"{ bigquery_dataset } .{ table_name } " ,
792+ metadata ,
793+ Column ("foo" , String ),
794+ Column ("bars" , ARRAY (String )),
795+ )
796+ metadata .create_all (engine )
797+ conn .execute (
798+ table .insert (),
799+ [dict (foo = "first" , bars = ["a" , "b" , "c" ]), dict (foo = "second" , bars = ["x" , "y" ])],
800+ )
801+ selectable = select (table .c ).select_from (table ).cte ("cte" )
802+ query = select (
803+ [
804+ selectable .c .foo ,
805+ func .unnest (selectable .c .bars ).column_valued ("unnest_bars" ),
806+ ]
807+ ).select_from (selectable )
808+ compiled = str (query .compile (engine ))
809+ assert " " .join (compiled .strip ().split ()) == (
810+ f"WITH `cte` "
811+ f"AS (SELECT `{ bigquery_dataset } .{ table_name } `.`foo` AS `foo`,"
812+ f" `{ bigquery_dataset } .{ table_name } `.`bars` AS `bars`"
813+ f" FROM `{ bigquery_dataset } .{ table_name } `) "
814+ f"SELECT `cte`.`foo`, `unnest_bars` "
815+ f"FROM `cte`, unnest(`cte`.`bars`) AS `unnest_bars`"
816+ )
817+
818+ assert sorted (r for r in conn .execute (query )) == [
819+ ("first" , "a" ),
820+ ("first" , "b" ),
821+ ("first" , "c" ),
822+ ("second" , "x" ),
823+ ("second" , "y" ),
824+ ]
825+
826+
779827@pytest .mark .skipif (
780828 packaging .version .parse (sqlalchemy .__version__ ) < packaging .version .parse ("1.4" ),
781829 reason = "regexp_match support requires version 1.4 or higher" ,
0 commit comments