change every Rc to Arc in schema internals

This commit is contained in:
Pere Diaz Bou
2025-07-28 10:51:17 +02:00
parent d273de483f
commit 752a876f9a
14 changed files with 61 additions and 55 deletions

View File

@@ -97,7 +97,7 @@ pub(crate) unsafe extern "C" fn register_scalar_function(
unsafe { unsafe {
(*ext_ctx.syms).functions.insert( (*ext_ctx.syms).functions.insert(
name_str.clone(), name_str.clone(),
Rc::new(ExternalFunc::new_scalar(name_str, func)), Arc::new(ExternalFunc::new_scalar(name_str, func)),
); );
} }
ResultCode::OK ResultCode::OK
@@ -123,7 +123,7 @@ pub(crate) unsafe extern "C" fn register_aggregate_function(
unsafe { unsafe {
(*ext_ctx.syms).functions.insert( (*ext_ctx.syms).functions.insert(
name_str.clone(), name_str.clone(),
Rc::new(ExternalFunc::new_aggregate( Arc::new(ExternalFunc::new_aggregate(
name_str, name_str,
args, args,
(init_func, step_func, finalize_func), (init_func, step_func, finalize_func),

View File

@@ -1,6 +1,7 @@
use std::fmt; use std::fmt;
use std::fmt::{Debug, Display}; use std::fmt::{Debug, Display};
use std::rc::Rc; use std::rc::Rc;
use std::sync::Arc;
use turso_ext::{FinalizeFunction, InitAggFunction, ScalarFunction, StepFunction}; use turso_ext::{FinalizeFunction, InitAggFunction, ScalarFunction, StepFunction};
use crate::LimboError; use crate::LimboError;
@@ -593,7 +594,7 @@ pub enum Func {
#[cfg(feature = "json")] #[cfg(feature = "json")]
Json(JsonFunc), Json(JsonFunc),
AlterTable(AlterTableFunc), AlterTable(AlterTableFunc),
External(Rc<ExternalFunc>), External(Arc<ExternalFunc>),
} }
impl Display for Func { impl Display for Func {

View File

@@ -1676,8 +1676,8 @@ pub type StepResult = vdbe::StepResult;
#[derive(Default)] #[derive(Default)]
pub struct SymbolTable { pub struct SymbolTable {
pub functions: HashMap<String, Rc<function::ExternalFunc>>, pub functions: HashMap<String, Arc<function::ExternalFunc>>,
pub vtabs: HashMap<String, Rc<VirtualTable>>, pub vtabs: HashMap<String, Arc<VirtualTable>>,
pub vtab_modules: HashMap<String, Rc<crate::ext::VTabImpl>>, pub vtab_modules: HashMap<String, Rc<crate::ext::VTabImpl>>,
} }
@@ -1726,7 +1726,7 @@ impl SymbolTable {
&self, &self,
name: &str, name: &str,
_arg_count: usize, _arg_count: usize,
) -> Option<Rc<function::ExternalFunc>> { ) -> Option<Arc<function::ExternalFunc>> {
self.functions.get(name).cloned() self.functions.get(name).cloned()
} }

View File

@@ -44,7 +44,10 @@ impl Schema {
Arc::new(Table::BTree(sqlite_schema_table().into())), Arc::new(Table::BTree(sqlite_schema_table().into())),
); );
for function in VirtualTable::builtin_functions() { for function in VirtualTable::builtin_functions() {
tables.insert(function.name.to_owned(), Arc::new(Table::Virtual(function))); tables.insert(
function.name.to_owned(),
Arc::new(Table::Virtual(Arc::new((*function).clone()))),
);
} }
Self { Self {
tables, tables,
@@ -62,12 +65,12 @@ impl Schema {
.any(|idx| idx.1.iter().any(|i| i.name == name)) .any(|idx| idx.1.iter().any(|i| i.name == name))
} }
pub fn add_btree_table(&mut self, table: Rc<BTreeTable>) { pub fn add_btree_table(&mut self, table: Arc<BTreeTable>) {
let name = normalize_ident(&table.name); let name = normalize_ident(&table.name);
self.tables.insert(name, Table::BTree(table).into()); self.tables.insert(name, Table::BTree(table).into());
} }
pub fn add_virtual_table(&mut self, table: Rc<VirtualTable>) { pub fn add_virtual_table(&mut self, table: Arc<VirtualTable>) {
let name = normalize_ident(&table.name); let name = normalize_ident(&table.name);
self.tables.insert(name, Table::Virtual(table).into()); self.tables.insert(name, Table::Virtual(table).into());
} }
@@ -87,7 +90,7 @@ impl Schema {
self.tables.remove(&name); self.tables.remove(&name);
} }
pub fn get_btree_table(&self, name: &str) -> Option<Rc<BTreeTable>> { pub fn get_btree_table(&self, name: &str) -> Option<Arc<BTreeTable>> {
let name = normalize_ident(name); let name = normalize_ident(name);
if let Some(table) = self.tables.get(&name) { if let Some(table) = self.tables.get(&name) {
table.btree() table.btree()
@@ -198,22 +201,23 @@ impl Schema {
// longer in the in-memory schema. We need to recreate it if // longer in the in-memory schema. We need to recreate it if
// the module is loaded in the symbol table. // the module is loaded in the symbol table.
let vtab = if let Some(vtab) = syms.vtabs.get(name) { let vtab = if let Some(vtab) = syms.vtabs.get(name) {
vtab.clone() Arc::new((**vtab).clone())
} else { } else {
let mod_name = module_name_from_sql(sql)?; let mod_name = module_name_from_sql(sql)?;
crate::VirtualTable::table( let vtab_rc = crate::VirtualTable::table(
Some(name), Some(name),
mod_name, mod_name,
module_args_from_sql(sql)?, module_args_from_sql(sql)?,
syms, syms,
)? )?;
Arc::new((*vtab_rc).clone())
}; };
self.add_virtual_table(vtab); self.add_virtual_table(vtab);
continue; continue;
} }
let table = BTreeTable::from_sql(sql, root_page as usize)?; let table = BTreeTable::from_sql(sql, root_page as usize)?;
self.add_btree_table(Rc::new(table)); self.add_btree_table(Arc::new(table));
} }
"index" => { "index" => {
let root_page_value = record_cursor.get_value(&row, 3)?; let root_page_value = record_cursor.get_value(&row, 3)?;
@@ -323,14 +327,17 @@ impl Clone for Schema {
.iter() .iter()
.map(|(name, table)| match table.deref() { .map(|(name, table)| match table.deref() {
Table::BTree(table) => { Table::BTree(table) => {
let table = Rc::deref(table); let table = Arc::deref(table);
(name.clone(), Arc::new(Table::BTree(Rc::new(table.clone()))))
}
Table::Virtual(table) => {
let table = Rc::deref(table);
( (
name.clone(), name.clone(),
Arc::new(Table::Virtual(Rc::new(table.clone()))), Arc::new(Table::BTree(Arc::new(table.clone()))),
)
}
Table::Virtual(table) => {
let table = Arc::deref(table);
(
name.clone(),
Arc::new(Table::Virtual(Arc::new(table.clone()))),
) )
} }
Table::FromClauseSubquery(from_clause_subquery) => ( Table::FromClauseSubquery(from_clause_subquery) => (
@@ -362,8 +369,8 @@ impl Clone for Schema {
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum Table { pub enum Table {
BTree(Rc<BTreeTable>), BTree(Arc<BTreeTable>),
Virtual(Rc<VirtualTable>), Virtual(Arc<VirtualTable>),
FromClauseSubquery(FromClauseSubquery), FromClauseSubquery(FromClauseSubquery),
} }
@@ -402,7 +409,7 @@ impl Table {
} }
} }
pub fn btree(&self) -> Option<Rc<BTreeTable>> { pub fn btree(&self) -> Option<Arc<BTreeTable>> {
match self { match self {
Self::BTree(table) => Some(table.clone()), Self::BTree(table) => Some(table.clone()),
Self::Virtual(_) => None, Self::Virtual(_) => None,
@@ -410,7 +417,7 @@ impl Table {
} }
} }
pub fn virtual_table(&self) -> Option<Rc<VirtualTable>> { pub fn virtual_table(&self) -> Option<Arc<VirtualTable>> {
match self { match self {
Self::Virtual(table) => Some(table.clone()), Self::Virtual(table) => Some(table.clone()),
_ => None, _ => None,
@@ -421,8 +428,8 @@ impl Table {
impl PartialEq for Table { impl PartialEq for Table {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
match (self, other) { match (self, other) {
(Self::BTree(a), Self::BTree(b)) => Rc::ptr_eq(a, b), (Self::BTree(a), Self::BTree(b)) => Arc::ptr_eq(a, b),
(Self::Virtual(a), Self::Virtual(b)) => Rc::ptr_eq(a, b), (Self::Virtual(a), Self::Virtual(b)) => Arc::ptr_eq(a, b),
_ => false, _ => false,
} }
} }

View File

@@ -1,7 +1,7 @@
// This module contains code for emitting bytecode instructions for SQL query execution. // This module contains code for emitting bytecode instructions for SQL query execution.
// It handles translating high-level SQL operations into low-level bytecode that can be executed by the virtual machine. // It handles translating high-level SQL operations into low-level bytecode that can be executed by the virtual machine.
use std::rc::Rc; use std::sync::Arc;
use tracing::{instrument, Level}; use tracing::{instrument, Level};
use turso_sqlite3_parser::ast::{self, Expr}; use turso_sqlite3_parser::ast::{self, Expr};
@@ -1055,7 +1055,7 @@ fn emit_update_insns(
start_reg: start, start_reg: start,
count: table_ref.columns().len(), count: table_ref.columns().len(),
check_generated: true, check_generated: true,
table_reference: Rc::clone(&btree_table), table_reference: Arc::clone(&btree_table),
}); });
} }

View File

@@ -1,4 +1,3 @@
use std::rc::Rc;
use std::sync::Arc; use std::sync::Arc;
use turso_sqlite3_parser::ast::{ use turso_sqlite3_parser::ast::{
@@ -439,7 +438,7 @@ pub fn translate_insert(
start_reg: columns_start_register, start_reg: columns_start_register,
count: num_cols, count: num_cols,
check_generated: true, check_generated: true,
table_reference: Rc::clone(&t), table_reference: Arc::clone(&t),
}); });
} }
_ => (), _ => (),
@@ -962,7 +961,7 @@ fn populate_column_registers(
// TODO: comeback here later to apply the same improvements on select // TODO: comeback here later to apply the same improvements on select
fn translate_virtual_table_insert( fn translate_virtual_table_insert(
mut program: ProgramBuilder, mut program: ProgramBuilder,
virtual_table: Rc<VirtualTable>, virtual_table: Arc<VirtualTable>,
columns: Option<DistinctNames>, columns: Option<DistinctNames>,
mut body: InsertBody, mut body: InsertBody,
on_conflict: Option<ResolveType>, on_conflict: Option<ResolveType>,

View File

@@ -490,7 +490,7 @@ fn generate_join_bitmasks(table_number_max_exclusive: usize, how_many: usize) ->
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::{cell::Cell, rc::Rc, sync::Arc}; use std::{cell::Cell, sync::Arc};
use turso_sqlite3_parser::ast::{self, Expr, Operator, SortOrder, TableInternalId}; use turso_sqlite3_parser::ast::{self, Expr, Operator, SortOrder, TableInternalId};
@@ -1640,8 +1640,8 @@ mod tests {
} }
/// Creates a BTreeTable with the given name and columns /// Creates a BTreeTable with the given name and columns
fn _create_btree_table(name: &str, columns: Vec<Column>) -> Rc<BTreeTable> { fn _create_btree_table(name: &str, columns: Vec<Column>) -> Arc<BTreeTable> {
Rc::new(BTreeTable { Arc::new(BTreeTable {
root_page: 1, // Page number doesn't matter for tests root_page: 1, // Page number doesn't matter for tests
name: name.to_string(), name: name.to_string(),
primary_key_columns: vec![], primary_key_columns: vec![],
@@ -1654,7 +1654,7 @@ mod tests {
/// Creates a TableReference for a BTreeTable /// Creates a TableReference for a BTreeTable
fn _create_table_reference( fn _create_table_reference(
table: Rc<BTreeTable>, table: Arc<BTreeTable>,
join_info: Option<JoinInfo>, join_info: Option<JoinInfo>,
internal_id: TableInternalId, internal_id: TableInternalId,
) -> JoinedTable { ) -> JoinedTable {

View File

@@ -1,4 +1,4 @@
use std::{cell::Cell, cmp::Ordering, rc::Rc, sync::Arc}; use std::{cell::Cell, cmp::Ordering, sync::Arc};
use turso_ext::{ConstraintInfo, ConstraintOp}; use turso_ext::{ConstraintInfo, ConstraintOp};
use turso_sqlite3_parser::ast::{self, SortOrder}; use turso_sqlite3_parser::ast::{self, SortOrder};
@@ -333,7 +333,7 @@ pub enum QueryDestination {
/// The cursor ID of the ephemeral table that will be used to store the results. /// The cursor ID of the ephemeral table that will be used to store the results.
cursor_id: CursorID, cursor_id: CursorID,
/// The table that will be used to store the results. /// The table that will be used to store the results.
table: Rc<BTreeTable>, table: Arc<BTreeTable>,
}, },
} }
@@ -887,13 +887,13 @@ impl Operation {
impl JoinedTable { impl JoinedTable {
/// Returns the btree table for this table reference, if it is a BTreeTable. /// Returns the btree table for this table reference, if it is a BTreeTable.
pub fn btree(&self) -> Option<Rc<BTreeTable>> { pub fn btree(&self) -> Option<Arc<BTreeTable>> {
match &self.table { match &self.table {
Table::BTree(_) => self.table.btree(), Table::BTree(_) => self.table.btree(),
_ => None, _ => None,
} }
} }
pub fn virtual_table(&self) -> Option<Rc<VirtualTable>> { pub fn virtual_table(&self) -> Option<Arc<VirtualTable>> {
match &self.table { match &self.table {
Table::Virtual(_) => self.table.virtual_table(), Table::Virtual(_) => self.table.virtual_table(),
_ => None, _ => None,

View File

@@ -1,6 +1,7 @@
use std::collections::HashSet; use std::collections::HashSet;
use std::ops::Range; use std::ops::Range;
use std::rc::Rc; use std::rc::Rc;
use std::sync::Arc;
use crate::ast; use crate::ast;
use crate::ext::VTabImpl; use crate::ext::VTabImpl;
@@ -772,7 +773,7 @@ pub fn translate_drop_table(
// cursor id 1 // cursor id 1
let sqlite_schema_cursor_id_1 = let sqlite_schema_cursor_id_1 =
program.alloc_cursor_id(CursorType::BTreeTable(schema_table.clone())); program.alloc_cursor_id(CursorType::BTreeTable(schema_table.clone()));
let simple_table_rc = Rc::new(BTreeTable { let simple_table_rc = Arc::new(BTreeTable {
root_page: 0, // Not relevant for ephemeral table definition root_page: 0, // Not relevant for ephemeral table definition
name: "ephemeral_scratch".to_string(), name: "ephemeral_scratch".to_string(),
has_rowid: true, has_rowid: true,

View File

@@ -1,5 +1,4 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc; use std::sync::Arc;
use crate::schema::{BTreeTable, Column, Type}; use crate::schema::{BTreeTable, Column, Type};
@@ -235,7 +234,7 @@ pub fn prepare_update_plan(
connection, connection,
)?; )?;
let table = Rc::new(BTreeTable { let table = Arc::new(BTreeTable {
root_page: 0, // Not relevant for ephemeral table definition root_page: 0, // Not relevant for ephemeral table definition
name: "ephemeral_scratch".to_string(), name: "ephemeral_scratch".to_string(),
has_rowid: true, has_rowid: true,

View File

@@ -111,7 +111,7 @@ pub fn parse_schema_rows(
schema.add_virtual_table(vtab); schema.add_virtual_table(vtab);
} else { } else {
let table = schema::BTreeTable::from_sql(sql, root_page as usize)?; let table = schema::BTreeTable::from_sql(sql, root_page as usize)?;
schema.add_btree_table(Rc::new(table)); schema.add_btree_table(Arc::new(table));
} }
} }
"index" => { "index" => {

View File

@@ -1,4 +1,4 @@
use std::{cell::Cell, cmp::Ordering, rc::Rc, sync::Arc}; use std::{cell::Cell, cmp::Ordering, sync::Arc};
use tracing::{instrument, Level}; use tracing::{instrument, Level};
use turso_sqlite3_parser::ast::{self, TableInternalId}; use turso_sqlite3_parser::ast::{self, TableInternalId};
@@ -115,11 +115,11 @@ pub struct ProgramBuilder {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum CursorType { pub enum CursorType {
BTreeTable(Rc<BTreeTable>), BTreeTable(Arc<BTreeTable>),
BTreeIndex(Arc<Index>), BTreeIndex(Arc<Index>),
Pseudo(PseudoCursorType), Pseudo(PseudoCursorType),
Sorter, Sorter,
VirtualTable(Rc<VirtualTable>), VirtualTable(Arc<VirtualTable>),
} }
impl CursorType { impl CursorType {

View File

@@ -1,6 +1,5 @@
use std::{ use std::{
num::{NonZero, NonZeroUsize}, num::{NonZero, NonZeroUsize},
rc::Rc,
sync::Arc, sync::Arc,
}; };
@@ -417,7 +416,7 @@ pub enum Insn {
/// GENERATED ALWAYS AS ... STATIC columns are only checked if P3 is zero. /// GENERATED ALWAYS AS ... STATIC columns are only checked if P3 is zero.
/// When P3 is non-zero, no type checking occurs for static generated columns. /// When P3 is non-zero, no type checking occurs for static generated columns.
check_generated: bool, // P3 check_generated: bool, // P3
table_reference: Rc<BTreeTable>, // P4 table_reference: Arc<BTreeTable>, // P4
}, },
// Make a record and write it to destination register. // Make a record and write it to destination register.

View File

@@ -25,14 +25,14 @@ pub struct VirtualTable {
} }
impl VirtualTable { impl VirtualTable {
pub(crate) fn readonly(self: &Rc<VirtualTable>) -> bool { pub(crate) fn readonly(self: &Arc<VirtualTable>) -> bool {
match &self.vtab_type { match &self.vtab_type {
VirtualTableType::Pragma(_) => true, VirtualTableType::Pragma(_) => true,
VirtualTableType::External(table) => table.readonly(), VirtualTableType::External(table) => table.readonly(),
} }
} }
pub(crate) fn builtin_functions() -> Vec<Rc<VirtualTable>> { pub(crate) fn builtin_functions() -> Vec<Arc<VirtualTable>> {
PragmaVirtualTable::functions() PragmaVirtualTable::functions()
.into_iter() .into_iter()
.map(|(tab, schema)| { .map(|(tab, schema)| {
@@ -43,12 +43,12 @@ impl VirtualTable {
kind: VTabKind::TableValuedFunction, kind: VTabKind::TableValuedFunction,
vtab_type: VirtualTableType::Pragma(tab), vtab_type: VirtualTableType::Pragma(tab),
}; };
Rc::new(vtab) Arc::new(vtab)
}) })
.collect() .collect()
} }
pub(crate) fn function(name: &str, syms: &SymbolTable) -> crate::Result<Rc<VirtualTable>> { pub(crate) fn function(name: &str, syms: &SymbolTable) -> crate::Result<Arc<VirtualTable>> {
let module = syms.vtab_modules.get(name); let module = syms.vtab_modules.get(name);
let (vtab_type, schema) = if module.is_some() { let (vtab_type, schema) = if module.is_some() {
ExtVirtualTable::create(name, module, Vec::new(), VTabKind::TableValuedFunction) ExtVirtualTable::create(name, module, Vec::new(), VTabKind::TableValuedFunction)
@@ -65,7 +65,7 @@ impl VirtualTable {
kind: VTabKind::TableValuedFunction, kind: VTabKind::TableValuedFunction,
vtab_type, vtab_type,
}; };
Ok(Rc::new(vtab)) Ok(Arc::new(vtab))
} }
pub fn table( pub fn table(
@@ -73,7 +73,7 @@ impl VirtualTable {
module_name: &str, module_name: &str,
args: Vec<turso_ext::Value>, args: Vec<turso_ext::Value>,
syms: &SymbolTable, syms: &SymbolTable,
) -> crate::Result<Rc<VirtualTable>> { ) -> crate::Result<Arc<VirtualTable>> {
let module = syms.vtab_modules.get(module_name); let module = syms.vtab_modules.get(module_name);
let (table, schema) = let (table, schema) =
ExtVirtualTable::create(module_name, module, args, VTabKind::VirtualTable)?; ExtVirtualTable::create(module_name, module, args, VTabKind::VirtualTable)?;
@@ -83,7 +83,7 @@ impl VirtualTable {
kind: VTabKind::VirtualTable, kind: VTabKind::VirtualTable,
vtab_type: VirtualTableType::External(table), vtab_type: VirtualTableType::External(table),
}; };
Ok(Rc::new(vtab)) Ok(Arc::new(vtab))
} }
fn resolve_columns(schema: String) -> crate::Result<Vec<Column>> { fn resolve_columns(schema: String) -> crate::Result<Vec<Column>> {