risingwave_common/types/
fields.rs

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
// Copyright 2024 RisingWave Labs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use super::DataType;
use crate::row::OwnedRow;
use crate::util::chunk_coalesce::DataChunkBuilder;

/// A struct can implements `Fields` when if can be represented as a relational Row.
///
/// # Derivable
///
/// This trait can be automatically derived with [`#[derive(Fields)]`](derive@super::Fields).
/// Type of the fields must implement [`WithDataType`](super::WithDataType) and [`ToOwnedDatum`](super::ToOwnedDatum).
///
/// ```
/// # use risingwave_common::types::Fields;
///
/// #[derive(Fields)]
/// struct Data {
///     v1: i16,
///     v2: i32,
/// }
/// ```
///
/// You can add `#[primary_key]` attribute to one of the fields to specify the primary key of the table.
///
/// ```
/// # use risingwave_common::types::Fields;
///
/// #[derive(Fields)]
/// struct Data {
///     #[primary_key]
///     v1: i16,
///     v2: i32,
/// }
/// ```
///
/// If the primary key is composite, you can add `#[primary_key(...)]` attribute to the struct to specify the order of the fields.
///
/// ```
/// # use risingwave_common::types::Fields;
///
/// #[derive(Fields)]
/// #[primary_key(v2, v1)]
/// struct Data {
///     v1: i16,
///     v2: i32,
/// }
/// ```
pub trait Fields {
    /// The primary key of the table.
    ///
    /// - `None` if the primary key is not applicable.
    /// - `Some(&[])` if the primary key is empty, i.e., there'll be at most one row in the table.
    const PRIMARY_KEY: Option<&'static [usize]>;

    /// Return the schema of the struct.
    fn fields() -> Vec<(&'static str, DataType)>;

    /// Convert the struct to an `OwnedRow`.
    fn into_owned_row(self) -> OwnedRow;

    /// Create a [`DataChunkBuilder`](crate::util::chunk_coalesce::DataChunkBuilder) with the schema of the struct.
    fn data_chunk_builder(capacity: usize) -> DataChunkBuilder {
        DataChunkBuilder::new(
            Self::fields().into_iter().map(|(_, ty)| ty).collect(),
            capacity,
        )
    }
}

#[cfg(test)]
mod tests {
    use bytes::Bytes;

    use super::*;
    use crate::types::{Fields, StructType, Timestamp, Timestamptz, F32};

    #[test]
    #[allow(dead_code)]
    fn test_macro() {
        #[derive(Fields)]
        struct Sub {
            v12: Timestamptz,
            v13: Bytes,
        }

        #[derive(Fields)]
        struct Data {
            v1: i16,
            v2: std::primitive::i32,
            v3: bool,
            v4: f32,
            v5: F32,
            v6: Option<f64>,
            v7: Vec<u8>,
            v8: std::vec::Vec<i16>,
            v9: Option<Vec<i64>>,
            v10: std::option::Option<Vec<Option<F32>>>,
            v11: Timestamp,
            v14: Sub,
        }

        assert_eq!(
            Data::fields(),
            vec![
                ("v1", DataType::Int16),
                ("v2", DataType::Int32),
                ("v3", DataType::Boolean),
                ("v4", DataType::Float32),
                ("v5", DataType::Float32),
                ("v6", DataType::Float64),
                ("v7", DataType::Bytea),
                ("v8", DataType::List(Box::new(DataType::Int16))),
                ("v9", DataType::List(Box::new(DataType::Int64))),
                ("v10", DataType::List(Box::new(DataType::Float32))),
                ("v11", DataType::Timestamp),
                (
                    "v14",
                    DataType::Struct(StructType::new(vec![
                        ("v12", DataType::Timestamptz),
                        ("v13", DataType::Bytea)
                    ]))
                )
            ]
        )
    }
}