1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
use CStr;
use PhantomData;
use NonNull;
use cratepg_sys;
use ;
type CursorName = String;
/// An SPI Cursor from a query
///
/// Represents a Postgres cursor (internally, a portal), allowing to retrieve result rows a few
/// at a time. Moreover, a cursor can be left open within a transaction, and accessed in
/// multiple independent Spi sessions within the transaction.
///
/// A cursor can be created via [`SpiClient::open_cursor()`] from a query.
/// Cursors are automatically closed on drop, unless explicitly left open using
/// [`Self::detach_into_name()`], which returns the cursor name; cursors left open can be retrieved
/// by name (in the same transaction) via [`SpiClient::find_cursor()`].
///
/// # Important notes about memory usage
/// Result sets ([`SpiTupleTable`]s) returned by [`SpiCursor::fetch()`] will not be freed until
/// the current Spi session is complete;
/// this is a Pgrx limitation that might get lifted in the future.
///
/// In the meantime, if you're using cursors to limit memory usage, make sure to use
/// multiple separate Spi sessions, retrieving the cursor by name.
///
/// # Examples
/// ## Simple cursor
/// ```rust,no_run
/// use pgrx::prelude::*;
/// # fn foo() -> spi::Result<()> {
/// Spi::connect_mut(|client| {
/// let mut cursor = client.open_cursor("SELECT * FROM generate_series(1, 5)", &[]);
/// assert_eq!(Some(1), cursor.fetch(1)?.get_one::<i32>()?);
/// assert_eq!(Some(2), cursor.fetch(2)?.get_one::<i32>()?);
/// assert_eq!(Some(3), cursor.fetch(3)?.get_one::<i32>()?);
/// Ok::<_, pgrx::spi::Error>(())
/// // <--- all three SpiTupleTable get freed by Spi::connect at this point
/// })
/// # }
/// ```
///
/// ## Cursor by name
/// ```rust,no_run
/// use pgrx::prelude::*;
/// # fn foo() -> spi::Result<()> {
/// let cursor_name = Spi::connect_mut(|client| {
/// let mut cursor = client.open_cursor("SELECT * FROM generate_series(1, 5)", &[]);
/// assert_eq!(Ok(Some(1)), cursor.fetch(1)?.get_one::<i32>());
/// Ok::<_, spi::Error>(cursor.detach_into_name()) // <-- cursor gets dropped here
/// // <--- first SpiTupleTable gets freed by Spi::connect at this point
/// })?;
/// Spi::connect_mut(|client| {
/// let mut cursor = client.find_cursor(&cursor_name)?;
/// assert_eq!(Ok(Some(2)), cursor.fetch(1)?.get_one::<i32>());
/// drop(cursor); // <-- cursor gets dropped here
/// // ... more code ...
/// Ok(())
/// // <--- second SpiTupleTable gets freed by Spi::connect at this point
/// })
/// # }
/// ```