MySQLでは以下を使用できますshow create table
:
(require '[clojure.java.jdbc :as jdbc])
(defn gen-script [db table]
(jdbc/with-connection db
(jdbc/with-query-results rs [(str "show create table " table)]
(get (first rs) (keyword "create table")))))
テスト:
(def db {:classname "com.mysql.jdbc.Driver"
:subprotocol "mysql"
:subname (str "//localhost:3306/testtest")
:user "root"
:password "..."})
(println (gen-script db "example"))
=> CREATE TABLE `example` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(30) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
他のDBでは、これから始めることができます。
(defn- gen-script [db table]
(jdbc/with-connection db
(let [conn (jdbc/connection)
meta (.getMetaData conn)]
(format "create table %s (\n%s\n)"
table
(apply str
(interpose ",\n"
(map (fn [x]
(format " %s %s(%s)%s%s%s"
(:column_name x)
(:type_name x)
(:column_size x)
(if (not= "YES" (:is_nullable x)) " NOT NULL" "")
(if (= "YES" (:is_autoincrement x)) " AUTO_INCREMENT""")
(if (= "YES" (:column_def x)) " DEFAULT" "")))
(resultset-seq (.getColumns meta nil nil table "%")))))))))
テスト:
(println (gen-script db "example"))
=> create table example (
id INT(10) NOT NULL AUTO_INCREMENT,
name VARCHAR(30),
age INT(10)
)。