summaryrefslogtreecommitdiffstats
path: root/kexi/plugins/scripting/scripts/copycenter/CopyCenterPluginKexiDB.py
blob: ca6a3f6ba3e7286867bae2effd27eedae741e2ca (plain)
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
"""
CopyCenterPlugin to provide 'KexiDB'.

Description:
This python-script is a plugin for the CopyCenter.py.

Author:
Sebastian Sauer <[email protected]>

Copyright:
GPL v2 or higher.
"""

class CopyCenterPlugin:
	""" The CopyCenterPlugin to provide abstract access to the 'KexiDB'
	framework to CopyCenter.py """

	name = "Kexi Database"
	""" The name this plugin has. The name should be unique and
	will be used for displaying a caption. """

	class Plugin:
		""" The implementation of a plugin which is published to the
		CopyCenter.py script. While there exists only one instance of
		the CopyCenterPlugin class, there will be n instances of this
		Plugin class (one for 'source' aka read-data-from and one for
		'destination' aka write-data-to) created from within the
		CopyCenter.py. The Source and Destination classes are extending
		this Plugin class with specialized functionality. """
		def __init__(self,copycenterplugin):
			""" Constructor. """
			self.copycenterplugin = copycenterplugin
			self.widget = None
			self.options = {
				'autoconnect' : False,
				'project' : '', #'~/test.kexi',
				'driver' : '', #'MySQL', #'SQLite3','MySQL',...
				'file' : '', #'/path/to/mysqlite3dbfile.kexi'
				'hostname' : '127.0.0.1',
				'port' : '',
				'usesocketfile' : False,
				'socketfile' : '',
				'username' : '',
				'password' : '',
				'database' : '',
				'table' : '',
				'fields' : '',
				'where' : '',
			}
			self.connection = copycenterplugin.Connection(self)
		def isFinished(self):
			return self.connection.isFinished()
		def finish(self):
			""" Called if reading is finished."""
			self.connection.finish()
		def createWidget(self, dialog, parent):
			""" Create and return a widget to modify the plugin settings. """
			return self.copycenterplugin.createWidget(dialog, self, parent)

	class Source(Plugin):
		""" Specialization of the Plugin class to implement the
		'source' aka read-data-from functionality. """
		plugintype = "Source"
		def init(self,copierer):
			""" Called if reading should be initialize. """
			self.connection.init(copierer)
			self.connection.initRead()
			# Called if a record should be readed.
			self.read = self.connection.readRecord

	class Destination(Plugin):
		""" Specialization of the Plugin class to implement the
		'destination' aka write-data-to functionality. """
		plugintype = "Destination"
		def init(self,copierer):
			""" Called if writing should be initialize. """
			self.connection.init(copierer)
			self.connection.initWrite()
			# Called if a record should be written.
			self.write = self.connection.writeRecord

	class Connection:
		""" Abstract access to work with KexiDB. """
		def __init__(self,plugin):
			self.plugin = plugin
			self.copierer = None
			self.kexidbconnection = None
			self.kexidbcursor = None
			self.tableschema = None
			self.fieldlist = None
		def lastError(self): return self.kexidbconnection.lastError()
		def connect(self): return self.kexidbconnection.connect()
		def disconnect(self):
			if self.kexidbconnection == None or self.kexidbconnection.disconnect():
				self.kexidbconnection = None
				return True
			return False
		def isConnected(self): return self.kexidbconnection != None and self.kexidbconnection.isConnected()
		def tableNames(self): return self.kexidbconnection.tableNames()
		def hasTableName(self,tablename): return tablename in self.kexidbconnection.tableNames()
		def tableSchema(self,tablename): return self.kexidbconnection.tableSchema(tablename)

		def init(self,copierer):
			self.copierer = copierer
			if self.kexidbconnection == None:
				if self.plugin.widget == None:
					raise Exception("No connection established.")
				self.copierer.appendProgressMessage("<i>Trying to connect...</i>")
				if self.plugin.widget.driverbox.driver == None:
					raise Exception("Invalid driver.")
				if not self.plugin.widget.connectClicked():
					raise Exception("Failed to connect.")
			connectiondata = self.kexidbconnection.data()
			self.copierer.appendProgressMessage("Connected: %s %s" % (connectiondata.driverName(),connectiondata.serverInfoString()))

			tablename = str(self.plugin.widget.tablebox.tableedit.text())
			if tablename == "":
				raise Exception("No table defined")
			fields = [ f.strip() for f in str(self.plugin.widget.fieldbox.fieldsedit.text()).split(",") if len(f) > 0 ]
			if len(fields) < 1:
				raise Exception("No fields defined")

			self.tableschema = self.kexidbconnection.tableSchema(tablename)
			if not self.tableschema: raise Exception("No such tableschema \"%s\"" % tablename)
			self.copierer.appendProgressMessage("Table: %s" % self.tableschema.name())

			if len(fields) == 1 and fields[0] == "*":
				self.fieldlist = self.tableschema.fieldlist()
			else:
				self.fieldlist = self.tableschema.fieldlist().subList(fields)
			if not self.fieldlist: raise Exception("No such fields \"%s\"" % fields)
			fieldlistnames = self.fieldlist.names()
			if len(fieldlistnames) < 1: raise Exception("No valid fields defined for \"%s\"" % fields)
			self.copierer.appendProgressMessage("Fields: %s" % fieldlistnames)
		def finish(self):
			if self.plugin.widget == None:
				self.disconnect()
			else:
				self.plugin.widget.disconnectClicked()
			self.kexidbcursor = None
			self.kexidbconnection = None
			self.tableschema = None
			self.fieldlist = None
			self.copierer = None
		def isFinished(self):
			return self.copierer == None

		def initRead(self):
			print("Initialize read")
			#queryschema = self.plugin.copycenterplugin.drivermanager.querySchema()
			queryschema = self.tableschema.query()
			queryschema.fieldlist().setFields(self.fieldlist)
			print("QuerySchema: %s" % queryschema.fieldlist().names())

			whereexpression = str(self.plugin.widget.whereedit.text())
			if whereexpression != "":
				print("WHERE-expression: %s" % whereexpression)
				if not queryschema.setWhereExpression(whereexpression):
					raise Exception("Invalid WHERE-expression.")

			#print "QuerySchema statement=%s" % queryschema.statement()
			self.kexidbcursor = self.kexidbconnection.executeQuerySchema(queryschema)
			if not self.kexidbcursor:
				raise Exception("Failed to create cursor.")
			if not self.kexidbcursor.moveFirst():
				raise Exception("The cursor has no records to read from.")

		def readRecord(self):
			if self.kexidbcursor == None or self.kexidbcursor.eof():
				return None
			record = []
			for i in range( self.kexidbcursor.fieldCount() ):
				record.append( self.kexidbcursor.value(i) )
			self.kexidbcursor.moveNext()
			#print "read record: %s" % record
			return record

		def initWrite(self):
			print("Initialize write")

		def writeRecord(self,record):
			print("write record: %s" % record)
			if self.kexidbconnection.insertRecord(self.fieldlist,record):
				print("=> insert successfully")
				self.copierer.writeSuccess(record, 1)
			else:
				print("=> insert failed: %s" % self.kexidbconnection.lastError())
  				self.copierer.writeFailed(record)
			#import time
  			#time.sleep(1)
  			return True

	def __init__(self, copycenter):
		""" Constructor.  """
		import krosskexidb
		self.drivermanager = krosskexidb.DriverManager()
		self.copycenter = copycenter

	def createWidget(self, dialog, plugin, parent):
		""" Each plugin may provide a tqt.TQWidget back to the
		CopyCenter.py. The widget will be used to configure our
		plugin settings. """

		from TQt import tqt
		import os
		import re

		self.dialog = dialog
		self.mainbox = None
		class ProjectBox(tqt.TQHBox):
			def __init__(self,main,copycenterplugin,plugin,parent):
				self.main = main
				self.copycenterplugin = copycenterplugin
				self.plugin = plugin

				tqt.TQHBox.__init__(self,parent)
				prjlabel = tqt.TQLabel("Project File:",self)
				self.prjcombo = tqt.TQComboBox(self)
				self.prjcombo.setEditable(True)
				self.prjcombo.insertItem("")

				path = copycenterplugin.copycenter.homepath
				for f in os.listdir(path):
					file = os.path.join(path,f)
					if os.path.isfile(file) and re.search(".+\\.(kexi|kexis|kexic)$",f):
						self.prjcombo.insertItem(os.path.join("~",f))

				prjlabel.setBuddy(self.prjcombo)
				prjsavebtn = tqt.TQPushButton("...",self)
				tqt.TQObject.connect(prjsavebtn, tqt.SIGNAL("clicked()"),self.buttonClicked)
				tqt.TQObject.connect(self.prjcombo, tqt.SIGNAL("textChanged(const TQString&)"), self.main.projectChanged)
				self.setStretchFactor(self.prjcombo,1)
			def buttonClicked(self):
				text = str(self.prjcombo.currentText())
				if text == "":
					text = self.copycenterplugin.copycenter.homepath
				elif re.search("^\\~(\\/|\\\\)",text):
					import os
					text = os.path.join(self.copycenterplugin.copycenter.homepath,text[2:])
				if self.plugin.plugintype == "Source":
					filename = tqt.TQFileDialog.getOpenFileName(text,"*.kexi *.kexis *.kexic;;*",self.copycenterplugin.dialog)
				else: # "Destination":
					filename = tqt.TQFileDialog.getSaveFileName(text,"*.kexi *.kexis *.kexic;;*",self.copycenterplugin.dialog)
				if str(filename) != "": self.prjcombo.setCurrentText(str(filename))

		class DriverBox(tqt.TQVBox):
			def __init__(self,main,parent):
				tqt.TQVBox.__init__(self,parent)
				self.main = main
				self.copycenterplugin = main.copycenterplugin
				self.plugin = main.plugin
				self.driver = None

				driverbox = tqt.TQHBox(self)
				driverlabel = tqt.TQLabel("Driver:",driverbox)
				self.drivercombo = tqt.TQComboBox(driverbox)
				self.drivercombo.insertItem("")
				for driver in self.copycenterplugin.drivermanager.driverNames():
					self.drivercombo.insertItem(driver)

				tqt.TQObject.connect(self.drivercombo, tqt.SIGNAL("activated(int)"), self.activated)
				driverlabel.setBuddy(self.drivercombo)
				driverbox.setStretchFactor(self.drivercombo,1)

				self.box = tqt.TQVBox(self)
				self.mainbox = None

			def activated(self,index):
				drivertext = str(self.drivercombo.currentText())

				self.box.hide()
				if self.mainbox:
					self.mainbox.hide()
					self.mainbox.destroy()
					self.mainbox = None
				if index == 0 or drivertext == "":
					self.driver = None
					self.box.show()
					self.main.updateConnectButtons()
					return False

				self.driver = self.copycenterplugin.drivermanager.driver(drivertext)

				mainbox = tqt.TQVBox(self.box)
				mainbox.setSpacing(2)

				if self.driver.isFileDriver():
					filebox = tqt.TQHBox(mainbox)
					filelabel = tqt.TQLabel("File:",filebox)
					self.fileedit = tqt.TQLineEdit(self.plugin.options['file'],filebox)
					filelabel.setBuddy(self.fileedit)
					filebox.setStretchFactor(self.fileedit,1)
					filebtn = tqt.TQPushButton("...",filebox)
					tqt.TQObject.connect(filebtn, tqt.SIGNAL("clicked()"), self.fileClicked)
				else:
					hostbox = tqt.TQHBox(mainbox)
					hostlabel = tqt.TQLabel("Hostname:",hostbox)
					self.hostedit = tqt.TQLineEdit(self.plugin.options['hostname'],hostbox)
					hostlabel.setBuddy(self.hostedit)
					hostbox.setStretchFactor(self.hostedit,1)

					portbox = tqt.TQHBox(mainbox)
					portlabel = tqt.TQLabel("Port:",portbox)
					self.portedit = tqt.TQLineEdit(self.plugin.options['port'],portbox)
					portlabel.setBuddy(self.portedit)
					portbox.setStretchFactor(self.portedit,1)

					sockbox = tqt.TQHBox(mainbox)
					self.sockfilecheckbox = tqt.TQCheckBox("Socket File:",sockbox)
					tqt.TQObject.connect(self.sockfilecheckbox, tqt.SIGNAL("toggled(bool)"), self.sockfilecheckboxClicked)
					self.sockfilebox = tqt.TQHBox(sockbox)
					self.sockfileedit = tqt.TQLineEdit(self.plugin.options['socketfile'],self.sockfilebox)
					self.sockfilebox.setEnabled(False)
					sockfilebtn = tqt.TQPushButton("...",self.sockfilebox)
					self.sockfilecheckbox.setChecked( str(self.plugin.options['usesocketfile']) == str(True) )
					tqt.TQObject.connect(sockfilebtn, tqt.SIGNAL("clicked()"), self.sockfileClicked)
					self.sockfilebox.setStretchFactor(self.sockfileedit,1)
					sockbox.setStretchFactor(self.sockfilebox,1)

					userbox = tqt.TQHBox(mainbox)
					userlabel = tqt.TQLabel("Username:",userbox)
					self.useredit = tqt.TQLineEdit(self.plugin.options['username'],userbox)
					userlabel.setBuddy(self.useredit)
					userbox.setStretchFactor(self.useredit,1)

					passbox = tqt.TQHBox(mainbox)
					passlabel = tqt.TQLabel("Password:",passbox)
					self.passedit = tqt.TQLineEdit(self.plugin.options['password'],passbox)
					self.passedit.setEchoMode(tqt.TQLineEdit.Password)
					passlabel.setBuddy(self.passedit)
					passbox.setStretchFactor(self.passedit,1)

					dbbox = tqt.TQHBox(mainbox)
					dblabel = tqt.TQLabel("Database:",dbbox)
					self.dbedit = tqt.TQLineEdit(self.plugin.options['database'],dbbox)
					dblabel.setBuddy(self.dbedit)
					dbbox.setStretchFactor(self.dbedit,1)
				#self.tablecombo.setText("")

				self.mainbox = mainbox
				self.mainbox.show()
				self.box.show()
				self.main.updateConnectButtons()
				return True

			def fileClicked(self):
				text = str(self.fileedit.text())
				if text == "": text = self.copycenterplugin.copycenter.homepath
				if self.plugin.plugintype == "Source":
					filename = tqt.TQFileDialog.getOpenFileName(text,"*",self.copycenterplugin.dialog)
				else: # "Destination":
					filename = tqt.TQFileDialog.getSaveFileName(text,"*",self.copycenterplugin.dialog)
				if str(filename) != "": self.fileedit.setText(str(filename))
			def sockfilecheckboxClicked(self,checked):
				self.sockfilebox.setEnabled(checked)

			def sockfileClicked(self):
				text = str(self.sockfileedit.text())
				if text == "": text = self.copycenterplugin.copycenter.homepath
				if self.plugin.plugintype == "Source":
					filename = tqt.TQFileDialog.getOpenFileName(text,"*",self.copycenterplugin.dialog)
				else: # "Destination":
					filename = tqt.TQFileDialog.getSaveFileName(text,"*",self.copycenterplugin.dialog)
				if str(filename) != "": self.sockfileedit.setText(str(filename))

		class TableBox(tqt.TQHBox):
			def __init__(self,copycenterplugin,plugin,parent):
				tqt.TQHBox.__init__(self,parent)
				self.copycenterplugin = copycenterplugin
				self.plugin = plugin
				tablelabel = tqt.TQLabel("Table:",self)
				self.tableedit = tqt.TQLineEdit(self.plugin.options['table'],self)
				self.tablebtn = tqt.TQPushButton("...",self)
				self.tablebtn.setEnabled(False)
				tqt.TQObject.connect(self.tablebtn, tqt.SIGNAL("clicked()"), self.buttonClicked)
				tablelabel.setBuddy(self.tableedit)
				self.setStretchFactor(self.tableedit,1)
			def buttonClicked(self):
				ListViewDialog = self.copycenterplugin.dialog.ListViewDialog
				class TableDialog(ListViewDialog):
					def __init__(self,tablebox):
						ListViewDialog.__init__(self,tablebox,"Tables")
						self.mainwidget = tablebox
						self.listview.addColumn("Name")
						text = str(self.mainwidget.tableedit.text())
						item = None
						for table in self.mainwidget.plugin.connection.tableNames():
							if item == None:
								item = tqt.TQListViewItem(self.listview,table)
							else:
								item = tqt.TQListViewItem(self.listview,item,table)
							if table == text:
								self.listview.setSelected(item,True)
								self.listview.ensureItemVisible(item)
						tqt.TQObject.connect(self.listview, tqt.SIGNAL("doubleClicked(TQListViewItem*, const TQPoint&, int)"), self.okClicked)
						tqt.TQObject.connect(self.okbtn, tqt.SIGNAL("clicked()"), self.okClicked)
					def okClicked(self):
						item = self.listview.selectedItem()
						if item == None:
							self.mainwidget.tableedit.setText("")
						else:
							self.mainwidget.tableedit.setText(item.text(0))
						self.close()
				dialog = TableDialog(self)
				dialog.show()

		class FieldBox(tqt.TQHBox):
			def __init__(self,copycenterplugin,plugin,parent):
				tqt.TQHBox.__init__(self,parent)
				self.copycenterplugin = copycenterplugin
				self.plugin = plugin
				self.tablename = ""
				fieldslabel = tqt.TQLabel("Fields:",self)
				self.fieldsedit = tqt.TQLineEdit(self.plugin.options['fields'],self)
				self.setStretchFactor(self.fieldsedit,1)
				fieldslabel.setBuddy(self.fieldsedit)
				self.fieldsbtn = tqt.TQPushButton("...",self)
				self.fieldsbtn.setEnabled(False)
				tqt.TQObject.connect(self.fieldsbtn, tqt.SIGNAL("clicked()"), self.fieldsClicked)
			def fieldsClicked(self):
				ListViewDialog = self.copycenterplugin.dialog.ListViewDialog
				class FieldsDialog(ListViewDialog):
					def __init__(self, fieldbox):
						ListViewDialog.__init__(self,fieldbox,"Fields")
						self.fieldbox = fieldbox
						self.listview.setSelectionMode(tqt.TQListView.Multi)
						self.listview.setSorting(-1)
						self.listview.header().setClickEnabled(False)
						self.listview.addColumn("Name")
						self.listview.addColumn("Type")
						self.listview.addColumn("Options")
						fieldslist = str(self.fieldbox.fieldsedit.text()).split(",")
						allfields = ("*" in fieldslist)
						tableschema = self.fieldbox.plugin.connection.tableSchema(self.fieldbox.tablename)
						item = None
						for field in tableschema.fieldlist().fields():
							opts = []
							for opt in ("isAutoInc","isNotNull","isNotEmpty"):
								if getattr(field,opt)():
									opts.append(opt[2:])
							item = self.addItem(( field.name(),field.type(),",".join(opts) ),item)
							if allfields or field.name() in fieldslist:
								self.listview.setSelected(item,True)
						tqt.TQObject.connect(self.okbtn, tqt.SIGNAL("clicked()"), self.okClicked)
					def okClicked(self):
						selitems = []
						item = self.listview.firstChild()
						while item:
							if item.isSelected():
								selitems.append(str(item.text(0)))
							item = item.nextSibling()
						self.fieldbox.fieldsedit.setText(",".join(selitems))
						self.close()
				dialog = FieldsDialog(self)
				dialog.show()
			def tableChanged(self, text):
				self.tablename = str(text)
				if self.plugin.connection.isConnected():
					if self.plugin.connection.hasTableName(self.tablename):
						self.fieldsbtn.setEnabled(True)
						return
				self.fieldsbtn.setEnabled(False)

		class MainBox(tqt.TQHBox):
			def __init__(self,copycenterplugin,plugin,parent):
				tqt.TQHBox.__init__(self,parent)
				self.copycenterplugin = copycenterplugin
				self.plugin = plugin

				self.prjbox = ProjectBox(self,copycenterplugin,plugin,parent)
				self.driverbox = DriverBox(self,parent)

				statusbar = tqt.TQHBox(parent)
				statusbar.setSpacing(2)
				#self.statuslabel = tqt.TQLabel("Disconnected",statusbar)
				#statusbar.setStretchFactor(self.statuslabel,1)
				statusbar.setStretchFactor(tqt.TQWidget(statusbar),1)
				self.connectbtn = tqt.TQPushButton("Connect",statusbar)
				self.connectbtn.setEnabled(False)
				tqt.TQObject.connect(self.connectbtn, tqt.SIGNAL("clicked()"),self.connectClicked)
				self.disconnectbtn = tqt.TQPushButton("Disconnect",statusbar)
				self.disconnectbtn.setEnabled(False)
				tqt.TQObject.connect(self.disconnectbtn, tqt.SIGNAL("clicked()"),self.disconnectClicked)

				#self.connectionbox = ConnectionBox(copycenterplugin,plugin,parent)
				self.tablebox = TableBox(copycenterplugin,plugin,parent)
				self.fieldbox = FieldBox(copycenterplugin,plugin,parent)
				tqt.TQObject.connect(self.tablebox.tableedit, tqt.SIGNAL("textChanged(const TQString&)"), self.fieldbox.tableChanged)

				if self.plugin.options['project'] != '':
					self.prjbox.prjcombo.setCurrentText(self.plugin.options['project'])

				if self.plugin.options['driver'] != '':
					try:
						item = str(self.driverbox.drivercombo.listBox().findItem(self.plugin.options['driver'],tqt.TQt.ExactMatch).text())
						self.driverbox.drivercombo.setCurrentText(item)
						self.driverbox.activated(item)
					except:
						pass

				if self.plugin.plugintype == "Destination":
					#typebox = tqt.TQHBox(parent)
					#label = tqt.TQLabel("Operation:",typebox)
					#combobox = tqt.TQComboBox(typebox)
					#combobox.insertItem("Append")
					#combobox.insertItem("Replace")
					#combobox.insertItem("Update")
					#combobox.insertItem("Update/Insert")
					#combobox.insertItem("Insert new")
					#label.setBuddy(combobox)
					#typebox.setStretchFactor(combobox,1)
					pass
				elif self.plugin.plugintype == "Source":
					wherebox = tqt.TQHBox(parent)
					wherelabel = tqt.TQLabel("Where:",wherebox)
					self.whereedit = tqt.TQLineEdit(self.plugin.options['where'],wherebox)

					#orderbox = tqt.TQHBox(parent)
					#orderlabel = tqt.TQLabel("Order By:",orderbox)
					#orderedit = tqt.TQLineEdit("",orderbox)

				#errbox = tqt.TQHBox(parent)
				#errlabel = tqt.TQLabel("On Error:",errbox)
				#errcombo = tqt.TQComboBox(errbox)
				#errcombo.insertItem("Ask")
				#errcombo.insertItem("Skip")
				#errcombo.insertItem("Abort")
				#errlabel.setBuddy(errcombo)
				#errbox.setStretchFactor(errcombo,1)

				if self.plugin.options['autoconnect']:
					self.connectClicked()

			def projectChanged(self, text):
				#if self.driverbox.drivercombo.currentItem() != 0:
				#	self.driverbox.drivercombo.setCurrentItem(0)

				file = str(text)
				import os
				if re.search("^\\~(\\/|\\\\)",file):
					file = os.path.join(self.copycenterplugin.copycenter.homepath,file[2:])
				if file == "" or not os.path.isfile(file):
					self.driverbox.drivercombo.setCurrentItem(0)
					self.driverbox.activated(0)
					return

				connectiondata = self.copycenterplugin.drivermanager.createConnectionDataByFile(file)
				if connectiondata == None:
					raise Exception("Unsupported file.")

				drivername = connectiondata.driverName().lower()
				print("driver: %s" % drivername)
				for i in range(1,self.driverbox.drivercombo.count()):
					if drivername == self.driverbox.drivercombo.text(i).lower():
						self.driverbox.drivercombo.setCurrentItem(i)
						self.driverbox.activated(i)
						break

				if self.driverbox.driver != None:
					if self.driverbox.driver.isFileDriver():
						self.driverbox.fileedit.setText(connectiondata.fileName())
					else: # server
						self.driverbox.hostedit.setText(connectiondata.hostName())
						self.driverbox.portedit.setText(str(connectiondata.port()))
						self.driverbox.sockfilecheckbox.setChecked(connectiondata.localSocketFileUsed())
						self.driverbox.sockfileedit.setText(connectiondata.localSocketFileName())
						self.driverbox.useredit.setText(connectiondata.userName())
						self.driverbox.passedit.setText(connectiondata.password())
						self.driverbox.dbedit.setText(connectiondata.databaseName())

			def connectClicked(self):
				if self.driverbox.driver == None:
					print("No driver selected.")
					return False
				connectiondata = self.copycenterplugin.drivermanager.createConnectionData()
				if self.driverbox.driver.isFileDriver():
					file = str(self.driverbox.fileedit.text())
					if file == "" or not os.path.isfile(file):
						tqt.TQMessageBox.critical(self,"Failed to connect","There exists no such database file \"%s\"" % file)
						return False
					connectiondata.setFileName(file)
					connectiondata.setDatabaseName(file)
				else:
					connectiondata.setHostName(str(self.driverbox.hostedit.text()))
					connectiondata.setPort(str(self.driverbox.portedit.text()))
					connectiondata.setLocalSocketFileUsed(self.driverbox.sockfilecheckbox.isChecked())
					connectiondata.setLocalSocketFileName(str(self.driverbox.sockfileedit.text()))
					connectiondata.setPassword(str(self.driverbox.passedit.text()))
					connectiondata.setUserName(str(self.driverbox.useredit.text()))
					connectiondata.setDatabaseName(str(self.driverbox.dbedit.text()))
				print("Creating connection")
				connection = self.driverbox.driver.createConnection(connectiondata)
				print("Trying to connect")
				if not connection.connect():
					tqt.TQMessageBox.critical(self,"Failed to connect",connection.lastError())
					return False
				print("Use database \"%s\"" % connectiondata.databaseName())
				if not connection.useDatabase( connectiondata.databaseName() ):
					tqt.TQMessageBox.critical(self,"Failed to connect",connection.lastError())
					return False
				print("dbnames = %s" % connection.databaseNames())
				print("tablenames = %s" % connection.tableNames())
				#self.useDatabase(connection, filename)

				self.plugin.connection.kexidbconnection = connection
				self.updateConnectButtons()
				return True

			def disconnectClicked(self):
				if not self.plugin.connection.disconnect():
					tqt.TQMessageBox.critical(self,"Failed to disconnect",self.plugin.connection.lastError())
					return
				self.updateConnectButtons()

			def updateConnectButtons(self):
				connected = self.plugin.connection.isConnected()
				self.prjbox.setEnabled(not connected)
				self.driverbox.setEnabled(not connected)
				self.connectbtn.setEnabled( (not connected) and (self.driverbox.driver != None) )
				self.disconnectbtn.setEnabled(connected)
				self.tablebox.tablebtn.setEnabled(connected)
				self.fieldbox.tableChanged(self.tablebox.tableedit.text())

			def getOptionValue(self,optionname):
				try:
					if optionname == 'project': return str(self.prjbox.prjcombo.currentText())
					elif optionname == 'driver': return str(self.driverbox.drivercombo.currentText())
					elif optionname == 'file': return str(self.driverbox.fileedit.text())
					elif optionname == 'hostname': return str(self.driverbox.hostedit.text())
					elif optionname == 'port': return str(self.driverbox.portedit.text())
					elif optionname == 'usesocketfile': return str(self.driverbox.sockfilecheckbox.isChecked())
					elif optionname == 'socketfile': return str(self.driverbox.sockfileedit.text())
					elif optionname == 'username': return str(self.driverbox.useredit.text())
					elif optionname == 'password': return str(self.driverbox.passedit.text())
					elif optionname == 'database': return str(self.driverbox.dbedit.text())
					elif optionname == 'table': return str(self.tablebox.tableedit.text())
					elif optionname == 'fields': return str(self.fieldbox.fieldsedit.text())
					elif optionname == 'where': return str(self.whereedit.text())
				except:
					pass
				return ""

		mainbox = MainBox(self,plugin,parent)
		plugin.widget = mainbox
		return mainbox