1## @file
2# This file is used to create/update/query/erase table for files
3#
4# Copyright (c) 2008 - 2014, Intel Corporation. All rights reserved.<BR>
5# This program and the accompanying materials
6# are licensed and made available under the terms and conditions of the BSD License
7# which accompanies this distribution.  The full text of the license may be found at
8# http://opensource.org/licenses/bsd-license.php
9#
10# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
12#
13
14##
15# Import Modules
16#
17import Common.LongFilePathOs as os
18
19import Common.EdkLogger as EdkLogger
20from CommonDataClass import DataClass
21from CommonDataClass.DataClass import FileClass
22
23## Convert to SQL required string format
24def ConvertToSqlString(StringList):
25    return map(lambda s: "'" + s.replace("'", "''") + "'", StringList)
26
27## TableFile
28#
29# This class defined a common table
30#
31# @param object:     Inherited from object class
32#
33# @param Cursor:     Cursor of the database
34# @param TableName:  Name of the table
35#
36class Table(object):
37    _COLUMN_ = ''
38    _ID_STEP_ = 1
39    _ID_MAX_ = 0x80000000
40    _DUMMY_ = 0
41
42    def __init__(self, Cursor, Name='', IdBase=0, Temporary=False):
43        self.Cur = Cursor
44        self.Table = Name
45        self.IdBase = int(IdBase)
46        self.ID = int(IdBase)
47        self.Temporary = Temporary
48
49    def __str__(self):
50        return self.Table
51
52    ## Create table
53    #
54    # Create a table
55    #
56    def Create(self, NewTable=True):
57        if NewTable:
58            self.Drop()
59
60        if self.Temporary:
61            SqlCommand = """create temp table IF NOT EXISTS %s (%s)""" % (self.Table, self._COLUMN_)
62        else:
63            SqlCommand = """create table IF NOT EXISTS %s (%s)""" % (self.Table, self._COLUMN_)
64        EdkLogger.debug(EdkLogger.DEBUG_8, SqlCommand)
65        self.Cur.execute(SqlCommand)
66        self.ID = self.GetId()
67
68    ## Insert table
69    #
70    # Insert a record into a table
71    #
72    def Insert(self, *Args):
73        self.ID = self.ID + self._ID_STEP_
74        if self.ID >= (self.IdBase + self._ID_MAX_):
75            self.ID = self.IdBase + self._ID_STEP_
76        Values = ", ".join([str(Arg) for Arg in Args])
77        SqlCommand = "insert into %s values(%s, %s)" % (self.Table, self.ID, Values)
78        EdkLogger.debug(EdkLogger.DEBUG_5, SqlCommand)
79        self.Cur.execute(SqlCommand)
80        return self.ID
81
82    ## Query table
83    #
84    # Query all records of the table
85    #
86    def Query(self):
87        SqlCommand = """select * from %s""" % self.Table
88        self.Cur.execute(SqlCommand)
89        for Rs in self.Cur:
90            EdkLogger.verbose(str(Rs))
91        TotalCount = self.GetId()
92
93    ## Drop a table
94    #
95    # Drop the table
96    #
97    def Drop(self):
98        SqlCommand = """drop table IF EXISTS %s""" % self.Table
99        try:
100            self.Cur.execute(SqlCommand)
101        except Exception, e:
102            print "An error occurred when Drop a table:", e.args[0]
103
104    ## Get count
105    #
106    # Get a count of all records of the table
107    #
108    # @retval Count:  Total count of all records
109    #
110    def GetCount(self):
111        SqlCommand = """select count(ID) from %s""" % self.Table
112        Record = self.Cur.execute(SqlCommand).fetchall()
113        return Record[0][0]
114
115    def GetId(self):
116        SqlCommand = """select max(ID) from %s""" % self.Table
117        Record = self.Cur.execute(SqlCommand).fetchall()
118        Id = Record[0][0]
119        if Id == None:
120            Id = self.IdBase
121        return Id
122
123    ## Init the ID of the table
124    #
125    # Init the ID of the table
126    #
127    def InitID(self):
128        self.ID = self.GetId()
129
130    ## Exec
131    #
132    # Exec Sql Command, return result
133    #
134    # @param SqlCommand:  The SqlCommand to be executed
135    #
136    # @retval RecordSet:  The result after executed
137    #
138    def Exec(self, SqlCommand):
139        EdkLogger.debug(EdkLogger.DEBUG_5, SqlCommand)
140        self.Cur.execute(SqlCommand)
141        RecordSet = self.Cur.fetchall()
142        return RecordSet
143
144    def SetEndFlag(self):
145        pass
146
147    def IsIntegral(self):
148        Result = self.Exec("select min(ID) from %s" % (self.Table))
149        if Result[0][0] != -1:
150            return False
151        return True
152
153    def GetAll(self):
154        return self.Exec("select * from %s where ID > 0 order by ID" % (self.Table))
155
156
157## TableDataModel
158#
159# This class defined a table used for data model
160#
161# @param object:       Inherited from object class
162#
163#
164class TableDataModel(Table):
165    _COLUMN_ = """
166        ID INTEGER PRIMARY KEY,
167        CrossIndex INTEGER NOT NULL,
168        Name VARCHAR NOT NULL,
169        Description VARCHAR
170        """
171    def __init__(self, Cursor):
172        Table.__init__(self, Cursor, 'DataModel')
173
174    ## Insert table
175    #
176    # Insert a record into table DataModel
177    #
178    # @param ID:           ID of a ModelType
179    # @param CrossIndex:   CrossIndex of a ModelType
180    # @param Name:         Name of a ModelType
181    # @param Description:  Description of a ModelType
182    #
183    def Insert(self, CrossIndex, Name, Description):
184        (Name, Description) = ConvertToSqlString((Name, Description))
185        return Table.Insert(self, CrossIndex, Name, Description)
186
187    ## Init table
188    #
189    # Create all default records of table DataModel
190    #
191    def InitTable(self):
192        EdkLogger.verbose("\nInitialize table DataModel started ...")
193        Count = self.GetCount()
194        if Count != None and Count != 0:
195            return
196        for Item in DataClass.MODEL_LIST:
197            CrossIndex = Item[1]
198            Name = Item[0]
199            Description = Item[0]
200            self.Insert(CrossIndex, Name, Description)
201        EdkLogger.verbose("Initialize table DataModel ... DONE!")
202
203    ## Get CrossIndex
204    #
205    # Get a model's cross index from its name
206    #
207    # @param ModelName:    Name of the model
208    # @retval CrossIndex:  CrossIndex of the model
209    #
210    def GetCrossIndex(self, ModelName):
211        CrossIndex = -1
212        SqlCommand = """select CrossIndex from DataModel where name = '""" + ModelName + """'"""
213        self.Cur.execute(SqlCommand)
214        for Item in self.Cur:
215            CrossIndex = Item[0]
216
217        return CrossIndex
218
219