11extern  crate  alloc; 
22
3+ use  alloc:: rc:: Rc ; 
34use  alloc:: string:: String ; 
45use  alloc:: vec:: Vec ; 
56use  alloc:: { format,  vec} ; 
@@ -11,6 +12,7 @@ use sqlite_nostd::Context;
1112
1213use  crate :: error:: { PSResult ,  PowerSyncError } ; 
1314use  crate :: ext:: ExtendedDatabase ; 
15+ use  crate :: state:: DatabaseState ; 
1416use  crate :: util:: { quote_identifier,  quote_json_path} ; 
1517use  crate :: { create_auto_tx_function,  create_sqlite_text_fn} ; 
1618
@@ -138,10 +140,8 @@ SELECT name, internal_name, local_only FROM powersync_tables WHERE name NOT IN (
138140    Ok ( ( ) ) 
139141} 
140142
141- fn  update_indexes ( db :  * mut  sqlite:: sqlite3 ,  schema :  & str )  -> Result < ( ) ,  PowerSyncError >  { 
143+ fn  update_indexes ( db :  * mut  sqlite:: sqlite3 ,  schema :  & Schema )  -> Result < ( ) ,  PowerSyncError >  { 
142144    let  mut  statements:  Vec < String >  = alloc:: vec![ ] ; 
143-     let  schema =
144-         serde_json:: from_str :: < Schema > ( schema) . map_err ( PowerSyncError :: as_argument_error) ?; 
145145    let  mut  expected_index_names:  Vec < String >  = vec ! [ ] ; 
146146
147147    { 
@@ -298,15 +298,20 @@ fn powersync_replace_schema_impl(
298298    args :  & [ * mut  sqlite:: value ] , 
299299)  -> Result < String ,  PowerSyncError >  { 
300300    let  schema = args[ 0 ] . text ( ) ; 
301+     let  state = unsafe  {  DatabaseState :: from_context ( & ctx)  } ; 
302+     let  parsed_schema =
303+         serde_json:: from_str :: < Schema > ( schema) . map_err ( PowerSyncError :: as_argument_error) ?; 
304+ 
301305    let  db = ctx. db_handle ( ) ; 
302306
303307    // language=SQLite 
304308    db. exec_safe ( "SELECT powersync_init()" ) . into_db_result ( db) ?; 
305309
306310    update_tables ( db,  schema) ?; 
307-     update_indexes ( db,  schema ) ?; 
311+     update_indexes ( db,  & parsed_schema ) ?; 
308312    update_views ( db,  schema) ?; 
309313
314+     state. set_schema ( parsed_schema) ; 
310315    Ok ( String :: from ( "" ) ) 
311316} 
312317
@@ -317,16 +322,16 @@ create_sqlite_text_fn!(
317322    "powersync_replace_schema" 
318323) ; 
319324
320- pub  fn  register ( db :  * mut  sqlite:: sqlite3 )  -> Result < ( ) ,  ResultCode >  { 
325+ pub  fn  register ( db :  * mut  sqlite:: sqlite3 ,   state :   Rc < DatabaseState > )  -> Result < ( ) ,  ResultCode >  { 
321326    db. create_function_v2 ( 
322327        "powersync_replace_schema" , 
323328        1 , 
324329        sqlite:: UTF8 , 
325-         None , 
330+         Some ( Rc :: into_raw ( state )   as   * mut   _ ) , 
326331        Some ( powersync_replace_schema) , 
327332        None , 
328333        None , 
329-         None , 
334+         Some ( DatabaseState :: destroy_rc ) , 
330335    ) ?; 
331336
332337    Ok ( ( ) ) 
0 commit comments