LoginSignup
6
5

More than 5 years have passed since last update.

はじめてのScala DBテーブルのカラム名を変換

Posted at

Scalaでカラム名を適当な名前に変換するツールを作る。

やりたいこと

日本語で書かれた単語から、予めプロジェクトごとに用意された辞書を元に、適当なカラム名を出力するツールを作ります。
ユーザ => USER
のような変換が目指すところです。

複数の単語で構成されるカラム名も同様に変換されなくてはなりません。
ユーザ名 => USER_NAME
ユーザID => USER_ID

今回は、Scalaのパターンマッチを使って、このロジックをスマートに書こうと思います。

準備

まず、辞書を引っ張ってきます。

val dictionary: List[Map[String, Any]] = DB readOnly {implicit session =>
        SQL("select * from henkanjisyo").map(rs => rs.toMap).list().apply()
    }

本文

辞書に対して与えられた単語のパターンマッチをします。さらに、マッチした単語があったかどうかで、マッチングを行って、なければ与えられた単語の末尾を一文字削って、関数に再帰させます。二番目のパターンマッチでは、パターンガードを使っています。

def logic2physic(dictionary: List[Map[String, Any]], targetStr: String, stock: String): String = {
    var destStr = ""
    var thisStock = ""
    var thisTarget = ""
    dictionary.foreach{article =>
      article("BF").toString match {
        case `targetStr` =>
          destStr = article("AF1").toString

        case _ => Nil
      }
    }

    destStr match {
      case "" if targetStr.isEmpty =>
        return "\n[error] No word correspond to the given word\n"

      case "" if !(targetStr.isEmpty) =>
        thisStock = targetStr.last.toString + stock
        thisTarget = targetStr.init
        return logic2physic(dictionary, thisTarget, thisStock)

      case _ if !(stock.isEmpty) =>
        destStr += logic2physic(dictionary, stock, "")
        return destStr

      case _ if stock.isEmpty =>
        return destStr

    }

  }

実際に動かしてみると、変換された値が返されます。

val target = "ユーザ名"
val destStr = logic2physic(dictionary, target, "")
print(destStr)        //USER_NAMEが出力される。
6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5