DataGripを使用してデータベースからクラスを生成する


この短いメモでは、ほぼすべてのデータベース(SQL Server、Oracle、DB2、Sybase、MySQL、PostgreSQL、SQLite、Apache Derby、 HyperSQL、H2)。


まえがき



DataGripは、さまざまなDBMSを操作するためのJetBrainsの比較的新しいIDEであり、機能を拡張するためのAPIを備えています。 タスクは、POCO(C#)クラスのジェネレーターを作成するために使用することです。
このすべてを読みたくないが、クラスの生成を開始したいだけの場合は、スクリプトを使用したリポジトリへのリンクがあります


スクリプト作成


DataGripでは、スクリプト(スクリプト拡張機能)を使用して機能を拡張できます。 Groovy、Clojure、およびJavaScriptがサポートされています。 これに関するサイトのドキュメントは非常に短いですが、Javaソースコードの形式のAPIを使用した例とアーカイブがあります。 ソースコードは<DataGrip_installation_dir>/lib/src/src_database-openapi.zipます。 サンプルは、IDEの[ファイル]-> [スクラッチ]パネルにあります。 DataGripは、データをさまざまな形式にエクスポートするためのスクリプトもサポートしています(この記事ではエクストラクターについては説明しません)。csv、json、およびhtml形式の例も[スクラッチ]パネルにあります。


したがって、スクリプトを作成するためにClojureを使用します。この例は、IDEのPOJOジェネレーターの基礎として使用されました。
DataGripでのClojureの構文と自動補完は確かにそうではないため、他のエディターを使用できます。
最初に、データベースからC#型への型マッピングを構成し、いくつかの定数を宣言します。


コード
 (def usings "using System;") (def default-type "string") (def type-mappings [ [["bit"] "bool"] [["tinyint"] "byte"] [["uniqueidentifier"] "Guid"] [["int"] "int"] [["bigint"] "long"] [["char"] "char"] [["varbinary" "image"] "byte[]" true] ; cannot be null [["double" "float" "real"] "double"] [["decimal" "money" "numeric" "smallmoney"] "decimal"] [["datetime" "timestamp" "date" "time"] "DateTime"] [["datetimeoffset"] "DateTimeOffset"] ]) (def new-line "\r\n") 

次に、文字列をPascalCaseにキャストする関数を作成します。


コード
 (defn- poco-name [name] (apply str (map clojure.string/capitalize (re-seq #"(?:[AZ]+)?[az\d]*" name)))) 

前に定義したマッピングに基づいて、データベースの型をC#の型に一致させます。


コード
 (defn- poco-type [data-type is-null] (let [spec (.. data-type getSpecification toLowerCase) spec-matches? (fn [pattern] (= (re-find #"^\w+" spec) pattern)) mapping-matches? (fn [[ps tn]] (when (some spec-matches? ps) [tn])) [type cant-be-null] (some mapping-matches? type-mappings) nullable-type (if (and type (not cant-be-null) is-null) (str type "?") type)] (or nullable-type default-type))) 

テーブルからすべての列を取得する関数は、一致する関数を呼び出し、さらに保存するために必要なオブジェクトを収集します。 ここでは、APIのメソッド、たとえばcom.intellij.database.util.DasUtil/getColumnsを使用します。これらのメソッドはすべて、上記のsrc_database-openapi.zipアーカイブで表示できます。


コード
 (defn- field-infos [table] (let [columns (com.intellij.database.util.DasUtil/getColumns table) field-info (fn [column] {:name (poco-name (.getName column)) :type (poco-type (.getDataType column) (not (.isNotNull column)))})] (map field-info columns))) 

プロパティとクラスのテキストを生成します。文字列を連結するだけでは特別なことはありません。 また、このテキストをファイルに書き込む機能。


コード
 (defn- property-text [field-info] (let [type (:type field-info) name (:name field-info)] (str " public " type " " name " { get; set; } " new-line))) (defn- poco-text [class-name fields] (apply str (flatten [usings new-line new-line "public class " class-name " " new-line "{" new-line (interpose new-line (interleave (map property-text fields))) "}" new-line]))) (defn- generate-poco [directory table] (let [class-name (poco-name (.getName table)) fields (field-infos table) file (java.io.File. directory (str class-name ".cs")) text (poco-text class-name fields)] (com.intellij.openapi.util.io.FileUtil/writeToFile file text))) 

最後に、ファイルを保存するためのディレクトリ選択ダイアログを開く機能と、選択したテーブルを決定して生成を開始する機能。


コード
 (defn- generate-pocos [directory] (let [table? (partial instance? com.intellij.database.model.DasTable)] (doseq [table (filter table? SELECTION)] (generate-poco directory table)))) (.chooseDirectoryAndSave FILES "Choose directory" "Choose where to generate POCOs to" (proxy [com.intellij.util.Consumer] [] (consume [directory] (generate-pocos directory) (.refresh FILES directory)))) 

スクリプトのインストール



GitHubの完全なスクリプトコード
インストールするには、ファイルをコピーするだけです Generate POCO.clj IDE>ファイル>スクラッチ>拡張機能> DataGrip>スキーマでGenerate POCO.groovyGenerate POCO.groovyます。
また、テーブルのコンテキストメニューでは、対応するサブメニュー項目が[スクリプト拡張機能]セクションに表示されます。


結果


次の表から


だった
 CREATE TABLE Users ( Id INT PRIMARY KEY NOT NULL IDENTITY, first_name NVARCHAR(255), Last_Name NVARCHAR(255), Email VARCHAR(255) NOT NULL, UserGuid UNIQUEIDENTIFIER, Age TINYINT NOT NULL, Address NVARCHAR(MAX), photo IMAGE, Salary MONEY, ADDITIONAL_INFO NVARCHAR(42) ); 

次のクラスが生成されます:


になっています
 using System; public class Users { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public Guid? UserGuid { get; set; } public byte Age { get; set; } public string Address { get; set; } public byte[] Photo { get; set; } public decimal? Salary { get; set; } public string AdditionalInfo { get; set; } } 

おわりに


このような非常に簡単な方法で、データベース内のテーブルを記述するC#クラスを生成し、日常業務を少し減らすことができます。 もちろん、C#によるPOCOクラスだけに限定されるものではなく、他の言語、フレームワークなどのあらゆるジェネレータを作成できます。



Source: https://habr.com/ru/post/J301324/


All Articles