Skip to main content

Transaction

Struct Transaction 

Source
pub struct Transaction<'graph> { /* private fields */ }
Expand description

A graph transaction that is confined to the thread where it was created.

ⓘ
use littlegraph_core::Transaction;

fn require_send<T: Send>() {}
require_send::<Transaction<'static>>();

A live transaction exclusively borrows its graph, so query execution cannot bypass the transaction handle:

ⓘ
use littlegraph_core::{Graph, Params};

fn bypass_transaction(graph: &mut Graph) {
    let transaction = graph.transaction().unwrap();
    graph.query("MATCH (n) RETURN n", Params::new()).unwrap();
    drop(transaction);
}

Implementations§

Source§

impl Transaction<'_>

Source

pub fn query(&mut self, query: &str, params: Params) -> Result<QueryResult>

Examples found in repository?
examples/workspace-spill-benchmark.rs (lines 72-75)
36fn main() -> Result<(), Box<dyn std::error::Error>> {
37    let options = parse_options()?;
38    let directory = tempfile::tempdir()?;
39    let database = prepare_database(directory.path(), options.fixture.as_deref())?;
40    let mut graph = Graph::open_neo4j_writable(&database)?;
41
42    let baseline_rss_kib = resident_set_kib().unwrap_or(0);
43    let stop = Arc::new(AtomicBool::new(false));
44    let peak_rss_kib = Arc::new(AtomicU64::new(baseline_rss_kib));
45    let peak_spill_bytes = Arc::new(AtomicU64::new(0));
46    let sampler = spawn_sampler(
47        database.clone(),
48        options.sample_interval,
49        stop.clone(),
50        peak_rss_kib.clone(),
51        peak_spill_bytes.clone(),
52    );
53
54    let total_start = Instant::now();
55    let mut transaction = graph.transaction_with_options(TransactionOptions {
56        spill_threshold_bytes: options.spill_threshold_bytes,
57        max_spill_bytes: Some(options.max_spill_bytes),
58        max_journal_bytes: options.max_journal_bytes,
59        ..TransactionOptions::default()
60    })?;
61    let payload = if options.update_existing { "y" } else { "x" }.repeat(options.payload_bytes);
62    let mutation_start = Instant::now();
63    for ordinal in 0..options.nodes {
64        let params = BTreeMap::from([
65            (
66                "ordinal".to_owned(),
67                Value::Integer(i64::try_from(ordinal)?),
68            ),
69            ("payload".to_owned(), Value::String(payload.clone())),
70        ]);
71        let result = if options.update_existing {
72            transaction.query(
73                "MATCH (n:LittlegraphSpillCapacity {ordinal: $ordinal}) SET n.payload = $payload RETURN n.ordinal",
74                params,
75            )?
76        } else {
77            transaction.query(
78                "CREATE (:SpillBenchmark {ordinal: $ordinal, payload: $payload})",
79                params,
80            )?
81        };
82        if options.update_existing && result.rows.len() != 1 {
83            return Err(format!(
84                "expected one LittlegraphSpillCapacity node for ordinal {ordinal}, found {}",
85                result.rows.len()
86            )
87            .into());
88        }
89    }
90    let mutation_elapsed = mutation_start.elapsed();
91    let commit_start = Instant::now();
92    transaction.commit()?;
93    let commit_elapsed = commit_start.elapsed();
94    let total_elapsed = total_start.elapsed();
95
96    sample_peaks(&database, &peak_rss_kib, &peak_spill_bytes);
97    stop.store(true, Ordering::Release);
98    sampler.join().map_err(|_| "workspace sampler panicked")?;
99
100    let peak_rss_kib = peak_rss_kib.load(Ordering::Relaxed);
101    println!(
102        "{{\"fixture\":{},\"update_existing\":{},\"nodes\":{},\"payload_bytes\":{},\"spill_threshold_bytes\":{},\"max_spill_bytes\":{},\"max_journal_bytes\":{},\"sample_interval_us\":{},\"baseline_rss_kib\":{},\"peak_rss_kib\":{},\"rss_delta_kib\":{},\"peak_spill_bytes\":{},\"mutation_ms\":{:.3},\"commit_ms\":{:.3},\"total_ms\":{:.3}}}",
103        options.fixture.is_some(),
104        options.update_existing,
105        options.nodes,
106        options.payload_bytes,
107        options
108            .spill_threshold_bytes
109            .map_or_else(|| "null".to_owned(), |value| value.to_string()),
110        options.max_spill_bytes,
111        options
112            .max_journal_bytes
113            .map_or_else(|| "null".to_owned(), |value| value.to_string()),
114        options.sample_interval.as_micros(),
115        baseline_rss_kib,
116        peak_rss_kib,
117        peak_rss_kib.saturating_sub(baseline_rss_kib),
118        peak_spill_bytes.load(Ordering::Relaxed),
119        mutation_elapsed.as_secs_f64() * 1000.0,
120        commit_elapsed.as_secs_f64() * 1000.0,
121        total_elapsed.as_secs_f64() * 1000.0,
122    );
123    Ok(())
124}
Source

pub fn cancel(&mut self)

Cancel this transaction. Rollback remains available.

Source

pub fn savepoint(&mut self) -> Result<Savepoint>

