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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
use crate::pq::ToArray;

/**
 * Rust type for [array](https://www.postgresql.org/docs/current/arrays.html).
 */
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Array<T> {
    ndim: usize,
    elemtype: crate::pq::Type,
    has_nulls: bool,
    dimensions: Vec<i32>,
    lower_bounds: Vec<i32>,
    data: Vec<T>,
}

impl<T: crate::FromSql> Array<T> {
    fn shift_idx(&self, indices: &[i32]) -> usize {
        if self.dimensions.len() != indices.len() {
            panic!();
        }

        let mut acc = 0;
        let mut stride = 1;

        for (x, idx) in indices.iter().enumerate().rev() {
            let dimension = self.dimensions[x];
            let lower_bounds = self.lower_bounds[x] - 1;

            let shifted = idx - lower_bounds;

            acc += shifted * stride;
            stride *= dimension;
        }

        acc as usize
    }
}

impl<T: crate::FromSql> Iterator for Array<T> {
    type Item = T;

    fn next(&mut self) -> Option<T> {
        if self.data.is_empty() {
            None
        } else {
            Some(self.data.remove(0))
        }
    }
}

macro_rules! tuple_impls {
    ($($name:ident : $t:ty),+) => {
        impl<T: crate::FromSql> std::ops::Index<($($t,)+)> for Array<T> {
            type Output = T;

            fn index(&self, ($($name,)+): ($($t,)+)) -> &Self::Output {
                let index = self.shift_idx(&[$($name,)+]);

                &self.data[index]
            }
        }
    }
}

tuple_impls!(a: i32);
tuple_impls!(a: i32, b: i32);
tuple_impls!(a: i32, b: i32, c: i32);
tuple_impls!(a: i32, b: i32, c: i32, d: i32);
tuple_impls!(a: i32, b: i32, c: i32, d: i32, e: i32);
tuple_impls!(a: i32, b: i32, c: i32, d: i32, e: i32, f: i32);
tuple_impls!(a: i32, b: i32, c: i32, d: i32, e: i32, f: i32, g: i32);
tuple_impls!(
    a: i32,
    b: i32,
    c: i32,
    d: i32,
    e: i32,
    f: i32,
    g: i32,
    h: i32
);
tuple_impls!(
    a: i32,
    b: i32,
    c: i32,
    d: i32,
    e: i32,
    f: i32,
    g: i32,
    h: i32,
    i: i32
);

impl<T: crate::FromSql> std::ops::Index<i32> for Array<T> {
    type Output = T;

    fn index(&self, index: i32) -> &Self::Output {
        self.index((index,))
    }
}

impl<T: crate::FromSql> crate::FromSql for Array<T> {
    /*
     * https://github.com/postgres/postgres/blob/REL_12_0/src/backend/utils/adt/arrayfuncs.c#L1012
     */
    fn from_text(ty: &crate::pq::Type, raw: Option<&str>) -> crate::Result<Self> {
        let raw = crate::not_null(raw)?;

        let mut has_nulls = false;
        let mut dimensions = Vec::new();
        let mut lower_bounds = Vec::new();
        let mut data = Vec::new();

        let elemtype = ty.elementype();

        let mut current = String::new();
        let mut it = raw.chars().peekable();

        #[allow(clippy::while_let_on_iterator)]
        while let Some(c) = it.next() {
            match c {
                '[' => (),
                ':' => {
                    lower_bounds.push(current.parse()?);
                    current = String::new();
                }
                ']' => {
                    let lower_bound = lower_bounds.last().unwrap_or(&0);
                    dimensions.push(current.parse::<i32>()? - lower_bound + 1);

                    current = String::new();
                }
                '0'..='9' | '-' => current.push(c),
                _ => break,
            }
        }

        #[allow(clippy::while_let_on_iterator)]
        while let Some(c) = it.next() {
            match c {
                '{' => current = String::new(),
                ',' | '}' => {
                    if !current.is_empty() {
                        let value = if current.eq_ignore_ascii_case("null") {
                            has_nulls = true;
                            None
                        } else if current.eq_ignore_ascii_case("'null'") {
                            Some(current.trim_matches('\''))
                        } else {
                            Some(current.as_str())
                        };
                        data.push(T::from_text(&elemtype, value)?);
                        current = String::new();
                    }
                }
                _ => current.push(c),
            }
        }

        let array = Self {
            ndim: dimensions.len(),
            elemtype,
            has_nulls,
            dimensions,
            lower_bounds,
            data,
        };

        Ok(array)
    }

