Skip to content

Proposal: r.default #884

Closed
Closed

Description

@mlucy

I think that we should have a term default with the following semantics:

  • r(X).default{|e| Y}
    • If X throws an error, the block is executed with e set to the text of that error and Y is returned.
    • If X returns NULL, the block is executed with e set to NULL and Y is returned.
  • r(X).default(Y)
    • If X throws an error or returns NULL, Y is returned.

I think that this is a good interface because it solves the very common problem of wanting to write:

table.update{|row| {:score => row[:score].default(0) + 1}}

Regardless of whether the user is using NULL or the absence of an attribute to represent non-existence.

It also allows people to drop malformed elements from a filter:

table.filter {|row|
  (row[:mother][:age] < row[:father][:age]).default(false)
}

Activity

  1. ghost assigned on May 22, 2013
  2. jdoliner commented on May 22, 2013

    @jdoliner
    Contributor

    So one objection I have with this is I think it's really weird to have the same command for handling null and handling errors. default makes a lot of intuitive sense as something that provides a value when one isn't present which is what null represents but an error isn't just a simple as the absence of a value so I don't think it makes the same intuitive sense. It also I think this is also potentially dangerous because it makes it very easy for an error to go unnoticed because people put a default in to handle null and then it handles error without them realizing it.

    Would people be opposed to having default handle null and catch handle errors. I think `catch is a term that everyone's pretty familiar with and this would more or less match the meaning of it that have in their heads.

  3. wmrowan commented on May 22, 2013

    @wmrowan
    Contributor

    I like the idea of accepting either a value or a function to run on the error. When combined with the upcoming regex command this would enable users to easily branch on different error messages (since we don't support different error types).

    I agree with @jdoliner that equating null and error in default is weird. In general we haven't really decided what we want null to mean. Here it's equivalent to an error, elsewhere it's a value just like any other. Some places it's a sentinel used to mean does not exist. I'd really like to clear this up before we define yet more inconsistent context specific behavior for null in different commands.

  4. mlucy commented on May 22, 2013

    @mlucy
    MemberAuthor

    I think it's really important that people be able to write something like:

    table.update{|row| {:score => row[:score].default(0) + 1}}

    And have it work regardless of whether score is NULL or non-existent. I think in general we want to move toward NULL and non-existence being more similar.

    We've been using NULL as a user value, but a lot of people seem to be using it to mean non-existence in their data sets (probably becaues of SQL's influence).


    I think having separate commands to handle NULL and errors is probably a bad idea, because I think people will end up having to write things like row[:score].default(0).catch{|e| 0} a lot.


    I don't feel terribly certain about the name default vs. catch. I think I like default slightly more because I think that 99% of the time people are going to be using this term while thinking "I want to provide a default value for this expression.". Also, if we do keep one term that handles both NULL and errors (which I think we should) then catch would be a very confusing name because people wouldn't expect those semantics.


    @coffeemug -- could you weigh in on this? I'm curious what you think, both about how confusing the two (three?) options are and what you think users actually want to do with this term.

  5. srh commented on May 22, 2013

    @srh
    Contributor

    I suspect very few people would want a null to remain null when passing .default(0), even people who'd expect has_fields to treat null fields as fields.

  6. jdoliner commented on May 22, 2013

    @jdoliner
    Contributor

    So it seems like we actually have 3 different uses cases here.

    • Recover from finding an unexpected null value.
    • Recover from an non existant value.
    • Recover from another kind of error, (division by 0, table already exists, etc.)

    @mlucy if I understand correctly is saying that default should work for cases 1 and 2. I'd agree with that but I think it's bad for it to work on case 3 because that gives users the potential to miss a bad error message and they probably won't realize that default catches all error messages.

    Suppose someone has some generic code they use to write things to the database and they want to keep track of all of the generated keys. This could easily happen in an ORM. In that case they might write:

    def insert_models(self, docs):
        self.generated_ids += table.insert(docs)["generated_ids"].default([]).run()

    this looks like perfectly reasonable code and it will work fine until a master dies and the write throws an error which they miss because of the default.

    I think we might be well served by looking at the behavior of throwing when an attribute is missing. Could we instead return something other than an error in that case which default would also handle? Maybe we could just return null in that case.

    Edit: added run()

  7. danielmewes commented on May 22, 2013

    @danielmewes
    Member

    Just a quick note: If catch will be implemented, please don't forget to also implement rethrow(). Calling r.error(...) with the error message is not equivalent, as it loses the backtrace.

    Also +1 to @jdoliner's concerns regarding catching both null and all errors with default. I don't know how difficult this is on the side of implementation, but from a user's perspective it makes total sense for default to catch null and absent fields, but not any other error. The fact that the absence of fields currently triggers an error which - except for its message - is indistinguishable from other errors is just an implementation detail.

  8. mlucy commented on May 22, 2013

    @mlucy
    MemberAuthor

    The problem with this is that if we want default to work on arbitrary expressions (which is really nice), we aren't 100% sure what error we'll get.

    So e.g.:

    table.filter {|user| 
      (user[:score] * user[:bonus]).default(0)
    }

    If score is NULL then the error we get is a type error from trying to multiple NULL and an integer, but we would still want the default to trigger.

    Or:

    table.get(obj[:attr]).default{...}

    If obj doesn't contain attr the error we get is that NULL isn't a valid value for a primary key.

    We spent a bit of time discussing limiting the set of errors that default catches before, and every time the problem was that we couldn't come up with a sufficiently restrictive set that didn't have any edge cases we'd forgotten. If we can come up with a set that we can prove is actually sufficient (and which is reasonably easy to implement), I'd be down with making default catch only a subset of errors and implementing a separate catch command.


    I'm not sure users will actually think to write this, but in the case you give you could implement that correctly as:

    table.insert(docs).do {|res|
      res[:generated_keys].default([])
    }

    I have very mixed feelings about the idea of accessing a missing attribute returning NULL. On the one hand, Ruby and Common Lisp do this, and it works reasonable well (although Common Lispers generally consider it a mistake). On the other hand, suddenly you can clobber data by accident:

    table.get(:user1).do {|user1|
      table.get(:user2).update {:partner => user1[:name]}
    }

    Currently if user is malformed and missing name we produce an error; the new behavior would be to clobber partner in user2 and continue silently.

    I think we probably shouldn't do this (not least because it would be a major change to existing semantics).


    I agree on adding rethrow to the language.

  9. danielmewes commented on May 22, 2013

    @danielmewes
    Member

    Hmm you are right, this is tricky.
    Somehow I feel like the current concept of default is still flawed, but I cannot quite pin it down at the moment.

    I guess the thing is that even if you write

    table.filter {|user| 
      (user[:score] * user[:bonus]).default(0)
    }
    

    still you basically just want to catch cases where one of the involved fields is missing. It is not really your intention to catch multiplications by null. This multiplication-failure is just a side effect of the thing that you actually want to catch, the missing value. (And if you actually want to catch problems with the multiplication, there should be a different command e.g. catch).

    Maybe the real problem is null here. If accessing a field which is null would trigger a very specific error, just as if it was absent, we wouldn't have this problem now. The multiplication could never happen, because the error would be thrown before it would be executed. default() could have the very straight-forward semantic of catching cases where at least one of the fields involved in the defaulted sub-expression is undefined.

    So I think the first step is to clarify what null means. If null is made equivalent to non-existence, I think default will be a lot cleaner. If null is just a value, maybe default should not be triggered on null. To get back to the multiplication example: If the user tries to multiply a string with a number, I don't think it would be appropriate to use the default. The value wouldn't simply be absent, but the schema would clearly be broken if such a thing happened in a query. The same should then hold for null.

    Considering null as non-existent would not even necessarily mean that setting a field to null should remove that field. If keys() is implemented, having fields which value you cannot access because it is non-existent might still make sense. Null in that sense would be somewhat similar to a null pointer in C. You can have such a pointer, but you can never dereference it. The field would have a name, but it wouldn't have a value. This would also be very close to the SQL interpretation of null I think.

  10. mlucy commented on May 23, 2013

    @mlucy
    MemberAuthor

    I guess I think of default as a more general operation than just one meant to substitute for a particular missing attribute. For instance, I think it's really important for people to be able to write:

    table.filter {|row|
      some_expression(row).default(false)
    }
    

    And have it drop all rows where some_expression doesn't make sense. (Several people have asked for this behavior, sometimes even as the default for filter, because the data in their tables is often sufficiently unstructured that writing some_expression to never produce an error is extremely difficult.)

    Even if you have well-structured data, it can be very useful to have default work like that. For example, if you want all the users whose average response times are greater than 500 ms:

    table.filter {|user|
      user[:response_times].do {|response_times|
        response_times.reduce{|a,b| a+b} / response_times.count > 500
      }.default(false)
    }
    

    Will work if response_times is non-existent, NULL, or empty, which is the behavior I would want.

    We also want people to be able to use default for reduce operations that don't make sense on empty streams rather than having to provide a base (which has confused so many people that I feel very strongly that we should remove it):

    possibly_empty_stream.reduce{|a,b| a+b}.default(0)

    I think there's a lot to be said for making NULL act even more like non-existence, but removing it entirely as a user value would require rethinking a LOT of stuff in the query language. For example, get returns NULL if the row you try to get doesn't exist, returning NULL from replace deletes the row, replace is passed NULL if you replace a row that doesn't exist, etc. etc.

  11. coffeemug commented on May 23, 2013

    @coffeemug
    Contributor

    Firstly, I think that we need to make a commitment to treat null values as non-existence by default, and provide a consistent flag to commands where it matters to modify this behavior. So x.default(y) should return y if x is either null or doesn't exit. Also, x.default(y, ignore_nulls=True) (name open for debate, but let's leave it for now), returns y iff x doesn't exist.

    Secondly, I agree with @jdoliner that it makes complete sense for default to handle nulls and non-existence, but is weird to handle other errors.

    Thirdly, I think that having a catch command that also deals with nulls for some reason is odd.

    Fourthly, I agree with @mlucy that we need a way to specify a default value for an arbitrary expression and have it work.


    So here's what I propose:

    • x.default(y, [ignore_nulls=False]
      • Always returns 'y' if x doesn't exist
      • Returns 'y' if x is null and ignore_nulls is set to False (which I strongly believe should be default throughout the language)
    • x.catch(fn)
      • returns the return value of fn if x throws
      • doesn't deal with nulls
    • x.catch_all(y, [ignore_nulls=False]) (name open for debate)
      • A combination of default and catch so people don't have to chain them
      • Equivalent to x.default(y, ignore_nulls).catch(lambda z: y)

    I don't think we can do a good job on this with less than three commands.

  12. mlucy commented on May 23, 2013

    @mlucy
    MemberAuthor

    I think that the cognitive load from having 3 ways to handle NULL/errors probably vastly outweighs the cognitive load from having a slightly non-intuitive behavior for one (or two) of them. This is especially bad because catch_all could easily substitute for either catch or default in 99% of circumstances.

    (Also, as a minor aside, I think that (obj[:attr1] * obj[:attr2]).default(0) reads waaaay better than (obj[:attr1] * obj[:attr2]).catch_all(0). The second reads like it's catching 0s somehow.)


    Four people have now chimed in and said that default handling all errors is confusing, so we should try to avoid doing that if at all possible.

    On the other hand, I like both of these solutions less:

    • Introducing 3 terms for error handling -- for reasons far too obvious and numerous to name.
    • Restricting the set of errors caught -- still requires having 2 terms for error handling, and it's very hard to define the right set of errors.

    I think that part of the problem here might be that the name default doesn't sound like it should do error handling. Maybe we could find a better name where we could combine semantics (to avoid having 3 terms) without it being confusing?

    Maybe something like:

    table.filter {|row|
      some_expression(row).on_error(false)
    }

    or:

    table.filter {|row|
      some_expression(row).on_failure(false)
    }
  13. mlucy commented on May 23, 2013

    @mlucy
    MemberAuthor

    Oh, or we could crib from Ruby:

    table.filter {|row|
      some_expression(row).rescue(false)
    }
  14. danielmewes commented on May 23, 2013

    @danielmewes
    Member

    @mlucy: Would there be a problem with having accessing a null value throw the same error as accessing a non-existent field? default would catch exactly that one error, while catch would catch either all, or all except for that one. The multiplication example would work with default exactly as you suggested.

    This behavior could still be changed by setting a flag on a per-query or per-command level, in which case null should probably trigger neither default nor any error.

  15. mlucy commented on May 23, 2013

    @mlucy
    MemberAuthor

    That's an interesting thought. Let me ponder.

  16. 21 remaining items

  17. wmrowan commented on May 24, 2013

    @wmrowan
    Contributor

    I haven't really been thinking about implementation details though all this talk about defining special semantics within certain operations within an expression passed to default sounds like a nightmare to me.

    I haven't thought about it too deeply but wouldn't we get the correct behavior if we just add type errors to default?

    • r({a:null})('a').eq(null).default(0) => true No error generated
    • r({a:null})('a').eq("foo").default(0) => 0 Caught type error cannot compare null and string
    • r({a:'foo')('b').eq('foo').default(0) => 0 Caught missing field error
  18. mlucy commented on May 28, 2013

    @mlucy
    MemberAuthor

    We eventually decided to just do the simple thing here:

    • We will classify some errors as "non-existence" errors. Tentatively, this includes the error you get when you access a non-existent key, the error you get when you try to use NULL in a context where it isn't allowed, and the error you get when you reduce over an empty stream.
    • default will evaluate its first argument. If its first argument throws a non-existence error or returns NULL, default will return its second argument. (Otherwise it returns the result of its first argument, or re-throws the error.)
    • A 0-arity r.error will re-throw the appropriate error when evaluated inside the default block.
    • The function passed to filter will have an implicit .default(false) on the end, which can be overridden with a new optional argument default which can map to any RQL expression (the most useful being RQL expressions that return true, false, or r.rethrow).
    • We won't do anything fancy with NULL comparing to things or accessing NULL fields throwing an error inside a default block.
  19. neumino commented on May 28, 2013

    @neumino
    Member

    Suppose I have this schema

    user = {
        name: ...
        contact:
            phone:....
            email: ....
    

    If I have understood, this query will never throw right? (even if name is not defined for some documents

    r.table("users").filter( r.row("name").eq("Michel") )
    

    This query never throws as long as contact is defined.
    If contact is undefined, it will throw an error, right?

    r.table("users").filter( r.row("contact")("email").eq("[email protected]") )
    

    This is going to be the behavior?

    r.expr(null).eq("blabla").default(5) // returns false
    r.expr(null).eq(null).default(5) // returns true
    object("non_existing_key").eq("blabla").default(5) // returns 5
    object("non_existing_key")("other_key").eq("blabla").default(5) // throws an error?
    object("existing_key")("non_existing_key").eq("blabla").default(5) // returns 5
    object("non_existing_key").default(3)("other_key").eq("blabla").default(5) // returns 5
    object("non_existing_key").default(null)("other_key").eq("blabla").default(5) // returns 5
    

    Could you give some examples with the first/second arguments? I'm not sure that I got everything.

  20. mlucy commented on May 28, 2013

    @mlucy
    MemberAuthor

    @neumino -- I don't quite understand those examples, but the last two definitely don't look right to me. Could you define an example object (like {:a => 1, :b => nil} # :c doesn't exist) and give examples in terms of that?

  21. neumino commented on May 28, 2013

    @neumino
    Member

    For this query

    r.table("users").filter{ |row| row[:name].eq("Michel") }

    Could you tell me if the predicate return true, false or throws an error
    Document 1:

    {
         :id => 1
         :name => nil
    }

    Document 2:

    {
         :id => 2
    }

    Same question for this query

    r.table("users").filter{ |row| row[:contact][:email].eq("[email protected]") }

    And these documents
    Document 1

    {
         :id => 1
         :contact => {
             :email => nil
         }
    }

    Document 2

    {
         :id => 1
         :contact => {
         }
    }

    Document 3

    {
         :id => 1
         :contact => nil
    }

    Document 4

    {
         :id => 1
    }

    Then are these results right?

    r.expr(null).eq("blabla").default(5) // returns false
    r.expr(null).eq(null).default(5) // returns true
    r.expr({ :id => 1})[:name].eq("blabla").default(5) // returns 5
    r.expr({ :id => 1 })[:contact][:email].eq("blabla").default(5) // throws an error?
    r.expr({ :contact => { :email => "[email protected]" } })[:contact][:phone].eq("blabla").default(5) // returns 5
    r.expr({ :id => 1 })[:contact].default(3)[:email].eq("blabla").default(5) // returns 5
    r.expr({ :id => 1 })[:contact].default(null)[:email].eq("blabla").default(5) // returns 5

    My apologies for any ruby error syntax : )

  22. mlucy commented on May 28, 2013

    @mlucy
    MemberAuthor
    • r.table("users").filter{ |row| row[:name].eq("Michel") }
      • Currently document 1 returns false and document 2 throws an error. Under the new proposal, filter will default to catching that error (since it's a non-existence error) and will not include document 2 in the final stream.
    • r.table("users").filter{ |row| row[:contact][:email].eq("[email protected]") }
      • Currently document 1 will return false, all the others throw an error. Under the new proposal, filter will default to catching that error (since it's a non-existence error) and will not include document 2 in the final stream.

    All your results are correct except for:

    • r.expr({ :id => 1 })[:contact].default(3)[:email].eq("blabla").default(5) // returns 5
      • This will throw an error. r.expr({ :id => 1 })[:contact].default(3) will return 3, and 3[:email] is a type error rather than a non-existence error, so the default(5) won't catch it.
  23. neumino commented on May 28, 2013

    @neumino
    Member

    Ok, thanks @mlucy.

    So in a filter, people just need to do

    object[:key1].default({})[:key2].default({})[:key3].eq("blabla")

    And they don't need to add a .default(false) at the end right?

    If that's the case, it's pretty close to the coffeescript syntax (which is pretty nice)

    object["key1"]?["key2"]?[key3] is "blabla"
  24. mlucy commented on May 28, 2013

    @mlucy
    MemberAuthor

    They could also just write object[:key1][:key2][:key3].eq("blabla"). It doesn't matter whether the non-existence error is thrown from the first or last access. If it's inside a filter, they can leave the default(false) off.

  25. neumino commented on May 28, 2013

    @neumino
    Member

    Ok, that's even better.
    👍 for the proposal then : )

  26. coffeemug commented on May 28, 2013

    @coffeemug
    Contributor

    👍 awesome!

  27. wmrowan commented on May 28, 2013

    @wmrowan
    Contributor

    I'm not sure that "simple" is the right word to describe this proposal but "simpler" relative to some of the other ideas contained herein is certainly appropriate. I'm reasonably happy with where this ended up though, of course, I have to repeat my usual concern that any "helpful" special casing based on what we assume to be the common pattern will come back to bite us in the rear.

    For now, I only ask, how do you think the documentation for this is going to look? This is still complicated enough (defining what distinguishes a non-existance error, highlighting contexts with an implicit default) that it might be really hard for users to pick up and use correctly.

  28. mlucy commented on May 29, 2013

    @mlucy
    MemberAuthor

    I'm not quite sure how to document it well. Does anyone have any good suggestions?

  29. coffeemug commented on May 29, 2013

    @coffeemug
    Contributor

    There are a few things we'll do:

    1. Document the relevant new and changed API functions in the API docs
    2. When one of the nonexistence error messages actually gets thrown to the user, include a URL to an FAQ in the error message.
    3. Write up an FAQ entry and describe how this works.

    Since filter will now not throw on non-existence by default, most people likely won't run into any of this stuff anyway.

  30. mlucy commented on Jun 6, 2013

    @mlucy
    MemberAuthor

    This is in next, review 581.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions