cassandra-rs icon indicating copy to clipboard operation
cassandra-rs copied to clipboard

Should/can Statement implement Clone?

Open rukai opened this issue 2 years ago • 4 comments

I tried digging through the recent PRs but couldnt find the reasoning for making executing a statement consume the statement. Should we make Statements cloneable to avoid reallocating the memory behind the CassStatement?

https://docs.datastax.com/en/developer/cpp-driver/2.3/api/struct.CassStatement/ Documents that CassStatement internally copies the query into a new allocation.

rukai avatar Mar 17 '23 03:03 rukai

Ah, cloning would be no good because the drop needs to free the CassStatement.

I guess a better question would be: Why do we need to consume Statements when executing them?

rukai avatar Mar 17 '23 03:03 rukai

@jhgg do you remember why executing a Statement consumes it? You mention the necessity in https://github.com/Metaswitch/cassandra-rs/pull/101#issue-784932157 but don't explain why. Is it just the ergonomics (i.e., consuming the statement means the caller doesn't have to worry about keeping it alive long enough) or is there a safety reason?

kw217 avatar Mar 17 '23 09:03 kw217

@rukai as you point out, the issue is that we need to drop the CassStatement when we're finished using it (e.g., once it's been passed to execute). That drop logic is attached to StatementInner in your code.

I think we can implement clone if we make pub struct Statement(Arc<StatementInner>, Session). Then the StatementInner gets dropped once all the references have been dropped.

kw217 avatar Apr 18 '23 08:04 kw217

Ah, this is interesting. execute consumes the statement so that it can drop it immediately after passing the pointer to the driver, rather than holding onto it until the future is complete. But if we use an Arc<parking_lot::Mutex<Statement>> we have to be very careful with our locking - just calling .inner() gives us a dangerous bare pointer that might be being used at the same time by another thread. Basically, all uses of .inner() in Statement, Batch, PreparedStatement need to be replaced with careful lock() and drop() calls.

kw217 avatar Apr 18 '23 10:04 kw217