    /*
     * https://github.com/postgres/postgres/blob/REL_12_0/src/backend/utils/adt/arrayfuncs.c#L1547
     */
    fn from_binary(_: &crate::pq::Type, raw: Option<&[u8]>) -> crate::Result<Self> {
        use std::io::Read;

        let mut buf = crate::not_null(raw)?;

        let ndim = crate::from_sql::read_i32(&mut buf)?;
        if ndim < 0 {
            panic!("Invalid array");
        }

        let has_nulls = crate::from_sql::read_i32(&mut buf)? != 0;

        let oid = crate::from_sql::read_u32(&mut buf)?;
        let elemtype: crate::pq::Type = oid.try_into().unwrap_or(crate::pq::Type {
            oid,
            descr: "Custom type",
            name: "custom",
            kind: libpq::types::Kind::Composite,
        });

        let mut dimensions = Vec::new();
        let mut lower_bounds = Vec::new();

        for _ in 0..ndim {
            let dimension = crate::from_sql::read_i32(&mut buf)?;
            dimensions.push(dimension);

            let lower_bound = crate::from_sql::read_i32(&mut buf)?;
            lower_bounds.push(lower_bound);
        }

        let mut data = Vec::new();

        while !buf.is_empty() {
            let len = crate::from_sql::read_u32(&mut buf)? as usize;

            let value = if len == 0xFFFF_FFFF {
                None
            } else {
                let mut data = vec![0; len];
                buf.read_exact(data.as_mut_slice())?;

                if data.eq_ignore_ascii_case(b"'null'") {
                    data.remove(0);
                    data.pop();
                }

                Some(data)
            };

            let element = T::from_sql(&elemtype, crate::pq::Format::Binary, value.as_deref())?;
            data.push(element);
        }

        let array = Self {
            ndim: ndim as usize,
            elemtype,
            has_nulls,
            dimensions,
            lower_bounds,
            data,
        };

        Ok(array)
    }
}

impl<T: crate::ToSql> crate::ToSql for Array<T> {
    fn ty(&self) -> crate::pq::Type {
        self.elemtype.to_array()
    }

    /*
     * https://github.com/postgres/postgres/blob/REL_12_0/src/backend/utils/adt/arrayfuncs.c#L172
     */
    fn to_text(&self) -> crate::Result<Option<String>> {
        if self.data.is_empty() {
            return "{}".to_text();
        }

        let mut data = String::new();

        let need_dims = self
            .lower_bounds
            .iter()
            .fold(false, |acc, x| acc | (*x != 1));

        if need_dims {
            for (dim, lb) in self.dimensions.iter().zip(&self.lower_bounds) {
                let hb = lb + dim - 1;
                data.push_str(&format!("[{lb}:{hb}]"));
            }

            data.push('=');
        }

        data.push('{');

        let mut indx = vec![0; self.ndim];
        let mut j = 0;
        let mut k = 0;

        'outer: loop {
            data.push_str(&(0..self.ndim - 1 - j).map(|_| "{").collect::<String>());

            let element = &self.data[k];

            let raw = element.to_text()?.map_or_else(
                || "null".to_string(),
                |mut x| {
                    if element.ty().is_text() && x.eq_ignore_ascii_case("null") {
                        x.insert(0, '\'');
                        x.push('\'');
                    }

                    x
                },
            );

            data.push_str(&raw);
            k += 1;

            for i in (0..self.ndim).rev() {
                j = i;
                indx[i] += 1;

                if indx[i] < self.dimensions[i] {
                    data.push(',');
                    break;
                }

                indx[i] = 0;
                data.push('}');

                if i == 0 {
                    break 'outer;
                }
            }
        }

        Ok(Some(data))
    }

    /*
     * https://github.com/postgres/postgres/blob/REL_12_0/src/backend/utils/adt/arrayfuncs.c#L1267
     */
    fn to_binary(&self) -> crate::Result<Option<Vec<u8>>> {
        let mut buf = Vec::new();

        crate::to_sql::write_i32(&mut buf, self.ndim as i32)?;
        crate::to_sql::write_i32(&mut buf, self.has_nulls as i32)?;
        crate::to_sql::write_i32(&mut buf, self.ty().elementype().oid as i32)?;

        for x in 0..self.ndim {
            crate::to_sql::write_i32(&mut buf, self.dimensions[x])?;
            crate::to_sql::write_i32(&mut buf, self.lower_bounds[x])?;
        }

        for d in &self.data {
            if let Some(raw) = d.to_binary()? {
                crate::to_sql::write_i32(&mut buf, raw.len() as i32)?;
                buf.extend(&raw);
            } else {
                crate::to_sql::write_i32(&mut buf, -1)?;
            }
        }

        Ok(Some(buf))
    }
}

