@@ -948,6 +948,34 @@ function createElectricSync<T extends Row<unknown>>(
948948 tagLength = undefined
949949 }
950950
951+ /**
952+ * Remove all tags for a row from both the tag set and the index
953+ * Used when a row is deleted
954+ */
955+ const clearTagsForRow = ( rowId : RowId ) : void => {
956+ if ( tagLength === undefined ) {
957+ return
958+ }
959+
960+ const rowTagSet = rowTagSets . get ( rowId )
961+ if ( ! rowTagSet ) {
962+ return
963+ }
964+
965+ // Remove each tag from the index
966+ for ( const tag of rowTagSet ) {
967+ const parsedTag = parseTag ( tag )
968+ const currentTagLength = getTagLength ( parsedTag )
969+ if ( currentTagLength === tagLength ) {
970+ removeTagFromIndex ( parsedTag , rowId , tagIndex , tagLength )
971+ }
972+ tagCache . delete ( tag )
973+ }
974+
975+ // Remove the row from the tag sets map
976+ rowTagSets . delete ( rowId )
977+ }
978+
951979 /**
952980 * Remove matching tags from a row based on a pattern
953981 * Returns true if the row's tag set is now empty
@@ -1227,7 +1255,7 @@ function createElectricSync<T extends Row<unknown>>(
12271255 // because shapes without subqueries don't contain tags
12281256 // so we should keep those around
12291257 if ( hasTags && rowTagSet ( ) . size === 0 ) {
1230- rowTagSets . delete ( rowId )
1258+ clearTagsForRow ( rowId )
12311259 write ( {
12321260 type : `delete` ,
12331261 value : message . value ,
@@ -1236,6 +1264,9 @@ function createElectricSync<T extends Row<unknown>>(
12361264 } ,
12371265 } )
12381266 } else {
1267+ if ( message . headers . operation === `delete` ) {
1268+ clearTagsForRow ( rowId )
1269+ }
12391270 write ( {
12401271 type : message . headers . operation ,
12411272 value : message . value ,
@@ -1324,6 +1355,7 @@ function createElectricSync<T extends Row<unknown>>(
13241355 // because shapes without subqueries don't contain tags
13251356 // so we should keep those around
13261357 if ( hasTags && rowTagSet ( ) . size === 0 ) {
1358+ clearTagsForRow ( rowId )
13271359 write ( {
13281360 type : `delete` ,
13291361 value : bufferedMsg . value ,
@@ -1332,6 +1364,9 @@ function createElectricSync<T extends Row<unknown>>(
13321364 } ,
13331365 } )
13341366 } else {
1367+ if ( bufferedMsg . headers . operation === `delete` ) {
1368+ clearTagsForRow ( rowId )
1369+ }
13351370 write ( {
13361371 type : bufferedMsg . headers . operation ,
13371372 value : bufferedMsg . value ,
0 commit comments