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
use std::{
    fmt::{self, Debug},
    sync::Arc,
};

use anyhow::Context;
use rmpv::Value;
use serde::{de::DeserializeOwned, Deserialize};

use super::{Index, IndexMetadata, OwnedIndex, SchemaEntityKey, SystemSpacesId, PRIMARY_INDEX_ID};
use crate::{
    client::ExecutorExt, tuple::Tuple, utils::UniqueIdNameMap, DmoResponse, Error, Executor,
    IteratorType, Result, Transaction,
};

/// Space metadata with its indices metadata from [system views](https://www.tarantool.io/en/doc/latest/reference/reference_lua/box_space/system_views/).
#[derive(Clone, Deserialize)]
pub struct SpaceMetadata {
    pub(super) id: u32,
    owner_id: u32,
    name: String,
    _engine: String, // TODO: enum
    _fields_count: u32,
    _flags: Value,       // TODO: parse flags
    _format: Vec<Value>, // TODO: parse format or remove it entirely
}

impl fmt::Debug for SpaceMetadata {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SpaceMetadata")
            .field("id", &self.id)
            .field("owner_id", &self.owner_id)
            .field("name", &self.name)
            .field("engine", &self._engine)
            // TODO: uncomment when fields implemented
            // .field("_flags", &self._flags)
            // .field("_format", &self._format)
            .finish()
    }
}

impl SpaceMetadata {
    /// Load metadata of single space by key.
    ///
    /// Can be loaded by index (if passed unsigned integer) or name (if passed `&str`).
    async fn load(conn: impl ExecutorExt, key: SchemaEntityKey) -> Result<Option<Self>> {
        Ok(conn
            .select(
                SystemSpacesId::VSpace as u32,
                key.space_index_id(),
                None,
                None,
                None,
                (key.into_value(),),
            )
            .await?
            .into_iter()
            .next())
    }

    /// Returns the id of this space.
    pub fn id(&self) -> u32 {
        self.id
    }

    /// Returns user id of ther owner of this space.
    pub fn owner_id(&self) -> u32 {
        self.owner_id
    }

    /// Returns a name of this space.
    pub fn name(&self) -> &str {
        self.name.as_ref()
    }

    // /// Returns map of idices in this space.
    // pub fn indices(&self) -> &UniqueIdNameMap<IndexMetadata> {
    //     &self.indices
    // }
}

/// Tarantool space.
///
/// This is a wrapper around [`Executor`], which allow to make space-related requests
/// on specific space. All requests over index uses primary index.
pub struct Space<E> {
    executor: E,
    metadata: Arc<SpaceMetadata>,
    primary_index_metadata: Arc<IndexMetadata>,
    indices_metadata: Arc<UniqueIdNameMap<IndexMetadata>>,
}

impl<E: Clone> Clone for Space<E> {
    fn clone(&self) -> Self {
        Self {
            executor: self.executor.clone(),
            metadata: self.metadata.clone(),
            primary_index_metadata: self.primary_index_metadata.clone(),
            indices_metadata: self.indices_metadata.clone(),
        }
    }
}

impl<E> Space<E> {
    fn get_index(&self, key: impl Into<SchemaEntityKey>) -> Option<&Arc<IndexMetadata>> {
        match key.into() {
            SchemaEntityKey::Id(x) => self.indices_metadata.get_by_id(x),
            SchemaEntityKey::Name(x) => self.indices_metadata.get_by_name(&x),
        }
    }

    pub fn executor(&self) -> &E {
        &self.executor
    }

    pub fn metadata(&self) -> &SpaceMetadata {
        &self.metadata
    }

    pub fn into_executor(self) -> E {
        self.executor
    }

    pub fn primary_index(&self) -> Index<&E> {
        Index::new(&self.executor, &self.primary_index_metadata, &self.metadata)
    }

    pub fn index(&self, key: impl Into<SchemaEntityKey>) -> Option<Index<&E>> {
        self.get_index(key)
            .map(|index| Index::new(&self.executor, index, &self.metadata))
    }
}

impl<E: Clone> Space<E> {
    pub fn owned_primary_index(&self) -> OwnedIndex<E> {
        OwnedIndex::new(
            self.executor.clone(),
            self.primary_index_metadata.clone(),
            self.metadata.clone(),
        )
    }

