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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
// © 2022 Christoph Grenz <https://grenz-bonn.de>
//
// SPDX-License-Identifier: MPL-2.0

use core::fmt;
use core::ops::Deref;
use core::str::FromStr;
#[cfg(feature = "std")]
use std::io;

use crate::category::Category;
use crate::character::Char;
use crate::class::Class;
use crate::error::ParseError;

/// Representation for an alphanumeric SQLSTATE code.
///
/// This struct can be treated like a 5-byte fixed-length string restricted to `A`-`Z` and `0`-`9`.
/// It is dereferencable as a [`str`] and can be converted into `[u8; 5]` or `&[u8]` using [`Into`]
/// and [`AsRef`].
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SqlState {
	code: [Char; 5],
}

impl SqlState {
	/// Creates an `SqlState` from a string.
	///
	/// # Errors
	/// Returns an `Err` if the string isn't of length 5 or contains characters other than `A`-`Z`
	/// and `0`-`9`.
	///
	/// # Examples
	/// ```
	/// # use sqlstate_inline::SqlState;
	/// # fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
	/// let input = "08001";
	/// let sqlstate = SqlState::from_str(input)?;
	///
	/// assert_eq!(input, &*sqlstate);
	/// # Ok(())
	/// # }
	/// ```
	#[inline]
	pub const fn from_str(value: &str) -> Result<Self, ParseError> {
		Self::from_bytes(value.as_bytes())
	}

	/// Creates an `SqlState` from a string, replacing invalid characters.
	///
	/// SQLSTATEs are strings of length 5 containing only ASCII characters `A`-`Z` and `0`-`9`.
	/// The first two characters designate the "class" and the remaining three characters designate
	/// the "subclass". This constructor truncates longer strings, and replaces missing or invalid
	/// characters by the following rules:
	///
	/// - an empty string is always replaced with [`SqlState::UNKNOWN`].
	/// - else every missing or invalid character is replaced with `X`.
	///
	/// # Examples
	/// ```
	/// # use sqlstate_inline::SqlState;
	/// let input = "080@Ä";
	/// let sqlstate = SqlState::from_str_lossy(input);
	///
	/// assert_eq!(SqlState("080XX"), sqlstate);
	/// ```
	#[inline]
	pub const fn from_str_lossy(value: &str) -> Self {
		Self::from_bytes_lossy(value.as_bytes())
	}

	/// Creates an `SqlState` from an ASCII byte string.
	///
	/// # Errors
	/// Returns an `Err` if the slice isn't of length 5 or contains ASCII character codes other
	/// than `A`-`Z` and `0`-`9`.
	///
	/// # Examples
	/// ```
	/// # use sqlstate_inline::SqlState;
	/// # fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
	/// let input = b"08001";
	/// let sqlstate = SqlState::from_bytes(input)?;
	///
	/// assert_eq!(input, AsRef::<[u8]>::as_ref(&sqlstate));
	/// # Ok(())
	/// # }
	/// ```
	#[inline]
	pub const fn from_bytes(value: &[u8]) -> Result<Self, ParseError> {
		match Char::new_array(value) {
			Ok(code) => Ok(Self { code }),
			Err(e) => Err(e),
		}
	}

	/// Creates an `SqlState` from a byte string, replacing invalid characters.
	///
	/// This is the ASCII byte string version of [`SqlState::from_str_lossy()`].
	#[inline]
	pub const fn from_bytes_lossy(value: &[u8]) -> Self {
		if value.is_empty() {
			Self::UNKNOWN
		} else {
			Self {
				code: Char::new_array_lossy(value, Char::X),
			}
		}
	}

	/// Creates an `SqlState` from an ASCII byte array.
	///
	/// # Errors
	/// Returns an `Err` if the array contains ASCII character codes other than `A`-`Z` and `0`-`9`.
	///
	/// # Examples
	/// ```
	/// # use sqlstate_inline::SqlState;
	/// # fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
	/// let input = [b'4', b'2', b'0', b'0', b'0'];
	/// let sqlstate = SqlState::from_byte_array(input)?;
	///
	/// assert_eq!(&input, AsRef::<[u8; 5]>::as_ref(&sqlstate));
	/// # Ok(())
	/// # }
	/// ```
	///
	/// # See also
	/// [`Class::from_bytes()`]
	pub const fn from_byte_array(value: [u8; 5]) -> Result<Self, ParseError> {
		match Char::new_array(&value) {
			Ok(code) => Ok(Self { code }),
			Err(e) => Err(e),
		}
	}

