diff --git a/crates/dojo-lang/src/manifest.rs b/crates/dojo-lang/src/manifest.rs index 58a34e1b96..6efcf62b26 100644 --- a/crates/dojo-lang/src/manifest.rs +++ b/crates/dojo-lang/src/manifest.rs @@ -87,7 +87,7 @@ impl Manifest { } /// Finds the inline modules annotated as components in the given crate_ids and - /// returns the corresponding Components. + /// returns the corresponding Models. fn find_components( &mut self, db: &dyn SemanticGroup, @@ -108,7 +108,7 @@ impl Manifest { .with_context(|| format!("Component {name} not found in target.")) .unwrap(); - self.0.components.push(dojo_world::manifest::Component { + self.0.components.push(dojo_world::manifest::Model { name: component.name, members: component.members, class_hash: *class_hash, diff --git a/crates/dojo-world/src/manifest.rs b/crates/dojo-world/src/manifest.rs index d4134a0b69..892ca365c8 100644 --- a/crates/dojo-world/src/manifest.rs +++ b/crates/dojo-world/src/manifest.rs @@ -52,7 +52,7 @@ pub struct Member { /// Represents a declaration of a component. #[serde_as] #[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq)] -pub struct Component { +pub struct Model { pub name: String, pub members: Vec, #[serde_as(as = "UfeHex")] @@ -106,7 +106,7 @@ pub struct Manifest { pub executor: Contract, pub systems: Vec, pub contracts: Vec, - pub components: Vec, + pub components: Vec, } impl Manifest { @@ -180,7 +180,7 @@ impl Manifest { .await .map_err(ManifestError::Provider)?; - components.push(Component { + components.push(Model { name: component.name.clone(), class_hash: result[0], ..Default::default() diff --git a/crates/dojo-world/src/migration/world_test.rs b/crates/dojo-world/src/migration/world_test.rs index cdd9f898c8..0d9e0d4e9d 100644 --- a/crates/dojo-world/src/migration/world_test.rs +++ b/crates/dojo-world/src/migration/world_test.rs @@ -1,5 +1,5 @@ use super::*; -use crate::manifest::{Component, Contract, Manifest, System}; +use crate::manifest::{Contract, Manifest, Model, System}; #[test] fn no_diff_when_local_and_remote_are_equal() { @@ -17,7 +17,7 @@ fn no_diff_when_local_and_remote_are_equal() { ..Default::default() }; - let components = vec![Component { + let components = vec![Model { members: vec![], name: "Component".into(), class_hash: 11_u32.into(), @@ -55,7 +55,7 @@ fn diff_when_local_and_remote_are_different() { ..Default::default() }; - let components = vec![Component { + let components = vec![Model { members: vec![], name: "Component".into(), class_hash: 11_u32.into(), diff --git a/crates/katana/core/src/fork/db.rs b/crates/katana/core/src/fork/db.rs index faa7131833..f7d55bb77a 100644 --- a/crates/katana/core/src/fork/db.rs +++ b/crates/katana/core/src/fork/db.rs @@ -253,6 +253,7 @@ mod tests { } #[tokio::test(flavor = "multi_thread")] + #[ignore] async fn fetch_from_provider_if_not_in_cache() { let provider = JsonRpcClient::new(HttpTransport::new(Url::parse(FORKED_ENDPOINT).unwrap())); let mut db = ForkedDb::new(Arc::new(provider), BlockId::Tag(BlockTag::Latest)); diff --git a/crates/sozo/src/ops/migration/mod.rs b/crates/sozo/src/ops/migration/mod.rs index 2c790f6282..56a18c0437 100644 --- a/crates/sozo/src/ops/migration/mod.rs +++ b/crates/sozo/src/ops/migration/mod.rs @@ -366,7 +366,7 @@ where return Ok(None); } - ws_config.ui().print_header(format!("# Components ({})", components.len())); + ws_config.ui().print_header(format!("# Models ({})", components.len())); let mut declare_output = vec![]; diff --git a/crates/torii/core/src/processors/mod.rs b/crates/torii/core/src/processors/mod.rs index 825653837e..85c006005b 100644 --- a/crates/torii/core/src/processors/mod.rs +++ b/crates/torii/core/src/processors/mod.rs @@ -6,7 +6,7 @@ use torii_client::contract::world::WorldContractReader; use crate::sql::Sql; -pub mod register_component; +pub mod register_model; pub mod register_system; pub mod store_set_record; pub mod store_system_call; diff --git a/crates/torii/core/src/processors/register_component.rs b/crates/torii/core/src/processors/register_model.rs similarity index 54% rename from crates/torii/core/src/processors/register_component.rs rename to crates/torii/core/src/processors/register_model.rs index b70760c9ea..71275b8b0f 100644 --- a/crates/torii/core/src/processors/register_component.rs +++ b/crates/torii/core/src/processors/register_model.rs @@ -1,7 +1,7 @@ use anyhow::{Error, Ok, Result}; use async_trait::async_trait; -use dojo_world::manifest::Component; -use starknet::core::types::{BlockWithTxs, Event, InvokeTransactionReceipt}; +use dojo_world::manifest::Model; +use starknet::core::types::{BlockId, BlockTag, BlockWithTxs, Event, InvokeTransactionReceipt}; use starknet::core::utils::parse_cairo_short_string; use starknet::providers::Provider; use torii_client::contract::world::WorldContractReader; @@ -11,17 +11,17 @@ use super::EventProcessor; use crate::sql::Sql; #[derive(Default)] -pub struct RegisterComponentProcessor; +pub struct RegisterModelProcessor; #[async_trait] -impl EventProcessor

