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
348
349
350
351
352
353
354
355
// Copyright (c) 2017 Anatoly Ikorsky
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

use futures_util::FutureExt;
use mysql_common::{
    io::ParseBuf,
    named_params::parse_named_params,
    packets::{ComStmtClose, StmtPacket},
};

use std::{borrow::Cow, sync::Arc};

use crate::{
    conn::routines::{ExecRoutine, PrepareRoutine},
    consts::CapabilityFlags,
    error::*,
    Column, Params,
};

use super::AsQuery;

/// Result of a `StatementLike::to_statement` call.
pub enum ToStatementResult<'a> {
    /// Statement is immediately available.
    Immediate(Statement),
    /// We need some time to get a statement and the operation itself may fail.
    Mediate(crate::BoxFuture<'a, Statement>),
}

pub trait StatementLike: Send + Sync {
    /// Returns a statement.
    fn to_statement<'a>(self, conn: &'a mut crate::Conn) -> ToStatementResult<'a>
    where
        Self: 'a;
}

fn to_statement_move<'a, T: AsQuery + 'a>(
    stmt: T,
    conn: &'a mut crate::Conn,
) -> ToStatementResult<'a> {
    let fut = async move {
        let query = stmt.as_query();
        let (named_params, raw_query) = parse_named_params(query.as_ref())?;
        let inner_stmt = match conn.get_cached_stmt(&*raw_query) {
            Some(inner_stmt) => inner_stmt,
            None => conn.prepare_statement(raw_query).await?,
        };
        Ok(Statement::new(inner_stmt, named_params))
    }
    .boxed();
    ToStatementResult::Mediate(fut)
}

impl StatementLike for Cow<'_, str> {
    fn to_statement<'a>(self, conn: &'a mut crate::Conn) -> ToStatementResult<'a>
    where
        Self: 'a,
    {
        to_statement_move(self, conn)
    }
}

impl StatementLike for &'_ str {
    fn to_statement<'a>(self, conn: &'a mut crate::Conn) -> ToStatementResult<'a>
    where
        Self: 'a,
    {
        to_statement_move(self, conn)
    }
}

impl StatementLike for String {
    fn to_statement<'a>(self, conn: &'a mut crate::Conn) -> ToStatementResult<'a>
    where
        Self: 'a,
    {
        to_statement_move(self, conn)
    }
}

impl StatementLike for Box<str> {
    fn to_statement<'a>(self, conn: &'a mut crate::Conn) -> ToStatementResult<'a>
    where
        Self: 'a,
    {
        to_statement_move(self, conn)
    }
}

impl StatementLike for Arc<str> {
    fn to_statement<'a>(self, conn: &'a mut crate::Conn) -> ToStatementResult<'a>
    where
        Self: 'a,
    {
        to_statement_move(self, conn)
    }
}

impl StatementLike for Cow<'_, [u8]> {
    fn to_statement<'a>(self, conn: &'a mut crate::Conn) -> ToStatementResult<'a>
    where
        Self: 'a,
    {
        to_statement_move(self, conn)
    }
}

impl StatementLike for &'_ [u8] {
    fn to_statement<'a>(self, conn: &'a mut crate::Conn) -> ToStatementResult<'a>
    where
        Self: 'a,
    {
        to_statement_move(self, conn)
    }
}

impl StatementLike for Vec<u8> {
    fn to_statement<'a>(self, conn: &'a mut crate::Conn) -> ToStatementResult<'a>
    where
        Self: 'a,
    {
        to_statement_move(self, conn)
    }
}

impl StatementLike for Box<[u8]> {
    fn to_statement<'a>(self, conn: &'a mut crate::Conn) -> ToStatementResult<'a>
    where
        Self: 'a,
    {
        to_statement_move(self, conn)
    }
}

impl StatementLike for Arc<[u8]> {
    fn to_statement<'a>(self, conn: &'a mut crate::Conn) -> ToStatementResult<'a>
    where
        Self: 'a,
    {
        to_statement_move(self, conn)
    }
}

impl StatementLike for Statement {
    fn to_statement<'a>(self, _conn: &'a mut crate::Conn) -> ToStatementResult<'static>
    where
        Self: 'a,
    {
        ToStatementResult::Immediate(self.clone())
    }
}

impl<T: StatementLike + Clone> StatementLike for &'_ T {
    fn to_statement<'a>(self, conn: &'a mut crate::Conn) -> ToStatementResult<'a>
    where
        Self: 'a,
    {
        self.clone().to_statement(conn)
    }
}

/// Statement data.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct StmtInner {
    pub(crate) raw_query: Arc<[u8]>,
    columns: Option<Box<[Column]>>,
    params: Option<Box<[Column]>>,
    stmt_packet: StmtPacket,
    connection_id: u32,
}