Capture the transaction’s current working state without touching disk.

Source

pub fn rollback_to(&mut self, savepoint: Savepoint) -> Result<()>

Restore a savepoint and discard every savepoint created after it.

Source

pub fn release_savepoint(&mut self, savepoint: Savepoint) -> Result<()>

Release a savepoint without changing the transaction’s working state.

Source

pub fn commit(self) -> Result<()>

Examples found in repository?
examples/workspace-spill-benchmark.rs (line 92)
36fn main() -> Result<(), Box<dyn std::error::Error>> {
37    let options = parse_options()?;
38    let directory = tempfile::tempdir()?;
39    let database = prepare_database(directory.path(), options.fixture.as_deref())?;
40    let mut graph = Graph::open_neo4j_writable(&database)?;
41
42    let baseline_rss_kib = resident_set_kib().unwrap_or(0);
43    let stop = Arc::new(AtomicBool::new(false));
44    let peak_rss_kib = Arc::new(AtomicU64::new(baseline_rss_kib));
45    let peak_spill_bytes = Arc::new(AtomicU64::new(0));
46    let sampler = spawn_sampler(
47        database.clone(),
48        options.sample_interval,
49        stop.clone(),
50        peak_rss_kib.clone(),
51        peak_spill_bytes.clone(),
52    );
53
54    let total_start = Instant::now();
55    let mut transaction = graph.transaction_with_options(TransactionOptions {
56        spill_threshold_bytes: options.spill_threshold_bytes,
57        max_spill_bytes: Some(options.max_spill_bytes),
58        max_journal_bytes: options.max_journal_bytes,
59        ..TransactionOptions::default()
60    })?;
61    let payload = if options.update_existing { "y" } else { "x" }.repeat(options.payload_bytes);
62    let mutation_start = Instant::now();
63    for ordinal in 0..options.nodes {
64        let params = BTreeMap::from([
65            (
66                "ordinal".to_owned(),
67                Value::Integer(i64::try_from(ordinal)?),
68            ),
69            ("payload".to_owned(), Value::String(payload.clone())),
70        ]);
71        let result = if options.update_existing {
72            transaction.query(
73                "MATCH (n:LittlegraphSpillCapacity {ordinal: $ordinal}) SET n.payload = $payload RETURN n.ordinal",
74                params,
75            )?
76        } else {
77            transaction.query(
78                "CREATE (:SpillBenchmark {ordinal: $ordinal, payload: $payload})",
79                params,
80            )?
81        };
82        if options.update_existing && result.rows.len() != 1 {
83            return Err(format!(
84                "expected one LittlegraphSpillCapacity node for ordinal {ordinal}, found {}",
85                result.rows.len()
86            )
87            .into());
88        }
89    }
90    let mutation_elapsed = mutation_start.elapsed();
91    let commit_start = Instant::now();
92    transaction.commit()?;
93    let commit_elapsed = commit_start.elapsed();
94    let total_elapsed = total_start.elapsed();
95
96    sample_peaks(&database, &peak_rss_kib, &peak_spill_bytes);
97    stop.store(true, Ordering::Release);
98    sampler.join().map_err(|_| "workspace sampler panicked")?;
99
100    let peak_rss_kib = peak_rss_kib.load(Ordering::Relaxed);
101    println!(
102        "{{\"fixture\":{},\"update_existing\":{},\"nodes\":{},\"payload_bytes\":{},\"spill_threshold_bytes\":{},\"max_spill_bytes\":{},\"max_journal_bytes\":{},\"sample_interval_us\":{},\"baseline_rss_kib\":{},\"peak_rss_kib\":{},\"rss_delta_kib\":{},\"peak_spill_bytes\":{},\"mutation_ms\":{:.3},\"commit_ms\":{:.3},\"total_ms\":{:.3}}}",
103        options.fixture.is_some(),
104        options.update_existing,
105        options.nodes,
106        options.payload_bytes,
107        options
108            .spill_threshold_bytes
109            .map_or_else(|| "null".to_owned(), |value| value.to_string()),
110        options.max_spill_bytes,
111        options
112            .max_journal_bytes
113            .map_or_else(|| "null".to_owned(), |value| value.to_string()),
114        options.sample_interval.as_micros(),
115        baseline_rss_kib,
116        peak_rss_kib,
117        peak_rss_kib.saturating_sub(baseline_rss_kib),
118        peak_spill_bytes.load(Ordering::Relaxed),
119        mutation_elapsed.as_secs_f64() * 1000.0,
120        commit_elapsed.as_secs_f64() * 1000.0,
121        total_elapsed.as_secs_f64() * 1000.0,
122    );
123    Ok(())
124}
Source

pub fn rollback(self) -> Result<()>

Trait Implementations§

Source§

impl<'graph> Debug for Transaction<'graph>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for Transaction<'_>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

§

impl<'graph> !RefUnwindSafe for Transaction<'graph>

§

impl<'graph> !Send for Transaction<'graph>

§

impl<'graph> !Sync for Transaction<'graph>

§

impl<'graph> !UnwindSafe for Transaction<'graph>

§

impl<'graph> Freeze for Transaction<'graph>

§

impl<'graph> Unpin for Transaction<'graph>

§

impl<'graph> UnsafeUnpin for Transaction<'graph>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.