Elixir: is the 'default' clause like catching an exception? - exception

It seems like the purpose of the default clause is to prevent the error from being raised if there is no pattern match. So is it fair to compare it to catching an exception (like in C#/Java), or does it serve any other purpose as well?

The default clause isn't really a "default" clause per se, more of a "catch-all" clause, which is useful for providing a default value if none of the provided patterns match. Often though, it will be used to prevent a match error (no matching pattern found), and raise a more meaningful error.

Related

Case-sensitive database search with Active Record

Does Active Record provide a way to generate SQL that forces a text search to be case-sensitive?
Ruby-on-Rails generators instructed to create a string-type column produce a simple VARCHAR(255) field, in a mysql database. It turns out that queries on such columns are case insensitive by default.
Thus, an Active Record search such as:
Secret.where(token: 'abcde')
will match records with tokens abcde, ABcdE, etc.
Without changing the underlying database column (e.g. specifying a utf8_bin collation) searches can be made case sensitive by explicitly tweaking the where clause:
Secret.where('binary token = ?', 'abcde')
However, this is database-specific, and I am wondering if Active Record has an idiom to accomplish the same for any database. Just as an example, something resembling the where.not construct:
Secret.where.binary(token: 'abcde')
Wouldn't this be a common enough need?
In short: there is NO ActiveRecord idiom for case-sensitive
search.
For case-insensitive search you can try to use
this.
It still works, but source code was changed a bit. So, use it on your
own risk.
In general, case sensitivity is subset of the Collation idiom.
And different DBMS use very different default collations for string(text) data types, including default case sensitivity.
Detailed description for MySQL.
There is a sql operator COLLATE which is very common across DBMS(but seems still is not in SQL Standard).
But ActiveRecord sources show it only in schema creation code.
Neither ActiveRecord, nor Arel gems do not use COLLATE in where search(sad).
Note: Please, don't miss the database tag(mysql etc) in a Question.
There are many Questions and Answers on SO without the tags(or with sql one), which are completely irrelevant for the most of DBMSs except author's one.

mysql regexp returns boolean rather than value

according to the docs selecting a REGXP will always produce a boolean (match or non match) but I'm trying to get the result, if it's a match, meaning if I'm doing...
select file_id REGEXP '^\d{10}' from my_table;
What I want back is not false or true but false or the actual 10 digits that start file_id.
Am I missing something? or is this really how mySQL has implemented regexp?!
I realize that in my case, I can use SUBSTR, but now I'm just curious why they would have deviated from the prescribed norm of how regexp matching works everywhere else.
In answer to your question, "is this really how MySQL has implemented regexp?" the answer is yes. It simply returns a boolean on success or failure to match.
In answer to your question, "why they would shave deviated form the prescribed norm", the answer is that it is more useful in queries to have boolean returns, since you are more often testing for the presence of something, not extracting something, based on a pattern. Extracting things is more often done using procedural languages, not relational databases.
To do what you want it to do, you might want to write a stored procedure that does the necessary string manipulation.

Why do most forums not specify the 'default' value for the ID (primary key) column?

Most forums do not specify any default value for the ID column.
I wonder why they don't do that.
For example SMF. They specify for every column a default value except for the (PRIMARY KEY) ID column.
EDIT: I now see that ^this^ part of the question was a bit 'stupid'.
Is there an performance advantage by specifying a default value?
Why shouldn't you specify by default an empty value?
Will 'NOT NULL' complain if you use the value: (similar to $var = ''; in php)
EDIT: But I assume that you want a database to complain if it doesn't get, for example, a username. Of course, I'll not allow registration fields to be left empty (and I do validate them server-side), but if I'm not mistaken, than, if by magic the input to the database is still empty, the database will accept this. Assuming the database uses NOT NULL and a default value. Question: So what than is the use of NOT NULL, in combination with a default value?
Thanks in advance.
Please keep in mind that I am Dutch an therefore I may have made some mistakes.
If we assume that a default value for an id, primary key, column in a database made sense (and was even valid), think what the consequences would be:
First off, it would allow the user, or the DB scripts, to supply no id information (which is fine, since most scripts rely on the database to deal with that aspect anyway), but
it would also allow the database not to 'deal with' it, and to simply insert the new record with the default value, whatever that might be. This means that
in many situations multiple records are likely to be inserted which have the same id value/primary key. If multiple entries, into for example a forum Database, have the same value, how would you tell your users apart? How would you identify them?
The reason that no 'default' is used is because, a: it wouldn't make sense to allow it in the first place, and b: it'd be invalid (albeit b is a consequence of a).
Is there a performance benefit to supplying a default value?
Not so much a 'performance' benefit, but it does mean that if no value is supplied the software has, at least, some idea what to expect (whether that default is a string, a number, an enum...).
Why shouldn't you specify by default an empty value?
I think that all entries to the database should be controlled, whether that's the values you allow to be inserted, or the values inserted in the event of an error, or a failure of the user to supply a value. Allowing null-entries to your database likely a controllable situation, but it seems needlessly complex to compensate for null entries, when a default can be specified.
Will 'NOT NULL' complain if you use the value: (similar to $var = ''; in php)?
It's been a while since I last used MySQL, but null is not similar to an empty string (in the way that JavaScript assesses '' to be 'falsy'), it means, absolutely, nothing. Empty. A whole vacuum, and non-existence, of information. NOT NULL, then, requirese some (albeit it doesn't specify exactly what) information. This is why a default should be supplied, since it specifies precisely what will be found in the database in the even of the user specifying no data.
Edited in response to comments from OP (below):
But I assume that you want a database to complain if it doesn't get, for example, a username. Of course, I'll not allow registration fields to be left empty (and I do validate them serverside), but if I'm not mistaken, than if by magic the input to the database is still empty, the database will accept this. If it uses NOT NULL and a default value. So what than is the use of NOT NULL, in combination with a default value?
I can't speak to all situations, or to the choices made by all database-/web-admins, but in my personal use-cases I'd suggest a consideration of:
First, would an empty-value make sense for this field, and:
Second, if an empty field doesn't make sense, should a default value be used?
In some situations I don't need the details from a user (their gender, for example) has almost no impact on me, or any services I provide, so I don't care whether they supply it, or not. In this case a default isn't used.
In other cases, such as their age, it might make a difference (I cant' remember the name of the law, but I recall some mention of Facebook, and other online societies, being required to only allow those of age 13, or older, to participate). In this case I ask my users to say agree that they are, in fact, over the age of 13 (via a checkbox) and then later offer them an input to insert their actual age/date-of-birth. In the absence of a supplied data-point (and, honestly, other than the (presumed) legal obligation I really don't care how old my users are) my database defaults to thirteen (or in the case of birthday it defaults to thirteen-years-ago today (albeit with help from the php scripts).
Now, the the aspect of NOT NULL and a default value? There'd be no sense, so far as I can see.
The whole concept of NOT NULL is to ensure a user-supplied value (otherwise the record isn't created, and the user can't join (or whatever) the service for which they're registering). The default value is to supply a fall-back value in this absence. And, logically, if the two are allowed together on the same field? The default would be inserted before the NOT NULL condition is triggered. So...why bother? Do you have evidence that somebody, or some software, used both conditions on the same field? I can't, honestly, think why.
The ID column is an auto_increment in most cases. So a default value is invalid.
Edit:
Will 'NOT NULL' complain if you use the value: (similar to $var = ''; in php)
With NULL, the literal NULL is meant. Not something like zero or an empty string.

MySQL - AND condition

Let's say I have a query like this:
SELECT bla WHERE foo LIKE '%bar%' AND boo = 'bar' AND whatvr IN ('foo', 'bar')...
I was wondering if MySQL continues to check all conditions when retrieving results.
For eg. if foo is not LIKE %bar%, will it continue to check if boo = 'bar', and so on ?
Would it be any faster if I put conditions that are less likely to be true at the end?
I'm sorry if this seems to be stupid question, I'm a complete noob when it comes to SQL :)
I don't think there are any guarantees about whether or not multiple conditions will be short-circuited, but...
In general, you should treat the query optimiser as a black box and assume -- unless you have evidence to the contrary -- that it will do its job properly. The optimiser's job is to ensure that the requested data is retrieved as efficiently as possible. If the most efficient plan involves short-circuiting then it'll do it; if it doesn't then it won't.
(Of course, query optimisers aren't perfect. If you have evidence that a query isn't being executed optimally then it's often worth re-ordering and/or re-stating the query to see if anything changes.)
What you're looking for is documentation on MySQL's short-circuit evaluation. I have, however, not been able to find anything better than people who were not able to find the documentation, but they claim to have tested it and found it to be true, i.e., MySQL short-circuits.
Would it be any faster if I put conditions that are less likely to be true at the end?
No, the optimizer will try and optimize (!) the order of processing. So, as for the order of tests, you should not assume anything.
I would not count on that : Where Optimisations. That link explains that other criterias prevail on the order.
You can't rely on MySQL evaluating conditions from left to right (as opposed to any programming language). This is because the "WHERE clause optimizer" looks for columns that are indexed and will look for this subset first.
For query optimization see the chapter Optimizing SELECT Statements in the MySQL reference manual.
If it does short-circuit when first condition fails( which is most likely ), it would be best to put those conditions, that are most likely to fail, first!
let's say we have 3 conditions, and all must be true( separated by "AND" ).
slow case:
1. never fail. All rows are looked through and success.
2. sometimes fail. All rows are looked through and still success.
3. often fail. All rows are looked through and this time we fail.
Result: It took a while, but can't find a match.
fast case:
1. often fail. All rows are looked through and matching fail.
2. sometimes fail. NOT looked through, because searching ended due to short-circuit.
3. never fail. NOT looked through, because searching ended due to short-circuit.
Result: Quickly figured, no match.
Correct me if I'm wrong.
I can imagine, that all conditions are checked, for each row looked ad. Which makes this matter ALOT less.
If your fields are ordered in the same order, as your conditions, you could maybe measure the difference.

NULL in table fields better than empty fields?

i wonder if one should have NULL in the fields with no value, or should it be empty?
what is best?
thanks
NULL means that no data is set, while empty string could be some valid data.
Thus, using NULL helps you to differentiate these two cases.
From a programming standpoint, I try to not allow null values for a few reasons. One of which is that code often has a bad reaction to unexpected NULL values. If a query filter ran faster checking null values I might consider using them but there is no evidence of this I have experienced. But I have experienced many a function which pooped out on doing some kind of comparison not testing for NULL before hand.
There is a certain argument that you should never allow NULL in your data, if you are using it to indicate that you don't know what the value should be or that you just don't have that data yet then use an explicit value in the field to indicate those states. Similarly for 'empty' fields. That said, I think everyone does it or has done it and may do it again. NULL has odd comparative properties which is why it's always best, if you can, to avoid it and have explicit values for missing data states.
Avoid NULLs in base tables whenever three valued logic is likely to come back to bite you. That's easy to say, but lengthy to explain. Three valued logic can sometimes be successfully managed, but your intuition is likely to be based on two valued logic, and can be misleading.
If you avoid NULLS in base tables, but create views or queries with outer joins, be prepared to deal with NULLS. NULLS in fields that are never used in where clauses and never used "incorrectly" with aggregates (as in sum(FIELD)) are OK.
NULL fields are always empty, but empty doesn't always imply NULL. In particular, an empty or non existent field in a form can translate into a non NULL value in a table. Autonumber fields are an example.
Oracle made a mistake way back in the 1980s by using the same representation for the VARCHAR string of length zero (the empty string), and NULL. They've been about to fix it "real soon now" for a quarter of a century. Don't hold your breath.
Don't use NULLs to convey a meaningful message. This almost always confuses your colleagues, even when they deny it.
Nulls are necessary amd important tools in dataase design. If you don'tknow the value at the time the record is inseerted, null is entirely appropriate and the best practice. Making an unknon into a known value such as empty string is silly. This especially true when you get away from string data into dates or numeric data. 0 is not the same as null, some arbitrary date far in the past or future is not the same as null. For that matter empty strings means there is no value, null means we don't know what the value is. This is an important distinction.
It's not hard to handle nulls, any competent programmer should be able to do so.