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
/**
 * This `struct` is created by the [`Connection::transaction`] method.
 *
 * [`Connection::transaction`]: crate::Connection::transaction
 */
pub struct Transaction<'c> {
    connection: &'c crate::Connection,
}

/**
 * <http://www.postgresql.org/docs/current/sql-set-constraints.html>
 */
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Constraints {
    Deferred,
    Immediate,
}

impl std::fmt::Display for Constraints {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            Self::Deferred => "deferred",
            Self::Immediate => "immediate",
        };

        f.write_str(s)
    }
}

/**
 * <https://www.postgresql.org/docs/current/sql-set-transaction.html>
 */
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum IsolationLevel {
    /**
     * A statement can only see rows committed before it began. This is the
     * default.
     */
    ReadCommitted,
    /**
     * All statements of the current transaction can only see rows committed
     * before the first query or data-modification statement was executed in
     * this transaction.
     */
    RepeatableRead,
    /**
     * All statements of the current transaction can only see rows committed
     * before the first query or data-modification statement was executed in
     * this transaction. If a pattern of reads and writes among concurrent
     * serializable transactions would create a situation which could not have
     * occurred for any serial (one-at-a-time) execution of those transactions,
     * one of them will be rolled back with a serialization_failure error.
     */
    Serializable,
}

impl std::fmt::Display for IsolationLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            Self::ReadCommitted => "read committed",
            Self::RepeatableRead => "repeatable read",
            Self::Serializable => "serializable",
        };

        f.write_str(s)
    }
}

/**
 * <https://www.postgresql.org/docs/current/sql-set-transaction.html>
 */
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AccessMode {
    ReadOnly,
    ReadWrite,
}

impl std::fmt::Display for AccessMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            Self::ReadOnly => "read only",
            Self::ReadWrite => "read write",
        };

        f.write_str(s)
    }
}

impl<'c> Transaction<'c> {
    pub(crate) fn new(connection: &'c crate::Connection) -> Self {
        Self { connection }
    }

    /**
     * Start a new transaction.
     */
    pub fn start(&self) -> crate::Result {
        self.exec("begin transaction")
    }

    /**
     * Commit a transaction.
     */
    pub fn commit(&self) -> crate::Result {
        self.exec("commit transaction")
    }

    /**
     * Rollback a transaction. If a `name` is specified, the transaction is
     * rollback to the given savepoint. Otherwise, the whole transaction is
     * rollback.
     */
    pub fn roolback(&self, name: Option<&str>) -> crate::Result {
        let query = match name {
            Some(name) => format!("rollback to savepoint {name}"),
            None => "rollback transaction".to_string(),
        };

        self.exec(&query)
    }

    /**
     * Set a savepoint in a transaction.
     */
    pub fn set_save_point(&self, name: &str) -> crate::Result {
        let query = format!("savepoint {name}");

        self.exec(&query)
    }

    /**
     * Drop a savepoint.
     */
    pub fn release_savepoint(&self, name: &str) -> crate::Result {
        let query = format!("release savepoint {name}");

        self.exec(&query)
    }

    /**
     * Tell if a transaction is open or not.
     */
    pub fn is_in_transaction(&self) -> crate::Result<bool> {
        let status = self.connection.transaction_status()?;

        let in_transaction = status == libpq::transaction::Status::Active
            || status == libpq::transaction::Status::InTrans
            || status == libpq::transaction::Status::InError;

        Ok(in_transaction)
    }

    /**
     * In PostgreSQL, an error during a transaction cancels all the queries and
     * rollback the transaction on commit. This method returns the current
     * transaction's status. If no transactions are open, it returns `None`.
     */
    pub fn is_transaction_ok(&self) -> crate::Result<Option<bool>> {
        if !self.is_in_transaction()? {
            return Ok(None);
        }

        let status = self.connection.transaction_status()?;

        Ok(Some(status == libpq::transaction::Status::InTrans))
    }

    /**
     * Set given constraints to deferred/immediate in the current transaction.
     * This applies to constraints being deferrable or deferred by default.
     * If the keys is `None`, ALL keys will be set at the given state.
     *
     * See <http://www.postgresql.org/docs/current/sql-set-constraints.html>
     */
    pub fn set_deferrable(
        &self,
        keys: Option<Vec<&str>>,
        constraints: Constraints,
    ) -> crate::Result {
        let name = if let Some(keys) = keys {
            keys.iter()
                .map(|key| self.escape_identifier(key))
                .collect::<crate::Result<Vec<_>>>()?
                .join(", ")
        } else {
            "ALL".to_string()
        };

        let query = format!("set constraints {name} {constraints}");

        self.exec(&query)
    }

    fn escape_identifier(&self, id: &str) -> crate::Result<String> {
        id.split('.')
            .map(|x| self.connection.escape_identifier(x))
            .collect::<crate::Result<Vec<_>>>()
            .map(|x| x.join("."))
    }

    /**
     * Transaction isolation level tells PostgreSQL how to manage with the
     * current transaction. The default is "READ COMMITTED".
     *
     * See <http://www.postgresql.org/docs/current/sql-set-transaction.html>
     */
    pub fn set_isolation_level(&self, level: IsolationLevel) -> crate::Result {
        let query = format!("set transaction isolation level {level}");

        self.exec(&query)
    }

    /**
     * Transaction access modes tell PostgreSQL if transaction are able to
     * write or read only.
     *
     * See <http://www.postgresql.org/docs/current/sql-set-transaction.html>
     */
    pub fn set_access_mode(&self, mode: AccessMode) -> crate::Result {
        let query = format!("set transaction {mode}");

        self.exec(&query)
    }

    fn exec(&self, query: &str) -> crate::Result {
        self.connection.execute(query).map(|_| ())
    }
}