3

I have the following regular expression pattern that matches fully qualified Microsoft SQL Server table names ([dbName].[schemaName].[tableName]), where the schema name is optional:

val tableNamePattern = """\[(\w+)\](?:\.\[(\w+)\])?\.\[(\w+)\]""".r

I am using it like this:

val tableNamePattern(database, schema, tableName) = fullyQualifiedTableName

When the schema name is missing (e.g.: [dbName].[tableName]), the schema value gets set to null.

Is there a Scala idiomatic way to set it to None instead, and to Some(schema) when the schemaName is provided?

Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems. -- Jamie Zawinski

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Ralph
  • 31,584
  • 38
  • 145
  • 282
  • Related: http://stackoverflow.com/questions/1842925/regex-matchdata-returning-null-why-not-optionstring – theon Sep 13 '13 at 20:19

1 Answers1

2

I'm going to copy the code from the accepted answer on the linked question, and without giving credit too. Here it is:

object Optional {
  def unapply[T](a: T) = if (null == a) Some(None) else Some(Some(a))
}

val tableNamePattern(database, Optional(schema), tablename) = fullyQualifiedTableName

PS: I just today wondered on twitter whether creating special-case extractors was as common as they were suggested. :)

Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
  • Makes me think of a (pseudocode follows) `extractor[T] Optional(a: T) = if (null == a) Some(None) else Some(Some(a))` macro of some sort :P – Erik Kaplun Sep 13 '13 at 20:29
  • Is there a word for this tactic? "Double-dipping" doesn't quite cover it. Is that expr equivalent to `Some(Option(a))`? Only asking because DRY is even more important with code that is cut/pasted a lot. Noting of course that it still doesn't work in 2.7.x. – som-snytt Sep 13 '13 at 23:06
  • @som-snytt I think it is equivalent, yes. – Daniel C. Sobral Sep 16 '13 at 02:11