Skip to content

Commit

Permalink
Merge pull request #31 from Lilit0x/functions/right
Browse files Browse the repository at this point in the history
RIGHT String Function: #13
  • Loading branch information
AmrDeveloper authored Sep 13, 2023
2 parents 847482d + 6237ee6 commit 3355ce7
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
25 changes: 24 additions & 1 deletion crates/gitql-ast/src/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ lazy_static! {
map.insert("replace", text_replace);
map.insert("substring", text_substring);
map.insert("stuff", text_stuff);
map.insert("right", text_right);

// Date functions
map.insert("current_date", date_current_date);
Expand Down Expand Up @@ -157,6 +158,13 @@ lazy_static! {
result: DataType::Text,
},
);
map.insert(
"right",
Prototype {
parameters: vec![DataType::Text, DataType::Number],
result: DataType::Text
},
);

// Date functions
map.insert(
Expand Down Expand Up @@ -284,7 +292,7 @@ fn text_replace(inputs: Vec<Value>) -> Value {
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();
Expand Down Expand Up @@ -323,6 +331,21 @@ fn text_stuff(inputs: Vec<Value>) -> Value {
return Value::Text(text.into_iter().collect());
}

fn text_right(inputs: Vec<Value>) -> Value {
let text = inputs[0].as_text();
if text.is_empty() {
return Value::Text("".to_string());
}

let number_of_chars = inputs[1].as_number() as usize;
if number_of_chars > text.len() {
return Value::Text(text);
}

let text = text.as_str();

return Value::Text(text[text.len() - number_of_chars..text.len()].to_string());
}

// Date functions

Expand Down
3 changes: 2 additions & 1 deletion docs/function/functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ note that all functions names are case-insensitive.
| 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. |
| 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).|
### String functions samples

```sql
Expand All @@ -38,6 +38,7 @@ SELECT CHAR(345) AS code
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
```

### Date functions
Expand Down

0 comments on commit 3355ce7

Please sign in to comment.