-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSQL2Java.py
More file actions
368 lines (272 loc) · 8.73 KB
/
SQL2Java.py
File metadata and controls
368 lines (272 loc) · 8.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
import sys
import os
# Automata's States
initalState = 0
createState = 1
attributeState = 2
constraintState = 3
endOfFileState = 5
# Processing variables
actualState = 0
actualFileIndex = 0;
actualLine = ''
actualTable = ''
tables = []
attributesInTable = {}
foreingKeysInTable = {}
primaryKeyInTable = {}
# To treat the SQL Sintax
constraintStatements = ['PRIMARY','INDEX','CONSTRAINT','FOREIGN','REFERENCES','ON']
primaryKeyStatement = 'PRIMARY KEY'
createStatement = 'CREATE TABLE'
openParentesis = '('
closeParentesis = ')'
foreingKeyStatement = 'FOREIGN KEY'
referencesStatement = 'REFERENCES'
# To create the Java class
classHeader = 'public final class'
startOfBlock = '{'
endOfBlock = '}'
endOfLine = ';'
publicStatement = 'public'
classEntryDefinition = 'public static abstract class'
classEntryInterface = 'implements BaseColumns'
entryDefinition = 'public static final String'
def currentLine():
line = fileByLines[actualFileIndex].upper()
line = line.replace('`', '')
return line
def generateDBHelper():
print 'package hunabsys.classifiertest;'
print ''
#print 'import hunabsys.classifiertest.entities'
print 'import android.content.Context;'
print 'import android.content.ContentValues;'
print 'import android.database.sqlite.SQLiteDatabase;'
print 'import android.database.sqlite.SQLiteOpenHelper;'
print ''
print 'public class DatabaseHelper extends SQLiteOpenHelper {'
print ' '
print '\t private static final String DATABASE_NAME = "contactsManager";'
print '\t private static final String LOG = "DatabaseHelper";'
print '\t private static final int DATABASE_VERSION = 1;'
# Print each table and its attributes
print '\t '
for table in tables:
print '\t private static final String TABLE_' + table + ' = "' + table + '";'
if not attributesInTable.has_key(table): continue
for attrSQL in attributesInTable[table].split('$'):
attr = attrSQL.split(' ')[0]
print '\t private static final String ' + table + '_' + attr + '="' + attr + '";'
tableDef = attributesInTable[table].replace('$', ',') + ' '
createTableVar = '\t private static final String CREATE_TABLE_' + table + ' = "'
createTableVar += 'CREATE TABLE ' + table + '( ' + tableDef
if primaryKeyInTable.has_key(table):
createTableVar += ',' + primaryKeyStatement + '(' + primaryKeyInTable[table] + ')'
if foreingKeysInTable.has_key(table):
for fkSQL in foreingKeysInTable[table].split('$'):
fk = fkSQL.split('.')
createTableVar += ',' + 'FOREIGN KEY (' + fk[0] +') '
createTableVar += 'REFERENCES ' + fk[1] + '(' + fk[2] + ')'
createTableVar += ')";'
print createTableVar
print '\t '
# prints the constructor and other methodsclear
print '\t public DatabaseHelper(Context context) {'
print '\t \tsuper(context, DATABASE_NAME, null, DATABASE_VERSION);'
print '\t }'
print '\t '
print '\t public void closeDB() {'
print '\t \t SQLiteDatabase db = this.getReadableDatabase();'
print '\t \t if (db != null && db.isOpen())'
print '\t \t \tdb.close();'
print '\t }'
print '\t '
print '\t @Override'
print '\t public void onCreate(SQLiteDatabase db) {'
for table in tables:
print '\t \t db.execSQL(CREATE_TABLE_' + table + ');'
print '\t }'
print '\t '
print '\t @Override'
print '\t public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {'
for table in tables:
print '\t \t db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE_' + table +');'
print '\t \t onCreate(db);'
print '\t }'
print '}'
def isEndOfFileState(state):
result = False
if state == endOfFileState:
result = True
return result
def isInitialState(state):
result = False
if state == initalState:
result = True
return result
def isCreateState(state):
result = False
if state == createState:
result = True
return result
def isAttributeState(state):
result = False
if state == attributeState:
result = True
return result
def isConstraintState(state):
result = False
if state == constraintState:
result = True
return result
def isTableDeclarationEnd(statement):
isEnd = False
numberOfCloseParentesis = statement.count(closeParentesis)
numberOfOpenParentesis = statement.count(openParentesis)
if numberOfOpenParentesis < numberOfCloseParentesis:
isEnd = True
return isEnd
def isEndOfFile():
result = False
if actualFileIndex >= numLines:
result = True
return result
def isPrimaryKeyConstraint(statement):
result = False
if primaryKeyStatement in statement:
result = True
return result
def isForeignKeyConstraint(statement):
result = False
if foreingKeyStatement in statement:
result = True
return result
def hasCreateStament(statement):
result = False
if createStatement in statement:
result = True
return result
def hasConstraint(statement):
result = False
statements = statement.split(' ')
for si in statements:
for constraint in constraintStatements:
if si == constraint:
result = True
break
return result
def getTableName(statement):
tableName = statement
tableName = tableName.replace('`', '')
tableName = tableName.replace(openParentesis, '')
tableName = tableName.replace(closeParentesis, '')
tableName = tableName.split('.')[1]
tableName = tableName.strip()
return tableName
def getAttribute(statement):
newAttribute = statement
newAttribute = newAttribute.replace(',', '')
newAttribute = newAttribute.lstrip()
return newAttribute
def getPrimaryKeyAttribute(statement):
primaryKey = statement
primaryKey = primaryKey.replace('`', '')
primaryKey = primaryKey.replace(',', '')
primaryKey = primaryKey.replace(openParentesis, '')
primaryKey = primaryKey.replace(closeParentesis, '')
primaryKey = primaryKey.replace(primaryKeyStatement, '')
primaryKey = primaryKey.lstrip()
return primaryKey
def getForeignKeyStatement(key, reference):
fk = key
ref = reference
fk = fk.replace(foreingKeyStatement, '')
fk = fk.replace(openParentesis, '')
fk = fk.replace(closeParentesis, '')
fk = fk.lstrip()
ref = ref.replace(openParentesis, '')
ref = ref.replace(closeParentesis, '')
ref = ref.replace(referencesStatement, '')
ref = ref.lstrip()
tablePart = ref.split(' ')[0].split('.')[1]
attrPart = ref.split(' ')[1]
return fk + '.' + tablePart + '.' + attrPart
def addNewTable(table):
tableDB = tables
tableDB.append(actualTable)
def addAttributeToTable(attribute, table):
# Reference to the attributes database
attributesDB = attributesInTable
if attributesDB.has_key(table):
attributesDB[table] = attributesDB[table] + '$' + attribute
else:
attributesDB[table] = attribute
def addPrimaryKey(table, primaryKey):
pkDB = primaryKeyInTable
pkDB[table] = primaryKey
def addForeignKey(table, foreignKey):
foreignKeyDB = foreingKeysInTable
if foreignKeyDB.has_key(table):
foreignKeyDB[table] = foreignKeyDB[table] + '$' + foreignKey
else:
foreignKeyDB[table] = foreignKey
##############################################
## THE FUN STARTS HERE! ##
##############################################
fileName = sys.argv[1]
isValidFile = False
fileByLines = open(fileName).read().split('\n')
numLines = len(fileByLines)
actualState = initalState
while not isEndOfFileState(actualState):
# Define where to stop
if isEndOfFile():
actualState = endOfFileState
else:
actualLine = currentLine()
# Detect the CREATE TABLE Statement
if isInitialState(actualState):
if hasCreateStament(actualLine):
actualState = createState
else:
# Take the next line
actualFileIndex = actualFileIndex + 1
# Ignore CREATE TABLE and get the table name
elif isCreateState(actualState):
tableName = getTableName(actualLine)
actualTable = tableName
addNewTable(actualTable)
# Lets look for the attributes
actualState = attributeState
actualFileIndex = actualFileIndex + 1
# Get the table attributes
elif isAttributeState(actualState):
attribute = getAttribute(actualLine)
# If the actual line has any constraint statements
if hasConstraint(attribute):
actualState = constraintState
else:
# It must be an attribute
addAttributeToTable(attribute, actualTable)
# Could be the table's declaration end
if isTableDeclarationEnd(attribute):
actualState = initalState
actualFileIndex = actualFileIndex + 1
# Get the constraints
elif isConstraintState(actualState):
if isPrimaryKeyConstraint(actualLine):
primaryKey = getPrimaryKeyAttribute(actualLine)
addPrimaryKey(actualTable, primaryKey)
elif isForeignKeyConstraint(actualLine):
# This is bit tricky
foreingPart = actualLine
referencesPart = fileByLines[actualFileIndex+1].upper()
fkStatement = getForeignKeyStatement(foreingPart, referencesPart)
addForeignKey(actualTable, fkStatement)
# Could this be the end?
if isTableDeclarationEnd(actualLine):
actualState = initalState
actualFileIndex = actualFileIndex + 1
# Print it! Just do it!
generateDBHelper()