impl<T: crate::FromSql + crate::ToSql> crate::entity::Simple for Array<T> {}

impl<T: crate::FromSql> From<Array<T>> for Vec<T> {
    fn from(array: Array<T>) -> Self {
        if array.ndim > 1 {
            panic!(
                "Unable to transform {} dimension array as vector",
                array.ndim
            );
        }

        array.collect()
    }
}

impl<T: crate::ToSql + Clone> From<&Vec<T>> for Array<T> {
    fn from(data: &Vec<T>) -> Self {
        use crate::ToSql;

        Self {
            ndim: 1,
            elemtype: data.ty(),
            dimensions: vec![data.len() as i32],
            lower_bounds: vec![1],
            has_nulls: false,
            data: data.clone(),
        }
    }
}

impl<T: crate::ToSql + Clone> crate::ToSql for Vec<T> {
    fn ty(&self) -> crate::pq::Type {
        for data in self {
            let ty = data.ty().to_array();

            if ty != crate::pq::types::UNKNOWN {
                return ty;
            }
        }

        crate::pq::types::UNKNOWN
    }

    fn to_text(&self) -> crate::Result<Option<String>> {
        crate::sql::Array::from(self).to_text()
    }

    fn to_binary(&self) -> crate::Result<Option<Vec<u8>>> {
        crate::sql::Array::from(self).to_binary()
    }
}

impl<T: crate::FromSql> crate::FromSql for Vec<T> {
    fn from_text(ty: &crate::pq::Type, raw: Option<&str>) -> crate::Result<Self> {
        Ok(crate::Array::from_text(ty, raw)?.into())
    }

    fn from_binary(ty: &crate::pq::Type, raw: Option<&[u8]>) -> crate::Result<Self> {
        Ok(crate::Array::from_binary(ty, raw)?.into())
    }
}

#[cfg(test)]
mod test {
    use crate::ToSql;

    #[test]
    fn array_from_vec() {
        let array = crate::Array::from(&vec![1, 2, 3]);

        assert_eq!(array.ndim, 1);
        assert_eq!(array[2], 3);
    }

    #[test]
    fn vec_to_text() {
        let vec = vec![1, 2, 3];

        assert_eq!(vec.to_text().unwrap(), Some("{1,2,3}".to_string()));
    }

    #[test]
    fn empty_vec() {
        let vec = Vec::<String>::new();

        assert_eq!(vec.to_text().unwrap(), Some("{}".to_string()));
    }

    #[test]
    fn array_index() {
        let array = crate::Array {
            ndim: 2,
            elemtype: crate::pq::types::INT8,
            has_nulls: false,
            dimensions: vec![3, 2],
            lower_bounds: vec![1, 1],
            data: vec![1, 2, 3, 4, 5, 6],
        };

        assert_eq!(array[(2, 1)], 6);
    }

    crate::sql_test!(_int4, Vec<i32>, [("'{1, 2}'", vec![1, 2]),]);

    crate::sql_test!(
        _int8,
        crate::Array<i64>,
        [(
            "'[1:1][-2:-1][3:5]={{{1,2,3},{4,5,6}}}'",
            crate::Array {
                ndim: 3,
                elemtype: crate::pq::types::INT8,
                has_nulls: false,
                dimensions: vec![1, 2, 3],
                lower_bounds: vec![1, -2, 3],
                data: vec![1, 2, 3, 4, 5, 6],
            }
        )]
    );

    crate::sql_test!(
        _float4,
        Vec<Option<f32>>,
        [("'{null, 2.}'", vec![None, Some(2.)]),]
    );

    crate::sql_test!(
        _varchar,
        Vec<Option<String>>,
        [(
            "'{str, null, \'\'null\'\', \'\'NuLl\'\', \'\'abcd\'\'}'",
            vec![
                Some("str".to_string()),
                None,
                Some("null".to_string()),
                Some("NuLl".to_string()),
                Some("'abcd'".to_string())
            ]
        )]
    );
}