-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Handle Option[x] values in FieldPredicate for SQL
- Loading branch information
1 parent
266d39d
commit 84baa35
Showing
4 changed files
with
65 additions
and
44 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package io.dockovpn.metastore.util | ||
|
||
import io.dockovpn.metastore.util.Strings.toCamelCase | ||
|
||
object Sql { | ||
|
||
type TableSchema = Map[String, String] | ||
|
||
def valueToSqlType(maybeOptValue: Any, sqlType: String): Any = { | ||
// unwrap Option if any | ||
val maybeNullValue = maybeOptValue match { | ||
case option: Option[Any] => | ||
option.orNull | ||
case _ => maybeOptValue | ||
} | ||
|
||
// decide which values need to be wrapped in single quotes | ||
val maybeQuotedValue = sqlType match { | ||
case a if a startsWith "varchar" => s"'$maybeNullValue'" | ||
case "tinyint(1)" => if (maybeNullValue.asInstanceOf[Boolean]) 1 else 0 | ||
case "timestamp" => s"'$maybeNullValue'" | ||
case "uuid" => s"'$maybeNullValue'" | ||
case _ => maybeNullValue | ||
} | ||
|
||
val sqlValue = if (maybeQuotedValue == "'null'" || maybeQuotedValue == null) | ||
"NULL" | ||
else maybeQuotedValue | ||
|
||
sqlValue | ||
} | ||
|
||
def predicateToSql(predicate: Predicate, schema: TableSchema): String = { | ||
predicate match { | ||
case FieldPredicate(field, _, value) => | ||
val columnName = toCamelCase(field) | ||
val sqlType = schema(columnName) | ||
val sqlValue = valueToSqlType(value, sqlType) | ||
if (sqlValue == "NULL") | ||
s"$columnName IS NULL" | ||
else | ||
s"$columnName = $sqlValue" | ||
case _ => "1=1" // not implemented | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters