1use mysql_common::{io::ParseBuf, packets::StmtPacket, proto::MyDeserialize};
10
11use std::{borrow::Cow, io, sync::Arc};
12
13use crate::{prelude::*, Column, Result};
14
15#[derive(Debug, Clone, Eq, PartialEq)]
16pub struct InnerStmt {
17 columns: Option<Vec<Column>>,
18 params: Option<Vec<Column>>,
19 stmt_packet: StmtPacket,
20 connection_id: u32,
21}
22
23impl<'de> MyDeserialize<'de> for InnerStmt {
24 const SIZE: Option<usize> = StmtPacket::SIZE;
25 type Ctx = u32;
26
27 fn deserialize(connection_id: Self::Ctx, buf: &mut ParseBuf<'de>) -> io::Result<Self> {
28 let stmt_packet = buf.parse(())?;
29
30 Ok(InnerStmt {
31 columns: None,
32 params: None,
33 stmt_packet,
34 connection_id,
35 })
36 }
37}
38
39impl InnerStmt {
40 pub fn with_params(mut self, params: Option<Vec<Column>>) -> Self {
41 self.params = params;
42 self
43 }
44
45 pub fn with_columns(mut self, columns: Option<Vec<Column>>) -> Self {
46 self.columns = columns;
47 self
48 }
49
50 pub fn columns(&self) -> &[Column] {
51 self.columns.as_ref().map(AsRef::as_ref).unwrap_or(&[])
52 }
53
54 pub fn params(&self) -> &[Column] {
55 self.params.as_ref().map(AsRef::as_ref).unwrap_or(&[])
56 }
57
58 pub fn id(&self) -> u32 {
59 self.stmt_packet.statement_id()
60 }
61
62 pub const fn connection_id(&self) -> u32 {
63 self.connection_id
64 }
65
66 pub fn num_params(&self) -> u16 {
67 self.stmt_packet.num_params()
68 }
69
70 pub fn num_columns(&self) -> u16 {
71 self.stmt_packet.num_columns()
72 }
73}
74
75#[derive(Debug, Clone, Eq, PartialEq)]
76pub struct Statement {
77 pub(crate) inner: Arc<InnerStmt>,
78 pub(crate) named_params: Option<Vec<Vec<u8>>>,
79}
80
81impl Statement {
82 pub(crate) fn new(inner: Arc<InnerStmt>, named_params: Option<Vec<Vec<u8>>>) -> Self {
83 Self {
84 inner,
85 named_params,
86 }
87 }
88
89 pub fn columns(&self) -> &[Column] {
90 self.inner.columns()
91 }
92
93 pub fn params(&self) -> &[Column] {
94 self.inner.params()
95 }
96
97 pub fn id(&self) -> u32 {
98 self.inner.id()
99 }
100
101 pub fn connection_id(&self) -> u32 {
102 self.inner.connection_id()
103 }
104
105 pub fn num_params(&self) -> u16 {
106 self.inner.num_params()
107 }
108
109 pub fn num_columns(&self) -> u16 {
110 self.inner.num_columns()
111 }
112}
113
114impl AsStatement for Statement {
115 fn as_statement<Q: Queryable>(&self, _queryable: &mut Q) -> Result<Cow<'_, Statement>> {
116 Ok(Cow::Borrowed(self))
117 }
118}
119
120impl<'a> AsStatement for &'a Statement {
121 fn as_statement<Q: Queryable>(&self, _queryable: &mut Q) -> Result<Cow<'_, Statement>> {
122 Ok(Cow::Borrowed(self))
123 }
124}
125
126impl<T: AsRef<str>> AsStatement for T {
127 fn as_statement<Q: Queryable>(&self, queryable: &mut Q) -> Result<Cow<'static, Statement>> {
128 let statement = queryable.prep(self.as_ref())?;
129 Ok(Cow::Owned(statement))
130 }
131}