edgedb / easy-edgedb

An illustrated textbook designed to be a one-stop shop for learning EdgeDB
https://www.edgedb.com/easy-edgedb
77 stars 39 forks source link

Chapter 15: call the function anyway #58

Closed daichen-daisy closed 1 year ago

daichen-daisy commented 2 years ago

https://github.com/edgedb/easy-edgedb/blob/9c5c0936fb14a2d1a1e8b6f56aa98e7b96f8c208/chapter15/index.md#L84-L88

In this part, I also feel confused. It feels like I could add the OPTIONAL in the return part like -> OPTIONAL str, but I don't think so. I am trying to rephrase this part to show my understanding. Please let me know if it's right. If my understanding is correct, maybe we could consider rewriting this part?


One other area where you need to trust the users is that the input is not empty because the function won't be called if the input is empty. For example:

function try(place: City) -> str
  using (
    SELECT 'Called!'
  );

Then, let's try to call it: SELECT try((SELECT City FILTER .name = 'London'));. The output is Called! as we expected. However, if you run SELECT try((SELECT City FILTER .name = 'Beijing'));, the output will be {} because we've never inserted any data for the city 'Beijing' in our database. Therefore, if we want the function to be called in any case, what could we do? We can put the keyword OPTIONAL in front of the parameter like this:

function try(place: OPTIONAL City) -> str
  using (
    SELECT 'Called!'
  );

{ref}The documentation <docs:ref_sdl_function_typequal> explains it like this: the function is called normally when the corresponding argument is empty. And: A notable example of a function that gets called on empty input is the coalescing operator. We first saw the coalescing operator ?? in Chapter 12. And when we look at {eql:op}its signature <docs:coalesce>, you can see the OPTIONAL in there:

OPTIONAL anytype ?? SET OF anytype -> SET OF anytype

Dhghomon commented 1 year ago

Thank you very much! I see the Chinese translation of Chapter 15 already has these two examples so just added them to the English version here:

https://github.com/edgedb/easy-edgedb/commit/06cfde0a54edafa0bef93896e0d3dc29f801431f