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
use {
	super::types::{ColumnInfo, ComplexTableName},
	crate::{result::Result, Column, DatabaseInner},
	serde::Serialize,
	thiserror::Error as ThisError,
};

#[derive(ThisError, Serialize, Debug, PartialEq)]
pub enum FetchError {
	#[error("table not found: {0}")]
	TableNotFound(String),
}

pub async fn fetch_columns(
	storage: &DatabaseInner,
	table: ComplexTableName,
) -> Result<Vec<ColumnInfo>> {
	let schema = storage
		.fetch_schema(&table.name)
		.await?
		.ok_or_else(|| FetchError::TableNotFound(table.name.clone()))?;
	let columns = schema
		.column_defs
		.iter()
		.map(|Column { name, .. }| {
			let index = schema
				.indexes
				.iter()
				.find_map(|index| (&index.column == name).then(|| index.name.clone()));
			ColumnInfo {
				table: table.clone(),
				name: name.clone(),
				index,
			}
		})
		.collect();
	Ok(columns)
}