dlg_create_constraint.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. """
  2. /***************************************************************************
  3. Name : DB Manager
  4. Description : Database manager plugin for QGIS
  5. Date : Oct 13, 2011
  6. copyright : (C) 2011 by Giuseppe Sucameli
  7. email : brush.tyler@gmail.com
  8. The content of this file is based on
  9. - PG_Manager by Martin Dobias (GPLv2 license)
  10. ***************************************************************************/
  11. /***************************************************************************
  12. * *
  13. * This program is free software; you can redistribute it and/or modify *
  14. * it under the terms of the GNU General Public License as published by *
  15. * the Free Software Foundation; either version 2 of the License, or *
  16. * (at your option) any later version. *
  17. * *
  18. ***************************************************************************/
  19. """
  20. from qgis.PyQt.QtCore import Qt
  21. from qgis.PyQt.QtWidgets import QDialog, QApplication
  22. from qgis.utils import OverrideCursor
  23. from .db_plugins.plugin import DbError
  24. from .dlg_db_error import DlgDbError
  25. from .db_plugins.plugin import TableConstraint
  26. from .ui.ui_DlgCreateConstraint import Ui_DbManagerDlgCreateConstraint as Ui_Dialog
  27. class DlgCreateConstraint(QDialog, Ui_Dialog):
  28. def __init__(self, parent=None, table=None, db=None):
  29. QDialog.__init__(self, parent)
  30. self.table = table
  31. self.db = self.table.database() if self.table and self.table.database() else db
  32. self.setupUi(self)
  33. self.buttonBox.accepted.connect(self.createConstraint)
  34. self.populateColumns()
  35. def populateColumns(self):
  36. self.cboColumn.clear()
  37. for fld in self.table.fields():
  38. self.cboColumn.addItem(fld.name)
  39. def createConstraint(self):
  40. constr = self.getConstraint()
  41. # now create the constraint
  42. with OverrideCursor(Qt.WaitCursor):
  43. try:
  44. self.table.addConstraint(constr)
  45. except DbError as e:
  46. DlgDbError.showError(e, self)
  47. return
  48. self.accept()
  49. def getConstraint(self):
  50. constr = TableConstraint(self.table)
  51. constr.name = ""
  52. constr.type = TableConstraint.TypePrimaryKey if self.radPrimaryKey.isChecked() else TableConstraint.TypeUnique
  53. constr.columns = []
  54. column = self.cboColumn.currentText()
  55. for fld in self.table.fields():
  56. if fld.name == column:
  57. constr.columns.append(fld.num)
  58. break
  59. return constr