for RegisterComponentProcessor { +impl EventProcessor

for RegisterModelProcessor { fn event_key(&self) -> String { "ComponentRegistered".to_string() } async fn process( &self, - _world: &WorldContractReader<'_, P>, + world: &WorldContractReader<'_, P>, db: &Sql, _provider: &P, _block: &BlockWithTxs, @@ -29,11 +29,11 @@ impl EventProcessor

for RegisterComponentProcessor { event: &Event, ) -> Result<(), Error> { let name = parse_cairo_short_string(&event.data[0])?; + let model = world.component(&name, BlockId::Tag(BlockTag::Latest)).await?; + let _schema = model.schema(BlockId::Tag(BlockTag::Latest)).await?; + info!("registered model: {}", name); - info!("registered component: {}", name); - - db.register_component(Component { name, class_hash: event.data[1], ..Default::default() }) - .await?; + db.register_model(Model { name, class_hash: event.data[1], ..Default::default() }).await?; Ok(()) } } diff --git a/crates/torii/core/src/sql.rs b/crates/torii/core/src/sql.rs index 9d5f2222d4..c778a60769 100644 --- a/crates/torii/core/src/sql.rs +++ b/crates/torii/core/src/sql.rs @@ -3,7 +3,7 @@ use std::collections::HashMap; use anyhow::Result; use async_trait::async_trait; use chrono::{DateTime, Utc}; -use dojo_world::manifest::{Component, Manifest, System}; +use dojo_world::manifest::{Manifest, Model, System}; use sqlx::pool::PoolConnection; use sqlx::sqlite::SqliteRow; use sqlx::{Executor, Pool, Row, Sqlite}; @@ -13,7 +13,7 @@ use tokio::sync::Mutex; use super::World; use crate::simple_broker::SimpleBroker; -use crate::types::{Component as ComponentType, Entity}; +use crate::types::{Entity, Model as ModelType}; #[cfg(test)] #[path = "sql_test.rs"] @@ -96,8 +96,8 @@ impl Sql { )]) .await; - for component in manifest.components { - self.register_component(component).await?; + for model in manifest.components { + self.register_model(model).await?; } for system in manifest.systems { @@ -151,24 +151,24 @@ impl Sql { Ok(()) } - pub async fn register_component(&self, component: Component) -> Result<()> { + pub async fn register_model(&self, model: Model) -> Result<()> { let mut sql_types = self.sql_types.lock().await; - let component_id = component.name.to_lowercase(); + let model_id = model.name.to_lowercase(); let mut queries = vec![format!( - "INSERT INTO components (id, name, class_hash) VALUES ('{}', '{}', '{:#x}') ON \ + "INSERT INTO models (id, name, class_hash) VALUES ('{}', '{}', '{:#x}') ON \ CONFLICT(id) DO UPDATE SET class_hash='{:#x}'", - component_id, component.name, component.class_hash, component.class_hash + model_id, model.name, model.class_hash, model.class_hash )]; - let mut component_table_query = format!( + let mut model_table_query = format!( "CREATE TABLE IF NOT EXISTS external_{} (entity_id TEXT NOT NULL PRIMARY KEY, ", - component.name.to_lowercase() + model.name.to_lowercase() ); - for member in &component.members { - // FIXME: defaults all unknown component types to Enum for now until we support nested - // components + for member in &model.members { + // FIXME: defaults all unknown model types to Enum for now until we support nested + // models let (sql_type, member_type) = match sql_types.get(&member.ty) { Some(sql_type) => (*sql_type, member.ty.as_str()), None => { @@ -178,26 +178,26 @@ impl Sql { }; queries.push(format!( - "INSERT OR IGNORE INTO component_members (component_id, name, type, key) VALUES \ - ('{}', '{}', '{}', {})", - component_id, member.name, member_type, member.key, + "INSERT OR IGNORE INTO model_members (model_id, name, type, key) VALUES ('{}', \ + '{}', '{}', {})", + model_id, member.name, member_type, member.key, )); - component_table_query.push_str(&format!("external_{} {}, ", member.name, sql_type)); + model_table_query.push_str(&format!("external_{} {}, ", member.name, sql_type)); } - component_table_query.push_str( + model_table_query.push_str( "created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (entity_id) REFERENCES entities(id));", ); - queries.push(component_table_query); + queries.push(model_table_query); self.queue(queries).await; // Since previous query has not been executed, we have to make sure created_at exists let created_at: DateTime = - match sqlx::query("SELECT created_at FROM components WHERE id = ?") - .bind(component_id.clone()) + match sqlx::query("SELECT created_at FROM models WHERE id = ?") + .bind(model_id.clone()) .fetch_one(&self.pool) .await { @@ -205,10 +205,10 @@ impl Sql { Err(_) => Utc::now(), }; - SimpleBroker::publish(ComponentType { - id: component_id, - name: component.name, - class_hash: format!("{:#x}", component.class_hash), + SimpleBroker::publish(ModelType { + id: model_id, + name: model.name, + class_hash: format!("{:#x}", model.class_hash), transaction_hash: "0x0".to_string(), created_at, }); @@ -230,7 +230,7 @@ impl Sql { pub async fn set_entity( &self, - component: String, + model: String, keys: Vec, values: Vec, ) -> Result<()> { @@ -241,22 +241,22 @@ impl Sql { .await?; let keys_str = felts_sql_string(&keys); - let component_names = component_names_sql_string(entity_result, &component)?; + let model_names = model_names_sql_string(entity_result, &model)?; let insert_entities = format!( - "INSERT INTO entities (id, keys, component_names) VALUES ('{}', '{}', '{}') ON \ + "INSERT INTO entities (id, keys, model_names) VALUES ('{}', '{}', '{}') ON \ CONFLICT(id) DO UPDATE SET - component_names=excluded.component_names, + model_names=excluded.model_names, updated_at=CURRENT_TIMESTAMP", - entity_id, keys_str, component_names + entity_id, keys_str, model_names ); let member_names_result = - sqlx::query("SELECT * FROM component_members WHERE component_id = ? ORDER BY id ASC") - .bind(component.to_lowercase()) + sqlx::query("SELECT * FROM model_members WHERE model_id = ? ORDER BY id ASC") + .bind(model.to_lowercase()) .fetch_all(&self.pool) .await?; - // keys are part of component members, so combine keys and component values array + // keys are part of model members, so combine keys and model values array let mut member_values: Vec = Vec::new(); member_values.extend(keys); member_values.extend(values); @@ -265,16 +265,16 @@ impl Sql { let names_str = members_sql_string(&member_names_result)?; let values_str = values_sql_string(&member_names_result, &member_values, &sql_types)?; - let insert_components = format!( + let insert_models = format!( "INSERT OR REPLACE INTO external_{} (entity_id {}) VALUES ('{}' {})", - component.to_lowercase(), + model.to_lowercase(), names_str, entity_id, values_str ); // tx commit required - self.queue(vec![insert_entities, insert_components]).await; + self.queue(vec![insert_entities, insert_models]).await; self.execute().await?; let query_result = sqlx::query("SELECT created_at FROM entities WHERE id = ?") @@ -286,28 +286,28 @@ impl Sql { SimpleBroker::publish(Entity { id: entity_id.clone(), keys: keys_str, - component_names, + model_names, created_at, updated_at: Utc::now(), }); Ok(()) } - pub async fn delete_entity(&self, component: String, key: FieldElement) -> Result<()> { - let query = format!("DELETE FROM {component} WHERE id = {key}"); + pub async fn delete_entity(&self, model: String, key: FieldElement) -> Result<()> { + let query = format!("DELETE FROM {model} WHERE id = {key}"); self.queue(vec![query]).await; Ok(()) } - pub async fn entity(&self, component: String, key: FieldElement) -> Result> { - let query = format!("SELECT * FROM {component} WHERE id = {key}"); + pub async fn entity(&self, model: String, key: FieldElement) -> Result> { + let query = format!("SELECT * FROM {model} WHERE id = {key}"); let mut conn: PoolConnection = self.pool.acquire().await?; let row: (i32, String, String) = sqlx::query_as(&query).fetch_one(&mut conn).await?; Ok(serde_json::from_str(&row.2).unwrap()) } - pub async fn entities(&self, component: String) -> Result>> { - let query = format!("SELECT * FROM {component}"); + pub async fn entities(&self, model: String) -> Result>> { + let query = format!("SELECT * FROM {model}"); let mut conn: PoolConnection = self.pool.acquire().await?; let mut rows = sqlx::query_as::<_, (i32, String, String)>(&query).fetch_all(&mut conn).await?; @@ -379,23 +379,20 @@ impl Executable for Sql { } } -fn component_names_sql_string( - entity_result: Option, - new_component: &str, -) -> Result { - let component_names = match entity_result { +fn model_names_sql_string(entity_result: Option, new_model: &str) -> Result { + let model_names = match entity_result { Some(entity) => { - let existing = entity.try_get::("component_names")?; - if existing.contains(new_component) { + let existing = entity.try_get::("model_names")?; + if existing.contains(new_model) { existing } else { - format!("{},{}", existing, new_component) + format!("{},{}", existing, new_model) } } - None => new_component.to_string(), + None => new_model.to_string(), }; - Ok(component_names) + Ok(model_names) } fn values_sql_string( diff --git a/crates/torii/core/src/sql_test.rs b/crates/torii/core/src/sql_test.rs index 731ae6c91b..bbe5d06bb1 100644 --- a/crates/torii/core/src/sql_test.rs +++ b/crates/torii/core/src/sql_test.rs @@ -1,7 +1,7 @@ use std::str::FromStr; use camino::Utf8PathBuf; -use dojo_world::manifest::{Component, Member, System}; +use dojo_world::manifest::{Member, Model, System}; use sqlx::sqlite::SqlitePool; use starknet::core::types::{Event, FieldElement}; @@ -18,12 +18,11 @@ async fn test_load_from_manifest(pool: SqlitePool) { let state = Sql::new(pool.clone(), FieldElement::ZERO).await.unwrap(); state.load_from_manifest(manifest.clone()).await.unwrap(); - let components = sqlx::query("SELECT * FROM components").fetch_all(&pool).await.unwrap(); - assert_eq!(components.len(), 2); + let models = sqlx::query("SELECT * FROM models").fetch_all(&pool).await.unwrap(); + assert_eq!(models.len(), 2); - let moves_components = - sqlx::query("SELECT * FROM external_moves").fetch_all(&pool).await.unwrap(); - assert_eq!(moves_components.len(), 0); + let moves_models = sqlx::query("SELECT * FROM external_moves").fetch_all(&pool).await.unwrap(); + assert_eq!(moves_models.len(), 0); let systems = sqlx::query("SELECT * FROM systems").fetch_all(&pool).await.unwrap(); assert_eq!(systems.len(), 3); @@ -52,7 +51,7 @@ async fn test_load_from_manifest(pool: SqlitePool) { assert_eq!(head, 1); state - .register_component(Component { + .register_model(Model { name: "Test".into(), members: vec![Member { name: "test".into(), ty: "u32".into(), key: false }], class_hash: FieldElement::TWO, @@ -63,7 +62,7 @@ async fn test_load_from_manifest(pool: SqlitePool) { state.execute().await.unwrap(); let (id, name, class_hash): (String, String, String) = - sqlx::query_as("SELECT id, name, class_hash FROM components WHERE id = 'test'") + sqlx::query_as("SELECT id, name, class_hash FROM models WHERE id = 'test'") .fetch_one(&pool) .await .unwrap(); @@ -72,9 +71,8 @@ async fn test_load_from_manifest(pool: SqlitePool) { assert_eq!(name, "Test"); assert_eq!(class_hash, format!("{:#x}", FieldElement::TWO)); - let test_components = - sqlx::query("SELECT * FROM external_test").fetch_all(&pool).await.unwrap(); - assert_eq!(test_components.len(), 0); + let test_models = sqlx::query("SELECT * FROM external_test").fetch_all(&pool).await.unwrap(); + assert_eq!(test_models.len(), 0); state .register_system(System { diff --git a/crates/torii/core/src/types.rs b/crates/torii/core/src/types.rs index ef21859ab9..62c7da91c4 100644 --- a/crates/torii/core/src/types.rs +++ b/crates/torii/core/src/types.rs @@ -33,14 +33,14 @@ impl fmt::LowerHex for SQLFieldElement { pub struct Entity { pub id: String, pub keys: String, - pub component_names: String, + pub model_names: String, pub created_at: DateTime, pub updated_at: DateTime, } #[derive(FromRow, Deserialize, Clone)] #[serde(rename_all = "camelCase")] -pub struct Component { +pub struct Model { pub id: String, pub name: String, pub class_hash: String, diff --git a/crates/torii/graphql/src/object/entity.rs b/crates/torii/graphql/src/object/entity.rs index 2890c5df34..c722195c62 100644 --- a/crates/torii/graphql/src/object/entity.rs +++ b/crates/torii/graphql/src/object/entity.rs @@ -9,11 +9,11 @@ use tokio_stream::StreamExt; use torii_core::simple_broker::SimpleBroker; use torii_core::types::Entity; -use super::component_state::{component_state_by_id_query, type_mapping_query}; use super::connection::{ connection_arguments, connection_output, decode_cursor, parse_connection_arguments, ConnectionArguments, }; +use super::model_state::{model_state_by_id_query, type_mapping_query}; use super::{ObjectTrait, TypeMapping, ValueMapping}; use crate::constants::DEFAULT_LIMIT; use crate::query::{query_by_id, ID}; @@ -31,7 +31,7 @@ impl Default for EntityObject { type_mapping: IndexMap::from([ (Name::new("id"), TypeRef::named(TypeRef::ID)), (Name::new("keys"), TypeRef::named_list(TypeRef::STRING)), - (Name::new("componentNames"), TypeRef::named(TypeRef::STRING)), + (Name::new("modelNames"), TypeRef::named(TypeRef::STRING)), (Name::new("createdAt"), TypeRef::named(ScalarType::DateTime.to_string())), (Name::new("updatedAt"), TypeRef::named(ScalarType::DateTime.to_string())), ]), @@ -45,7 +45,7 @@ impl EntityObject { IndexMap::from([ (Name::new("id"), Value::from(entity.id)), (Name::new("keys"), Value::from(keys)), - (Name::new("componentNames"), Value::from(entity.component_names)), + (Name::new("modelNames"), Value::from(entity.model_names)), ( Name::new("createdAt"), Value::from(entity.created_at.format("%Y-%m-%d %H:%M:%S").to_string()), @@ -72,29 +72,24 @@ impl ObjectTrait for EntityObject { } fn nested_fields(&self) -> Option> { - Some(vec![Field::new("components", TypeRef::named_list("ComponentUnion"), move |ctx| { + Some(vec![Field::new("models", TypeRef::named_list("ModelUnion"), move |ctx| { FieldFuture::new(async move { match ctx.parent_value.try_to_value()? { Value::Object(indexmap) => { let mut conn = ctx.data::>()?.acquire().await?; - let components = - csv_to_vec(&extract::(indexmap, "componentNames")?); + let models = csv_to_vec(&extract::(indexmap, "modelNames")?); let id = extract::(indexmap, "id")?; let mut results: Vec> = Vec::new(); - for component_name in components { - let table_name = component_name.to_lowercase(); + for model_name in models { + let table_name = model_name.to_lowercase(); let type_mapping = type_mapping_query(&mut conn, &table_name).await?; - let state = component_state_by_id_query( - &mut conn, - &table_name, - &id, - &type_mapping, - ) - .await?; + let state = + model_state_by_id_query(&mut conn, &table_name, &id, &type_mapping) + .await?; results.push(FieldValue::with_type( FieldValue::owned_any(state), - component_name, + model_name, )); } diff --git a/crates/torii/graphql/src/object/inputs/order_input.rs b/crates/torii/graphql/src/object/inputs/order_input.rs index ace95726f4..c4c4cdee30 100644 --- a/crates/torii/graphql/src/object/inputs/order_input.rs +++ b/crates/torii/graphql/src/object/inputs/order_input.rs @@ -38,7 +38,7 @@ impl InputObjectTrait for OrderInputObject { // Direction enum has only two members ASC and DESC let direction = Enum::new("Direction").item("ASC").item("DESC"); - // Field Order enum consist of all members of a component + // Field Order enum consist of all members of a model let field_order = self .type_mapping .iter() diff --git a/crates/torii/graphql/src/object/inputs/where_input.rs b/crates/torii/graphql/src/object/inputs/where_input.rs index 6fa62379c4..a5b2c804b6 100644 --- a/crates/torii/graphql/src/object/inputs/where_input.rs +++ b/crates/torii/graphql/src/object/inputs/where_input.rs @@ -15,7 +15,7 @@ pub struct WhereInputObject { impl WhereInputObject { // Iterate through an object's type mapping and create a new mapping for whereInput. For each of - // the object type (component member), we add 6 additional types for comparators (great than, + // the object type (model member), we add 6 additional types for comparators (great than, // not equal, etc). Only filter on our custom scalar types and ignore async-graphql's types. // Due to sqlite column constraints, u8 thru u64 are treated as numerics and the rest of the // types are treated as strings. diff --git a/crates/torii/graphql/src/object/mod.rs b/crates/torii/graphql/src/object/mod.rs index 07484c0938..2a2d9215ac 100644 --- a/crates/torii/graphql/src/object/mod.rs +++ b/crates/torii/graphql/src/object/mod.rs @@ -1,9 +1,9 @@ -pub mod component; -pub mod component_state; pub mod connection; pub mod entity; pub mod event; pub mod inputs; +pub mod model; +pub mod model_state; pub mod system; pub mod system_call; diff --git a/crates/torii/graphql/src/object/component.rs b/crates/torii/graphql/src/object/model.rs similarity index 59% rename from crates/torii/graphql/src/object/component.rs rename to crates/torii/graphql/src/object/model.rs index 7cb038d9b6..6090b5d105 100644 --- a/crates/torii/graphql/src/object/component.rs +++ b/crates/torii/graphql/src/object/model.rs @@ -6,7 +6,7 @@ use indexmap::IndexMap; use sqlx::{Pool, Sqlite}; use tokio_stream::StreamExt; use torii_core::simple_broker::SimpleBroker; -use torii_core::types::Component; +use torii_core::types::Model; use super::connection::connection_output; use super::{ObjectTrait, TypeMapping, ValueMapping}; @@ -14,12 +14,12 @@ use crate::constants::DEFAULT_LIMIT; use crate::query::{query_all, query_by_id, query_total_count, ID}; use crate::types::ScalarType; -pub struct ComponentObject { +pub struct ModelObject { pub type_mapping: TypeMapping, } -impl Default for ComponentObject { - // Eventually used for component metadata +impl Default for ModelObject { + // Eventually used for model metadata fn default() -> Self { Self { type_mapping: IndexMap::from([ @@ -32,28 +32,28 @@ impl Default for ComponentObject { } } } -impl ComponentObject { - pub fn value_mapping(component: Component) -> ValueMapping { +impl ModelObject { + pub fn value_mapping(model: Model) -> ValueMapping { IndexMap::from([ - (Name::new("id"), Value::from(component.id)), - (Name::new("name"), Value::from(component.name)), - (Name::new("classHash"), Value::from(component.class_hash)), - (Name::new("transactionHash"), Value::from(component.transaction_hash)), + (Name::new("id"), Value::from(model.id)), + (Name::new("name"), Value::from(model.name)), + (Name::new("classHash"), Value::from(model.class_hash)), + (Name::new("transactionHash"), Value::from(model.transaction_hash)), ( Name::new("createdAt"), - Value::from(component.created_at.format("%Y-%m-%d %H:%M:%S").to_string()), + Value::from(model.created_at.format("%Y-%m-%d %H:%M:%S").to_string()), ), ]) } } -impl ObjectTrait for ComponentObject { +impl ObjectTrait for ModelObject { fn name(&self) -> &str { - "component" + "model" } fn type_name(&self) -> &str { - "Component" + "Model" } fn type_mapping(&self) -> &TypeMapping { @@ -66,8 +66,8 @@ impl ObjectTrait for ComponentObject { FieldFuture::new(async move { let mut conn = ctx.data::>()?.acquire().await?; let id = ctx.args.try_get("id")?.string()?.to_string(); - let component = query_by_id(&mut conn, "components", ID::Str(id)).await?; - let result = ComponentObject::value_mapping(component); + let model = query_by_id(&mut conn, "models", ID::Str(id)).await?; + let result = ModelObject::value_mapping(model); Ok(Some(Value::Object(result))) }) }) @@ -77,19 +77,17 @@ impl ObjectTrait for ComponentObject { fn resolve_many(&self) -> Option { Some(Field::new( - "components", + "models", TypeRef::named(format!("{}Connection", self.type_name())), |ctx| { FieldFuture::new(async move { let mut conn = ctx.data::>()?.acquire().await?; - let total_count = - query_total_count(&mut conn, "components", &Vec::new()).await?; - let data: Vec = - query_all(&mut conn, "components", DEFAULT_LIMIT).await?; - let components: Vec = - data.into_iter().map(ComponentObject::value_mapping).collect(); + let total_count = query_total_count(&mut conn, "models", &Vec::new()).await?; + let data: Vec = query_all(&mut conn, "models", DEFAULT_LIMIT).await?; + let models: Vec = + data.into_iter().map(ModelObject::value_mapping).collect(); - Ok(Some(Value::Object(connection_output(components, total_count)))) + Ok(Some(Value::Object(connection_output(models, total_count)))) }) }, )) @@ -105,20 +103,16 @@ impl ObjectTrait for ComponentObject { Some(id) => Some(id.string()?.to_string()), None => None, }; - // if id is None, then subscribe to all components - // if id is Some, then subscribe to only the component with that id - Ok(SimpleBroker::::subscribe().filter_map( - move |component: Component| { - if id.is_none() || id == Some(component.id.clone()) { - Some(Ok(Value::Object(ComponentObject::value_mapping( - component, - )))) - } else { - // id != component.id, so don't send anything, still listening - None - } - }, - )) + // if id is None, then subscribe to all models + // if id is Some, then subscribe to only the model with that id + Ok(SimpleBroker::::subscribe().filter_map(move |model: Model| { + if id.is_none() || id == Some(model.id.clone()) { + Some(Ok(Value::Object(ModelObject::value_mapping(model)))) + } else { + // id != model.id, so don't send anything, still listening + None + } + })) }) } }) diff --git a/crates/torii/graphql/src/object/component_state.rs b/crates/torii/graphql/src/object/model_state.rs similarity index 90% rename from crates/torii/graphql/src/object/component_state.rs rename to crates/torii/graphql/src/object/model_state.rs index a8986447f6..81596d96f2 100644 --- a/crates/torii/graphql/src/object/component_state.rs +++ b/crates/torii/graphql/src/object/model_state.rs @@ -28,8 +28,8 @@ use crate::utils::extract_value::extract; const BOOLEAN_TRUE: i64 = 1; #[derive(FromRow, Deserialize)] -pub struct ComponentMembers { - pub component_id: String, +pub struct ModelMembers { + pub model_id: String, pub name: String, #[serde(rename = "type")] pub ty: String, @@ -37,7 +37,7 @@ pub struct ComponentMembers { pub created_at: DateTime, } -pub struct ComponentStateObject { +pub struct ModelStateObject { pub name: String, pub type_name: String, pub type_mapping: TypeMapping, @@ -45,7 +45,7 @@ pub struct ComponentStateObject { pub order_input: OrderInputObject, } -impl ComponentStateObject { +impl ModelStateObject { pub fn new(name: String, type_name: String, type_mapping: TypeMapping) -> Self { let where_input = WhereInputObject::new(type_name.as_str(), &type_mapping); let order_input = OrderInputObject::new(type_name.as_str(), &type_mapping); @@ -53,7 +53,7 @@ impl ComponentStateObject { } } -impl ObjectTrait for ComponentStateObject { +impl ObjectTrait for ModelStateObject { fn name(&self) -> &str { &self.name } @@ -62,12 +62,12 @@ impl ObjectTrait for ComponentStateObject { &self.type_name } - // Type mapping contains all component members and their corresponding type + // Type mapping contains all model members and their corresponding type fn type_mapping(&self) -> &TypeMapping { &self.type_mapping } - // Associate component to its parent entity + // Associate model to its parent entity fn nested_fields(&self) -> Option> { Some(vec![entity_field()]) } @@ -84,7 +84,7 @@ impl ObjectTrait for ComponentStateObject { let name = self.name.clone(); let type_mapping = self.type_mapping.clone(); let where_mapping = self.where_input.type_mapping.clone(); - let field_name = format!("{}Components", self.name()); + let field_name = format!("{}Models", self.name()); let field_type = format!("{}Connection", self.type_name()); let mut field = Field::new(field_name, TypeRef::named(field_type), move |ctx| { @@ -99,10 +99,10 @@ impl ObjectTrait for ComponentStateObject { let filters = parse_where_argument(&ctx, &where_mapping)?; let connection = parse_connection_arguments(&ctx)?; let data = - component_states_query(&mut conn, &table_name, &order, &filters, &connection) + model_states_query(&mut conn, &table_name, &order, &filters, &connection) .await?; let total_count = query_total_count(&mut conn, &table_name, &filters).await?; - let connection = component_connection(&data, &type_mapping, total_count)?; + let connection = model_connection(&data, &type_mapping, total_count)?; Ok(Some(Value::Object(connection))) }) @@ -135,7 +135,7 @@ fn entity_field() -> Field { }) } -pub async fn component_state_by_id_query( +pub async fn model_state_by_id_query( conn: &mut PoolConnection, name: &str, id: &str, @@ -148,7 +148,7 @@ pub async fn component_state_by_id_query( value_mapping_from_row(&row, fields) } -pub async fn component_states_query( +pub async fn model_states_query( conn: &mut PoolConnection, table_name: &str, order: &Option, @@ -216,14 +216,14 @@ pub async fn component_states_query( sqlx::query(&query).fetch_all(conn).await } -// TODO: make `connection_output()` more generic. Currently, `component_connection()` method +// TODO: make `connection_output()` more generic. Currently, `model_connection()` method // required as we need to explicity add `entity_id` to each edge. -pub fn component_connection( +pub fn model_connection( data: &[SqliteRow], types: &TypeMapping, total_count: i64, ) -> sqlx::Result { - let component_edges = data + let model_edges = data .iter() .map(|row| { // entity_id and created_at used to create cursor @@ -245,7 +245,7 @@ pub fn component_connection( Ok(ValueMapping::from([ (Name::new("totalCount"), Value::from(total_count)), - (Name::new("edges"), Value::List(component_edges?)), + (Name::new("edges"), Value::List(model_edges?)), // TODO: add pageInfo ])) } @@ -282,25 +282,25 @@ fn fetch_boolean(row: &SqliteRow, column_name: &str) -> sqlx::Result { pub async fn type_mapping_query( conn: &mut PoolConnection, - component_id: &str, + model_id: &str, ) -> sqlx::Result { - let component_members: Vec = sqlx::query_as( + let model_members: Vec = sqlx::query_as( r#" SELECT - component_id, + model_id, name, type AS ty, key, created_at - FROM component_members WHERE component_id = ? + FROM model_members WHERE model_id = ? "#, ) - .bind(component_id) + .bind(model_id) .fetch_all(conn) .await?; let mut type_mapping = TypeMapping::new(); - for member in component_members { + for member in model_members { type_mapping.insert(Name::new(member.name), TypeRef::named(member.ty)); } diff --git a/crates/torii/graphql/src/query/filter.rs b/crates/torii/graphql/src/query/filter.rs index 6ece9a9d89..5fd8cde198 100644 --- a/crates/torii/graphql/src/query/filter.rs +++ b/crates/torii/graphql/src/query/filter.rs @@ -49,7 +49,7 @@ pub fn parse_filter(input: &Name, value: FilterValue) -> Filter { for (suffix, comparator) in suffixes { if let Some(field) = input.strip_suffix(suffix) { - // Filtering only applies to component members which are stored in db with + // Filtering only applies to model members which are stored in db with // external_{name} return Filter { field: format!("external_{}", field), diff --git a/crates/torii/graphql/src/schema.rs b/crates/torii/graphql/src/schema.rs index ccb4291eaa..a5c4a2cda7 100644 --- a/crates/torii/graphql/src/schema.rs +++ b/crates/torii/graphql/src/schema.rs @@ -3,21 +3,21 @@ use async_graphql::dynamic::{ Field, Object, Scalar, Schema, Subscription, SubscriptionField, Union, }; use sqlx::SqlitePool; -use torii_core::types::Component; +use torii_core::types::Model; -use super::object::component_state::{type_mapping_query, ComponentStateObject}; use super::object::connection::page_info::PageInfoObject; use super::object::entity::EntityObject; use super::object::event::EventObject; +use super::object::model_state::{type_mapping_query, ModelStateObject}; use super::object::system::SystemObject; use super::object::system_call::SystemCallObject; use super::object::ObjectTrait; use super::types::ScalarType; use super::utils::format_name; -use crate::object::component::ComponentObject; +use crate::object::model::ModelObject; // The graphql schema is built dynamically at runtime, this is because we won't know the schema of -// the components until runtime. There are however, predefined objects such as entities and +// the models until runtime. There are however, predefined objects such as entities and // system_calls, their schema is known but we generate them dynamically as well since async-graphql // does not allow mixing of static and dynamic schemas. pub async fn build_schema(pool: &SqlitePool) -> Result { @@ -26,18 +26,18 @@ pub async fn build_schema(pool: &SqlitePool) -> Result { // predefined objects let mut objects: Vec> = vec![ Box::::default(), - Box::::default(), + Box::::default(), Box::::default(), Box::::default(), Box::::default(), Box::::default(), ]; - // register dynamic component objects - let (component_objects, component_union) = component_objects(pool).await?; - objects.extend(component_objects); + // register dynamic model objects + let (model_objects, model_union) = model_objects(pool).await?; + objects.extend(model_objects); - schema_builder = schema_builder.register(component_union); + schema_builder = schema_builder.register(model_union); // collect resolvers for single and plural queries let mut fields: Vec = Vec::new(); @@ -111,31 +111,30 @@ pub async fn build_schema(pool: &SqlitePool) -> Result { .map_err(|e| e.into()) } -async fn component_objects(pool: &SqlitePool) -> Result<(Vec>, Union)> { +async fn model_objects(pool: &SqlitePool) -> Result<(Vec>, Union)> { let mut conn = pool.acquire().await?; let mut objects: Vec> = Vec::new(); - let components: Vec = - sqlx::query_as("SELECT * FROM components").fetch_all(&mut conn).await?; + let models: Vec = sqlx::query_as("SELECT * FROM models").fetch_all(&mut conn).await?; - // component union object - let mut component_union = Union::new("ComponentUnion"); + // model union object + let mut model_union = Union::new("ModelUnion"); - // component state objects - for component_metadata in components { - let field_type_mapping = type_mapping_query(&mut conn, &component_metadata.id).await?; + // model state objects + for model_metadata in models { + let field_type_mapping = type_mapping_query(&mut conn, &model_metadata.id).await?; if !field_type_mapping.is_empty() { - let (name, type_name) = format_name(&component_metadata.name); - let state_object = Box::new(ComponentStateObject::new( + let (name, type_name) = format_name(&model_metadata.name); + let state_object = Box::new(ModelStateObject::new( name.clone(), type_name.clone(), field_type_mapping, )); - component_union = component_union.possible_type(&type_name); + model_union = model_union.possible_type(&type_name); objects.push(state_object); } } - Ok((objects, component_union)) + Ok((objects, model_union)) } diff --git a/crates/torii/graphql/src/tests/common/mod.rs b/crates/torii/graphql/src/tests/common/mod.rs index a19c321f9d..0ddb2d947a 100644 --- a/crates/torii/graphql/src/tests/common/mod.rs +++ b/crates/torii/graphql/src/tests/common/mod.rs @@ -25,7 +25,7 @@ pub struct Edge { #[derive(Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct Entity { - pub component_names: String, + pub model_names: String, pub keys: Option>, pub created_at: Option, } @@ -73,13 +73,13 @@ pub async fn run_graphql_subscription( pub async fn entity_fixtures(pool: &SqlitePool) { let state = init(pool).await; - // Set entity with one moves component + // Set entity with one moves model // remaining: 10, last_direction: 0 let key = vec![FieldElement::ONE]; let moves_values = vec![FieldElement::from_hex_be("0xa").unwrap(), FieldElement::ZERO]; state.set_entity("Moves".to_string(), key, moves_values.clone()).await.unwrap(); - // Set entity with one position component + // Set entity with one position model // x: 42 // y: 69 let key = vec![FieldElement::TWO]; @@ -89,7 +89,7 @@ pub async fn entity_fixtures(pool: &SqlitePool) { ]; state.set_entity("Position".to_string(), key, position_values.clone()).await.unwrap(); - // Set an entity with both moves and position components + // Set an entity with both moves and position models // remaining: 1, last_direction: 0 // x: 69 // y: 42 @@ -138,7 +138,7 @@ pub async fn paginate( edges {{ cursor node {{ - componentNames + modelNames }} }} }} diff --git a/crates/torii/graphql/src/tests/entities_test.rs b/crates/torii/graphql/src/tests/entities_test.rs index 2f20cb86bb..3acf973c7f 100644 --- a/crates/torii/graphql/src/tests/entities_test.rs +++ b/crates/torii/graphql/src/tests/entities_test.rs @@ -15,7 +15,7 @@ mod tests { r#" {{ entity(id: "{:#x}") {{ - componentNames + modelNames }} }} "#, @@ -25,12 +25,12 @@ mod tests { let entity = value.get("entity").ok_or("no entity found").unwrap(); let entity: Entity = serde_json::from_value(entity.clone()).unwrap(); - assert_eq!(entity.component_names, "Moves".to_string()); + assert_eq!(entity.model_names, "Moves".to_string()); } #[ignore] #[sqlx::test(migrations = "../migrations")] - async fn test_entity_components(pool: SqlitePool) { + async fn test_entity_models(pool: SqlitePool) { entity_fixtures(&pool).await; let entity_id = poseidon_hash_many(&[FieldElement::THREE]); @@ -38,7 +38,7 @@ mod tests { r#" {{ entity (id: "{:#x}") {{ - components {{ + models {{ __typename ... on Moves {{ remaining @@ -57,15 +57,15 @@ mod tests { let value = run_graphql_query(&pool, &query).await; let entity = value.get("entity").ok_or("no entity found").unwrap(); - let components = entity.get("components").ok_or("no components found").unwrap(); - let component_moves: Moves = serde_json::from_value(components[0].clone()).unwrap(); - let component_position: Position = serde_json::from_value(components[1].clone()).unwrap(); + let models = entity.get("models").ok_or("no models found").unwrap(); + let model_moves: Moves = serde_json::from_value(models[0].clone()).unwrap(); + let model_position: Position = serde_json::from_value(models[1].clone()).unwrap(); - assert_eq!(component_moves.__typename, "Moves"); - assert_eq!(component_moves.remaining, 1); - assert_eq!(component_position.__typename, "Position"); - assert_eq!(component_position.x, 69); - assert_eq!(component_position.y, 42); + assert_eq!(model_moves.__typename, "Moves"); + assert_eq!(model_moves.remaining, 1); + assert_eq!(model_position.__typename, "Position"); + assert_eq!(model_position.x, 69); + assert_eq!(model_position.y, 42); } #[sqlx::test(migrations = "../migrations")] diff --git a/crates/torii/graphql/src/tests/mod.rs b/crates/torii/graphql/src/tests/mod.rs index 93d63a4072..b578891237 100644 --- a/crates/torii/graphql/src/tests/mod.rs +++ b/crates/torii/graphql/src/tests/mod.rs @@ -1,4 +1,4 @@ mod common; -mod components_test; mod entities_test; +mod models_test; mod subscription_test; diff --git a/crates/torii/graphql/src/tests/components_test.rs b/crates/torii/graphql/src/tests/models_test.rs similarity index 81% rename from crates/torii/graphql/src/tests/components_test.rs rename to crates/torii/graphql/src/tests/models_test.rs index 62b653e13e..824e8487be 100644 --- a/crates/torii/graphql/src/tests/components_test.rs +++ b/crates/torii/graphql/src/tests/models_test.rs @@ -16,12 +16,12 @@ mod tests { #[ignore] #[sqlx::test(migrations = "../migrations")] - async fn test_component_no_filter(pool: SqlitePool) { + async fn test_model_no_filter(pool: SqlitePool) { entity_fixtures(&pool).await; let query = r#" { - movesComponents { + movesModels { totalCount edges { node { @@ -32,7 +32,7 @@ mod tests { cursor } } - positionComponents { + positionModels { totalCount edges { node { @@ -48,14 +48,13 @@ mod tests { let value = run_graphql_query(&pool, query).await; - let moves_components = value.get("movesComponents").ok_or("no moves found").unwrap(); + let moves_mdoels = value.get("movesModels").ok_or("no moves found").unwrap(); let moves_connection: Connection = - serde_json::from_value(moves_components.clone()).unwrap(); + serde_json::from_value(moves_mdoels.clone()).unwrap(); - let position_components = - value.get("positionComponents").ok_or("no position found").unwrap(); + let position_mdoels = value.get("positionModels").ok_or("no position found").unwrap(); let position_connection: Connection = - serde_json::from_value(position_components.clone()).unwrap(); + serde_json::from_value(position_mdoels.clone()).unwrap(); assert_eq!(moves_connection.edges[0].node.remaining, 10); assert_eq!(position_connection.edges[0].node.x, 42); @@ -64,10 +63,10 @@ mod tests { #[ignore] #[sqlx::test(migrations = "../migrations")] - async fn test_component_where_filter(pool: SqlitePool) { + async fn test_model_where_filter(pool: SqlitePool) { entity_fixtures(&pool).await; - // fixtures inserts two position components with members (x: 42, y: 69) and (x: 69, y: 42) + // fixtures inserts two position mdoels with members (x: 42, y: 69) and (x: 69, y: 42) // the following filters and expected total results can be simply calculated let where_filters = Vec::from([ ("where: { x: 42 }", 1), @@ -84,7 +83,7 @@ mod tests { let query = format!( r#" {{ - positionComponents ({}) {{ + positionModels ({}) {{ totalCount edges {{ node {{ @@ -101,7 +100,7 @@ mod tests { ); let value = run_graphql_query(&pool, &query).await; - let positions = value.get("positionComponents").ok_or("no positions found").unwrap(); + let positions = value.get("positionModels").ok_or("no positions found").unwrap(); let connection: Connection = serde_json::from_value(positions.clone()).unwrap(); assert_eq!(connection.total_count, expected_total); @@ -110,7 +109,7 @@ mod tests { #[ignore] #[sqlx::test(migrations = "../migrations")] - async fn test_component_ordering(pool: SqlitePool) { + async fn test_model_ordering(pool: SqlitePool) { entity_fixtures(&pool).await; let orders: Vec = vec![ @@ -148,7 +147,7 @@ mod tests { let query = format!( r#" {{ - positionComponents (order: {{ direction: {}, field: {} }}) {{ + positionModels (order: {{ direction: {}, field: {} }}) {{ totalCount edges {{ node {{ @@ -165,7 +164,7 @@ mod tests { ); let value = run_graphql_query(&pool, &query).await; - let positions = value.get("positionComponents").ok_or("no positions found").unwrap(); + let positions = value.get("positionModels").ok_or("no positions found").unwrap(); let connection: Connection = serde_json::from_value(positions.clone()).unwrap(); assert_eq!(connection.total_count, 2); @@ -175,12 +174,12 @@ mod tests { #[ignore] #[sqlx::test(migrations = "../migrations")] - async fn test_component_entity_relationship(pool: SqlitePool) { + async fn test_model_entity_relationship(pool: SqlitePool) { entity_fixtures(&pool).await; let query = r#" { - positionComponents { + positionModels { totalCount edges { node { @@ -189,7 +188,7 @@ mod tests { y entity { keys - componentNames + modelNames } } cursor @@ -199,9 +198,9 @@ mod tests { "#; let value = run_graphql_query(&pool, query).await; - let positions = value.get("positionComponents").ok_or("no positions found").unwrap(); + let positions = value.get("positionModels").ok_or("no positions found").unwrap(); let connection: Connection = serde_json::from_value(positions.clone()).unwrap(); let entity = connection.edges[0].node.entity.as_ref().unwrap(); - assert_eq!(entity.component_names, "Position".to_string()); + assert_eq!(entity.model_names, "Position".to_string()); } } diff --git a/crates/torii/graphql/src/tests/subscription_test.rs b/crates/torii/graphql/src/tests/subscription_test.rs index 0ae7fc60d7..f58d567350 100644 --- a/crates/torii/graphql/src/tests/subscription_test.rs +++ b/crates/torii/graphql/src/tests/subscription_test.rs @@ -3,7 +3,7 @@ mod tests { use std::time::Duration; use async_graphql::value; - use dojo_world::manifest::{Component, Member}; + use dojo_world::manifest::{Member, Model}; use sqlx::SqlitePool; use starknet_crypto::{poseidon_hash_many, FieldElement}; use tokio::sync::mpsc; @@ -21,7 +21,7 @@ mod tests { let entity_id = format!("{:#x}", poseidon_hash_many(&key)); let keys_str = key.iter().map(|k| format!("{:#x}", k)).collect::>().join(","); let expected_value: async_graphql::Value = value!({ - "entityUpdated": { "id": entity_id.clone(), "keys":vec![keys_str.clone()], "componentNames": "Moves" } + "entityUpdated": { "id": entity_id.clone(), "keys":vec![keys_str.clone()], "modelNames": "Moves" } }); let (tx, mut rx) = mpsc::channel(10); @@ -29,7 +29,7 @@ mod tests { // 1. Open process and sleep.Go to execute subscription tokio::time::sleep(Duration::from_secs(1)).await; - // Set entity with one moves component + // Set entity with one moves model // remaining: 10, last_direction: 0 let moves_values = vec![FieldElement::from_hex_be("0xa").unwrap(), FieldElement::ZERO]; state.set_entity("Moves".to_string(), key, moves_values).await.unwrap(); @@ -44,7 +44,7 @@ mod tests { r#" subscription { entityUpdated { - id, keys, componentNames + id, keys, modelNames } }"#, ) @@ -65,7 +65,7 @@ mod tests { let entity_id = format!("{:#x}", poseidon_hash_many(&key)); let keys_str = key.iter().map(|k| format!("{:#x}", k)).collect::>().join(","); let expected_value: async_graphql::Value = value!({ - "entityUpdated": { "id": entity_id.clone(), "keys":vec![keys_str.clone()], "componentNames": "Moves" } + "entityUpdated": { "id": entity_id.clone(), "keys":vec![keys_str.clone()], "modelNames": "Moves" } }); let (tx, mut rx) = mpsc::channel(10); @@ -73,7 +73,7 @@ mod tests { // 1. Open process and sleep.Go to execute subscription tokio::time::sleep(Duration::from_secs(1)).await; - // Set entity with one moves component + // Set entity with one moves model // remaining: 10, last_direction: 0 let moves_values = vec![FieldElement::from_hex_be("0xa").unwrap(), FieldElement::ZERO]; state.set_entity("Moves".to_string(), key, moves_values).await.unwrap(); @@ -88,7 +88,7 @@ mod tests { r#" subscription { entityUpdated(id: "0x579e8877c7755365d5ec1ec7d3a94a457eff5d1f40482bbe9729c064cdead2") { - id, keys, componentNames + id, keys, modelNames } }"#, ) @@ -100,18 +100,18 @@ mod tests { } #[sqlx::test(migrations = "../migrations")] - async fn test_component_subscription(pool: SqlitePool) { + async fn test_model_subscription(pool: SqlitePool) { // Sleep in order to run this test at the end in a single thread tokio::time::sleep(Duration::from_secs(2)).await; let state = Sql::new(pool.clone(), FieldElement::ZERO).await.unwrap(); - // 0. Preprocess component value + // 0. Preprocess model value let name = "Test".to_string(); - let component_id = name.to_lowercase(); + let model_id = name.to_lowercase(); let class_hash = FieldElement::TWO; let hex_class_hash = format!("{:#x}", class_hash); let expected_value: async_graphql::Value = value!({ - "componentRegistered": { "id": component_id.clone(), "name":name, "classHash": hex_class_hash } + "modelRegistered": { "id": model_id.clone(), "name":name, "classHash": hex_class_hash } }); let (tx, mut rx) = mpsc::channel(7); @@ -119,13 +119,13 @@ mod tests { // 1. Open process and sleep.Go to execute subscription tokio::time::sleep(Duration::from_secs(1)).await; - let component = Component { + let model = Model { name, members: vec![Member { name: "test".into(), ty: "u32".into(), key: false }], class_hash, ..Default::default() }; - state.register_component(component).await.unwrap(); + state.register_model(model).await.unwrap(); // 3. fn publish() is called from state.set_entity() tx.send(()).await.unwrap(); @@ -136,7 +136,7 @@ mod tests { &pool, r#" subscription { - componentRegistered { + modelRegistered { id, name, classHash } }"#, @@ -149,18 +149,18 @@ mod tests { } #[sqlx::test(migrations = "../migrations")] - async fn test_component_subscription_with_id(pool: SqlitePool) { + async fn test_model_subscription_with_id(pool: SqlitePool) { // Sleep in order to run this test at the end in a single thread tokio::time::sleep(Duration::from_secs(2)).await; let state = Sql::new(pool.clone(), FieldElement::ZERO).await.unwrap(); - // 0. Preprocess component value + // 0. Preprocess model value let name = "Test".to_string(); - let component_id = name.to_lowercase(); + let model_id = name.to_lowercase(); let class_hash = FieldElement::TWO; let hex_class_hash = format!("{:#x}", class_hash); let expected_value: async_graphql::Value = value!({ - "componentRegistered": { "id": component_id.clone(), "name":name, "classHash": hex_class_hash } + "modelRegistered": { "id": model_id.clone(), "name":name, "classHash": hex_class_hash } }); let (tx, mut rx) = mpsc::channel(7); @@ -168,13 +168,13 @@ mod tests { // 1. Open process and sleep.Go to execute subscription tokio::time::sleep(Duration::from_secs(1)).await; - let component = Component { + let model = Model { name, members: vec![Member { name: "test".into(), ty: "u32".into(), key: false }], class_hash, ..Default::default() }; - state.register_component(component).await.unwrap(); + state.register_model(model).await.unwrap(); // 3. fn publish() is called from state.set_entity() tx.send(()).await.unwrap(); @@ -185,7 +185,7 @@ mod tests { &pool, r#" subscription { - componentRegistered(id: "test") { + modelRegistered(id: "test") { id, name, classHash } }"#, diff --git a/crates/torii/migrations/20230316154230_setup.sql b/crates/torii/migrations/20230316154230_setup.sql index 0b49e4e2e0..280596cec8 100644 --- a/crates/torii/migrations/20230316154230_setup.sql +++ b/crates/torii/migrations/20230316154230_setup.sql @@ -13,7 +13,7 @@ CREATE TABLE worlds ( created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ); -CREATE TABLE components ( +CREATE TABLE models ( id TEXT NOT NULL PRIMARY KEY, name TEXT NOT NULL, class_hash TEXT NOT NULL, @@ -21,20 +21,20 @@ CREATE TABLE components ( created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ); -CREATE INDEX idx_components_created_at ON components (created_at); +CREATE INDEX idx_models_created_at ON models (created_at); -CREATE TABLE component_members( +CREATE TABLE model_members( id INTEGER PRIMARY KEY AUTOINCREMENT, - component_id TEXT NOT NULL, + model_id TEXT NOT NULL, name TEXT NOT NULL, type TEXT NOT NULL, key BOOLEAN NOT NULL, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, - FOREIGN KEY (component_id) REFERENCES components(id) - UNIQUE (component_id, name) + FOREIGN KEY (model_id) REFERENCES models(id) + UNIQUE (model_id, name) ); -CREATE INDEX idx_component_members_component_id ON component_members (component_id); +CREATE INDEX idx_model_members_model_id ON model_members (model_id); CREATE TABLE system_calls ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -61,7 +61,7 @@ CREATE INDEX idx_systems_created_at ON systems (created_at); CREATE TABLE entities ( id TEXT NOT NULL PRIMARY KEY, keys TEXT, - component_names TEXT, + model_names TEXT, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ); diff --git a/crates/torii/server/src/cli.rs b/crates/torii/server/src/cli.rs index 91c55750e0..70461c4b07 100644 --- a/crates/torii/server/src/cli.rs +++ b/crates/torii/server/src/cli.rs @@ -13,7 +13,7 @@ use starknet::providers::jsonrpc::HttpTransport; use starknet::providers::JsonRpcClient; use tokio_util::sync::CancellationToken; use torii_client::contract::world::WorldContractReader; -use torii_core::processors::register_component::RegisterComponentProcessor; +use torii_core::processors::register_model::RegisterModelProcessor; use torii_core::processors::register_system::RegisterSystemProcessor; use torii_core::processors::store_set_record::StoreSetRecordProcessor; use torii_core::processors::store_system_call::StoreSystemCallProcessor; @@ -97,7 +97,7 @@ async fn main() -> anyhow::Result<()> { db.load_from_manifest(manifest.clone()).await?; let processors = Processors { event: vec![ - Box::new(RegisterComponentProcessor), + Box::new(RegisterModelProcessor), Box::new(RegisterSystemProcessor), Box::new(StoreSetRecordProcessor), ],