plugin.py 46.6 KB
Newer Older
xuebingbing's avatar
xuebingbing committed
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 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
# -*- coding: utf-8 -*-

"""
/***************************************************************************
Name                 : DB Manager
Description          : Database manager plugin for QGIS
Date                 : May 23, 2011
copyright            : (C) 2011 by Giuseppe Sucameli
email                : brush.tyler@gmail.com

 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""
from builtins import str
from builtins import range

from qgis.PyQt.QtCore import Qt, QObject, pyqtSignal
from qgis.PyQt.QtWidgets import QApplication, QAction, QMenu, QInputDialog, QMessageBox
from qgis.PyQt.QtGui import QKeySequence, QIcon

from qgis.gui import QgsMessageBar
from qgis.core import (
    Qgis,
    QgsApplication,
    QgsSettings,
    QgsMapLayerType,
    QgsWkbTypes,
    QgsProviderConnectionException,
    QgsProviderRegistry,
)
from ..db_plugins import createDbPlugin


class BaseError(Exception):

    """Base class for exceptions in the plugin."""

    def __init__(self, e):
        if isinstance(e, Exception):
            msg = e.args[0] if len(e.args) > 0 else ''
        else:
            msg = e

        if not isinstance(msg, str):
            msg = str(msg, 'utf-8', 'replace')  # convert from utf8 and replace errors (if any)

        self.msg = msg
        Exception.__init__(self, msg)

    def __unicode__(self):
        return self.msg


class InvalidDataException(BaseError):
    pass


class ConnectionError(BaseError):
    pass


class DbError(BaseError):

    def __init__(self, e, query=None):
        BaseError.__init__(self, e)
        self.query = str(query) if query is not None else None

    def __unicode__(self):
        if self.query is None:
            return BaseError.__unicode__(self)

        msg = QApplication.translate("DBManagerPlugin", "Error:\n{0}").format(BaseError.__unicode__(self))
        if self.query:
            msg += QApplication.translate("DBManagerPlugin", "\n\nQuery:\n{0}").format(self.query)
        return msg


class DBPlugin(QObject):
    deleted = pyqtSignal()
    changed = pyqtSignal()
    aboutToChange = pyqtSignal()

    def __init__(self, conn_name, parent=None):
        QObject.__init__(self, parent)
        self.connName = conn_name
        self.db = None

    def __del__(self):
        pass  # print "DBPlugin.__del__", self.connName

    def connectionIcon(self):
        return QgsApplication.getThemeIcon("/mIconDbSchema.svg")

    def connectionName(self):
        return self.connName

    def database(self):
        return self.db

    def info(self):
        from .info_model import DatabaseInfo

        return DatabaseInfo(None)

    def connect(self, parent=None):
        raise NotImplementedError('Needs to be implemented by subclasses')

    def connectToUri(self, uri):
        self.db = self.databasesFactory(self, uri)
        if self.db:
            return True
        return False

    def reconnect(self):
        if self.db is not None:
            uri = self.db.uri()
            self.db.deleteLater()
            self.db = None
            return self.connectToUri(uri)
        return self.connect(self.parent())

    def remove(self):

        # Try the new API first, fallback to legacy
        try:
            md = QgsProviderRegistry.instance().providerMetadata(self.providerName())
            md.deleteConnection(self.connectionName())
        except (AttributeError, QgsProviderConnectionException) as ex:
            settings = QgsSettings()
            settings.beginGroup(u"/%s/%s" % (self.connectionSettingsKey(), self.connectionName()))
            settings.remove("")

        self.deleted.emit()
        return True

    @classmethod
    def addConnection(self, conn_name, uri):
        raise NotImplementedError('Needs to be implemented by subclasses')

    @classmethod
    def icon(self):
        return None

    @classmethod
    def typeName(self):
        # return the db typename (e.g. 'postgis')
        pass

    @classmethod
    def typeNameString(self):
        # return the db typename string (e.g. 'PostGIS')
        pass

    @classmethod
    def providerName(self):
        # return the provider's name (e.g. 'postgres')
        pass

    @classmethod
    def connectionSettingsKey(self):
        # return the key used to store the connections in settings
        pass

    @classmethod
    def connections(self):
        # get the list of connections

        conn_list = []

        # First try with the new core API, if that fails, proceed with legacy code
        try:
            md = QgsProviderRegistry.instance().providerMetadata(self.providerName())
            for name in md.dbConnections(False).keys():
                conn_list.append(createDbPlugin(self.typeName(), name))
        except (AttributeError, QgsProviderConnectionException) as ex:
            settings = QgsSettings()
            settings.beginGroup(self.connectionSettingsKey())
            for name in settings.childGroups():
                conn_list.append(createDbPlugin(self.typeName(), name))
            settings.endGroup()

        return conn_list

    def databasesFactory(self, connection, uri):
        return None

    @classmethod
    def addConnectionActionSlot(self, item, action, parent):
        raise NotImplementedError('Needs to be implemented by subclasses')

    def removeActionSlot(self, item, action, parent):
        QApplication.restoreOverrideCursor()
        try:
            res = QMessageBox.question(parent, QApplication.translate("DBManagerPlugin", "DB Manager"),
                                       QApplication.translate("DBManagerPlugin",
                                                              "Really remove connection to {0}?").format(item.connectionName()),
                                       QMessageBox.Yes | QMessageBox.No)
            if res != QMessageBox.Yes:
                return
        finally:
            QApplication.setOverrideCursor(Qt.WaitCursor)

        item.remove()


class DbItemObject(QObject):
    changed = pyqtSignal()
    aboutToChange = pyqtSignal()
    deleted = pyqtSignal()

    def __init__(self, parent=None):
        QObject.__init__(self, parent)

    def database(self):
        return None

    def refresh(self):
        self.changed.emit()  # refresh the item data reading them from the db

    def info(self):
        pass

    def runAction(self):
        pass

    def registerActions(self, mainWindow):
        pass


class Database(DbItemObject):

    def __init__(self, dbplugin, uri):
        DbItemObject.__init__(self, dbplugin)
        self.connector = self.connectorsFactory(uri)

    def connectorsFactory(self, uri):
        return None

    def __del__(self):
        self.connector = None
        pass  # print "Database.__del__", self

    def connection(self):
        return self.parent()

    def dbplugin(self):
        return self.parent()

    def database(self):
        return self

    def uri(self):
        return self.connector.uri()

    def publicUri(self):
        return self.connector.publicUri()

    def delete(self):
        self.aboutToChange.emit()
        ret = self.connection().remove()
        if ret is not False:
            self.deleted.emit()
        return ret

    def info(self):
        from .info_model import DatabaseInfo

        return DatabaseInfo(self)

    def sqlResultModel(self, sql, parent):
        from .data_model import SqlResultModel

        return SqlResultModel(self, sql, parent)

    def sqlResultModelAsync(self, sql, parent):
        from .data_model import SqlResultModelAsync

        return SqlResultModelAsync(self, sql, parent)

    def columnUniqueValuesModel(self, col, table, limit=10):
        l = ""
        if limit is not None:
            l = "LIMIT %d" % limit
        return self.sqlResultModel("SELECT DISTINCT %s FROM %s %s" % (col, table, l), self)

    def uniqueIdFunction(self):
        """Return a SQL function used to generate a unique id for rows of a query"""
        # may be overloaded by derived classes
        return "row_number() over ()"

    def toSqlLayer(self, sql, geomCol, uniqueCol, layerName="QueryLayer", layerType=None, avoidSelectById=False, filter=""):
        from qgis.core import QgsVectorLayer, QgsRasterLayer

        if uniqueCol is None:
            if hasattr(self, 'uniqueIdFunction'):
                uniqueFct = self.uniqueIdFunction()
                if uniqueFct is not None:
                    q = 1
                    while "_subq_%d_" % q in sql:
                        q += 1
                    sql = u"SELECT %s AS _uid_,* FROM (%s\n) AS _subq_%d_" % (uniqueFct, sql, q)
                    uniqueCol = "_uid_"

        uri = self.uri()
        uri.setDataSource("", u"(%s\n)" % sql, geomCol, filter, uniqueCol)
        if avoidSelectById:
            uri.disableSelectAtId(True)
        provider = self.dbplugin().providerName()
        if layerType == QgsMapLayerType.RasterLayer:
            return QgsRasterLayer(uri.uri(False), layerName, provider)
        return QgsVectorLayer(uri.uri(False), layerName, provider)

    def registerAllActions(self, mainWindow):
        self.registerDatabaseActions(mainWindow)
        self.registerSubPluginActions(mainWindow)

    def registerSubPluginActions(self, mainWindow):
        # load plugins!
        try:
            exec(u"from .%s.plugins import load" % self.dbplugin().typeName(), globals())
        except ImportError:
            pass
        else:
            load(self, mainWindow)  # NOQA

    def registerDatabaseActions(self, mainWindow):
        action = QAction(QApplication.translate("DBManagerPlugin", "&Re-connect"), self)
        mainWindow.registerAction(action, QApplication.translate("DBManagerPlugin", "&Database"),
                                  self.reconnectActionSlot)

        if self.schemas() is not None:
            action = QAction(QApplication.translate("DBManagerPlugin", "&Create Schema…"), self)
            mainWindow.registerAction(action, QApplication.translate("DBManagerPlugin", "&Schema"),
                                      self.createSchemaActionSlot)
            action = QAction(QApplication.translate("DBManagerPlugin", "&Delete (Empty) Schema"), self)
            mainWindow.registerAction(action, QApplication.translate("DBManagerPlugin", "&Schema"),
                                      self.deleteSchemaActionSlot)

        action = QAction(QApplication.translate("DBManagerPlugin", "Delete Selected Item"), self)
        mainWindow.registerAction(action, None, self.deleteActionSlot)
        action.setShortcuts(QKeySequence.Delete)

        action = QAction(QgsApplication.getThemeIcon("/mActionCreateTable.svg"),
                         QApplication.translate("DBManagerPlugin", "&Create Table…"), self)
        mainWindow.registerAction(action, QApplication.translate("DBManagerPlugin", "&Table"),
                                  self.createTableActionSlot)
        action = QAction(QgsApplication.getThemeIcon("/mActionEditTable.svg"),
                         QApplication.translate("DBManagerPlugin", "&Edit Table…"), self)
        mainWindow.registerAction(action, QApplication.translate("DBManagerPlugin", "&Table"), self.editTableActionSlot)
        action = QAction(QgsApplication.getThemeIcon("/mActionDeleteTable.svg"),
                         QApplication.translate("DBManagerPlugin", "&Delete Table/View…"), self)
        mainWindow.registerAction(action, QApplication.translate("DBManagerPlugin", "&Table"),
                                  self.deleteTableActionSlot)
        action = QAction(QApplication.translate("DBManagerPlugin", "&Empty Table…"), self)
        mainWindow.registerAction(action, QApplication.translate("DBManagerPlugin", "&Table"),
                                  self.emptyTableActionSlot)

        if self.schemas() is not None:
            action = QAction(QApplication.translate("DBManagerPlugin", "&Move to Schema"), self)
            action.setMenu(QMenu(mainWindow))

            def invoke_callback():
                return mainWindow.invokeCallback(self.prepareMenuMoveTableToSchemaActionSlot)

            action.menu().aboutToShow.connect(invoke_callback)
            mainWindow.registerAction(action, QApplication.translate("DBManagerPlugin", "&Table"))

    def reconnectActionSlot(self, item, action, parent):
        db = item.database()
        db.connection().reconnect()
        db.refresh()

    def deleteActionSlot(self, item, action, parent):
        if isinstance(item, Schema):
            self.deleteSchemaActionSlot(item, action, parent)
        elif isinstance(item, Table):
            self.deleteTableActionSlot(item, action, parent)
        else:
            QApplication.restoreOverrideCursor()
            parent.infoBar.pushMessage(QApplication.translate("DBManagerPlugin", "Cannot delete the selected item."),
                                       Qgis.Info, parent.iface.messageTimeout())
            QApplication.setOverrideCursor(Qt.WaitCursor)

    def createSchemaActionSlot(self, item, action, parent):
        QApplication.restoreOverrideCursor()
        try:
            if not isinstance(item, (DBPlugin, Schema, Table)) or item.database() is None:
                parent.infoBar.pushMessage(
                    QApplication.translate("DBManagerPlugin", "No database selected or you are not connected to it."),
                    Qgis.Info, parent.iface.messageTimeout())
                return
            (schema, ok) = QInputDialog.getText(parent, QApplication.translate("DBManagerPlugin", "New schema"),
                                                QApplication.translate("DBManagerPlugin", "Enter new schema name"))
            if not ok:
                return
        finally:
            QApplication.setOverrideCursor(Qt.WaitCursor)

        self.createSchema(schema)

    def deleteSchemaActionSlot(self, item, action, parent):
        QApplication.restoreOverrideCursor()
        try:
            if not isinstance(item, Schema):
                parent.infoBar.pushMessage(
                    QApplication.translate("DBManagerPlugin", "Select an empty schema for deletion."),
                    Qgis.Info, parent.iface.messageTimeout())
                return
            res = QMessageBox.question(parent, QApplication.translate("DBManagerPlugin", "DB Manager"),
                                       QApplication.translate("DBManagerPlugin",
                                                              "Really delete schema {0}?").format(item.name),
                                       QMessageBox.Yes | QMessageBox.No)
            if res != QMessageBox.Yes:
                return
        finally:
            QApplication.setOverrideCursor(Qt.WaitCursor)

        item.delete()

    def schemasFactory(self, row, db):
        return None

    def schemas(self):
        schemas = self.connector.getSchemas()
        if schemas is not None:
            schemas = [self.schemasFactory(x, self) for x in schemas]
        return schemas

    def createSchema(self, name):
        self.connector.createSchema(name)
        self.refresh()

    def createTableActionSlot(self, item, action, parent):
        QApplication.restoreOverrideCursor()
        if not hasattr(item, 'database') or item.database() is None:
            parent.infoBar.pushMessage(
                QApplication.translate("DBManagerPlugin", "No database selected or you are not connected to it."),
                Qgis.Info, parent.iface.messageTimeout())
            return
        from ..dlg_create_table import DlgCreateTable

        DlgCreateTable(item, parent).exec_()
        QApplication.setOverrideCursor(Qt.WaitCursor)

    def editTableActionSlot(self, item, action, parent):
        QApplication.restoreOverrideCursor()
        try:
            if not isinstance(item, Table) or item.isView:
                parent.infoBar.pushMessage(QApplication.translate("DBManagerPlugin", "Select a table to edit."),
                                           Qgis.Info, parent.iface.messageTimeout())
                return

            if isinstance(item, RasterTable):
                parent.infoBar.pushMessage(QApplication.translate("DBManagerPlugin", "Editing of raster tables is not supported."),
                                           Qgis.Info, parent.iface.messageTimeout())
                return

            from ..dlg_table_properties import DlgTableProperties

            DlgTableProperties(item, parent).exec_()
        finally:
            QApplication.setOverrideCursor(Qt.WaitCursor)

    def deleteTableActionSlot(self, item, action, parent):
        QApplication.restoreOverrideCursor()
        try:
            if not isinstance(item, Table):
                parent.infoBar.pushMessage(
                    QApplication.translate("DBManagerPlugin", "Select a table/view for deletion."),
                    Qgis.Info, parent.iface.messageTimeout())
                return
            res = QMessageBox.question(parent, QApplication.translate("DBManagerPlugin", "DB Manager"),
                                       QApplication.translate("DBManagerPlugin",
                                                              "Really delete table/view {0}?").format(item.name),
                                       QMessageBox.Yes | QMessageBox.No)
            if res != QMessageBox.Yes:
                return
        finally:
            QApplication.setOverrideCursor(Qt.WaitCursor)

        item.delete()

    def emptyTableActionSlot(self, item, action, parent):
        QApplication.restoreOverrideCursor()
        try:
            if not isinstance(item, Table) or item.isView:
                parent.infoBar.pushMessage(QApplication.translate("DBManagerPlugin", "Select a table to empty it."),
                                           Qgis.Info, parent.iface.messageTimeout())
                return
            res = QMessageBox.question(parent, QApplication.translate("DBManagerPlugin", "DB Manager"),
                                       QApplication.translate("DBManagerPlugin",
                                                              "Really delete all items from table {0}?").format(item.name),
                                       QMessageBox.Yes | QMessageBox.No)
            if res != QMessageBox.Yes:
                return
        finally:
            QApplication.setOverrideCursor(Qt.WaitCursor)

        item.empty()

    def prepareMenuMoveTableToSchemaActionSlot(self, item, menu, mainWindow):
        """ populate menu with schemas """
        def slot(x):
            return lambda: mainWindow.invokeCallback(self.moveTableToSchemaActionSlot, x)

        menu.clear()
        for schema in self.schemas():
            menu.addAction(schema.name, slot(schema))

    def moveTableToSchemaActionSlot(self, item, action, parent, new_schema):
        QApplication.restoreOverrideCursor()
        try:
            if not isinstance(item, Table):
                parent.infoBar.pushMessage(QApplication.translate("DBManagerPlugin", "Select a table/view."),
                                           Qgis.Info, parent.iface.messageTimeout())
                return
        finally:
            QApplication.setOverrideCursor(Qt.WaitCursor)

        item.moveToSchema(new_schema)

    def tablesFactory(self, row, db, schema=None):
        typ, row = row[0], row[1:]
        if typ == Table.VectorType:
            return self.vectorTablesFactory(row, db, schema)
        elif typ == Table.RasterType:
            return self.rasterTablesFactory(row, db, schema)
        return self.dataTablesFactory(row, db, schema)

    def dataTablesFactory(self, row, db, schema=None):
        return None

    def vectorTablesFactory(self, row, db, schema=None):
        return None

    def rasterTablesFactory(self, row, db, schema=None):
        return None

    def tables(self, schema=None, sys_tables=False):
        tables = self.connector.getTables(schema.name if schema else None, sys_tables)
        if tables is not None:
            ret = []
            for t in tables:
                table = self.tablesFactory(t, self, schema)
                ret.append(table)

                # Similarly to what to browser does, if the geom type is generic geometry,
                # we additionnly add three copies of the layer to allow importing
                if isinstance(table, VectorTable):
                    if table.geomType == 'GEOMETRY':
                        point_table = self.tablesFactory(t, self, schema)
                        point_table.geomType = 'POINT'
                        ret.append(point_table)

                        line_table = self.tablesFactory(t, self, schema)
                        line_table.geomType = 'LINESTRING'
                        ret.append(line_table)

                        poly_table = self.tablesFactory(t, self, schema)
                        poly_table.geomType = 'POLYGON'
                        ret.append(poly_table)

        return ret

    def createTable(self, table, fields, schema=None):
        field_defs = [x.definition() for x in fields]
        pkeys = [x for x in fields if x.primaryKey]
        pk_name = pkeys[0].name if len(pkeys) > 0 else None

        ret = self.connector.createTable((schema, table), field_defs, pk_name)
        if ret is not False:
            self.refresh()
        return ret

    def createVectorTable(self, table, fields, geom, schema=None):
        ret = self.createTable(table, fields, schema)
        if not ret:
            return False

        try:
            createGeomCol = geom is not None
            if createGeomCol:
                geomCol, geomType, geomSrid, geomDim = geom[:4]
                createSpatialIndex = geom[4] if len(geom) > 4 else False

                self.connector.addGeometryColumn((schema, table), geomCol, geomType, geomSrid, geomDim)

                if createSpatialIndex:
                    # commit data definition changes, otherwise index can't be built
                    self.connector._commit()
                    self.connector.createSpatialIndex((schema, table), geomCol)

        finally:
            self.refresh()
        return True

    def explicitSpatialIndex(self):
        return False

    def spatialIndexClause(self, src_table, src_column, dest_table, dest_table_column):
        return None

    def hasLowercaseFieldNamesOption(self):
        return False


class Schema(DbItemObject):

    def __init__(self, db):
        DbItemObject.__init__(self, db)
        self.oid = self.name = self.owner = self.perms = None
        self.comment = None
        self.tableCount = 0

    def __del__(self):
        pass  # print "Schema.__del__", self

    def database(self):
        return self.parent()

    def schema(self):
        return self

    def tables(self):
        return self.database().tables(self)

    def delete(self):
        self.aboutToChange.emit()
        ret = self.database().connector.deleteSchema(self.name)
        if ret is not False:
            self.deleted.emit()
        return ret

    def rename(self, new_name):
        self.aboutToChange.emit()
        ret = self.database().connector.renameSchema(self.name, new_name)
        if ret is not False:
            self.name = new_name
            # FIXME: refresh triggers
            self.refresh()
        return ret

    def info(self):
        from .info_model import SchemaInfo

        return SchemaInfo(self)


class Table(DbItemObject):
    TableType, VectorType, RasterType = list(range(3))

    def __init__(self, db, schema=None, parent=None):
        DbItemObject.__init__(self, db)
        self._schema = schema
        if hasattr(self, 'type'):
            return
        self.type = Table.TableType

        self.name = self.isView = self.owner = self.pages = None
        self.comment = None
        self.rowCount = None

        self._fields = self._indexes = self._constraints = self._triggers = self._rules = None

    def __del__(self):
        pass  # print "Table.__del__", self

    def canBeAddedToCanvas(self):
        return True

    def database(self):
        return self.parent()

    def schema(self):
        return self._schema

    def schemaName(self):
        return self.schema().name if self.schema() else None

    def quotedName(self):
        return self.database().connector.quoteId((self.schemaName(), self.name))

    def delete(self):
        self.aboutToChange.emit()
        if self.isView:
            ret = self.database().connector.deleteView((self.schemaName(), self.name))
        else:
            ret = self.database().connector.deleteTable((self.schemaName(), self.name))
        if ret is not False:
            self.deleted.emit()
        return ret

    def rename(self, new_name):
        self.aboutToChange.emit()
        ret = self.database().connector.renameTable((self.schemaName(), self.name), new_name)
        if ret is not False:
            self.name = new_name
            self._triggers = None
            self._rules = None
            self._constraints = None
            self.refresh()
        return ret

    def empty(self):
        self.aboutToChange.emit()
        ret = self.database().connector.emptyTable((self.schemaName(), self.name))
        if ret is not False:
            self.refreshRowCount()
        return ret

    def moveToSchema(self, schema):
        self.aboutToChange.emit()
        if self.schema() == schema:
            return True
        ret = self.database().connector.moveTableToSchema((self.schemaName(), self.name), schema.name)
        if ret is not False:
            self.schema().refresh()
            schema.refresh()
        return ret

    def info(self):
        from .info_model import TableInfo

        return TableInfo(self)

    def uri(self):
        uri = self.database().uri()
        schema = self.schemaName() if self.schemaName() else ''
        geomCol = self.geomColumn if self.type in [Table.VectorType, Table.RasterType] else ""
        uniqueCol = self.getValidQgisUniqueFields(True) if self.isView else None
        uri.setDataSource(schema, self.name, geomCol if geomCol else None, None, uniqueCol.name if uniqueCol else "")
        return uri

    def mimeUri(self):
        layerType = "raster" if self.type == Table.RasterType else "vector"
        return u"%s:%s:%s:%s" % (layerType, self.database().dbplugin().providerName(), self.name, self.uri().uri(False))

    def toMapLayer(self):
        from qgis.core import QgsVectorLayer, QgsRasterLayer

        provider = self.database().dbplugin().providerName()
        uri = self.uri().uri(False)
        if self.type == Table.RasterType:
            return QgsRasterLayer(uri, self.name, provider)
        return QgsVectorLayer(uri, self.name, provider)

    def getValidQgisUniqueFields(self, onlyOne=False):
        """ list of fields valid to load the table as layer in Qgis canvas.
                Qgis automatically search for a valid unique field, so it's
                needed only for queries and views """

        ret = []

        # add the pk
        pkcols = [x for x in self.fields() if x.primaryKey]
        if len(pkcols) == 1:
            ret.append(pkcols[0])

        # then add both oid, serial and int fields with an unique index
        indexes = self.indexes()
        if indexes is not None:
            for idx in indexes:
                if idx.isUnique and len(idx.columns) == 1:
                    fld = idx.fields()[idx.columns[0]]
                    if fld.dataType in ["oid", "serial", "int4", "int8"] and fld not in ret:
                        ret.append(fld)

        # and finally append the other suitable fields
        for fld in self.fields():
            if fld.dataType in ["oid", "serial", "int4", "int8"] and fld not in ret:
                ret.append(fld)

        if onlyOne:
            return ret[0] if len(ret) > 0 else None
        return ret

    def tableDataModel(self, parent):
        pass

    def tableFieldsFactory(self, row, table):
        raise NotImplementedError('Needs to be implemented by subclasses')

    def fields(self):
        if self._fields is None:
            fields = self.database().connector.getTableFields((self.schemaName(), self.name))
            if fields is not None:
                self._fields = [self.tableFieldsFactory(x, self) for x in fields]
        return self._fields

    def refreshFields(self):
        self._fields = None  # refresh table fields
        self.refresh()

    def addField(self, fld):
        self.aboutToChange.emit()
        ret = self.database().connector.addTableColumn((self.schemaName(), self.name), fld.definition())
        if ret is not False:
            self.refreshFields()
        return ret

    def deleteField(self, fld):
        self.aboutToChange.emit()
        ret = self.database().connector.deleteTableColumn((self.schemaName(), self.name), fld.name)
        if ret is not False:
            self.refreshFields()
            self.refreshConstraints()
            self.refreshIndexes()
        return ret

    def addGeometryColumn(self, geomCol, geomType, srid, dim, createSpatialIndex=False):
        self.aboutToChange.emit()
        ret = self.database().connector.addGeometryColumn((self.schemaName(), self.name), geomCol, geomType, srid, dim)
        if not ret:
            return False

        try:
            if createSpatialIndex:
                # commit data definition changes, otherwise index can't be built
                self.database().connector._commit()
                self.database().connector.createSpatialIndex((self.schemaName(), self.name), geomCol)

        finally:
            self.schema().refresh() if self.schema() else self.database().refresh()  # another table was added
        return True

    def tableConstraintsFactory(self):
        return None

    def constraints(self):
        if self._constraints is None:
            constraints = self.database().connector.getTableConstraints((self.schemaName(), self.name))
            if constraints is not None:
                self._constraints = [self.tableConstraintsFactory(x, self) for x in constraints]
        return self._constraints

    def refreshConstraints(self):
        self._constraints = None  # refresh table constraints
        self.refresh()

    def addConstraint(self, constr):
        self.aboutToChange.emit()
        if constr.type == TableConstraint.TypePrimaryKey:
            ret = self.database().connector.addTablePrimaryKey((self.schemaName(), self.name),
                                                               constr.fields()[constr.columns[0]].name)
        elif constr.type == TableConstraint.TypeUnique:
            ret = self.database().connector.addTableUniqueConstraint((self.schemaName(), self.name),
                                                                     constr.fields()[constr.columns[0]].name)
        else:
            return False
        if ret is not False:
            self.refreshConstraints()
        return ret

    def deleteConstraint(self, constr):
        self.aboutToChange.emit()
        ret = self.database().connector.deleteTableConstraint((self.schemaName(), self.name), constr.name)
        if ret is not False:
            self.refreshConstraints()
        return ret

    def tableIndexesFactory(self):
        return None

    def indexes(self):
        if self._indexes is None:
            indexes = self.database().connector.getTableIndexes((self.schemaName(), self.name))
            if indexes is not None:
                self._indexes = [self.tableIndexesFactory(x, self) for x in indexes]
        return self._indexes

    def refreshIndexes(self):
        self._indexes = None  # refresh table indexes
        self.refresh()

    def addIndex(self, idx):
        self.aboutToChange.emit()
        ret = self.database().connector.createTableIndex((self.schemaName(), self.name), idx.name,
                                                         idx.fields()[idx.columns[0]].name)
        if ret is not False:
            self.refreshIndexes()
        return ret

    def deleteIndex(self, idx):
        self.aboutToChange.emit()
        ret = self.database().connector.deleteTableIndex((self.schemaName(), self.name), idx.name)
        if ret is not False:
            self.refreshIndexes()
        return ret

    def tableTriggersFactory(self, row, table):
        return None

    def triggers(self):
        if self._triggers is None:
            triggers = self.database().connector.getTableTriggers((self.schemaName(), self.name))
            if triggers is not None:
                self._triggers = [self.tableTriggersFactory(x, self) for x in triggers]
        return self._triggers

    def refreshTriggers(self):
        self._triggers = None  # refresh table triggers
        self.refresh()

    def tableRulesFactory(self, row, table):
        return None

    def rules(self):
        if self._rules is None:
            rules = self.database().connector.getTableRules((self.schemaName(), self.name))
            if rules is not None:
                self._rules = [self.tableRulesFactory(x, self) for x in rules]
        return self._rules

    def refreshRules(self):
        self._rules = None  # refresh table rules
        self.refresh()

    def refreshRowCount(self):
        self.aboutToChange.emit()
        prevRowCount = self.rowCount
        try:
            self.rowCount = self.database().connector.getTableRowCount((self.schemaName(), self.name))
            self.rowCount = int(self.rowCount) if self.rowCount is not None else None
        except DbError:
            self.rowCount = None
        if self.rowCount != prevRowCount:
            self.refresh()

    def runAction(self, action):
        action = str(action)

        if action.startswith("rows/"):
            if action == "rows/count":
                self.refreshRowCount()
                return True

        elif action.startswith("triggers/"):
            parts = action.split('/')
            trigger_action = parts[1]

            msg = QApplication.translate("DBManagerPlugin", "Do you want to {0} all triggers?").format(trigger_action)
            QApplication.restoreOverrideCursor()
            try:
                if QMessageBox.question(None, QApplication.translate("DBManagerPlugin", "Table triggers"), msg,
                                        QMessageBox.Yes | QMessageBox.No) == QMessageBox.No:
                    return False
            finally:
                QApplication.setOverrideCursor(Qt.WaitCursor)

            if trigger_action == "enable" or trigger_action == "disable":
                enable = trigger_action == "enable"
                self.aboutToChange.emit()
                self.database().connector.enableAllTableTriggers(enable, (self.schemaName(), self.name))
                self.refreshTriggers()
                return True

        elif action.startswith("trigger/"):
            parts = action.split('/')
            trigger_name = parts[1]
            trigger_action = parts[2]

            msg = QApplication.translate("DBManagerPlugin", "Do you want to {0} trigger {1}?").format(
                trigger_action, trigger_name)
            QApplication.restoreOverrideCursor()
            try:
                if QMessageBox.question(None, QApplication.translate("DBManagerPlugin", "Table trigger"), msg,
                                        QMessageBox.Yes | QMessageBox.No) == QMessageBox.No:
                    return False
            finally:
                QApplication.setOverrideCursor(Qt.WaitCursor)

            if trigger_action == "delete":
                self.aboutToChange.emit()
                self.database().connector.deleteTableTrigger(trigger_name, (self.schemaName(), self.name))
                self.refreshTriggers()
                return True

            elif trigger_action == "enable" or trigger_action == "disable":
                enable = trigger_action == "enable"
                self.aboutToChange.emit()
                self.database().connector.enableTableTrigger(trigger_name, enable, (self.schemaName(), self.name))
                self.refreshTriggers()
                return True

        return False


class VectorTable(Table):

    def __init__(self, db, schema=None, parent=None):
        if not hasattr(self, 'type'):  # check if the superclass constructor was called yet!
            Table.__init__(self, db, schema, parent)
        self.type = Table.VectorType
        self.geomColumn = self.geomType = self.geomDim = self.srid = None
        self.estimatedExtent = self.extent = None

    def info(self):
        from .info_model import VectorTableInfo

        return VectorTableInfo(self)

    def uri(self):
        uri = super().uri()
        for f in self.fields():
            if f.primaryKey:
                uri.setKeyColumn(f.name)
                break
        uri.setWkbType(QgsWkbTypes.parseType(self.geomType))
        return uri

    def hasSpatialIndex(self, geom_column=None):
        geom_column = geom_column if geom_column is not None else self.geomColumn
        fld = None
        for fld in self.fields():
            if fld.name == geom_column:
                break
        if fld is None:
            return False

        for idx in self.indexes():
            if fld.num in idx.columns:
                return True
        return False

    def createSpatialIndex(self, geom_column=None):
        self.aboutToChange.emit()
        geom_column = geom_column if geom_column is not None else self.geomColumn
        ret = self.database().connector.createSpatialIndex((self.schemaName(), self.name), geom_column)
        if ret is not False:
            self.refreshIndexes()
        return ret

    def deleteSpatialIndex(self, geom_column=None):
        self.aboutToChange.emit()
        geom_column = geom_column if geom_column is not None else self.geomColumn
        ret = self.database().connector.deleteSpatialIndex((self.schemaName(), self.name), geom_column)
        if ret is not False:
            self.refreshIndexes()
        return ret

    def refreshTableExtent(self):
        prevExtent = self.extent
        try:
            self.extent = self.database().connector.getTableExtent((self.schemaName(), self.name), self.geomColumn)
        except DbError:
            self.extent = None
        if self.extent != prevExtent:
            self.refresh()

    def refreshTableEstimatedExtent(self):
        prevEstimatedExtent = self.estimatedExtent
        try:
            self.estimatedExtent = self.database().connector.getTableEstimatedExtent((self.schemaName(), self.name),
                                                                                     self.geomColumn)
        except DbError:
            self.estimatedExtent = None
        if self.estimatedExtent != prevEstimatedExtent:
            self.refresh()

    def runAction(self, action):
        action = str(action)

        if action.startswith("spatialindex/"):
            parts = action.split('/')
            spatialIndex_action = parts[1]

            msg = QApplication.translate("DBManagerPlugin", "Do you want to {0} spatial index for field {1}?").format(
                spatialIndex_action, self.geomColumn)
            QApplication.restoreOverrideCursor()
            try:
                if QMessageBox.question(None, QApplication.translate("DBManagerPlugin", "Spatial Index"), msg,
                                        QMessageBox.Yes | QMessageBox.No) == QMessageBox.No:
                    return False
            finally:
                QApplication.setOverrideCursor(Qt.WaitCursor)

            if spatialIndex_action == "create":
                self.createSpatialIndex()
                return True
            elif spatialIndex_action == "delete":
                self.deleteSpatialIndex()
                return True

        if action.startswith("extent/"):
            if action == "extent/get":
                self.refreshTableExtent()
                return True

            if action == "extent/estimated/get":
                self.refreshTableEstimatedExtent()
                return True

        return Table.runAction(self, action)


class RasterTable(Table):

    def __init__(self, db, schema=None, parent=None):
        if not hasattr(self, 'type'):  # check if the superclass constructor was called yet!
            Table.__init__(self, db, schema, parent)
        self.type = Table.RasterType
        self.geomColumn = self.geomType = self.pixelSizeX = self.pixelSizeY = self.pixelType = self.isExternal = self.srid = None
        self.extent = None

    def info(self):
        from .info_model import RasterTableInfo

        return RasterTableInfo(self)


class TableSubItemObject(QObject):

    def __init__(self, table):
        QObject.__init__(self, table)

    def table(self):
        return self.parent()

    def database(self):
        return self.table().database() if self.table() else None


class TableField(TableSubItemObject):

    def __init__(self, table):
        TableSubItemObject.__init__(self, table)
        self.num = self.name = self.dataType = self.modifier = self.notNull = self.default = self.hasDefault = self.primaryKey = None
        self.comment = None

    def type2String(self):
        if self.modifier is None or self.modifier == -1:
            return u"%s" % self.dataType
        return u"%s (%s)" % (self.dataType, self.modifier)

    def default2String(self):
        if not self.hasDefault:
            return ''
        return self.default if self.default is not None else "NULL"

    def definition(self):
        from .connector import DBConnector

        quoteIdFunc = self.database().connector.quoteId if self.database() else DBConnector.quoteId

        name = quoteIdFunc(self.name)
        not_null = "NOT NULL" if self.notNull else ""

        txt = u"%s %s %s" % (name, self.type2String(), not_null)
        if self.hasDefault:
            txt += u" DEFAULT %s" % self.default2String()
        return txt

    def getComment(self):
        """Returns the comment for a field"""
        return ''

    def delete(self):
        return self.table().deleteField(self)

    def rename(self, new_name):
        return self.update(new_name)

    def update(self, new_name, new_type_str=None, new_not_null=None, new_default_str=None, new_comment=None):
        self.table().aboutToChange.emit()
        if self.name == new_name:
            new_name = None
        if self.type2String() == new_type_str:
            new_type_str = None
        if self.notNull == new_not_null:
            new_not_null = None
        if self.default2String() == new_default_str:
            new_default_str = None
        if self.comment == new_comment:
            new_comment = None
        ret = self.table().database().connector.updateTableColumn((self.table().schemaName(), self.table().name),
                                                                  self.name, new_name, new_type_str,
                                                                  new_not_null, new_default_str, new_comment)
        if ret is not False:
            self.table().refreshFields()
        return ret


class TableConstraint(TableSubItemObject):

    """ class that represents a constraint of a table (relation) """

    TypeCheck, TypeForeignKey, TypePrimaryKey, TypeUnique, TypeExclusion, TypeUnknown = list(range(6))
    types = {"c": TypeCheck, "f": TypeForeignKey, "p": TypePrimaryKey, "u": TypeUnique, "x": TypeExclusion}

    onAction = {"a": "NO ACTION", "r": "RESTRICT", "c": "CASCADE", "n": "SET NULL", "d": "SET DEFAULT"}
    matchTypes = {"u": "UNSPECIFIED", "f": "FULL", "p": "PARTIAL", "s": "SIMPLE"}

    def __init__(self, table):
        TableSubItemObject.__init__(self, table)
        self.name = self.type = self.columns = None

    def type2String(self):
        if self.type == TableConstraint.TypeCheck:
            return QApplication.translate("DBManagerPlugin", "Check")
        if self.type == TableConstraint.TypePrimaryKey:
            return QApplication.translate("DBManagerPlugin", "Primary key")
        if self.type == TableConstraint.TypeForeignKey:
            return QApplication.translate("DBManagerPlugin", "Foreign key")
        if self.type == TableConstraint.TypeUnique:
            return QApplication.translate("DBManagerPlugin", "Unique")
        if self.type == TableConstraint.TypeExclusion:
            return QApplication.translate("DBManagerPlugin", "Exclusion")
        return QApplication.translate("DBManagerPlugin", 'Unknown')

    def fields(self):
        def fieldFromNum(num, fields):
            """ return field specified by its number or None if doesn't exist """
            for fld in fields:
                if fld.num == num:
                    return fld
            return None

        fields = self.table().fields()
        cols = {}
        for num in self.columns:
            cols[num] = fieldFromNum(num, fields)
        return cols

    def delete(self):
        return self.table().deleteConstraint(self)


