Skip to content

Commit

Permalink
Merge pull request #28 from Lilit0x/functions/substring
Browse files Browse the repository at this point in the history
SUBSTRING String Function: #13
  • Loading branch information
AmrDeveloper authored Sep 11, 2023
2 parents 9b1bb36 + 0d33a39 commit fe42610
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
25 changes: 25 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("substring", text_substring);

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

// Date functions
map.insert(
Expand Down Expand Up @@ -242,6 +250,23 @@ fn text_char(inputs: Vec<Value>) -> Value {
return Value::Text("".to_string());
}

fn text_substring(inputs: Vec<Value>) -> Value {
let text = inputs[0].as_text();
//according to the specs, a stirng starts at position 1.
//but in Rust, the index of a string starts from 0
let start = inputs[1].as_number() as usize - 1;
let length = inputs[2].as_number();

if start > text.len() || length > text.len() as i64 {
return Value::Text(text);
}
if length < 0 {
return Value::Text("".to_string());
}

return Value::Text(text[start..(start + length as usize)].to_string());
}

// Date functions

fn date_current_date(_inputs: Vec<Value>) -> Value {
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. |
| SUBSTRING | Text, Number, Number | Text | Extracts some characters from a string. |

### String functions samples

Expand All @@ -32,6 +33,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 name, SUBSTRING(name, 1, 5) AS extract FROM commits
```

### Date functions
Expand Down

0 comments on commit fe42610

Please sign in to comment.