	/// Returns the general category for this SQLSTATE.
	///
	/// # Examples
	/// ```
	/// # use sqlstate_inline::{SqlState, Category};
	/// let sqlstate = SqlState("08001");
	/// assert_eq!(sqlstate.category(), Category::Exception);
	/// ```
	#[inline]
	pub const fn category(&self) -> Category {
		match self {
			sqlstate![0 0 ..] => Category::Success,
			sqlstate![0 1 ..] => Category::Warning,
			sqlstate![0 2 ..] => Category::NoData,
			_ => Category::Exception,
		}
	}

	/// Returns the class code for this SQLSTATE.
	/// ```
	/// # use sqlstate_inline::{SqlState, Class};
	/// let sqlstate = SqlState("42000");
	/// let class = sqlstate.class();
	///
	/// assert_eq!(class, Class::SYNTAX_ERROR_OR_ACCESS_RULE_VIOLATION);
	/// assert_eq!(&class, "42");
	/// ```
	#[inline]
	pub const fn class(&self) -> Class {
		match self.code {
			[a, b, _, _, _] => Class { code: [a, b] },
		}
	}

	/// Returns whether this code is implementation-specific and not reserved for standard conditions.
	///
	/// All classes and all subclasses starting with `5`-`9` or `I`-`Z` are implementation-specific.
	///
	/// # Examples
	/// ```
	/// # use sqlstate_inline::{SqlState, Category};
	/// let sqlstate = SqlState("42000");
	/// assert_eq!(sqlstate.is_implementation_specific(), false);
	///
	/// let sqlstate = SqlState("XRUST");
	/// assert_eq!(sqlstate.is_implementation_specific(), true);
	/// ```
	#[inline]
	pub const fn is_implementation_specific(&self) -> bool {
		!matches!(
			self.code[0],
			Char::_0
				| Char::_1 | Char::_2
				| Char::_3 | Char::_4
				| Char::A | Char::B
				| Char::C | Char::D
				| Char::E | Char::F
				| Char::G | Char::H
		) && !matches!(
			self.code[2],
			Char::_0
				| Char::_1 | Char::_2
				| Char::_3 | Char::_4
				| Char::A | Char::B
				| Char::C | Char::D
				| Char::E | Char::F
				| Char::G | Char::H
		)
	}

	/// Returns whether the SQLSTATE contains a subclass
	///
	/// `false` if the code is a generic class code ending in `000`.
	#[inline]
	pub const fn has_subclass(&self) -> bool {
		!matches!(self.code, [_, _, Char::_0, Char::_0, Char::_0])
	}

	/// `SqlState("99999")`
	pub const UNKNOWN: Self = sqlstate![9 9 9 9 9];
}

impl fmt::Debug for SqlState {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
		f.debug_tuple("SqlState").field(&&**self).finish()
	}
}

impl fmt::Display for SqlState {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
		f.write_str(self)
	}
}

impl AsRef<str> for SqlState {
	#[inline]
	fn as_ref(&self) -> &str {
		self
	}
}

impl AsRef<[u8]> for SqlState {
	#[inline]
	fn as_ref(&self) -> &[u8] {
		Char::array_as_bytes(&self.code)
	}
}

impl AsRef<[u8; 5]> for SqlState {
	#[inline]
	fn as_ref(&self) -> &[u8; 5] {
		Char::array_as_bytes(&self.code)
	}
}

impl From<SqlState> for [u8; 5] {
	#[inline]
	fn from(sqlstate: SqlState) -> Self {
		sqlstate.code.map(Char::as_byte)
	}
}

impl Deref for SqlState {
	type Target = str;
	#[inline]
	fn deref(&self) -> &Self::Target {
		Char::array_as_str(&self.code)
	}
}

impl PartialEq<str> for SqlState {
	fn eq(&self, other: &str) -> bool {
		&**self == other
	}
}

impl PartialEq<[u8]> for SqlState {
	fn eq(&self, other: &[u8]) -> bool {
		AsRef::<[u8]>::as_ref(self) == other
	}
}

