diff --git a/crates/gitql-ast/src/function.rs b/crates/gitql-ast/src/function.rs index 058e9cf2..25ca627d 100644 --- a/crates/gitql-ast/src/function.rs +++ b/crates/gitql-ast/src/function.rs @@ -33,6 +33,7 @@ lazy_static! { map.insert("substring", text_substring); map.insert("stuff", text_stuff); map.insert("right", text_right); + map.insert("translate", text_translate); // Date functions map.insert("current_date", date_current_date); @@ -165,6 +166,13 @@ lazy_static! { result: DataType::Text }, ); + map.insert( + "translate", + Prototype { + parameters: vec![DataType::Text, DataType::Text, DataType::Text], + result: DataType::Text + }, + ); // Date functions map.insert( @@ -347,6 +355,23 @@ fn text_right(inputs: Vec) -> Value { return Value::Text(text[text.len() - number_of_chars..text.len()].to_string()); } +fn text_translate(inputs: Vec) -> Value { + let mut text = inputs[0].as_text(); + let characters = inputs[1].as_text(); + let translations = inputs[2].as_text(); + + if translations.len() != characters.len() { + return Value::Text("".to_string()); + } + + let translations = translations.chars().collect::>(); + for (idx, letter) in characters.char_indices() { + text = text.replace(letter, &char::to_string(&translations[idx])); + } + + return Value::Text(text); +} + // Date functions fn date_current_date(_inputs: Vec) -> Value { diff --git a/crates/gitql-ast/src/lib.rs b/crates/gitql-ast/src/lib.rs index 92752cd7..847d24dc 100644 --- a/crates/gitql-ast/src/lib.rs +++ b/crates/gitql-ast/src/lib.rs @@ -1,4 +1,5 @@ pub mod aggregation; +pub mod date_utils; pub mod expression; pub mod function; pub mod object; @@ -6,4 +7,3 @@ pub mod scope; pub mod statement; pub mod types; pub mod value; -pub mod date_utils; \ No newline at end of file diff --git a/docs/function/functions.md b/docs/function/functions.md index d8986547..e6529aea 100644 --- a/docs/function/functions.md +++ b/docs/function/functions.md @@ -22,6 +22,7 @@ note that all functions names are case-insensitive. | SUBSTRING | Text, Number, Number | Text | Extracts some characters from a string. | | STUFF | Text, Number, Number, Text | Deletes a part of a string and then inserts another part into the string, starting at a specified position. | | RIGHT | Text, Number | Text | Extracts a number of characters from a string (starting from right).| +| TRANSLATE | Text, Text, Text, | Text | Returns the string from the first argument after the characters specified in the second argument are translated into the characters specified in the third argument. | ### String functions samples ```sql @@ -39,6 +40,7 @@ SELECT REPLACE("ABC ABC ABC", "a", "c") as replacedText SELECT name, SUBSTRING(name, 1, 5) AS extract FROM commits SELECT STUFF("GQL tutorial!", 13, 1, " is fun!") SELECT RIGHT("AmrDeveloper", 3) AS extract +SELECT TRANSLATE("Amr[Dev]{eloper}", "[]{}", "()()") ``` ### Date functions