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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
//! The advisory lock form: a lock on each row's key, held by the delivery's session, holds the row.
use crateDialect;
use crateTableSpec;
use crate;
/// The advisory lock form of a dialect: the claim of candidates, the lock and the unlock of a key in
/// the session, and the take of a candidate once its lock is held.
///
/// A table with `#[inbox(advisory_lock = "..")]` takes its rows this way. The key template names
/// columns of the row ([`Form::Advisory`](crate::Form::Advisory)), and the database renders each
/// row's key from them as text. A claim selects candidates with their keys
/// ([`advisory_claim`](Self::advisory_claim)), locks each key on the delivery's own connection
/// ([`lock`](Self::lock), bound as [`Param::Key`](crate::Param::Key)), and takes the row while it
/// is still claimable ([`take`](Self::take)), counting its attempt. No transaction stays open
/// while the handler runs. The settlements are the statements every form runs, naming the row
/// alone, and the unlock ([`unlock`](Self::unlock)) follows them; a crash ends the session and
/// releases its locks at once. A dialect implements this trait where it builds these statements,
/// and a table with `advisory_lock` does not compile against a dialect that does not. Every
/// built-in dialect implements it.
///
/// The lock and the unlock return one 64-bit integer, nonzero when the lock was taken or released,
/// so one decode serves every database. A dialect whose database keeps no locks returns neither
/// statement, and the broker keeps the keys in work in the process: [`Sqlite`](crate::Sqlite) does.
///
/// # Examples
///
/// A dialect for a database without a built-in one builds the advisory lock form itself. On SQL
/// Server an application lock the delivery's session owns holds the row:
///
/// ```
/// # use std::num::NonZeroUsize;
/// # use ruststream_sqlx_dialect::TableName;
/// use ruststream_sqlx_dialect::{
/// Advisory, ClaimShape, Dialect, Param, Statement, StatementError, TableSpec,
/// };
///
/// /// SQL Server, a database without a built-in dialect.
/// #[derive(Debug)]
/// pub struct Mssql;
///
/// // A table with `advisory_lock` mounts on `Mssql`.
/// impl Advisory for Mssql {
/// // The candidates of `email_jobs` (`advisory_lock = "email-{job_id}"`) in id order, each
/// // with its key. `APPLOCK_TEST` leaves out the keys another session holds.
/// fn advisory_claim(&self, _spec: &TableSpec<'_>) -> Result<Statement, StatementError> {
/// Ok(Statement::new(
/// "SELECT TOP (@p1) [job_id], CONCAT(N'email-', [job_id]) AS [__lock] \
/// FROM [email_jobs] \
/// WHERE APPLOCK_TEST('public', CONCAT(N'email-', [job_id]), \
/// 'Exclusive', 'Session') = 1 \
/// ORDER BY [job_id]",
/// [Param::Limit],
/// ))
/// }
///
/// // An application lock the session owns, tried without waiting: `sp_getapplock` answers
/// // zero or more when it granted the lock.
/// fn lock(&self) -> Option<Statement> {
/// Some(Statement::new(
/// "DECLARE @result int; \
/// EXEC @result = sp_getapplock @Resource = @p1, @LockMode = 'Exclusive', \
/// @LockOwner = 'Session', @LockTimeout = 0; \
/// SELECT CAST(CASE WHEN @result >= 0 THEN 1 ELSE 0 END AS bigint)",
/// [Param::Key],
/// ))
/// }
///
/// // The release of the session's lock. A key the session does not hold answers zero, as
/// // `sp_releaseapplock` would raise an error for it.
/// fn unlock(&self) -> Option<Statement> {
/// Some(Statement::new(
/// "IF APPLOCK_MODE('public', @p1, 'Session') = 'NoLock' SELECT CAST(0 AS bigint) \
/// ELSE BEGIN DECLARE @result int; \
/// EXEC @result = sp_releaseapplock @Resource = @p1, @LockOwner = 'Session'; \
/// SELECT CAST(CASE WHEN @result = 0 THEN 1 ELSE 0 END AS bigint) END",
/// [Param::Key],
/// ))
/// }
///
/// fn take(
/// &self,
/// _spec: &TableSpec<'_>,
/// _shape: ClaimShape,
/// ) -> Result<Vec<Statement>, StatementError> {
/// Ok(vec![Statement::new(
/// "UPDATE [email_jobs] SET [attempt] = [attempt] + 1 \
/// OUTPUT deleted.[job_id], deleted.[attempt], deleted.[payload] \
/// WHERE [job_id] = @p1",
/// [Param::Id],
/// )])
/// }
/// }
/// # impl Dialect for Mssql {
/// # fn name(&self) -> &'static str { "mssql" }
/// # fn quote_into(&self, ident: &str, out: &mut String) { out.push('['); out.push_str(&ident.replace(']', "]]")); out.push(']'); }
/// # fn placeholder_into(&self, index: NonZeroUsize, out: &mut String) { out.push_str("@p"); out.push_str(&index.to_string()); }
/// # fn fetch(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedFetch { dialect: self.name() }) }
/// # fn ack(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// # fn retry(&self, spec: &TableSpec<'_>) -> Result<Option<Statement>, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// # fn retry_after(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// # fn discard(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// # fn dead_letter_group(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// # fn dead_letter_table(&self, spec: &TableSpec<'_>, target: TableName<'_>) -> Result<Vec<Statement>, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// # fn insert(&self, spec: &TableSpec<'_>) -> Result<Statement, StatementError> { Err(StatementError::UnsupportedForm { dialect: self.name(), form: spec.form().name() }) }
/// # }
/// ```