Skip to content

Commit

Permalink
Merge pull request #25 from Lilit0x/functions/replace
Browse files Browse the repository at this point in the history
REPLACE String Function: #13
  • Loading branch information
AmrDeveloper authored Sep 12, 2023
2 parents fe42610 + cf944a7 commit 16f8824
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
27 changes: 27 additions & 0 deletions crates/gitql-ast/src/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ lazy_static! {
map.insert("left", text_left);
map.insert("datalength", text_datalength);
map.insert("char", text_char);
map.insert("replace", text_replace);
map.insert("substring", text_substring);

// Date functions
Expand Down Expand Up @@ -135,6 +136,12 @@ lazy_static! {
},
);
map.insert(
"replace",
Prototype {
parameters: vec![DataType::Text, DataType::Text, DataType::Text],
},
);
map.insert({
"substring",
Prototype {
parameters: vec![DataType::Text, DataType::Number, DataType::Number],
Expand Down Expand Up @@ -250,6 +257,26 @@ fn text_char(inputs: Vec<Value>) -> Value {
return Value::Text("".to_string());
}

fn text_replace(inputs: Vec<Value>) -> Value {
let text = inputs[0].as_text();
let old_string = inputs[1].as_text();
let new_string = inputs[2].as_text();

let mut result = String::new();
let mut end = 0;
for (begin, matched_part) in text
.to_lowercase()
.match_indices(&old_string.to_lowercase())
{
result.push_str(&text.get(end..begin).unwrap());
result.push_str(&new_string);
end = begin + matched_part.len();
}
result.push_str(&text.get(end..text.len()).unwrap());

return Value::Text(result);
}

fn text_substring(inputs: Vec<Value>) -> Value {
let text = inputs[0].as_text();
//according to the specs, a stirng starts at position 1.
Expand Down
2 changes: 2 additions & 0 deletions docs/function/functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ note that all functions names are case-insensitive.
| LEFT | Text, Number | Text | Extracts a number of characters from a string (starting from left). |
| DATALENGTH | Text | Number | Returns the number of bytes used to represent an expression. |
| CHAR | Number | Text | Returns the character based on the ASCII code. |
| REPLACE | Text, Text, Text | Text | Replaces all occurrences of a substring within a string, with a new substring. |
| SUBSTRING | Text, Number, Number | Text | Extracts some characters from a string. |

### String functions samples
Expand All @@ -33,6 +34,7 @@ SELECT name, ASCII(name) AS firstCharAscii FROM commits
SELECT LEFT("AmrDeveloper", 3) AS extract
SELECT DATALENGTH("AmrDeveloper") as bytelength
SELECT CHAR(345) AS code
SELECT REPLACE("ABC ABC ABC", "a", "c") as replacedText
SELECT name, SUBSTRING(name, 1, 5) AS extract FROM commits
```

Expand Down

0 comments on commit 16f8824

Please sign in to comment.