Skip to main content

reifydb_engine/expression/
access.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2// Copyright (c) 2025 ReifyDB
3
4use std::sync::Arc;
5
6use reifydb_core::{
7	error::diagnostic::query::column_not_found, interface::identifier::ColumnPrimitive, value::column::Column,
8};
9use reifydb_rql::expression::AccessPrimitiveExpression;
10use reifydb_type::{error, fragment::Fragment};
11
12use crate::{Result, expression::context::EvalContext};
13
14pub(crate) fn access_lookup(ctx: &EvalContext, expr: &AccessPrimitiveExpression) -> Result<Column> {
15	// Extract primitive name based on the ColumnPrimitive type
16	let source = match &expr.column.primitive {
17		ColumnPrimitive::Primitive {
18			primitive,
19			..
20		} => primitive,
21		ColumnPrimitive::Alias(alias) => alias,
22	};
23	let column = expr.column.name.text().to_string();
24
25	// Build the full qualified name for aliased columns
26	let qualified_name = format!("{}.{}", source.text(), &column);
27
28	// Find columns - try both qualified name and unqualified name
29	let matching_col = ctx.columns.iter().find(|col| {
30		// First try to match the fully qualified name (for aliased columns)
31		if col.name().text() == qualified_name {
32			return true;
33		}
34
35		// For non-aliased columns, just match on the column name
36		// (but only if this isn't an aliased access)
37		if matches!(&expr.column.primitive, ColumnPrimitive::Primitive { .. }) {
38			if col.name().text() == column {
39				// Make sure this column doesn't belong to a different source
40				// by checking if it has a dot in the name (qualified)
41				return !col.name().text().contains('.');
42			}
43		}
44
45		false
46	});
47
48	if let Some(col) = matching_col {
49		// Extract the column data and preserve it
50		Ok(col.with_new_data(col.data().clone()))
51	} else {
52		// If not found, return an error with proper diagnostic
53		Err(error!(column_not_found(Fragment::Statement {
54			column: expr.column.name.column(),
55			line: expr.column.name.line(),
56			text: Arc::from(format!("{}.{}", source.text(), &column)),
57		})))
58	}
59}