impl StmtInner {
    pub(crate) fn from_payload(
        pld: &[u8],
        connection_id: u32,
        raw_query: Arc<[u8]>,
    ) -> std::io::Result<Self> {
        let stmt_packet = ParseBuf(pld).parse(())?;

        Ok(Self {
            raw_query,
            columns: None,
            params: None,
            stmt_packet,
            connection_id,
        })
    }

    pub(crate) fn with_params(mut self, params: Vec<Column>) -> Self {
        self.params = if params.is_empty() {
            None
        } else {
            Some(params.into_boxed_slice())
        };
        self
    }

    pub(crate) fn with_columns(mut self, columns: Vec<Column>) -> Self {
        self.columns = if columns.is_empty() {
            None
        } else {
            Some(columns.into_boxed_slice())
        };
        self
    }

    pub(crate) fn columns(&self) -> &[Column] {
        self.columns.as_ref().map(AsRef::as_ref).unwrap_or(&[])
    }

    pub(crate) fn params(&self) -> &[Column] {
        self.params.as_ref().map(AsRef::as_ref).unwrap_or(&[])
    }

    pub(crate) fn id(&self) -> u32 {
        self.stmt_packet.statement_id()
    }

    pub(crate) const fn connection_id(&self) -> u32 {
        self.connection_id
    }

    pub(crate) fn num_params(&self) -> u16 {
        self.stmt_packet.num_params()
    }

    pub(crate) fn num_columns(&self) -> u16 {
        self.stmt_packet.num_columns()
    }
}

/// Prepared statement.
///
/// Statement is only valid for connection with id `Statement::connection_id()`.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Statement {
    pub(crate) inner: Arc<StmtInner>,
    pub(crate) named_params: Option<Vec<Vec<u8>>>,
}

impl Statement {
    pub(crate) fn new(inner: Arc<StmtInner>, named_params: Option<Vec<Vec<u8>>>) -> Self {
        Self {
            inner,
            named_params,
        }
    }

    /// Returned columns.
    pub fn columns(&self) -> &[Column] {
        self.inner.columns()
    }

    /// Required parameters.
    pub fn params(&self) -> &[Column] {
        self.inner.params()
    }

    /// MySql statement identifier.
    pub fn id(&self) -> u32 {
        self.inner.id()
    }

    /// MySql connection identifier.
    pub fn connection_id(&self) -> u32 {
        self.inner.connection_id()
    }

    /// Number of parameters.
    pub fn num_params(&self) -> u16 {
        self.inner.num_params()
    }

    /// Number of columns.
    pub fn num_columns(&self) -> u16 {
        self.inner.num_columns()
    }
}

impl crate::Conn {
    /// Low-level helpers, that reads the given number of column packets terminated by EOF packet.
    ///
    /// Requires `num > 0`.
    pub(crate) async fn read_column_defs<U>(&mut self, num: U) -> Result<Vec<Column>>
    where
        U: Into<usize>,
    {
        let num = num.into();
        debug_assert!(num > 0);
        let packets = self.read_packets(num).await?;
        let defs = packets
            .into_iter()
            .map(|x| ParseBuf(&*x).parse(()))
            .collect::<std::result::Result<Vec<Column>, _>>()
            .map_err(Error::from)?;

        if !self
            .capabilities()
            .contains(CapabilityFlags::CLIENT_DEPRECATE_EOF)
        {
            self.read_packet().await?;
        }

        Ok(defs)
    }

    /// Helper, that retrieves `Statement` from `StatementLike`.
    pub(crate) async fn get_statement<U>(&mut self, stmt_like: U) -> Result<Statement>
    where
        U: StatementLike,
    {
        match stmt_like.to_statement(self) {
            ToStatementResult::Immediate(statement) => Ok(statement),
            ToStatementResult::Mediate(statement) => statement.await,
        }
    }

    /// Low-level helper, that prepares the given statement.
    ///
    /// `raw_query` is a query with `?` placeholders (if any).
    async fn prepare_statement(&mut self, raw_query: Cow<'_, [u8]>) -> Result<Arc<StmtInner>> {
        let inner_stmt = self.routine(PrepareRoutine::new(raw_query)).await?;

        if let Some(old_stmt) = self.cache_stmt(&inner_stmt) {
            self.close_statement(old_stmt.id()).await?;
        }

        Ok(inner_stmt)
    }

    /// Helper, that executes the given statement with the given params.
    pub(crate) async fn execute_statement<P>(
        &mut self,
        statement: &Statement,
        params: P,
    ) -> Result<()>
    where
        P: Into<Params>,
    {
        self.routine(ExecRoutine::new(statement, params.into()))
            .await?;
        Ok(())
    }

    /// Helper, that closes statement with the given id.
    pub(crate) async fn close_statement(&mut self, id: u32) -> Result<()> {
        self.stmt_cache_mut().remove(id);
        self.write_command(&ComStmtClose::new(id)).await
    }
}