#[cfg(feature = "std")]
impl From<SqlState> for io::ErrorKind {
	/// Converts the SQLSTATE to an [`std::io::ErrorKind`].
	///
	/// Convert well-known codes that have a rough equivalent to the corresponding `ErrorKind` on
	/// a best-effort basis and falls back to [`ErrorKind::Other`] for everything else. Thus this
	/// mapping is not considered stable and might change once new `ErrorKind` variants are added.
	///
	/// [`ErrorKind::Other`]: `io::ErrorKind::Other`
	fn from(state: SqlState) -> Self {
		match state {
			// 08: Connection errors
			sqlstate![0 8 0 0 1] | sqlstate![0 8 0 0 4] => Self::ConnectionRefused,
			sqlstate![0 8 0 0 3] => Self::ConnectionAborted,
			sqlstate![0 8 ..] => Self::ConnectionReset,

			// 0A: Unsupported
			sqlstate![0 A ..] => Self::Unsupported,

			// 21: Cardinality error
			sqlstate![2 1 ..] => Self::InvalidInput,

			// 22: Query data errors
			sqlstate![2 2 ..] => Self::InvalidData,

			// 23: Constraint violation
			sqlstate![2 3 5 0 5] => Self::AlreadyExists,
			sqlstate![2 3 ..] => Self::PermissionDenied,

			// 25: Invalid transaction state
			//sqlstate![2 5 0 0 6] => Self::ReadOnlyFilesystem,
			sqlstate![2 5 P 0 3] => Self::TimedOut,

			// 26: Invalid statement name
			sqlstate![2 6 ..] => Self::InvalidData,

			// 28: Authorization
			sqlstate![2 8 ..] => Self::PermissionDenied,

			// 40: Transaction rollback
			//sqlstate![4 0 0 0 1] => Self::ResourceBusy,
			sqlstate![4 0 0 0 2] => Self::PermissionDenied,
			//sqlstate![4 0 P 0 1] => Self::Deadlock,

			// 42: Query syntax error or access rule violation
			sqlstate![4 2 5 ..] => Self::PermissionDenied,
			sqlstate![4 2 S 0 1] => Self::AlreadyExists,
			sqlstate![4 2 S 0 2] | sqlstate![4 2 S 1 2] => Self::NotFound,
			sqlstate![4 2 ..] => Self::InvalidInput,

			// 44: WITH CHECK OPTION violation
			sqlstate![4 4 ..] => Self::PermissionDenied,

			// 53 (PostgreSQL): Resource exhaustion
			//sqlstate![5 3 1 0 0] => Self::StorageFull,
			sqlstate![5 3 2 0 0] => Self::OutOfMemory,
			sqlstate![5 3 3 0 0] => Self::ConnectionRefused,

			// 54 (PostgreSQL): Program limit exceeded
			sqlstate![5 4 ..] => Self::InvalidInput,

			// 57 (PostgreSQL): Intervention
			sqlstate![5 7 0 1 4] => Self::Interrupted,
			sqlstate![5 7 P 0 1] => Self::ConnectionReset,
			sqlstate![5 7 P 0 2] => Self::ConnectionReset,
			sqlstate![5 7 P 0 3] => Self::ConnectionRefused,
			//sqlstate![5 7 P 0 4] => Self::StaleNetworkFileHandle,
			sqlstate![5 7 P 0 5] => Self::ConnectionAborted,

			// 70 (MySQL): Interruption
			sqlstate![7 0 1 0 0] => Self::Interrupted,

			// HV: Foreign data wrappers
			sqlstate![H V 0 0 1] => Self::OutOfMemory,
			//sqlstate![H V 0 0 B] => Self::StaleNetworkFileHandle,
			sqlstate![H V 0 0 N] => Self::BrokenPipe,

			// HY: Call level interface
			sqlstate![H Y 0 0 1] => Self::OutOfMemory,
			sqlstate![H Y 0 0 8] => Self::TimedOut,

			// XX (PostgreSQL): Internal Error / Data corruption
			sqlstate![X X 0 0 1] | sqlstate![X X 0 0 2] => Self::UnexpectedEof,

			_ => Self::Other,
		}
	}
}

impl FromStr for SqlState {
	type Err = ParseError;

	fn from_str(s: &str) -> Result<Self, Self::Err> {
		Self::from_bytes(s.as_bytes())
	}
}

impl TryFrom<&[u8]> for SqlState {
	type Error = ParseError;

	fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
		Self::from_bytes(bytes)
	}
}

impl TryFrom<[u8; 5]> for SqlState {
	type Error = ParseError;

	fn try_from(bytes: [u8; 5]) -> Result<Self, Self::Error> {
		Self::from_byte_array(bytes)
	}
}

impl TryFrom<&str> for SqlState {
	type Error = ParseError;

	fn try_from(string: &str) -> Result<Self, Self::Error> {
		Self::from_str(string)
	}
}

#[cfg(feature = "serde")]
impl serde::Serialize for SqlState {
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: serde::Serializer,
	{
		serializer.serialize_str(self)
	}
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for SqlState {
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where
		D: serde::Deserializer<'de>,
	{
		deserializer
			.deserialize_str(crate::character::de::ArrayVisitor::new())
			.map(|arr| Self { code: arr })
	}
}

// Statically assert the intended memory layouts (5 bytes with multiple niches)
const _: () = assert!(core::mem::size_of::<SqlState>() == 5);
const _: () = assert!(core::mem::size_of::<Option<Option<SqlState>>>() == 5);