チェンジセット 236

差分発生行の前後
無視リスト:
コミット日時:
2008/02/09 17:58:29 (4 年前)
コミッタ:
daoki2
ログメッセージ:

support drop/truncate and build SQL statement

ファイル:

凡例:

変更無し
追加
削除
更新
コピー
移動
  • as3/Utils/src/org/libspark/utils/SqlUtil.as

    r205 r236  
    33 * 
    44 * @author      Copyright (c) 2008 daoki2 
    5  * @version     1.0.1 
     5 * @version     1.0.2 
    66 * @link        http://snippets.libspark.org/ 
    77 * @link        http://homepage.mac.com/daoki2/ 
     
    4444 
    4545       /** 
     46        * Build Insert SQL Statement 
     47        * @param        table   Table to insert data 
     48        * @param        rows    Data to insert 
     49        * @return               Insert SQL Statement 
     50        */ 
     51        public static function buildInsert(table:String, rows:ArrayCollection):String { 
     52            var sql:String = "INSERT INTO " + table + "("; 
     53            for each(var val:* in rows) 
     54                sql += val.column + ", "; 
     55            sql = sql.substring(0, sql.length - 2); 
     56            sql += ") VALUES ("; 
     57            for each(val in rows) { 
     58                if (val.type == "TEXT") { 
     59                    sql += "'"; 
     60                    if (val.value != null) 
     61                        sql += val.value; 
     62                    sql += "'"; 
     63                } else { 
     64                    sql += val.value; 
     65                } 
     66                sql += ", "; 
     67            } 
     68            sql = sql.substring(0, sql.length - 2); 
     69            sql += ")"; 
     70            return sql; 
     71        } 
     72 
     73       /** 
     74        * Build Select All SQL Statement 
     75        * @param        db      The SQLConnection of the specified DataBase 
     76        * @param        table   Table to build the SQL statement 
     77        * @return               Select All SQL Statement 
     78        */ 
     79        static public function buildSelectAll(db:SQLConnection, table:String):String { 
     80            var columns:ArrayCollection = getColumnDef(db, table); 
     81            var sql:String = "SELECT "; 
     82            for each(var val:* in columns) 
     83                sql += val.name + ", "; 
     84            sql = sql.substring(0, sql.length - 2); 
     85            sql += " FROM " + table; 
     86            return sql; 
     87        } 
     88 
     89       /** 
     90        * Build Create Table SQL Statement 
     91        * @param        db      The SQLConnection of the specified DataBase 
     92        * @param        table   Table to build the SQL statement 
     93        * @return               Create Table SQL Statement 
     94        */ 
     95        static public function buildTableDefs(db:SQLConnection, table:String):Array { 
     96            var result:Array = new Array(); 
     97            var sqlschema:SQLSchemaResult; 
     98            try { 
     99                db.loadSchema(SQLTableSchema, table); 
     100                sqlschema = db.getSchemaResult(); 
     101                result.push(sqlschema.tables[0].sql); 
     102                db.loadSchema(SQLIndexSchema, table); 
     103                sqlschema = db.getSchemaResult(); 
     104                for each (var val:* in sqlschema.indices) { 
     105                    result.push(val.sql); 
     106                } 
     107            } catch (err:Error) { 
     108            } 
     109            return result; 
     110        } 
     111 
     112       /** 
     113        * Drop the specified index from the DataBase 
     114        * @param        db              The SQLConnection of the specified DataBase 
     115        * @param        index           The Index to drop from DataBase 
     116        * @return       true/false      If it succed to drop the index   
     117        */ 
     118        static public function dropIndex(db:SQLConnection, index:String):Boolean { 
     119            var result:Object; 
     120 
     121            if (index == "" || index == null) 
     122                return false; 
     123 
     124            var sql:String = "DROP INDEX IF EXISTS " + index; 
     125 
     126            result = executeSQLStatement(db, sql); 
     127            if (!result.status) 
     128                Alert.show(result.message, "ERROR!:dropIndex"); 
     129            return result.status; 
     130        } 
     131 
     132       /** 
     133        * Drop the specified table from the DataBase 
     134        * @param        db              The SQLConnection of the specified DataBase 
     135        * @param        table           The Table to drop from DataBase 
     136        * @return       true/false      If it succed to drop the table   
     137        */ 
     138        static public function dropTable(db:SQLConnection, table:String):Boolean { 
     139            var result:Object; 
     140 
     141            if (table == "" || table == null) 
     142                return false; 
     143 
     144            var sql:String = "DROP TABLE IF EXISTS " + table; 
     145 
     146            result = executeSQLStatement(db, sql); 
     147            if (!result.status) 
     148                Alert.show(result.message, "ERROR!:dropTable"); 
     149            return result.status; 
     150        } 
     151 
     152       /** 
    46153        * Create index of the specified table 
    47154        * @param        db              The SQLConnection of the specified DataBase 
     
    54161        */ 
    55162        static public function createIndex(db:SQLConnection, table:String, indexDefs:ArrayCollection):Boolean { 
    56             var result:Boolean = true; 
    57             var stmt:SQLStatement = new SQLStatement; 
    58             stmt.sqlConnection = db; 
     163            var result:Object; 
     164            var lastResult:Boolean = true 
    59165            var sql:String = ""; 
    60166            for each(var val:* in indexDefs) { 
    61167                sql = "CREATE INDEX IF NOT EXISTS " + val.name + " ON " + table + "(" + val.columns + ")"; 
    62                 stmt.text = sql; 
    63                 try { 
    64                     stmt.execute(); 
    65                 } catch (err:Error) { 
    66                     Alert.show(err.toString(), "ERROR!:createIndex"); 
    67                     result = false; 
     168 
     169                result = executeSQLStatement(db, sql); 
     170                if (!result.status) { 
     171                    Alert.show(result.message, "ERROR!:createIndex"); 
     172                    lastResult = false; 
    68173                } 
    69174            } 
    70             return result; 
     175            return lastResult; 
    71176        } 
    72177 
     
    85190        */ 
    86191        static public function createTable(db:SQLConnection, table:String, tableDefs:ArrayCollection):Boolean { 
    87             var result:Boolean = true; 
    88             var stmt:SQLStatement = new SQLStatement; 
    89             stmt.sqlConnection = db; 
     192            var result:Object; 
    90193            var sql:String = "CREATE TABLE IF NOT EXISTS " + table + " ("; 
    91194            for each(var val:* in tableDefs) { 
     
    99202                sql += ", "; 
    100203            } 
    101             stmt.text = sql.substr(0, sql.length - 2); 
    102             stmt.text += ")"; 
    103             try { 
    104                 stmt.execute(); 
    105             } catch (err:Error) { 
    106                 Alert.show(err.toString(), "ERROR!:createTable"); 
    107                 result = false; 
    108             } 
    109             return result; 
     204            sql = sql.substr(0, sql.length - 2); 
     205            sql += ")"; 
     206 
     207            result = executeSQLStatement(db, sql); 
     208            if (!result.status) 
     209                Alert.show(result.message, "ERROR!:createTable"); 
     210 
     211            return result.status; 
    110212        } 
    111213 
     
    119221        */ 
    120222        static public function deleteRow(db:SQLConnection, table:String, keyColumn:String, keyValue:int):Boolean { 
    121             var result:Boolean = false
     223            var result:Object
    122224            var sql:String = "DELETE FROM " + table + " WHERE " + keyColumn + " = " + keyValue; 
    123             try { 
    124                 var stmt:SQLStatement = new SQLStatement; 
    125                 stmt.sqlConnection = db; 
    126                 stmt.text = sql; 
    127                 stmt.execute(); 
    128             } catch (err:Error) { 
    129                 Alert.show(err.toString(), "ERROR!:update"); 
    130                 result = false; 
    131             } 
    132             return result; 
    133  
     225 
     226            result = executeSQLStatement(db, sql); 
     227            if (!result.status) 
     228                Alert.show(result.message, "ERROR!:delete"); 
     229            return result.status; 
    134230        } 
    135231 
     
    168264                } 
    169265            } 
     266            return result; 
     267        } 
     268 
     269       /** 
     270        * Get the columns definition of the specified table 
     271        * @param        db      The SQLConnection of the specified DataBase 
     272        * @param        table   The table name which you want the column defs 
     273        * @return               The ArrayCollection of the columns definition 
     274        *                       and it contains the following params 
     275        *                        - name         : Column name 
     276        *                        - type         : The Data type of the column 
     277        *                        - primaryKey   : If this column is primary key 
     278        *                        - autoIncrement: If this column increment automatically 
     279        *                        - allowNull    : If this column allow null value 
     280        */ 
     281        static public function getColumnDef(db:SQLConnection, table:String):ArrayCollection { 
     282            var result:ArrayCollection = new ArrayCollection(); 
     283            db.loadSchema(SQLTableSchema, table); 
     284            var sqlschema:SQLSchemaResult = db.getSchemaResult(); 
     285            for each(var column:* in sqlschema.tables[0].columns) 
     286                result.addItem({name:column.name, type:column.dataType, primaryKey:column.primaryKey, 
     287                    autoIncrement:column.autoIncrement, allowNull:column.allowNull}); 
     288            return result; 
     289        } 
     290 
     291       /** 
     292        * Get the Data & Column Defs of the table 
     293        * @param        db      The SQLConnection of the specified DataBase 
     294        * @param        sql     The SQL string 
     295        * @return       result  The Array which contains column defs and data 
     296        *                       The following are the description 
     297        *                        - result[0]: The Array of the columns name 
     298        *                        - result[1]: The SQLResult of the sql which executed 
     299        */ 
     300        static public function getData(db:SQLConnection, sql:String):Array { 
     301            var result:Array = new Array(); 
     302            var columns:Array = getResultColumns(sql); 
     303            var resultData:SQLResult = getResultData(db, sql); 
     304            result.push(columns); 
     305            result.push(resultData); 
    170306            return result; 
    171307        } 
     
    200336 
    201337       /** 
     338        * Get the row count of the table 
     339        * @param        db      The SQLConnection of the specified DataBase 
     340        * @param        table   The table name which you want to get the row count 
     341        * @return               The row count of the table 
     342        */ 
     343        static public function getRowCount(db:SQLConnection, table:String):uint { 
     344            var sql:String = "select count(*) as count from " + table; 
     345            var row:SQLResult = getResultData(db, sql); 
     346            if (row != null) 
     347                return row.data[0].count; 
     348            return 0; 
     349        } 
     350 
     351       /** 
    202352        * Get the table list of the specified DataBase 
    203353        * @param        db      The SQLConnection of the specified DataBase 
     
    218368 
    219369       /** 
    220         * Get the columns definition of the specified table 
    221         * @param        db      The SQLConnection of the specified DataBase 
    222         * @param        table   The table name which you want the column defs 
    223         * @return               The ArrayCollection of the columns definition 
    224         *                       and it contains the following params 
    225         *                        - name         : Column name 
    226         *                        - type         : The Data type of the column 
    227         *                        - primaryKey   : If this column is primary key 
    228         *                        - autoIncrement: If this column increment automatically 
    229         *                        - allowNull    : If this column allow null value 
    230         */ 
    231         static public function getColumnDef(db:SQLConnection, table:String):ArrayCollection { 
    232             var result:ArrayCollection = new ArrayCollection(); 
    233             db.loadSchema(SQLTableSchema, table); 
    234             var sqlschema:SQLSchemaResult = db.getSchemaResult(); 
    235             for each(var column:* in sqlschema.tables[0].columns) 
    236                 result.addItem({name:column.name, type:column.dataType, primaryKey:column.primaryKey, 
    237                     autoIncrement:column.autoIncrement, allowNull:column.allowNull}); 
    238             return result; 
    239         } 
    240  
    241        /** 
    242         * Get the row count of the table 
    243         * @param        db      The SQLConnection of the specified DataBase 
    244         * @param        table   The table name which you want to get the row count 
    245         * @return               The row count of the table 
    246         */ 
    247         static public function getRowCount(db:SQLConnection, table:String):uint { 
    248             var sql:SQLStatement = new SQLStatement(); 
    249             sql.sqlConnection = db; 
    250             sql.text = "select count(*) as count from " + table; 
     370        * Insert row to the specified table 
     371        * @param        db              The SQLConnection of the specified DataBase 
     372        * @param        table           The table to insert the data 
     373        * @param        rows            The ArrayCollection of the data to insert 
     374        *                               and it contains the following params 
     375        *                                - column: Column name  
     376        *                                - value : Column value 
     377        *                                - type  : Data type of the column 
     378        * @return       true/false      If it succeed to insert the row data 
     379        */ 
     380        public static function insertRow(db:SQLConnection, table:String, rows:ArrayCollection):Boolean { 
     381            var result:Object; 
     382            var sql:String = buildInsert(table, rows); 
     383 
     384            result = executeSQLStatement(db, sql); 
     385            if (!result.status) 
     386                Alert.show(result.message, "ERROR!:insert"); 
     387            return result.status; 
     388        } 
     389 
     390       /** 
     391        * Remove the whole data of the specified table 
     392        * @param        db              The SQLConnection of the specified DataBase 
     393        * @param        table           The table to remove the whole data 
     394        * @parem        keyColumn       The column name of the primary key 
     395        * @return       true/false      If it succed to trancate the table       
     396        */ 
     397        static public function trancateTable(db:SQLConnection, table:String, keyColumn:String):Boolean { 
     398            var result:Object; 
     399 
     400            if (table == "" || table == null || keyColumn == "" || keyColumn == null) 
     401                return false; 
     402 
     403            var sql:String = "DELETE FROM " + table + " WHERE " + keyColumn + " > 0"; 
     404 
     405            result = executeSQLStatement(db, sql); 
     406            if (!result.status) 
     407                Alert.show(result.message, "ERROR!:trancateTable"); 
     408            return result.status; 
     409        } 
     410 
     411       /** 
     412        * Update row of the specified table 
     413        * @param        db              The SQLConnection of the specified DataBase 
     414        * @param        table           The table to update the data 
     415        * @param        keyColumn       The column name to specify the row 
     416        * @param        keyValue        The column value to specify the row 
     417        * @param        updateColumn    The column name to update 
     418        * @param        updateValue     The column value to update 
     419        * @param        updateType      The data type of the column to update 
     420        * @return       true/false      If it succeed to update the row data 
     421        */ 
     422        public static function updateRow(db:SQLConnection, table:String, keyColumn:String, keyValue:int, 
     423                                   updateColumn:String, updateValue:String, updateType:String):Boolean { 
     424            var result:Object; 
     425 
     426            if (updateType == "TEXT") 
     427                updateValue = "'" + updateValue + "'"; 
     428 
     429            var sql:String = "UPDATE " + table + " SET " + updateColumn + " = " + updateValue 
     430                           + " WHERE " + keyColumn + " = " + keyValue; 
     431 
     432            result = executeSQLStatement(db, sql); 
     433            if (!result.status) 
     434                Alert.show(result.message, "ERROR!:update"); 
     435            return result.status; 
     436        } 
     437 
     438       /** 
     439        * private method 
     440        */ 
     441 
     442       /** 
     443        * Execute SQL statement 
     444        */ 
     445        public static function executeSQLStatement(db:SQLConnection, sql:String):Object { 
     446            var status:Boolean = true; 
     447            var message:String = ""; 
    251448            try { 
    252                 sql.execute(); 
    253                 var row:SQLResult = sql.getResult(); 
    254                 return row.data[0].count; 
    255             } catch(err:Error) { 
    256                 Alert.show(err.toString(), "ERROR!:getRowCount"); 
    257                 return 0; 
    258             } 
    259             return 0; 
    260         } 
    261  
    262        /** 
    263         * Get the Data & Column Defs of the table 
    264         * @param        db      The SQLConnection of the specified DataBase 
    265         * @param        sql     The SQL string 
    266         * @return       result  The Array which contains column defs and data 
    267         *                       The following are the description 
    268         *                        - result[0]: The Array of the columns name 
    269         *                        - result[1]: The SQLResult of the sql which executed 
    270         */ 
    271         static public function getData(db:SQLConnection, sql:String):Array { 
    272             var result:Array = new Array(); 
    273             var columns:Array = getResultColumns(sql); 
    274             var resultData:SQLResult = getResultData(db, sql); 
    275             result.push(columns); 
    276             result.push(resultData); 
    277             return result; 
     449                var stmt:SQLStatement = new SQLStatement; 
     450                stmt.sqlConnection = db; 
     451                stmt.text = sql; 
     452                stmt.execute(); 
     453            } catch (err:Error) { 
     454                status = false; 
     455                message = err.toString(); 
     456            } 
     457            return {status: status, message: message}; 
    278458        } 
    279459 
     
    281461        * Get the Columns of the Result set 
    282462        */ 
    283         static private function getResultColumns(sql:String):Array { 
     463        private static function getResultColumns(sql:String):Array { 
    284464            var result:Array = new Array(); 
    285465            var startIndex:Number = 0; 
     
    306486                startIndex = val.toUpperCase().search("AS "); 
    307487                if (startIndex == -1) 
    308                     result.push(rm_ws(val)); 
     488                    result.push(removeWhitespace(val)); 
    309489                else 
    310                     result.push(rm_ws(val.slice(startIndex + 3))); 
    311             } 
    312             return result; 
    313         } 
    314  
    315        /** 
    316         * Remove the white space from the string 
    317         */ 
    318         private static function rm_ws(txt:String):String { 
    319             var val:String = ""; 
    320             for (var i:int = 0; i < txt.length; i++) 
    321                 if (txt.charAt(i) != ' ') 
    322                     val += txt.charAt(i); 
    323             return val; 
     490                    result.push(removeWhitespace(val.slice(startIndex + 3))); 
     491            } 
     492            return result; 
    324493        } 
    325494 
     
    336505            } catch(err:Error) { 
    337506                Alert.show(err.toString(), "ERROR!:getResultData"); 
     507                //trace("getResultData:", sql); 
    338508                return null; 
    339509            } 
     
    342512 
    343513       /** 
    344         * Insert row to the specified table 
    345         * @param        db              The SQLConnection of the specified DataBase 
    346         * @param        table           The table to insert the data 
    347         * @param        rows            The ArrayCollection of the data to insert 
    348         *                               and it contains the following params 
    349         *                                - column: Column name  
    350         *                                - value : Column value 
    351         *                                - type  : Data type of the column 
    352         * @return       true/false      If it succeed to insert the row data 
    353         */ 
    354         public static function insertRow(db:SQLConnection, table:String, rows:ArrayCollection):Boolean { 
    355             var result:Boolean = true; 
    356             var sql:String = "INSERT INTO " + table + "("; 
    357             for each(var val:* in rows) 
    358                 sql += val.column + ", "; 
    359             sql = sql.substring(0, sql.length - 2); 
    360             sql += ") VALUES ("; 
    361             for each(val in rows) { 
    362                 if (val.type == "TEXT") { 
    363                     sql += "'"; 
    364                     if (val.value != null) 
    365                         sql += val.value; 
    366                     sql += "'"; 
    367                 } else { 
    368                     sql += val.value; 
    369                 } 
    370                 sql += ", "; 
    371             } 
    372             sql = sql.substring(0, sql.length - 2); 
    373             sql += ")"; 
    374             try { 
    375                 var stmt:SQLStatement = new SQLStatement(); 
    376                 stmt.sqlConnection = db; 
    377                 stmt.text = sql; 
    378                 stmt.execute(); 
    379             } catch (err:Error) { 
    380                 Alert.show(err.toString(), "ERROR!:insert"); 
    381                 result = false; 
    382             } 
    383             return result; 
    384         } 
    385  
    386        /** 
    387         * Update row of the specified table 
    388         * @param        db              The SQLConnection of the specified DataBase 
    389         * @param        table           The table to update the data 
    390         * @param        keyColumn       The column name to specify the row 
    391         * @param        keyValue        The column value to specify the row 
    392         * @param        updateColumn    The column name to update 
    393         * @param        updateValue     The column value to update 
    394         * @param        updateType      The data type of the column to update 
    395         * @return       true/false      If it succeed to update the row data 
    396         */ 
    397         public static function updateRow(db:SQLConnection, table:String, keyColumn:String, keyValue:int, 
    398                                    updateColumn:String, updateValue:String, updateType:String):Boolean { 
    399             var result:Boolean = true; 
    400  
    401             if (updateType == "TEXT") 
    402                 updateValue = "'" + updateValue + "'"; 
    403  
    404             var sql:String = "UPDATE " + table + " SET " + updateColumn + " = " + updateValue 
    405                            + " WHERE " + keyColumn + " = " + keyValue; 
    406             try { 
    407                 var stmt:SQLStatement = new SQLStatement; 
    408                 stmt.sqlConnection = db; 
    409                 stmt.text = sql; 
    410                 stmt.execute(); 
    411             } catch (err:Error) { 
    412                 Alert.show(err.toString(), "ERROR!:update"); 
    413                 result = false; 
    414             } 
    415             return result; 
     514        * Remove the white space from the string 
     515        */ 
     516        private static function removeWhitespace(txt:String):String { 
     517            var val:String = ""; 
     518            for (var i:int = 0; i < txt.length; i++) 
     519                if (txt.charAt(i) != ' ') 
     520                    val += txt.charAt(i); 
     521            return val; 
    416522        } 
    417523    }