11extern crate alloc;
2- use alloc:: { ffi:: CString , string:: String } ;
3- use core:: ffi:: c_char;
2+ use alloc:: { boxed :: Box , collections :: BTreeMap , ffi:: CString , format , string:: String , vec :: Vec } ;
3+ use core:: { ffi:: c_char, mem } ;
44use crsql_bundle:: test_exports;
55use sqlite:: { Connection , ResultCode } ;
66use sqlite_nostd as sqlite;
@@ -10,6 +10,11 @@ fn make_site() -> *mut c_char {
1010 inner_ptr
1111}
1212
13+ fn convert_to_bytes ( id : * mut c_char ) -> Vec < u8 > {
14+ let site_id_string = unsafe { CString :: from_raw ( id) } ;
15+ site_id_string. into_bytes ( )
16+ }
17+
1318fn get_site_id ( db : * mut sqlite:: sqlite3 ) -> * mut c_char {
1419 let stmt = db
1520 . prepare_v2 ( "SELECT crsql_site_id();" )
@@ -112,8 +117,49 @@ fn test_next_db_version() -> Result<(), String> {
112117 Ok ( ( ) )
113118}
114119
120+ fn test_get_or_set_site_ordinal ( ) -> Result < ( ) , ResultCode > {
121+ let c = crate :: opendb ( ) . expect ( "db opened" ) ;
122+ let db = & c. db ;
123+ let raw_db = db. db ;
124+ let ext_data = unsafe { test_exports:: c:: crsql_newExtData ( raw_db, get_site_id ( raw_db) ) } ;
125+
126+ let site_id = convert_to_bytes ( get_site_id ( raw_db) ) ;
127+ let ordinal = unsafe { test_exports:: db_version:: get_or_set_site_ordinal ( ext_data, & site_id) ? } ;
128+ assert_eq ! ( 0 , ordinal) ;
129+
130+ let mut ordinals = unsafe {
131+ mem:: ManuallyDrop :: new ( Box :: from_raw (
132+ ( * ext_data) . ordinalMap as * mut BTreeMap < Vec < u8 > , i64 > ,
133+ ) )
134+ } ;
135+
136+ assert_eq ! ( 0 , * ( ordinals. get( & site_id) . unwrap( ) ) ) ;
137+
138+ // update ordinal in db but it should remain the same on the map
139+ let update_stmt =
140+ raw_db. prepare_v2 ( "UPDATE crsql_site_id SET ordinal = 8 WHERE site_id = ?" ) ?;
141+ update_stmt. bind_blob ( 1 , & site_id, sqlite:: Destructor :: STATIC ) ?;
142+ update_stmt. step ( ) ?;
143+
144+ let ordinal = unsafe { test_exports:: db_version:: get_or_set_site_ordinal ( ext_data, & site_id) ? } ;
145+ assert_eq ! ( 0 , ordinal) ;
146+
147+ // clear ordinals and call func again, we should get update
148+ ordinals. clear ( ) ;
149+ let ordinal = unsafe { test_exports:: db_version:: get_or_set_site_ordinal ( ext_data, & site_id) ? } ;
150+ assert_eq ! ( 8 , ordinal) ;
151+
152+ unsafe {
153+ test_exports:: c:: crsql_freeExtData ( ext_data) ;
154+ } ;
155+ Ok ( ( ) )
156+ }
157+
115158pub fn run_suite ( ) -> Result < ( ) , String > {
116159 test_fetch_db_version_from_storage ( ) ?;
117160 test_next_db_version ( ) ?;
161+ if let Err ( rc) = test_get_or_set_site_ordinal ( ) {
162+ return Err ( format ! ( "test_get_or_set_site_ordinal failed: {:?}" , rc) ) ;
163+ }
118164 Ok ( ( ) )
119165}
0 commit comments