001/*
002 * Copyright (c) 2009 The openGion Project.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
013 * either express or implied. See the License for the specific language
014 * governing permissions and limitations under the License.
015 */
016package org.opengion.plugin.table;
017
018import java.io.File;
019import java.io.PrintWriter;
020
021import org.opengion.fukurou.system.OgBuilder ;                          // 6.4.4.1 (2016/03/18)
022import org.opengion.fukurou.db.DBUtil;
023import org.opengion.fukurou.db.Transaction;                     // 5.5.2.6 (2012/05/25)
024import org.opengion.fukurou.util.ErrorMessage;
025import org.opengion.fukurou.util.FileUtil;
026import org.opengion.fukurou.util.FixLengthData;
027import org.opengion.fukurou.util.StringUtil;
028import org.opengion.hayabusa.common.HybsSystem;
029import org.opengion.hayabusa.common.HybsSystemException;
030import org.opengion.hayabusa.db.AbstractTableFilter;
031import org.opengion.hayabusa.db.DBTableModel;
032
033/**
034 * TableFilter_INDEX は、TableUpda インターフェースを継承した、DBTableModel 処理用の
035 * 実装クラスです。
036 *
037 * ここでは、インデックス一覧の検索結果より、GF07 のインデックスカラム定義テーブルから
038 * 必要な情報を取得し、インデックス作成スクリプトを作成します。
039 * 出力ファイルは、テーブル名+"C.sql" という命名規則で作成します。
040 * 検索では、(SYSTEM_ID,TBLSYU,TABLE_NAME,TABLE_LABEL,INDEX_NAME,NAME_JA,INDTYPE,TABLESPACE_NAME,INITIAL_EXTENT)
041 * の項目を取得する必要があります。
042 *
043 * 6.1.0.0 (2014/12/26) より、NEXT_EXTENT は使用しなくなりました。
044 *
045 * パラメータは、tableFilterタグの keys, vals にそれぞれ記述するか、BODY 部にCSS形式で記述します。
046 * 【パラメータ】
047 *  {
048 *       DIR : {@BASE_DIR}/sql/install/02_INDEX ;    出力ファイルの基準フォルダ(必須)
049 *       XML : false ;                                    XML出力を行うかどうか[true/false]を指定します(初期値:false)。
050 *       DROP: false ;                                    INDEX構文の前に、DROP構文を出力するかどうか[true/false]を指定します(初期値:false)。
051 *  }
052 *
053 * @og.formSample
054 * ●形式:
055 *      select SYSTEM_ID,TBLSYU,TABLE_NAME,TABLE_LABEL,INDEX_NAME,NAME_JA,INDTYPE,TABLESPACE_NAME,INITIAL_EXTENT from GF07
056 *      ① <og:tableFilter classId="INDEX" keys="DIR,XML" vals="{@BASE_DIR}/sql/install/02_INDEX,false" />
057 *
058 *      ② <og:tableFilter classId="INDEX" >
059 *               {
060 *                   DIR : {@BASE_DIR}/sql/install/02_INDEX ;
061 *                   XML : false ;
062 *                   DROP: false ;
063 *               }
064 *         </og:tableFilter>
065 *
066 * @og.rev 5.6.6.0 (2013/07/05) keys の整合性チェックを追加
067 *
068 * @version  0.9.0  2000/10/17
069 * @author   Kazuhiko Hasegawa
070 * @since    JDK1.1,
071 */
072public class TableFilter_INDEX extends AbstractTableFilter {
073        /** このプログラムのVERSION文字列を設定します。   {@value} */
074        private static final String VERSION = "7.3.0.0 (2021/01/06)" ;
075
076        // 6.1.0.0 (2014/12/26) NEXT_EXTENT は、使いません。
077        private static final String[] DBKEY = {"SYSTEM_ID","TBLSYU","TABLE_NAME","TABLE_LABEL","INDEX_NAME","NAME_JA","INDTYPE",
078                                                        "TABLESPACE_NAME","INITIAL_EXTENT" };
079
080        // 5.1.1.0 (2009/12/01) データのアクセス用の配列番号のIDを private ⇒ protected にします。
081        /** データのアクセス用の配列番号 {@value} */
082        protected static final int SYSTEM_ID            = 0;
083        /** データのアクセス用の配列番号 {@value} */
084        protected static final int TBLSYU                       = 1;
085        /** データのアクセス用の配列番号 {@value} */
086        protected static final int TABLE_NAME           = 2;
087        /** データのアクセス用の配列番号 {@value} */
088        protected static final int TABLE_LABEL          = 3;            // GF02 の NAME_JA より JOIN
089        /** データのアクセス用の配列番号 {@value} */
090        protected static final int INDEX_NAME           = 4;
091        /** データのアクセス用の配列番号 {@value} */
092        protected static final int INDTYPE                      = 6;
093        /** データのアクセス用の配列番号 {@value} */
094        protected static final int TABLESPACE_NAME      = 7;
095        /** データのアクセス用の配列番号 {@value} */
096        protected static final int INITIAL_EXTENT       = 8;
097
098        // 5.1.1.2 (2009/12/10)
099//      private static final String GF07_SEL = "select A.CLM, B.USE_LENGTH"
100        private static final String GF07_SEL = "select A.CLM, B.USE_LENGTH,A.SEQNO"                     // 7.3.0.0 (2021/01/06) 順番が必要
101                                                                                        + " from GF07 A left outer join GF05 B"
102                                                                                        + " on    A.SYSTEM_ID  = B.SYSTEM_ID"
103                                                                                        + " and   A.TBLSYU     = B.TBLSYU"
104                                                                                        + " and   A.TABLE_NAME = B.TABLE_NAME"
105                                                                                        + " and   A.CLM        = B.CLM"
106                                                                                        + " and   B.FGJ        = '1'"
107                                                                                        + " where A.SYSTEM_ID=? and A.TBLSYU=? and A.TABLE_NAME=? and A.INDEX_NAME=?"
108                                                                                        + " and   A.FGJ='1'"
109                                                                //                      + " order by A.SEQNO" ;
110                                                                                        + " order by ABS(A.SEQNO)" ;                            // 7.3.0.0 (2021/01/06) 絶対値でソート(ORACLEのみ可能?)
111
112 //     private static final String ENCODE = "Windows-31J" ;
113        private static final String ENCODE = "UTF-8" ; // 4.3.6.6 (2009/05/15)
114
115        private static final String CMNT  = "************************************************************************" ;
116
117        private static final int X = FixLengthData.X ;
118        private static final int K = FixLengthData.K ;
119
120        /** 各種定数 */
121        // 6.0.2.3 (2014/10/10) AbstractTableFilter へ移動
122
123        /** XML形式かどうか  */
124
125        /**
126         * デフォルトコンストラクター
127         *
128         * @og.rev 6.4.1.1 (2016/01/16) keysMap を、サブクラスから設定させるように変更。
129         */
130        public TableFilter_INDEX() {
131                super();
132                initSet( "DIR"  , "出力ファイルの基準フォルダ(必須)"                                                   );
133                initSet( "XML"  , "XML出力を行うかどうか[true/false]を指定(初期値:false)"              );
134                initSet( "DROP" , "INDEX構文の前に、DROP構文を出力するかどうか(初期値:false)"       );
135        }
136
137        /**
138         * DBTableModel処理を実行します。
139         *
140         * @og.rev 3.8.7.0 (2006/12/15) アクセスログ取得の為,ApplicationInfoオブジェクトを設定
141         * @og.rev 4.0.0.0 (2007/11/28) メソッドの戻り値をチェックします。
142         * @og.rev 4.3.7.0 (2009/06/01) XML出力機能追加
143         * @og.rev 5.1.1.0 (2009/12/01) XML_START_TAG に、tableName をセットします。
144         * @og.rev 5.1.9.0 (2010/08/01) Transaction 対応
145         * @og.rev 5.5.2.6 (2012/05/25) protected変数を、private化したため、getterメソッドで取得するように変更
146         * @og.rev 5.6.9.2 (2013/10/18) INDEXを作成する前に、削除構文を入れるかどうかを指定。
147         * @og.rev 6.0.2.3 (2014/10/10) EXEC_END_TAG を追加。キャッシュします。
148         * @og.rev 6.0.2.3 (2014/10/10) isDrop=false の場合、まとめDropファイル(AllDropC.xml)を作成します。
149         * @og.rev 6.5.0.1 (2016/10/21) ErrorMessage をまとめるのと、直接 Throwable を渡します。
150         * @og.rev 7.3.0.0 (2021/01/06) SEQNO がマイナスの場合、カラムに DESC を付ける(逆順カラム)
151         *
152         * @return      実行結果のテーブルモデル
153         */
154        public DBTableModel execute() {
155                isXml  = StringUtil.nval( getValue( "XML" ), false );
156                execEndTag = isXml ? CR + EXEC_END_TAG : ";" ;  // 6.0.2.3 (2014/10/10)
157
158                final File dir = new File( getValue( "DIR" ) );
159                if( ! dir.exists() && ! dir.mkdirs() ) {
160                        final String errMsg = "所定のフォルダが作成できませんでした。[" + dir + "]" ;
161                        // 4.3.4.4 (2009/01/01)
162                        throw new HybsSystemException( errMsg );
163                }
164
165                // 6.0.2.3 (2014/10/10) isDrop=false の場合、まとめDropファイル(AllDropC.xml)を作成します。
166                // 5.6.9.2 (2013/10/18) DROP構文を出力するかどうか
167                final boolean isDrop = StringUtil.nval( getValue( "DROP" ), false );
168                PrintWriter dropWriter = null;
169                if( !isDrop ) {                                 // isDrop == false の場合に、まとめDropする。
170                        dropWriter = FileUtil.getPrintWriter( new File( dir,"AllDrop" + ( isXml ? "C.xml" : "C.sql" ) ),ENCODE );
171                        if( isXml ) { dropWriter.println( XML_START_TAG ); }
172                }
173
174                String[] data  = null;
175                String bkTableName = null;
176                PrintWriter writer = null;
177                final Transaction tran = getTransaction();                              // 5.5.2.6 (2012/05/25)
178                final StringBuilder buf = new StringBuilder( BUFFER_MIDDLE ) ;  // 6.1.0.0 (2014/12/26) refactoring
179                final int[] clmNo = getTableColumnNo( DBKEY );
180                // 6.4.1.1 (2016/01/16) PMD refactoring. Avoid declaring a variable if it is unreferenced before a possible exit point.
181                final DBTableModel table = getDBTableModel();           // 5.5.2.6 (2012/05/25) インターフェースにgetterメソッド追加
182                final int rowCnt = table.getRowCount();
183                for( int row=0; row<rowCnt; row++ ) {
184                        String tableName = null;
185                        String indexName = null;
186                        try {
187                                data  = table.getValues( row );
188                                final String systemId  = data[clmNo[SYSTEM_ID]];
189                                final String tblsyu    = data[clmNo[TBLSYU]];
190                                tableName = data[clmNo[TABLE_NAME]];
191                                indexName = data[clmNo[INDEX_NAME]];
192
193                                // テーブルがキーブレイクすると、セーブファイルを切り替える。
194                                if( ! tableName.equals( bkTableName ) ) {
195                                        if( writer != null ) {
196                                                if( isXml ) { writer.println( XML_END_TAG ); }
197                                                writer.close();
198                                        }
199                                        bkTableName = tableName;
200                                        writer = FileUtil.getPrintWriter( new File( dir,tableName + ( isXml ? "C.xml" : "C.sql" ) ),ENCODE );
201                                        if( isXml ) { writer.println( XML_START_TAG.replace( "xxx",tableName ) ); }             // 5.1.1.0 (2009/12/01) tableName をセット
202                                        writer.print( makeHeadLine( clmNo,data ) );
203                                }
204
205                                final String[] vals = new String[] { systemId,tblsyu,tableName,indexName };
206                                final String[][] gf07 = DBUtil.dbExecute( GF07_SEL,vals,tran );                                         // 5.1.9.0 (2010/08/01) Transaction 対応
207                                if( gf07.length == 0 ) {
208                                        System.out.println( "TABLE=[" + tableName + "],INDEX=[" + indexName + "] is Not Found!" );
209                                        continue;
210                                }
211                                // テーブルに対するカラム列
212                                buf.setLength(0);
213                                for( int j=0; j<gf07.length; j++ ) {
214                                        // 5.1.1.2 (2009/12/10)
215                                        // 7.3.0.0 (2021/01/06) SEQNO がマイナスの場合、カラムに DESC を付ける(逆順カラム)
216                //                      buf.append( makeIndexClmStr( gf07[j][0], gf07[j][1] ) ).append( ',' );                          // 6.0.2.5 (2014/10/31) char を append する。
217                                        buf.append( makeIndexClmStr( gf07[j][0], gf07[j][1], gf07[j][2] ) ).append( ',' );      // 7.3.0.0 (2021/01/06)
218                                }
219                                buf.deleteCharAt( buf.length()-1 );                     // 最後の "," を取り除く処理
220
221                                // 5.6.9.2 (2013/10/18) DROP構文を出力する。
222                                if( isDrop ) {
223                                        writer.print( makeDropLine( clmNo,data ) );
224                                }
225                                // 6.0.2.3 (2014/10/10) isDrop=false の場合、まとめDropファイルを作成します。
226                                else {
227                                        dropWriter.print( makeDropLine( clmNo,data ) );
228                                }
229
230                                final String clms = buf.toString();
231                                writer.print( makeLineList( clmNo,data,clms ) );
232                                writer.println( makeEndLine( clmNo,data ) );
233                        }
234                        catch( final RuntimeException ex ) {
235                                // 6.5.0.1 (2016/10/21) ErrorMessage をまとめるのと、直接 Throwable を渡します。
236                                final ErrorMessage errMessage = makeErrorMessage( "TableFilter_INDEX Error",ErrorMessage.NG )
237                                        .addMessage( row+1,ErrorMessage.NG,"INDEX"
238                                                , "TABLE=[" + tableName + "],INDEX=[" + indexName + "]"
239                                                , StringUtil.array2csv( data )
240                                        )
241                                        .addMessage( ex );
242                                // BAT から呼び出す場合があるため、標準エラー出力にも情報を出しておきます。
243                                System.out.println( errMessage );
244                        }
245                }
246                if( isXml ) { writer.println( XML_END_TAG ); }
247                writer.close();                                 // 6.0.2.3 (2014/10/10) nullチェック不要。その前でエラーになるはず。
248                if( dropWriter != null ) {              // こちらは使わないケースがあるので、nullチェックは必要。
249                        if( isXml ) { dropWriter.println( XML_END_TAG ); }
250                        dropWriter.close();
251                }
252
253                return table;
254        }
255
256        /**
257         * ヘッダー部分の処理を実行します。
258         *
259         * @og.rev 5.6.6.0 (2013/07/05) FixLengthData の簡易コンストラクタを使用
260         *
261         * @param       clmNo   カラム番号配列
262         * @param       data    1行分のデータ配列
263         *
264         * @return      ヘッダー部分の文字列
265         * @og.rtnNotNull
266         */
267        protected String makeHeadLine( final int[] clmNo,final String[] data ) {
268                final String tableName = data[clmNo[TABLE_NAME]];
269                final String LINE1 = tableName + " ( " + data[clmNo[TABLE_LABEL]] + " )" ;
270                final String LINE2 = "Created : " + HybsSystem.getDate() ;
271
272                // 5.6.6.0 (2013/07/05) FixLengthData の簡易コンストラクタを使用
273                final int[] addLen = new int[] { 0,0,0 };       // 各データ間のスペース
274                final int[] type   = new int[] { X,K,X };       // 各データの種別 X:半角 S:空白前埋め K:全角混在
275                final FixLengthData fixData = new FixLengthData( addLen,type );
276
277                final String[][] outData = new String[][] {
278                        { "/**",        CMNT ,  "**/" },
279                        { "/* ",        LINE1,  " */" },
280                        { "/* ",        LINE2,  " */" },
281                        { "/**",        CMNT ,  "**/" },
282                };
283
284                fixData.addAllListData( outData );
285
286                return fixData.getAllFixData();
287        }
288
289        /**
290         * インデックス作成の処理を実行します。
291         *
292         * @og.rev 5.3.8.0 (2011/08/01) プライマリキー対応
293         * @og.rev 5.6.9.2 (2013/10/18) INDTYPE で、その他ではなく、2:通常 で判断する。
294         * @og.rev 6.4.0.5 (2016/01/09) INDTYPE が 9:未使用 の場合の処理を追加。
295         * @og.rev 6.4.4.1 (2016/03/18) StringBuilderの代わりに、OgBuilderを使用する。
296         *
297         * @param       clmNo   カラム番号配列
298         * @param       data    1行分のデータ配列
299         * @param   clms        カラム名(CSV形式)
300         *
301         * @return      作成された1行分の文字列
302         * @og.rtnNotNull
303         */
304        protected String makeLineList( final int[] clmNo,final String[] data,final String clms ) {
305                // 6.4.0.5 (2016/01/09) INDTYPE が 9:未使用 の場合の処理を追加。
306                final String idxtype   = data[clmNo[INDTYPE]];
307
308                if( "9".equals( idxtype ) ) { return ""; }              // 6.4.0.5 (2016/01/09)
309
310                final String tableName = data[clmNo[TABLE_NAME]];
311                final String indexName = data[clmNo[INDEX_NAME]];
312
313                return new OgBuilder()
314                                .appendCR()                                                                                             // 先頭に、改行を入れておきます。
315                                .appendIfCR( isXml , EXEC_START_TAG )
316                                .appendIf( "0".equals( idxtype )                                                        // 0:プライマリキー
317                                                        , "ALTER TABLE "                , tableName
318                                                        , " ADD CONSTRAINT "    , indexName
319                                                        , " PRIMARY KEY ( " , clms , " )" )
320                                .appendIf( "1".equals( idxtype )                                                        // 1:ユニークキー
321                                                        , "ALTER TABLE "                , tableName
322                                                        , " ADD CONSTRAINT "    , indexName
323                                                        , " UNIQUE( " , clms , " )" )
324                                .appendIf( "2".equals( idxtype )                                                        // 2:通常
325                                                        , "CREATE INDEX "               , indexName
326                                                        , " ON "                                , tableName
327                                                        , "( " , clms , " )" )
328                                .toString();
329        }
330
331        /**
332         * 定義の最後の部分の処理を実行します。
333         *
334         * 6.1.0.0 (2014/12/26) より、
335         *   1.TABLESPACE_NAME を指定しない場合は、TABLESPACE 句を出力しません。
336         *   2.INITIAL_EXTENT を 0 で指定した場合は、STORAGE 句を出力しません。
337         *   3.NEXT と PCTINCREASE は、出力しません。
338         *
339         * @og.rev 5.3.9.0 (2011/09/01) プライマリキー対応2
340         * @og.rev 6.0.2.3 (2014/10/10) isXml で、CR + EXEC_END_TAG のキャッシュ(execEndTag)を利用します。
341         * @og.rev 6.1.0.0 (2014/12/26) TABLESPACE_NAME,INITIAL_EXTENT が未設定の場合、設定しません。
342         * @og.rev 6.4.4.1 (2016/03/18) StringBuilderの代わりに、OgBuilderを使用する。
343         *
344         * @param       clmNo   カラム番号配列
345         * @param       data    1行分のデータ配列
346         *
347         * @return      定義の最後の部分
348         * @og.rtnNotNull
349         */
350        protected String makeEndLine( final int[] clmNo,final String[] data ) {
351
352                // 6.1.0.0 (2014/12/26) TABLESPACE_NAME,INITIAL_EXTENT が未設定の場合、設定しません。
353                final String tblSpcse = data[clmNo[TABLESPACE_NAME]] ;
354                final String initExt  = data[clmNo[INITIAL_EXTENT]] ;
355
356                final OgBuilder buf = new OgBuilder()
357                                .appendCR();                                                                                            // 先頭に、改行を入れておきます。
358
359                if( !StringUtil.isNull( tblSpcse ) || !StringUtil.isNull( initExt ) ) {
360                        final String idxtype   = data[clmNo[INDTYPE]];
361                        buf.appendIf( "0".equals( idxtype ) || "1".equals( idxtype )    // 0:プライマリキー , 1:ユニークキー
362                                                        , "USING INDEX " )
363                                .appendIfCR( !StringUtil.isNull( tblSpcse )
364                                                        , "TABLESPACE " , tblSpcse )
365                                .appendIfCR( !StringUtil.isNull( initExt ) && initExt.charAt(0) != '0'
366                                                        , "STORAGE( INITIAL " , initExt , "K )" );
367                }
368
369                return buf.append( execEndTag ).toString();
370        }
371
372        /**
373         * インデックス削除の構文を、作成します。
374         *
375         * @og.rev 5.6.9.2 (2013/10/18) 新規作成
376         * @og.rev 6.0.2.3 (2014/10/10) isXml で、CR + EXEC_END_TAG のキャッシュ(execEndTag)を利用します。
377         * @og.rev 6.4.4.1 (2016/03/18) StringBuilderの代わりに、OgBuilderを使用する。
378         *
379         * @param       clmNo   カラム番号配列
380         * @param       data    1行分のデータ配列
381         *
382         * @return      作成された1行分の文字列
383         * @og.rtnNotNull
384         */
385        protected String makeDropLine( final int[] clmNo,final String[] data ) {
386                final String tableName = data[clmNo[TABLE_NAME]];
387                final String indexName = data[clmNo[INDEX_NAME]];
388                final String idxtype   = data[clmNo[INDTYPE]];
389
390                return new OgBuilder()
391                                .appendCR()                                                                                                     // 先頭に、改行を入れておきます。
392                                .appendIfCR( isXml , EXEC_START_TAG )
393                                .appendIf( "0".equals( idxtype ) || "1".equals( idxtype )               // 0:プライマリキー、1:ユニークキー
394                                                        , "ALTER TABLE "                , tableName
395                                                        , " DROP CONSTRAINT "   , indexName )
396                                .appendIf( "2".equals( idxtype )                                                                // 2:通常
397                                                        , "DROP INDEX "                 , indexName )
398                                .append( execEndTag )
399                                .toString();
400        }
401
402        /**
403         * インデックスを作成するための文字列を返します。
404         * 通常、カラム名をそのまま返します。
405         *
406         * 7.3.0.0 (2021/01/06)
407         *   seqNoがマイナスの場合は、カラム名に DESC を付けて逆インデックスにします。
408         *
409         * ※ ORACLEの場合、逆インデックスはバグがあったり、正インデックスで自動判断するそうなので、
410         *    基本的には使わない方が良いそうです。
411         *
412         * ※ FIREBERD には、カラムごとの逆インデックスは定義できません。
413         *    エラーチェックは入れていませんので、ご注意ください。
414         *
415         * ※ MySQL は、8.0で採用されています。それ以前のバージョンでは動作しません。
416         * ※ MySQL の 500バイト以上のカラムのインデックス制限が解除されているかどうかは、未調査です。
417         *
418         * @og.rev 7.3.0.0 (2021/01/06) SEQNO がマイナスの場合、カラムに DESC を付ける(逆順カラム)
419         *
420         * @param       clm             カラム名
421         * @param       useLen  カラムのバイト数
422         * @param       seqNo   カラム順(マイナスの場合は、逆順)…DERBY以外には使用しないことにします。
423         *
424         * @return      インデックスカラムの文字列
425         * @see TableFilter_INDEX_MYSQL
426         */
427//      protected String makeIndexClmStr( final String clm, final String useLen ) {
428        protected String makeIndexClmStr( final String clm, final String useLen, final String seqNo ) {
429                return clm;
430        }
431}