Now we created a new Type called IntPairType that can be used as Function parameter, return type or column type, but we need a custom value that can represent this type, it's almost the same concept, so lets start creating the IntPairValue.
usegitql_ast::types::base::DataType;usesuper::base::Value;#[derive(Clone)]pubstructIntPairValue{pubfirst:i64,pubsecond:i64,}implValueforIntPairValue{/// Define the literal representation for our new Valuefnliteral(&self)->String{format!("({}, {})",self.first,self.second)}/// Define how to check equality between this value and otherfnequals(&self,other:&Box<dynValue>)->bool{ifletSome(other_int_pair)=other.as_any().downcast_ref::<IntPairValue>(){returnself.first==other_int_pair.first&&self.second==other_int_pair.second;}false}/// You can define how to order between IntPair values or None to disable orderingfncompare(&self,other:&Box<dynValue>)->Option<Ordering>{None}fndata_type(&self)->Box<dynDataType>{Box::new(IntPairType)}fnas_any(&self)->&dynAny{self}/// As we allowed `+` between IntPair types in `can_perform_add_op_with` /// We need also to define how this operator will workfnadd_op(&self,other:&Box<dynValue>)->Result<Box<dynValue>,String>{ifletSome(other_int)=other.as_any().downcast_ref::<IntPairValue>(){letfirst=self.first+other_int.first;letsecond=self.second+other_int.second;returnOk(Box::new(IntPairValue{first,second}));}/// Write your exception messageErr("Unexpected type to perform `+` with".to_string())}}
// Append the function implementationletmutstd_functions=standard_functions().to_owned();std_functions.insert("new_int_pair",new_int_pair);// Append the function signatureletmutstd_signatures=standard_function_signatures().to_owned();std_signatures.insert("new_int_pair",Signature{// Take two Integers valuesparameters:vec![Box::new(IntType),Box::new(IntType)],// Return IntPair Valuereturn_type:Box::new(IntPairValue),});
After connecting everything together in the next step, you can perform query like this
SELECTnew_int_pair(1,2)+new_int_pair(3,4);
And got result like (4, 6).
Going forward
This is just a quick example of how to create your own types, but you can create any type you want, even Data structures like Map and allow
index operator for it so you can write