class TableIndex(TableSubItemObject):

    def __init__(self, table):
        TableSubItemObject.__init__(self, table)
        self.name = self.columns = self.isUnique = None

    def fields(self):
        def fieldFromNum(num, fields):
            """ return field specified by its number or None if doesn't exist """
            for fld in fields:
                if fld.num == num:
                    return fld
            return None

        fields = self.table().fields()
        cols = {}
        for num in self.columns:
            cols[num] = fieldFromNum(num, fields)
        return cols

    def delete(self):
        return self.table().deleteIndex(self)


class TableTrigger(TableSubItemObject):

    """ class that represents a trigger """

    # Bits within tgtype (pg_trigger.h)
    TypeRow = (1 << 0)  # row or statement
    TypeBefore = (1 << 1)  # before or after
    # events: one or more
    TypeInsert = (1 << 2)
    TypeDelete = (1 << 3)
    TypeUpdate = (1 << 4)
    TypeTruncate = (1 << 5)

    def __init__(self, table):
        TableSubItemObject.__init__(self, table)
        self.name = self.function = None

    def type2String(self):
        trig_type = u''
        trig_type += "Before " if self.type & TableTrigger.TypeBefore else "After "
        if self.type & TableTrigger.TypeInsert:
            trig_type += "INSERT "
        if self.type & TableTrigger.TypeUpdate:
            trig_type += "UPDATE "
        if self.type & TableTrigger.TypeDelete:
            trig_type += "DELETE "
        if self.type & TableTrigger.TypeTruncate:
            trig_type += "TRUNCATE "
        trig_type += "\n"
        trig_type += "for each "
        trig_type += "row" if self.type & TableTrigger.TypeRow else "statement"
        return trig_type


class TableRule(TableSubItemObject):

    def __init__(self, table):
        TableSubItemObject.__init__(self, table)
        self.name = self.definition = None