@@ -173,9 +173,30 @@ def _create_table(
173173 track_rows_processed : bool = True ,
174174 ** kwargs : t .Any ,
175175 ) -> None :
176+ table_name = (
177+ table_name_or_schema .this
178+ if isinstance (table_name_or_schema , exp .Schema )
179+ else table_name_or_schema
180+ )
181+ catalog = exp .to_table (table_name ).catalog or self .get_current_catalog ()
182+
176183 partitioned_by_exps = None
177- if self ._get_catalog_type (self .get_current_catalog ()) == "ducklake" :
184+ insert_expression = None
185+ if self ._get_catalog_type (catalog ) == "ducklake" :
178186 partitioned_by_exps = kwargs .pop ("partitioned_by" , None )
187+ if (
188+ partitioned_by_exps
189+ and expression is not None
190+ and (replace or not exists or not self .table_exists (table_name ))
191+ ):
192+ insert_expression = expression .copy ()
193+ query = t .cast (exp .Query , expression )
194+ expression = (
195+ exp .select ("*" )
196+ .from_ (query .subquery ("_sqlmesh_schema_only" , copy = False ))
197+ .where (exp .false ())
198+ .limit (0 )
199+ )
179200
180201 super ()._create_table (
181202 table_name_or_schema ,
@@ -191,12 +212,6 @@ def _create_table(
191212 )
192213
193214 if partitioned_by_exps :
194- # Schema object contains column definitions, so we extract Table
195- table_name = (
196- table_name_or_schema .this
197- if isinstance (table_name_or_schema , exp .Schema )
198- else table_name_or_schema
199- )
200215 table_name_str = (
201216 table_name .sql (dialect = self .dialect )
202217 if isinstance (table_name , exp .Table )
@@ -207,6 +222,12 @@ def _create_table(
207222 )
208223 self .execute (f"ALTER TABLE { table_name_str } SET PARTITIONED BY ({ partitioned_by_str } );" )
209224
225+ if insert_expression is not None :
226+ self .execute (
227+ exp .insert (insert_expression , exp .to_table (table_name )),
228+ track_rows_processed = track_rows_processed ,
229+ )
230+
210231 def _drop_object (
211232 self ,
212233 name : TableName | SchemaName ,
0 commit comments