    pub fn owned_index(&self, key: impl Into<SchemaEntityKey>) -> Option<OwnedIndex<E>> {
        self.get_index(key).map(|index| {
            OwnedIndex::new(self.executor.clone(), index.clone(), self.metadata.clone())
        })
    }
}

impl<E: Executor> Space<E> {
    /// Load metadata of single space by its key.
    ///
    /// Can be called with space's index (if passed unsigned integer) or name (if passed `&str`).
    pub(crate) async fn load(executor: E, key: SchemaEntityKey) -> Result<Option<Self>> {
        let Some(space_metadata) = SpaceMetadata::load(&executor, key).await? else {
            return Ok(None);
        };

        let indices = IndexMetadata::load_by_space_id(&executor, space_metadata.id)
            .await
            .and_then(|x| {
                UniqueIdNameMap::try_from_iter(x)
                    .context("Duplicate indices in space")
                    .map_err(Error::Other)
            })?;
        let Some(primary_index) = indices.get_by_id(PRIMARY_INDEX_ID).cloned() else {
            return Err(Error::SpaceMissingPrimaryIndex);
        };

        Ok(Some(Self {
            executor,
            metadata: space_metadata.into(),
            primary_index_metadata: primary_index,
            indices_metadata: indices.into(),
        }))
    }

    /// Iterator over indices in this space.
    pub fn indices(&self) -> impl Iterator<Item = Index<&E>> {
        self.indices_metadata
            .iter()
            .map(|index| Index::new(&self.executor, index, &self.metadata))
    }

    /// Call `select` with primary index on current space.
    ///
    /// For details see [`ExecutorExt::select`].
    pub async fn select<T, A>(
        &self,
        limit: Option<u32>,
        offset: Option<u32>,
        iterator: Option<IteratorType>,
        keys: A,
    ) -> Result<Vec<T>>
    where
        T: DeserializeOwned,
        A: Tuple + Send,
    {
        self.executor
            .select(
                self.metadata.id,
                PRIMARY_INDEX_ID,
                limit,
                offset,
                iterator,
                keys,
            )
            .await
    }

    /// Call `insert` on current space.
    ///
    /// For details see [`ExecutorExt::insert`].
    pub async fn insert<T>(&self, tuple: T) -> Result<DmoResponse>
    where
        T: Tuple + Send,
    {
        self.executor.insert(self.metadata.id, tuple).await
    }

    /// Call `update` with primary index on current space.
    ///
    /// For details see [`ExecutorExt::update`].
    pub async fn update<K, O>(&self, keys: K, ops: O) -> Result<DmoResponse>
    where
        K: Tuple + Send,
        O: Tuple + Send,
    {
        self.executor
            .update(self.metadata.id, PRIMARY_INDEX_ID, keys, ops)
            .await
    }

    /// Call `upsert` on current space.
    ///
    /// For details see [`ExecutorExt::upsert`].
    pub async fn upsert<T, O>(&self, tuple: T, ops: O) -> Result<DmoResponse>
    where
        T: Tuple + Send,
        O: Tuple + Send,
    {
        self.executor.upsert(self.metadata.id, tuple, ops).await
    }

    /// Call `replace` on current space.
    ///
    /// For details see [`ExecutorExt::replace`].
    pub async fn replace<T>(&self, tuple: T) -> Result<DmoResponse>
    where
        T: Tuple + Send,
    {
        self.executor.replace(self.metadata.id, tuple).await
    }

    /// Call `delete` with primary index on current space.
    ///
    /// For details see [`ExecutorExt::delete`].
    pub async fn delete<T>(&self, keys: T) -> Result<DmoResponse>
    where
        T: Tuple + Send,
    {
        self.executor
            .delete(self.metadata.id, PRIMARY_INDEX_ID, keys)
            .await
    }
}

impl Space<Transaction> {
    /// Commit inner tranasction.
    pub async fn commit(self) -> Result<()> {
        self.executor.commit().await
    }

    /// Rollback inner tranasction.
    pub async fn rollback(self) -> Result<()> {
        self.executor.rollback().await
    }
}

impl<E: Debug> fmt::Debug for Space<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SpaceMetadata")
            .field("executor", &self.executor)
            .field("metadata", &self.metadata)
            .finish()
    }
}