root/as3/Utils/src/org/libspark/utils/SqlUtil.as

リビジョン 804, 20.3 kB (コミッタ: michi, コミット時期: 6 ヶ月 前)

asdoc追加

  • svn:executable 属性の設定値: *
Line 
1 /**
2  * The SQLite Utility Class for ActionScript 3.0
3  *
4  * @author      Copyright (c) 2008 daoki2
5  * @version     1.0.2
6  * @link        http://snippets.libspark.org/
7  * @link        http://homepage.mac.com/daoki2/
8  *
9  * Copyright (c) 2008 daoki2
10  *
11  * Permission is hereby granted, free of charge, to any person obtaining a copy
12  * of this software and associated documentation files (the "Software"), to deal
13  * in the Software without restriction, including without limitation the rights
14  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15  * copies of the Software, and to permit persons to whom the Software is
16  * furnished to do so, subject to the following conditions:
17  *
18  * The above copyright notice and this permission notice shall be included in
19  * all copies or substantial portions of the Software.
20  *
21  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27  * THE SOFTWARE.
28  */
29
30 package org.libspark.utils {
31     import flash.errors.IllegalOperationError;
32     import mx.collections.ArrayCollection;
33     import mx.controls.Alert;
34     import flash.data.*;
35
36         /**
37          * <span style="color:#FF0000; font-weight:bold;">(Flex Only)</span>
38          */
39     public class SqlUtil {
40
41        /**
42         * Constructor
43         */
44         public function SqlUtil() {
45             throw new IllegalOperationError("SqlUtil class can not create instance");
46         }
47
48        /**
49         * Build Insert SQL Statement
50         * @param        table   Table to insert data
51         * @param        rows    Data to insert
52         * @return               Insert SQL Statement
53         */
54         public static function buildInsert(table:String, rows:ArrayCollection):String {
55             var sql:String = "INSERT INTO " + table + "(";
56             for each(var val:* in rows)
57                 sql += val.column + ", ";
58             sql = sql.substring(0, sql.length - 2);
59             sql += ") VALUES (";
60             for each(val in rows) {
61                 if (val.type == "TEXT") {
62                     sql += "'";
63                     if (val.value != null)
64                         sql += val.value;
65                     sql += "'";
66                 } else {
67                     sql += val.value;
68                 }
69                 sql += ", ";
70             }
71             sql = sql.substring(0, sql.length - 2);
72             sql += ")";
73             return sql;
74         }
75
76        /**
77         * Build Select All SQL Statement
78         * @param        db      The SQLConnection of the specified DataBase
79         * @param        table   Table to build the SQL statement
80         * @return               Select All SQL Statement
81         */
82         static public function buildSelectAll(db:SQLConnection, table:String):String {
83             var columns:ArrayCollection = getColumnDef(db, table);
84             var sql:String = "SELECT ";
85             for each(var val:* in columns)
86                 sql += val.name + ", ";
87             sql = sql.substring(0, sql.length - 2);
88             sql += " FROM " + table;
89             return sql;
90         }
91
92        /**
93         * Build Create Table SQL Statement
94         * @param        db      The SQLConnection of the specified DataBase
95         * @param        table   Table to build the SQL statement
96         * @return               Create Table SQL Statement
97         */
98         static public function buildTableDefs(db:SQLConnection, table:String):Array {
99             var result:Array = new Array();
100             var sqlschema:SQLSchemaResult;
101             try {
102                 db.loadSchema(SQLTableSchema, table);
103                 sqlschema = db.getSchemaResult();
104                 result.push(sqlschema.tables[0].sql);
105                 db.loadSchema(SQLIndexSchema, table);
106                 sqlschema = db.getSchemaResult();
107                 for each (var val:* in sqlschema.indices) {
108                     result.push(val.sql);
109                 }
110             } catch (err:Error) {
111             }
112             return result;
113         }
114
115        /**
116         * Drop the specified index from the DataBase
117         * @param        db              The SQLConnection of the specified DataBase
118         * @param        index           The Index to drop from DataBase
119         * @return       true/false      If it succed to drop the index 
120         */
121         static public function dropIndex(db:SQLConnection, index:String):Boolean {
122             var result:Object;
123
124             if (index == "" || index == null)
125                 return false;
126
127             var sql:String = "DROP INDEX IF EXISTS " + index;
128
129             result = executeSQLStatement(db, sql);
130             if (!result.status)
131                 Alert.show(result.message, "ERROR!:dropIndex");
132             return result.status;
133         }
134
135        /**
136         * Drop the specified table from the DataBase
137         * @param        db              The SQLConnection of the specified DataBase
138         * @param        table           The Table to drop from DataBase
139         * @return       true/false      If it succed to drop the table 
140         */
141         static public function dropTable(db:SQLConnection, table:String):Boolean {
142             var result:Object;
143
144             if (table == "" || table == null)
145                 return false;
146
147             var sql:String = "DROP TABLE IF EXISTS " + table;
148
149             result = executeSQLStatement(db, sql);
150             if (!result.status)
151                 Alert.show(result.message, "ERROR!:dropTable");
152             return result.status;
153         }
154
155        /**
156         * Create index of the specified table
157         * @param        db              The SQLConnection of the specified DataBase
158         * @param        table           The table to create index
159         * @param        indexDefs       ArrayCollection of the index definition
160         *                               and it contains the following params.
161         *                                - name   : Index name
162         *                                - columns: The list of the column
163         * @return       true/false      If it succeed to create the index
164         */
165         static public function createIndex(db:SQLConnection, table:String, indexDefs:ArrayCollection):Boolean {
166             var result:Object;
167             var lastResult:Boolean = true
168             var sql:String = "";
169             for each(var val:* in indexDefs) {
170                 sql = "CREATE INDEX IF NOT EXISTS " + val.name + " ON " + table + "(" + val.columns + ")";
171
172                 result = executeSQLStatement(db, sql);
173                 if (!result.status) {
174                     Alert.show(result.message, "ERROR!:createIndex");
175                     lastResult = false;
176                 }
177             }
178             return lastResult;
179         }
180
181        /**
182         * Create table to the specified database
183         * @param        db              The SQLConnection of the specified DataBase
184         * @param        table           The table name
185         * @param        tableDefs       ArrayCollection of the table definition
186         *                               and it contains the following params.
187         *                                - name         : Column name
188         *                                - type         : The data type of the column
189         *                                - primaryKey   : If the column is primary key
190         *                                - autoIncrement: If it will increment the value automatically
191         *                                - allowNull    : If the column allows null value
192         * @return       true/false      If it succeed to create the table
193         */
194         static public function createTable(db:SQLConnection, table:String, tableDefs:ArrayCollection):Boolean {
195             var result:Object;
196             var sql:String = "CREATE TABLE IF NOT EXISTS " + table + " (";
197             for each(var val:* in tableDefs) {
198                 sql += val.name + " " + val.type;
199                 if (val.primaryKey)
200                     sql += " " + "PRIMARY KEY";
201                 if (val.autoIncrement)
202                     sql += " " + "AUTOINCREMENT";
203                 if (!val.allowNull)
204                     sql += " " + "NOT NULL";
205                 sql += ", ";
206             }
207             sql = sql.substr(0, sql.length - 2);
208             sql += ")";
209
210             result = executeSQLStatement(db, sql);
211             if (!result.status)
212                 Alert.show(result.message, "ERROR!:createTable");
213
214             return result.status;
215         }
216
217        /**
218         * Delete row from the specified table
219         * @param        db              The SQLConnection of the specified DataBase
220         * @param        table           The table to delete the row
221         * @param        keyColumn       The column name that specify the row
222         * @param        keyValue        The column value that specify the row
223         * @return       true/false      If it succeed to delete the row
224         */
225         static public function deleteRow(db:SQLConnection, table:String, keyColumn:String, keyValue:int):Boolean {
226             var result:Object;
227             var sql:String = "DELETE FROM " + table + " WHERE " + keyColumn + " = " + keyValue;
228
229             result = executeSQLStatement(db, sql);
230             if (!result.status)
231                 Alert.show(result.message, "ERROR!:delete");
232             return result.status;
233         }
234
235        /**
236         * Check if the index exists in the specified table
237         * @param        db              The SQLConnection of the specified DataBase
238         * @param        table           The table if contains the index
239         * @param        index           The index name to check
240         * @return       true/false      If the index exists in the table
241         */
242         static public function existsIndex(db:SQLConnection, table:String, index:String):Boolean {
243             var result:Boolean = false;
244             var indexList:ArrayCollection = getIndexList(db, table);
245             for each(var val:* in indexList) {
246                 if(val.name == index) {
247                     result = true;
248                     break;
249                 }
250             }
251             return result;
252         }
253
254        /**
255         * Check if the table exists in the database
256         * @param        db              The SQLConnection of the specified DataBase
257         * @param        table           The table name to check
258         * @return       true/false      If the table exists in the table
259         */
260         static public function existsTable(db:SQLConnection, table:String):Boolean {
261             var result:Boolean = false;
262             var tableList:Array = getTableList(db);
263             for each(var val:* in tableList) {
264                 if(val == table) {
265                     result = true;
266                     break;
267                 }
268             }
269             return result;
270         }
271
272        /**
273         * Get the columns definition of the specified table
274         * @param        db      The SQLConnection of the specified DataBase
275         * @param        table   The table name which you want the column defs
276         * @return               The ArrayCollection of the columns definition
277         *                       and it contains the following params
278         *                        - name         : Column name
279         *                        - type         : The Data type of the column
280         *                        - primaryKey   : If this column is primary key
281         *                        - autoIncrement: If this column increment automatically
282         *                        - allowNull    : If this column allow null value
283         */
284         static public function getColumnDef(db:SQLConnection, table:String):ArrayCollection {
285             var result:ArrayCollection = new ArrayCollection();
286             db.loadSchema(SQLTableSchema, table);
287             var sqlschema:SQLSchemaResult = db.getSchemaResult();
288             for each(var column:* in sqlschema.tables[0].columns)
289                 result.addItem({name:column.name, type:column.dataType, primaryKey:column.primaryKey,
290                     autoIncrement:column.autoIncrement, allowNull:column.allowNull});
291             return result;
292         }
293
294        /**
295         * Get the Data & Column Defs of the table
296         * @param        db      The SQLConnection of the specified DataBase
297         * @param        sql     The SQL string
298         * @return       result  The Array which contains column defs and data
299         *                       The following are the description
300         *                        - result[0]: The Array of the columns name
301         *                        - result[1]: The SQLResult of the sql which executed
302         */
303         static public function getData(db:SQLConnection, sql:String):Array {
304             var result:Array = new Array();
305             var columns:Array = getResultColumns(sql);
306             var resultData:SQLResult = getResultData(db, sql);
307             result.push(columns);
308             result.push(resultData);
309             return result;
310         }
311
312        /**
313         * Get the index list of the specified table
314         * @param        db      The SQLConnection of the specified DataBase
315         * @param        table   The table to get the list of index
316         * @return               The ArrayCollection of the index
317         *                       and it contains the following params
318         *                        - name   : Index name
319         *                        - columns: The column list
320         */
321         static public function getIndexList(db:SQLConnection, table:String):ArrayCollection {
322             var result:ArrayCollection = new ArrayCollection();
323             try {
324                 db.loadSchema(SQLIndexSchema, table);
325                 var sqlschema:SQLSchemaResult = db.getSchemaResult();
326                 for each(var index:* in sqlschema.indices) {
327                     if (table == null)
328                         result.addItem({name: index.name, columns: ""});
329                     else
330                         result.addItem({name: index.name,
331                                columns: index.sql.substring(index.sql.search("ON " + table)
332                                             + table.length + 4, index.sql.length - 1)});
333                 }
334             } catch (err:Error) {
335                 //Alert.show(err.toString(), "ERROR!:getIndexList");
336             }
337             return result;
338         }
339
340        /**
341         * Get the row count of the table
342         * @param        db      The SQLConnection of the specified DataBase
343         * @param        table   The table name which you want to get the row count
344         * @return               The row count of the table
345         */
346         static public function getRowCount(db:SQLConnection, table:String):uint {
347             var sql:String = "select count(*) as count from " + table;
348             var row:SQLResult = getResultData(db, sql);
349             if (row != null)
350                 return row.data[0].count;
351             return 0;
352         }
353
354        /**
355         * Get the table list of the specified DataBase
356         * @param        db      The SQLConnection of the specified DataBase
357         * @return               The Array of the table name
358         */
359         static public function getTableList(db:SQLConnection):Array {
360             var result:Array = new Array();
361             try {
362                 db.loadSchema(SQLTableSchema);
363                 var sqlschema:SQLSchemaResult = db.getSchemaResult();
364                 for each(var table:* in sqlschema.tables)
365                     result.push(SQLTableSchema(table).name);
366             } catch (err:Error) {
367                 //Alert.show(err.toString(), "ERROR!");
368             }
369             return result;
370         }
371
372        /**
373         * Insert row to the specified table
374         * @param        db              The SQLConnection of the specified DataBase
375         * @param        table           The table to insert the data
376         * @param        rows            The ArrayCollection of the data to insert
377         *                               and it contains the following params
378         *                                - column: Column name
379         *                                - value : Column value
380         *                                - type  : Data type of the column
381         * @return       true/false      If it succeed to insert the row data
382         */
383         public static function insertRow(db:SQLConnection, table:String, rows:ArrayCollection):Boolean {
384             var result:Object;
385             var sql:String = buildInsert(table, rows);
386
387             result = executeSQLStatement(db, sql);
388             if (!result.status)
389                 Alert.show(result.message, "ERROR!:insert");
390             return result.status;
391         }
392
393        /**
394         * Remove the whole data of the specified table
395         * @param        db              The SQLConnection of the specified DataBase
396         * @param        table           The table to remove the whole data
397         * @parem        keyColumn       The column name of the primary key
398         * @return       true/false      If it succed to trancate the table     
399         */
400         static public function trancateTable(db:SQLConnection, table:String, keyColumn:String):Boolean {
401             var result:Object;
402
403             if (table == "" || table == null || keyColumn == "" || keyColumn == null)
404                 return false;
405
406             var sql:String = "DELETE FROM " + table + " WHERE " + keyColumn + " > 0";
407
408             result = executeSQLStatement(db, sql);
409             if (!result.status)
410                 Alert.show(result.message, "ERROR!:trancateTable");
411             return result.status;
412         }
413
414        /**
415         * Update row of the specified table
416         * @param        db              The SQLConnection of the specified DataBase
417         * @param        table           The table to update the data
418         * @param        keyColumn       The column name to specify the row
419         * @param        keyValue        The column value to specify the row
420         * @param        updateColumn    The column name to update
421         * @param        updateValue     The column value to update
422         * @param        updateType      The data type of the column to update
423         * @return       true/false      If it succeed to update the row data
424         */
425         public static function updateRow(db:SQLConnection, table:String, keyColumn:String, keyValue:int,
426                                    updateColumn:String, updateValue:String, updateType:String):Boolean {
427             var result:Object;
428
429             if (updateType == "TEXT")
430                 updateValue = "'" + updateValue + "'";
431
432             var sql:String = "UPDATE " + table + " SET " + updateColumn + " = " + updateValue
433                            + " WHERE " + keyColumn + " = " + keyValue;
434
435             result = executeSQLStatement(db, sql);
436             if (!result.status)
437                 Alert.show(result.message, "ERROR!:update");
438             return result.status;
439         }
440
441        /**
442         * private method
443         */
444
445        /**
446         * Execute SQL statement
447         */
448         public static function executeSQLStatement(db:SQLConnection, sql:String):Object {
449             var status:Boolean = true;
450             var message:String = "";
451             try {
452                 var stmt:SQLStatement = new SQLStatement;
453                 stmt.sqlConnection = db;
454                 stmt.text = sql;
455                 stmt.execute();
456             } catch (err:Error) {
457                 status = false;
458                 message = err.toString();
459             }
460             return {status: status, message: message};
461         }
462
463        /**
464         * Get the Columns of the Result set
465         */
466         private static function getResultColumns(sql:String):Array {
467             var result:Array = new Array();
468             var startIndex:Number = 0;
469             var endIndex:Number = 0;
470
471             var selectPos:Number = sql.toUpperCase().search("SELECT ");
472             if (selectPos == -1)
473                 return null;
474
475             var distinctPos:Number = sql.toUpperCase().search("DISTINCT ");
476             if (distinctPos == -1)
477                 startIndex = selectPos + 7;
478             else
479                 startIndex = distinctPos + 9;
480
481             endIndex = sql.toUpperCase().search(" FROM");
482             if (endIndex == -1)
483                 return null;
484
485             var columns:String = sql.slice(startIndex, endIndex);
486
487             var column:Array = columns.split(",");
488             for each(var val:* in column) {
489                 startIndex = val.toUpperCase().search("AS ");
490                 if (startIndex == -1)
491                     result.push(removeWhitespace(val));
492                 else
493                     result.push(removeWhitespace(val.slice(startIndex + 3)));
494             }
495             return result;
496         }
497
498        /**
499         * Get the Data of the Result set
500         */
501         private static function getResultData(db:SQLConnection, sql:String):SQLResult {
502             var stmt:SQLStatement = new SQLStatement;
503             stmt.sqlConnection = db;
504             stmt.text = sql;
505             try {
506                 stmt.execute();
507                 return stmt.getResult();
508             } catch(err:Error) {
509                 Alert.show(err.toString(), "ERROR!:getResultData");
510                 //trace("getResultData:", sql);
511                 return null;
512             }
513             return null;
514         }
515
516        /**
517         * Remove the white space from the string
518         */
519         private static function removeWhitespace(txt:String):String {
520             var val:String = "";
521             for (var i:int = 0; i < txt.length; i++)
522                 if (txt.charAt(i) != ' ')
523                     val += txt.charAt(i);
524             return val;
525         }
526     }
527 }
Note: リポジトリブラウザについてのヘルプは TracBrowser を参照してください。