Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update syscall #2022

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions crates/bindings-sys/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,8 @@ pub mod raw {
/// - `SCHEDULE_AT_DELAY_TOO_LONG`, when the delay specified in the row was too long.
pub fn datastore_insert_bsatn(table_id: TableId, row_ptr: *mut u8, row_len_ptr: *mut usize) -> u16;

pub fn datastore_update_bsatn(table_id: TableId, index_id: IndexId, row_ptr: *mut u8, row_len_ptr: *mut usize) -> u16;

/// Schedules a reducer to be called asynchronously, nonatomically,
/// and immediately on a best effort basis.
///
Expand Down Expand Up @@ -732,6 +734,13 @@ pub fn datastore_insert_bsatn(table_id: TableId, row: &mut [u8]) -> Result<&[u8]
cvt(unsafe { raw::datastore_insert_bsatn(table_id, row_ptr, row_len) }).map(|()| &row[..*row_len])
}

#[inline]
pub fn datastore_update_bsatn(table_id: TableId, index_id: IndexId, row: &mut [u8]) -> Result<&[u8], Errno> {
let row_ptr = row.as_mut_ptr();
let row_len = &mut row.len();
cvt(unsafe { raw::datastore_update_bsatn(table_id, index_id, row_ptr, row_len) }).map(|()| &row[..*row_len])
}

/// Deletes those rows, in the table identified by `table_id`,
/// that match any row in the byte string `relation`.
///
Expand Down
37 changes: 32 additions & 5 deletions crates/bindings/src/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -374,11 +374,8 @@ where
/// or if either the delete or the insertion would violate a constraint.
#[track_caller]
pub fn update(&self, new_row: Tbl::Row) -> Tbl::Row {
let (deleted, buf) = self._delete(Col::get_field(&new_row));
if !deleted {
update_row_didnt_exist(Tbl::TABLE_NAME, Col::COLUMN_NAME)
}
insert::<Tbl>(new_row, buf).unwrap_or_else(|e| panic!("{e}"))
let buf = IterBuf::take();
update::<Tbl>(Col::index_id(), new_row, buf).unwrap_or_else(|e| panic!("{e}"))
}
}

Expand Down Expand Up @@ -856,6 +853,36 @@ fn insert<T: Table>(mut row: T::Row, mut buf: IterBuf) -> Result<T::Row, TryInse
})
}



/// Insert a row of type `T` into the table identified by `table_id`.
#[track_caller]
fn update<T: Table>(index_id: IndexId, mut row: T::Row, mut buf: IterBuf) -> Result<T::Row, TryInsertError<T>> {
let table_id = T::table_id();
// Encode the row as bsatn into the buffer `buf`.
buf.clear();
buf.serialize_into(&row).unwrap();

// Insert row into table.
// When table has an auto-incrementing column, we must re-decode the changed `buf`.
let res = sys::datastore_update_bsatn(table_id, index_id, &mut buf).map(|gen_cols| {
// Let the caller handle any generated columns written back by `sys::insert` to `buf`.
//T::integrate_generated_columns(&mut row, gen_cols);
row
});
res.map_err(|e| {
let err = match e {
sys::Errno::UNIQUE_ALREADY_EXISTS => {
T::UniqueConstraintViolation::get().map(TryInsertError::UniqueConstraintViolation)
}
// sys::Errno::AUTO_INC_OVERFLOW => Tbl::AutoIncOverflow::get().map(TryInsertError::AutoIncOverflow),
_ => None,
};
err.unwrap_or_else(|| panic!("unexpected insertion error: {e}"))
})
}


/// A table iterator which yields values of the `TableType` corresponding to the table.
struct TableIter<T: DeserializeOwned> {
/// The underlying source of our `Buffer`s.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -491,7 +491,7 @@ impl CommittedState {
tx_data
}

fn merge_apply_deletes(&mut self, tx_data: &mut TxData, delete_tables: BTreeMap<TableId, DeleteTable>) {
fn merge_apply_deletes(&mut self, tx_data: &mut TxData, delete_tables: IntMap<TableId, DeleteTable>) {
for (table_id, row_ptrs) in delete_tables {
if let Some((table, blob_store)) = self.get_table_and_blob_store(table_id) {
let mut deletes = Vec::with_capacity(row_ptrs.len());
Expand All @@ -500,7 +500,7 @@ impl CommittedState {
// holds only committed rows which should be deleted,
// i.e. `RowPointer`s with `SquashedOffset::COMMITTED_STATE`,
// so no need to check before applying the deletes.
for row_ptr in row_ptrs.iter().copied() {
for row_ptr in row_ptrs {
debug_assert!(row_ptr.squashed_offset().is_committed_state());

// TODO: re-write `TxData` to remove `ProductValue`s
Expand All @@ -524,7 +524,7 @@ impl CommittedState {
fn merge_apply_inserts(
&mut self,
tx_data: &mut TxData,
insert_tables: BTreeMap<TableId, Table>,
insert_tables: IntMap<TableId, Table>,
tx_blob_store: impl BlobStore,
) {
// TODO(perf): Consider moving whole pages from the `insert_tables` into the committed state,
Expand Down
16 changes: 13 additions & 3 deletions crates/core/src/db/datastore/locking_tx_datastore/datastore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use super::{
tx::TxId,
tx_state::TxState,
};
use crate::execution_context::Workload;
use crate::{db::datastore::system_tables::ST_RESERVED_SEQUENCE_RANGE, execution_context::Workload};
use crate::{
db::{
datastore::{
Expand All @@ -33,7 +33,7 @@ use spacetimedb_durability::TxOffset;
use spacetimedb_lib::db::auth::StAccess;
use spacetimedb_lib::{Address, Identity};
use spacetimedb_paths::server::SnapshotDirPath;
use spacetimedb_primitives::{ColList, ConstraintId, IndexId, SequenceId, TableId};
use spacetimedb_primitives::{ColId, ColList, ConstraintId, IndexId, SequenceId, TableId};
use spacetimedb_sats::{bsatn, buffer::BufReader, AlgebraicValue, ProductValue};
use spacetimedb_schema::schema::{IndexSchema, SequenceSchema, TableSchema};
use spacetimedb_snapshot::{ReconstructedSnapshot, SnapshotRepository};
Expand Down Expand Up @@ -564,7 +564,11 @@ impl MutTxDatastore for Locking {
table_id: TableId,
mut row: ProductValue,
) -> Result<(AlgebraicValue, RowRef<'a>)> {
let (gens, row_ref) = tx.insert(table_id, &mut row)?;
let (gens, row_ref) = if table_id.0 <= ST_RESERVED_SEQUENCE_RANGE {
tx.insert(table_id, &mut row)?
} else {
tx.insert_2(table_id, &mut row)?
};
Ok((gens, row_ref.collapse()))
}

Expand Down Expand Up @@ -601,6 +605,12 @@ impl MutTxDatastore for Locking {
}
}

impl Locking {
pub(crate) fn update<'a>(&'a self, tx: &'a mut MutTxId, table_id: TableId, index_id: IndexId, row: ProductValue) -> std::result::Result<(AlgebraicValue, RowRef<'_>), DBError> {
tx.update(table_id, index_id, row)
}
}

/// This utility is responsible for recording all transaction metrics.
pub(super) fn record_metrics(
ctx: &ExecutionContext,
Expand Down
Loading
Loading