@@ -6,7 +6,7 @@ use turso_parser::{
66
77use crate :: {
88 function:: { AlterTableFunc , Func } ,
9- schema:: { Column , Table , RESERVED_TABLE_PREFIXES } ,
9+ schema:: { Column , ForeignKey , Table , RESERVED_TABLE_PREFIXES } ,
1010 translate:: {
1111 emitter:: Resolver ,
1212 expr:: { walk_expr, WalkControl } ,
@@ -308,8 +308,63 @@ pub fn translate_alter_table(
308308 ) ) ;
309309 }
310310
311+ let mut column_foreign_keys = Vec :: new ( ) ;
312+ for constraint in & col_def. constraints {
313+ if let ast:: ColumnConstraint :: ForeignKey {
314+ clause,
315+ defer_clause,
316+ } = & constraint. constraint
317+ {
318+ let foreign_key = ForeignKey {
319+ child_columns : vec ! [ new_column_name. clone( ) ] ,
320+ parent_table : normalize_ident ( clause. tbl_name . as_str ( ) ) ,
321+ parent_columns : clause
322+ . columns
323+ . iter ( )
324+ . map ( |c| normalize_ident ( c. col_name . as_str ( ) ) )
325+ . collect ( ) ,
326+ on_delete : clause
327+ . args
328+ . iter ( )
329+ . find_map ( |arg| {
330+ if let ast:: RefArg :: OnDelete ( act) = arg {
331+ Some ( * act)
332+ } else {
333+ None
334+ }
335+ } )
336+ . unwrap_or ( ast:: RefAct :: NoAction ) ,
337+ on_update : clause
338+ . args
339+ . iter ( )
340+ . find_map ( |arg| {
341+ if let ast:: RefArg :: OnUpdate ( act) = arg {
342+ Some ( * act)
343+ } else {
344+ None
345+ }
346+ } )
347+ . unwrap_or ( ast:: RefAct :: NoAction ) ,
348+ deferred : match defer_clause {
349+ Some ( defer_clause) => {
350+ defer_clause. deferrable
351+ && matches ! (
352+ defer_clause. init_deferred,
353+ Some ( ast:: InitDeferredPred :: InitiallyDeferred )
354+ )
355+ }
356+ None => false ,
357+ } ,
358+ } ;
359+ column_foreign_keys. push ( foreign_key) ;
360+ }
361+ }
362+
311363 // TODO: All quoted ids will be quoted with `[]`, we should store some info from the parsed AST
312364 btree. columns . push ( column. clone ( ) ) ;
365+ for foreign_key in & column_foreign_keys {
366+ btree. foreign_keys . push ( Arc :: new ( foreign_key. clone ( ) ) ) ;
367+ }
313368
314369 let sql = btree. to_sql ( ) ;
315370 let mut escaped = String :: with_capacity ( sql. len ( ) ) ;
@@ -351,6 +406,7 @@ pub fn translate_alter_table(
351406 program. emit_insn ( Insn :: AddColumn {
352407 table : table_name. to_owned ( ) ,
353408 column,
409+ foreign_keys : column_foreign_keys,
354410 } ) ;
355411 } ,
356412 ) ?
0 commit comments