Skip to content

Commit 297a94f

Browse files
committedMar 21, 2015
Fix formatting of db manager python code
1 parent 57046c5 commit 297a94f

40 files changed

+7295
-6995
lines changed
 

‎python/plugins/db_manager/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020
***************************************************************************/
2121
"""
2222

23+
2324
def classFactory(iface):
2425
from .db_manager_plugin import DBManagerPlugin
26+
2527
return DBManagerPlugin(iface)

‎python/plugins/db_manager/db_manager.py

Lines changed: 400 additions & 389 deletions
Large diffs are not rendered by default.

‎python/plugins/db_manager/db_manager_plugin.py

Lines changed: 45 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -24,53 +24,56 @@
2424
from PyQt4.QtGui import QAction, QIcon, QApplication
2525

2626
try:
27-
from . import resources_rc
27+
from . import resources_rc
2828
except ImportError:
29-
pass
29+
pass
30+
3031

3132
class DBManagerPlugin:
32-
def __init__(self, iface):
33-
self.iface = iface
34-
self.dlg = None
33+
def __init__(self, iface):
34+
self.iface = iface
35+
self.dlg = None
36+
37+
def initGui(self):
38+
self.action = QAction(QIcon(":/db_manager/icon"), QApplication.translate("DBManagerPlugin", "DB Manager"),
39+
self.iface.mainWindow())
40+
self.action.setObjectName("dbManager")
41+
QObject.connect(self.action, SIGNAL("triggered()"), self.run)
42+
# Add toolbar button and menu item
43+
if hasattr(self.iface, 'addDatabaseToolBarIcon'):
44+
self.iface.addDatabaseToolBarIcon(self.action)
45+
else:
46+
self.iface.addToolBarIcon(self.action)
47+
if hasattr(self.iface, 'addPluginToDatabaseMenu'):
48+
self.iface.addPluginToDatabaseMenu(QApplication.translate("DBManagerPlugin", "DB Manager"), self.action)
49+
else:
50+
self.iface.addPluginToMenu(QApplication.translate("DBManagerPlugin", "DB Manager"), self.action)
3551

36-
def initGui(self):
37-
self.action = QAction( QIcon(":/db_manager/icon"), QApplication.translate("DBManagerPlugin","DB Manager"), self.iface.mainWindow() )
38-
self.action.setObjectName("dbManager")
39-
QObject.connect( self.action, SIGNAL( "triggered()" ), self.run )
40-
# Add toolbar button and menu item
41-
if hasattr( self.iface, 'addDatabaseToolBarIcon' ):
42-
self.iface.addDatabaseToolBarIcon(self.action)
43-
else:
44-
self.iface.addToolBarIcon(self.action)
45-
if hasattr( self.iface, 'addPluginToDatabaseMenu' ):
46-
self.iface.addPluginToDatabaseMenu( QApplication.translate("DBManagerPlugin","DB Manager"), self.action )
47-
else:
48-
self.iface.addPluginToMenu( QApplication.translate("DBManagerPlugin","DB Manager"), self.action )
52+
def unload(self):
53+
# Remove the plugin menu item and icon
54+
if hasattr(self.iface, 'removePluginDatabaseMenu'):
55+
self.iface.removePluginDatabaseMenu(QApplication.translate("DBManagerPlugin", "DB Manager"), self.action)
56+
else:
57+
self.iface.removePluginMenu(QApplication.translate("DBManagerPlugin", "DB Manager"), self.action)
58+
if hasattr(self.iface, 'removeDatabaseToolBarIcon'):
59+
self.iface.removeDatabaseToolBarIcon(self.action)
60+
else:
61+
self.iface.removeToolBarIcon(self.action)
4962

50-
def unload(self):
51-
# Remove the plugin menu item and icon
52-
if hasattr( self.iface, 'removePluginDatabaseMenu' ):
53-
self.iface.removePluginDatabaseMenu( QApplication.translate("DBManagerPlugin","DB Manager"), self.action )
54-
else:
55-
self.iface.removePluginMenu( QApplication.translate("DBManagerPlugin","DB Manager"), self.action )
56-
if hasattr( self.iface, 'removeDatabaseToolBarIcon' ):
57-
self.iface.removeDatabaseToolBarIcon(self.action)
58-
else:
59-
self.iface.removeToolBarIcon(self.action)
63+
if self.dlg is not None:
64+
self.dlg.close()
6065

61-
if self.dlg is not None:
62-
self.dlg.close()
66+
def run(self):
67+
# keep opened only one instance
68+
if self.dlg is None:
69+
from db_manager import DBManager
6370

64-
def run(self):
65-
# keep opened only one instance
66-
if self.dlg is None:
67-
from db_manager import DBManager
68-
self.dlg = DBManager(self.iface)
69-
QObject.connect(self.dlg, SIGNAL("destroyed(QObject *)"), self.onDestroyed)
70-
self.dlg.show()
71-
self.dlg.raise_()
72-
self.dlg.setWindowState( self.dlg.windowState() & ~Qt.WindowMinimized )
73-
self.dlg.activateWindow()
71+
self.dlg = DBManager(self.iface)
72+
QObject.connect(self.dlg, SIGNAL("destroyed(QObject *)"), self.onDestroyed)
73+
self.dlg.show()
74+
self.dlg.raise_()
75+
self.dlg.setWindowState(self.dlg.windowState() & ~Qt.WindowMinimized)
76+
self.dlg.activateWindow()
7477

75-
def onDestroyed(self, obj):
76-
self.dlg = None
78+
def onDestroyed(self, obj):
79+
self.dlg = None

‎python/plugins/db_manager/db_model.py

Lines changed: 466 additions & 461 deletions
Large diffs are not rendered by default.

‎python/plugins/db_manager/db_plugins/__init__.py

Lines changed: 29 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -20,44 +20,49 @@
2020
***************************************************************************/
2121
"""
2222

23+
2324
class NotSupportedDbType(Exception):
24-
def __init__(self, dbtype):
25-
self.msg = self.tr("%s is not supported yet") % dbtype
26-
Exception(self, self.msg)
25+
def __init__(self, dbtype):
26+
self.msg = self.tr("%s is not supported yet") % dbtype
27+
Exception(self, self.msg)
2728

28-
def __str__(self):
29-
return self.msg.encode('utf-8')
29+
def __str__(self):
30+
return self.msg.encode('utf-8')
3031

3132

3233
def initDbPluginList():
33-
import os
34-
current_dir = os.path.dirname(__file__)
35-
for name in os.listdir(current_dir):
36-
if not os.path.isdir( os.path.join( current_dir, name ) ):
37-
continue
34+
import os
35+
36+
current_dir = os.path.dirname(__file__)
37+
for name in os.listdir(current_dir):
38+
if not os.path.isdir(os.path.join(current_dir, name)):
39+
continue
40+
41+
try:
42+
exec ( u"from .%s import plugin as mod" % name )
43+
except ImportError, e:
44+
DBPLUGIN_ERRORS.append(u"%s: %s" % (name, e.message))
45+
continue
3846

39-
try:
40-
exec( u"from .%s import plugin as mod" % name )
41-
except ImportError, e:
42-
DBPLUGIN_ERRORS.append( u"%s: %s" % (name, e.message) )
43-
continue
47+
pluginclass = mod.classFactory()
48+
SUPPORTED_DBTYPES[pluginclass.typeName()] = pluginclass
4449

45-
pluginclass = mod.classFactory()
46-
SUPPORTED_DBTYPES[ pluginclass.typeName() ] = pluginclass
50+
return len(SUPPORTED_DBTYPES) > 0
4751

48-
return len(SUPPORTED_DBTYPES) > 0
4952

5053
def supportedDbTypes():
51-
return sorted(SUPPORTED_DBTYPES.keys())
54+
return sorted(SUPPORTED_DBTYPES.keys())
55+
5256

5357
def getDbPluginErrors():
54-
return DBPLUGIN_ERRORS
58+
return DBPLUGIN_ERRORS
59+
5560

5661
def createDbPlugin(dbtype, conn_name=None):
57-
if dbtype not in SUPPORTED_DBTYPES:
58-
raise NotSupportedDbType( dbtype )
59-
dbplugin = SUPPORTED_DBTYPES[ dbtype ]
60-
return dbplugin if conn_name is None else dbplugin(conn_name)
62+
if dbtype not in SUPPORTED_DBTYPES:
63+
raise NotSupportedDbType(dbtype)
64+
dbplugin = SUPPORTED_DBTYPES[dbtype]
65+
return dbplugin if conn_name is None else dbplugin(conn_name)
6166

6267

6368
# initialize the plugin list

‎python/plugins/db_manager/db_plugins/connector.py

Lines changed: 159 additions & 155 deletions
Original file line numberDiff line numberDiff line change
@@ -24,198 +24,202 @@
2424

2525
from .plugin import DbError, ConnectionError
2626

27+
2728
class DBConnector:
28-
def __init__(self, uri):
29-
self.connection = None
30-
self._uri = uri
29+
def __init__(self, uri):
30+
self.connection = None
31+
self._uri = uri
32+
33+
def __del__(self):
34+
pass # print "DBConnector.__del__", self._uri.connectionInfo()
35+
if self.connection is not None:
36+
self.connection.close()
37+
self.connection = None
38+
3139

32-
def __del__(self):
33-
pass # print "DBConnector.__del__", self._uri.connectionInfo()
34-
if self.connection is not None:
35-
self.connection.close()
36-
self.connection = None
40+
def uri(self):
41+
return QgsDataSourceURI(self._uri.uri())
3742

43+
def publicUri(self):
44+
publicUri = QgsDataSourceURI.removePassword(self._uri.uri())
45+
return QgsDataSourceURI(publicUri)
3846

39-
def uri(self):
40-
return QgsDataSourceURI( self._uri.uri() )
4147

42-
def publicUri(self):
43-
publicUri = QgsDataSourceURI.removePassword( self._uri.uri() )
44-
return QgsDataSourceURI( publicUri )
48+
def hasSpatialSupport(self):
49+
return False
4550

51+
def hasRasterSupport(self):
52+
return False
4653

47-
def hasSpatialSupport(self):
48-
return False
54+
def hasCustomQuerySupport(self):
55+
return False
4956

50-
def hasRasterSupport(self):
51-
return False
57+
def hasTableColumnEditingSupport(self):
58+
return False
5259

53-
def hasCustomQuerySupport(self):
54-
return False
5560

56-
def hasTableColumnEditingSupport(self):
57-
return False
61+
def execution_error_types(self):
62+
raise Exception("DBConnector.execution_error_types() is an abstract method")
5863

64+
def connection_error_types(self):
65+
raise Exception("DBConnector.connection_error_types() is an abstract method")
5966

60-
def execution_error_types(self):
61-
raise Exception("DBConnector.execution_error_types() is an abstract method")
67+
def error_types(self):
68+
return self.connection_error_types() + self.execution_error_types()
6269

63-
def connection_error_types(self):
64-
raise Exception("DBConnector.connection_error_types() is an abstract method")
70+
def _execute(self, cursor, sql):
71+
if cursor is None:
72+
cursor = self._get_cursor()
73+
try:
74+
cursor.execute(unicode(sql))
6575

66-
def error_types(self):
67-
return self.connection_error_types() + self.execution_error_types()
76+
except self.connection_error_types() as e:
77+
raise ConnectionError(e)
6878

69-
def _execute(self, cursor, sql):
70-
if cursor is None:
71-
cursor = self._get_cursor()
72-
try:
73-
cursor.execute(unicode(sql))
79+
except self.execution_error_types() as e:
80+
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
81+
self._rollback()
82+
raise DbError(e, sql)
7483

75-
except self.connection_error_types() as e:
76-
raise ConnectionError(e)
84+
return cursor
7785

78-
except self.execution_error_types() as e:
79-
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
80-
self._rollback()
81-
raise DbError(e, sql)
86+
def _execute_and_commit(self, sql):
87+
""" tries to execute and commit some action, on error it rolls back the change """
88+
self._execute(None, sql)
89+
self._commit()
8290

83-
return cursor
91+
def _get_cursor(self, name=None):
92+
try:
93+
if name is not None:
94+
name = unicode(name).encode('ascii', 'replace').replace('?', "_")
95+
self._last_cursor_named_id = 0 if not hasattr(self,
96+
'_last_cursor_named_id') else self._last_cursor_named_id + 1
97+
return self.connection.cursor("%s_%d" % (name, self._last_cursor_named_id))
8498

85-
def _execute_and_commit(self, sql):
86-
""" tries to execute and commit some action, on error it rolls back the change """
87-
self._execute(None, sql)
88-
self._commit()
99+
return self.connection.cursor()
89100

90-
def _get_cursor(self, name=None):
91-
try:
92-
if name is not None:
93-
name = unicode(name).encode('ascii', 'replace').replace( '?', "_" )
94-
self._last_cursor_named_id = 0 if not hasattr(self, '_last_cursor_named_id') else self._last_cursor_named_id + 1
95-
return self.connection.cursor( "%s_%d" % (name, self._last_cursor_named_id) )
101+
except self.connection_error_types(), e:
102+
raise ConnectionError(e)
96103

97-
return self.connection.cursor()
104+
except self.execution_error_types(), e:
105+
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
106+
self._rollback()
107+
raise DbError(e)
98108

99-
except self.connection_error_types(), e:
100-
raise ConnectionError(e)
109+
def _close_cursor(self, c):
110+
try:
111+
if c and not c.closed:
112+
c.close()
101113

102-
except self.execution_error_types(), e:
103-
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
104-
self._rollback()
105-
raise DbError(e)
114+
except self.error_types(), e:
115+
pass
106116

107-
def _close_cursor(self, c):
108-
try:
109-
if c and not c.closed:
110-
c.close()
117+
return
111118

112-
except self.error_types(), e:
113-
pass
114119

115-
return
120+
def _fetchall(self, c):
121+
try:
122+
return c.fetchall()
116123

124+
except self.connection_error_types(), e:
125+
raise ConnectionError(e)
117126

118-
def _fetchall(self, c):
119-
try:
120-
return c.fetchall()
127+
except self.execution_error_types(), e:
128+
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
129+
self._rollback()
130+
raise DbError(e)
121131

122-
except self.connection_error_types(), e:
123-
raise ConnectionError(e)
132+
def _fetchone(self, c):
133+
try:
134+
return c.fetchone()
124135

125-
except self.execution_error_types(), e:
126-
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
127-
self._rollback()
128-
raise DbError(e)
136+
except self.connection_error_types(), e:
137+
raise ConnectionError(e)
129138

130-
def _fetchone(self, c):
131-
try:
132-
return c.fetchone()
139+
except self.execution_error_types(), e:
140+
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
141+
self._rollback()
142+
raise DbError(e)
133143

134-
except self.connection_error_types(), e:
135-
raise ConnectionError(e)
136144

137-
except self.execution_error_types(), e:
138-
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
139-
self._rollback()
140-
raise DbError(e)
145+
def _commit(self):
146+
try:
147+
self.connection.commit()
141148

149+
except self.connection_error_types(), e:
150+
raise ConnectionError(e)
142151

143-
def _commit(self):
144-
try:
145-
self.connection.commit()
152+
except self.execution_error_types(), e:
153+
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
154+
self._rollback()
155+
raise DbError(e)
146156

147-
except self.connection_error_types(), e:
148-
raise ConnectionError(e)
149157

150-
except self.execution_error_types(), e:
151-
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
152-
self._rollback()
153-
raise DbError(e)
158+
def _rollback(self):
159+
try:
160+
self.connection.rollback()
161+
162+
except self.connection_error_types(), e:
163+
raise ConnectionError(e)
164+
165+
except self.execution_error_types(), e:
166+
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
167+
self._rollback()
168+
raise DbError(e)
169+
170+
171+
def _get_cursor_columns(self, c):
172+
try:
173+
if c.description:
174+
return map(lambda x: x[0], c.description)
154175

176+
except self.connection_error_types() + self.execution_error_types(), e:
177+
return []
178+
179+
180+
@classmethod
181+
def quoteId(self, identifier):
182+
if hasattr(identifier, '__iter__'):
183+
ids = list()
184+
for i in identifier:
185+
if i is None or i == "":
186+
continue
187+
ids.append(self.quoteId(i))
188+
return u'.'.join(ids)
189+
190+
identifier = unicode(
191+
identifier) if identifier is not None else unicode() # make sure it's python unicode string
192+
return u'"%s"' % identifier.replace('"', '""')
193+
194+
@classmethod
195+
def quoteString(self, txt):
196+
""" make the string safe - replace ' with '' """
197+
if hasattr(txt, '__iter__'):
198+
txts = list()
199+
for i in txt:
200+
if i is None:
201+
continue
202+
txts.append(self.quoteString(i))
203+
return u'.'.join(txts)
204+
205+
txt = unicode(txt) if txt is not None else unicode() # make sure it's python unicode string
206+
return u"'%s'" % txt.replace("'", "''")
155207

156-
def _rollback(self):
157-
try:
158-
self.connection.rollback()
208+
@classmethod
209+
def getSchemaTableName(self, table):
210+
if not hasattr(table, '__iter__'):
211+
return (None, table)
212+
elif len(table) < 2:
213+
return (None, table[0])
214+
else:
215+
return (table[0], table[1])
159216

160-
except self.connection_error_types(), e:
161-
raise ConnectionError(e)
162-
163-
except self.execution_error_types(), e:
164-
# do the rollback to avoid a "current transaction aborted, commands ignored" errors
165-
self._rollback()
166-
raise DbError(e)
167-
168-
169-
def _get_cursor_columns(self, c):
170-
try:
171-
if c.description:
172-
return map(lambda x: x[0], c.description)
173-
174-
except self.connection_error_types() + self.execution_error_types(), e:
175-
return []
176-
177-
178-
@classmethod
179-
def quoteId(self, identifier):
180-
if hasattr(identifier, '__iter__'):
181-
ids = list()
182-
for i in identifier:
183-
if i is None or i == "":
184-
continue
185-
ids.append( self.quoteId(i) )
186-
return u'.'.join( ids )
187-
188-
identifier = unicode(identifier) if identifier is not None else unicode() # make sure it's python unicode string
189-
return u'"%s"' % identifier.replace('"', '""')
190-
191-
@classmethod
192-
def quoteString(self, txt):
193-
""" make the string safe - replace ' with '' """
194-
if hasattr(txt, '__iter__'):
195-
txts = list()
196-
for i in txt:
197-
if i is None:
198-
continue
199-
txts.append( self.quoteString(i) )
200-
return u'.'.join( txts )
201-
202-
txt = unicode(txt) if txt is not None else unicode() # make sure it's python unicode string
203-
return u"'%s'" % txt.replace("'", "''")
204-
205-
@classmethod
206-
def getSchemaTableName(self, table):
207-
if not hasattr(table, '__iter__'):
208-
return (None, table)
209-
elif len(table) < 2:
210-
return (None, table[0])
211-
else:
212-
return (table[0], table[1])
213-
214-
@classmethod
215-
def getSqlDictionary(self):
216-
""" return a generic SQL dictionary """
217-
try:
218-
from ..sql_dictionary import getSqlDictionary
219-
return getSqlDictionary()
220-
except ImportError:
221-
return []
217+
@classmethod
218+
def getSqlDictionary(self):
219+
""" return a generic SQL dictionary """
220+
try:
221+
from ..sql_dictionary import getSqlDictionary
222+
223+
return getSqlDictionary()
224+
except ImportError:
225+
return []

‎python/plugins/db_manager/db_plugins/data_model.py

Lines changed: 253 additions & 248 deletions
Large diffs are not rendered by default.

‎python/plugins/db_manager/db_plugins/html_elems.py

Lines changed: 98 additions & 92 deletions
Original file line numberDiff line numberDiff line change
@@ -20,136 +20,142 @@
2020
***************************************************************************/
2121
"""
2222

23+
2324
class HtmlContent:
24-
def __init__(self, data):
25-
self.data = data if not isinstance(data, HtmlContent) else data.data
25+
def __init__(self, data):
26+
self.data = data if not isinstance(data, HtmlContent) else data.data
27+
28+
def toHtml(self):
29+
if isinstance(self.data, list) or isinstance(self.data, tuple):
30+
html = u''
31+
for item in self.data:
32+
html += HtmlContent(item).toHtml()
33+
return html
2634

27-
def toHtml(self):
28-
if isinstance(self.data, list) or isinstance(self.data, tuple):
29-
html = u''
30-
for item in self.data:
31-
html += HtmlContent(item).toHtml()
32-
return html
35+
if hasattr(self.data, 'toHtml'):
36+
return self.data.toHtml()
3337

34-
if hasattr(self.data, 'toHtml' ):
35-
return self.data.toHtml()
38+
html = unicode(self.data).replace("\n", "<br>")
39+
return html
3640

37-
html = unicode(self.data).replace("\n", "<br>")
38-
return html
41+
def hasContents(self):
42+
if isinstance(self.data, list) or isinstance(self.data, tuple):
43+
empty = True
44+
for item in self.data:
45+
if item.hasContents():
46+
empty = False
47+
break
48+
return not empty
3949

40-
def hasContents(self):
41-
if isinstance(self.data, list) or isinstance(self.data, tuple):
42-
empty = True
43-
for item in self.data:
44-
if item.hasContents():
45-
empty = False
46-
break
47-
return not empty
50+
if hasattr(self.data, 'hasContents'):
51+
return self.data.hasContents()
4852

49-
if hasattr(self.data, 'hasContents'):
50-
return self.data.hasContents()
53+
return len(self.data) > 0
5154

52-
return len(self.data) > 0
5355

5456
class HtmlElem:
55-
def __init__(self, tag, data, attrs=None):
56-
self.tag = tag
57-
self.data = data if isinstance(data, HtmlContent) else HtmlContent(data)
58-
self.attrs = attrs if attrs is not None else dict()
59-
if 'tag' in self.attrs:
60-
self.setTag( self.attrs['tag'] )
61-
del self.attrs['tag']
57+
def __init__(self, tag, data, attrs=None):
58+
self.tag = tag
59+
self.data = data if isinstance(data, HtmlContent) else HtmlContent(data)
60+
self.attrs = attrs if attrs is not None else dict()
61+
if 'tag' in self.attrs:
62+
self.setTag(self.attrs['tag'])
63+
del self.attrs['tag']
6264

63-
def setTag(self, tag):
64-
self.tag = tag
65+
def setTag(self, tag):
66+
self.tag = tag
6567

66-
def getOriginalData(self):
67-
return self.data.data
68+
def getOriginalData(self):
69+
return self.data.data
6870

69-
def setAttr(self, name, value):
70-
self.attrs[name] = value
71+
def setAttr(self, name, value):
72+
self.attrs[name] = value
7173

72-
def getAttrsHtml(self):
73-
html = u''
74-
for k, v in self.attrs.iteritems():
75-
html += u' %s="%s"' % ( k, v )
76-
return html
74+
def getAttrsHtml(self):
75+
html = u''
76+
for k, v in self.attrs.iteritems():
77+
html += u' %s="%s"' % ( k, v )
78+
return html
7779

78-
def openTagHtml(self):
79-
return u"<%s%s>" % ( self.tag, self.getAttrsHtml() )
80+
def openTagHtml(self):
81+
return u"<%s%s>" % ( self.tag, self.getAttrsHtml() )
8082

81-
def closeTagHtml(self):
82-
return u"</%s>" % self.tag
83+
def closeTagHtml(self):
84+
return u"</%s>" % self.tag
8385

84-
def toHtml(self):
85-
return u"%s%s%s" % ( self.openTagHtml(), self.data.toHtml(), self.closeTagHtml() )
86+
def toHtml(self):
87+
return u"%s%s%s" % ( self.openTagHtml(), self.data.toHtml(), self.closeTagHtml() )
8688

87-
def hasContents(self):
88-
return self.data.toHtml() != ""
89+
def hasContents(self):
90+
return self.data.toHtml() != ""
8991

9092

9193
class HtmlParagraph(HtmlElem):
92-
def __init__(self, data, attrs=None):
93-
HtmlElem.__init__(self, 'p', data, attrs)
94+
def __init__(self, data, attrs=None):
95+
HtmlElem.__init__(self, 'p', data, attrs)
9496

9597

9698
class HtmlListItem(HtmlElem):
97-
def __init__(self, data, attrs=None):
98-
HtmlElem.__init__(self, 'li', data, attrs)
99+
def __init__(self, data, attrs=None):
100+
HtmlElem.__init__(self, 'li', data, attrs)
101+
99102

100103
class HtmlList(HtmlElem):
101-
def __init__(self, items, attrs=None):
102-
# make sure to have HtmlListItem items
103-
items = list(items)
104-
for i, item in enumerate(items):
105-
if not isinstance(item, HtmlListItem):
106-
items[i] = HtmlListItem( item )
107-
HtmlElem.__init__(self, 'ul', items, attrs)
104+
def __init__(self, items, attrs=None):
105+
# make sure to have HtmlListItem items
106+
items = list(items)
107+
for i, item in enumerate(items):
108+
if not isinstance(item, HtmlListItem):
109+
items[i] = HtmlListItem(item)
110+
HtmlElem.__init__(self, 'ul', items, attrs)
108111

109112

110113
class HtmlTableCol(HtmlElem):
111-
def __init__(self, data, attrs=None):
112-
HtmlElem.__init__(self, 'td', data, attrs)
114+
def __init__(self, data, attrs=None):
115+
HtmlElem.__init__(self, 'td', data, attrs)
116+
117+
def closeTagHtml(self):
118+
# FIX INVALID BEHAVIOR: an empty cell as last table's cell break margins
119+
return u"&nbsp;%s" % HtmlElem.closeTagHtml(self)
113120

114-
def closeTagHtml(self):
115-
# FIX INVALID BEHAVIOR: an empty cell as last table's cell break margins
116-
return u"&nbsp;%s" % HtmlElem.closeTagHtml(self)
117121

118122
class HtmlTableRow(HtmlElem):
119-
def __init__(self, cols, attrs=None):
120-
# make sure to have HtmlTableCol items
121-
cols = list(cols)
122-
for i, c in enumerate(cols):
123-
if not isinstance(c, HtmlTableCol):
124-
cols[i] = HtmlTableCol( c )
125-
HtmlElem.__init__(self, 'tr', cols, attrs)
123+
def __init__(self, cols, attrs=None):
124+
# make sure to have HtmlTableCol items
125+
cols = list(cols)
126+
for i, c in enumerate(cols):
127+
if not isinstance(c, HtmlTableCol):
128+
cols[i] = HtmlTableCol(c)
129+
HtmlElem.__init__(self, 'tr', cols, attrs)
130+
126131

127132
class HtmlTableHeader(HtmlTableRow):
128-
def __init__(self, cols, attrs=None):
129-
HtmlTableRow.__init__(self, cols, attrs)
130-
for c in self.getOriginalData():
131-
c.setTag('th')
133+
def __init__(self, cols, attrs=None):
134+
HtmlTableRow.__init__(self, cols, attrs)
135+
for c in self.getOriginalData():
136+
c.setTag('th')
137+
132138

133139
class HtmlTable(HtmlElem):
134-
def __init__(self, rows, attrs=None):
135-
# make sure to have HtmlTableRow items
136-
rows = list(rows)
137-
for i, r in enumerate(rows):
138-
if not isinstance(r, HtmlTableRow):
139-
rows[i] = HtmlTableRow( r )
140-
HtmlElem.__init__(self, 'table', rows, attrs)
140+
def __init__(self, rows, attrs=None):
141+
# make sure to have HtmlTableRow items
142+
rows = list(rows)
143+
for i, r in enumerate(rows):
144+
if not isinstance(r, HtmlTableRow):
145+
rows[i] = HtmlTableRow(r)
146+
HtmlElem.__init__(self, 'table', rows, attrs)
141147

142148

143149
class HtmlWarning(HtmlContent):
144-
def __init__(self, data):
145-
data = [ '<img src=":/icons/warning-20px.png">&nbsp;&nbsp; ', data ]
146-
HtmlContent.__init__(self, data)
150+
def __init__(self, data):
151+
data = ['<img src=":/icons/warning-20px.png">&nbsp;&nbsp; ', data]
152+
HtmlContent.__init__(self, data)
147153

148154

149155
class HtmlSection(HtmlContent):
150-
def __init__(self, title, content=None):
151-
data = [ '<div class="section"><h2>', title, '</h2>' ]
152-
if content is not None:
153-
data.extend( [ '<div>', content, '</div>' ] )
154-
data.append( '</div>' )
155-
HtmlContent.__init__(self, data)
156+
def __init__(self, title, content=None):
157+
data = ['<div class="section"><h2>', title, '</h2>']
158+
if content is not None:
159+
data.extend(['<div>', content, '</div>'])
160+
data.append('</div>')
161+
HtmlContent.__init__(self, data)

‎python/plugins/db_manager/db_plugins/info_model.py

Lines changed: 369 additions & 351 deletions
Large diffs are not rendered by default.

‎python/plugins/db_manager/db_plugins/plugin.py

Lines changed: 998 additions & 948 deletions
Large diffs are not rendered by default.

‎python/plugins/db_manager/db_plugins/postgis/connector.py

Lines changed: 767 additions & 747 deletions
Large diffs are not rendered by default.

‎python/plugins/db_manager/db_plugins/postgis/data_model.py

Lines changed: 53 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -24,57 +24,60 @@
2424

2525
from ..data_model import TableDataModel, SqlResultModel
2626

27-
class PGTableDataModel(TableDataModel):
28-
def __init__(self, table, parent=None):
29-
self.cursor = None
30-
TableDataModel.__init__(self, table, parent)
31-
32-
if self.table.rowCount is None:
33-
self.table.refreshRowCount()
34-
if self.table.rowCount is None:
35-
return
36-
37-
self.connect(self.table, SIGNAL("aboutToChange"), self._deleteCursor)
38-
self._createCursor()
39-
40-
def _createCursor(self):
41-
fields_txt = u", ".join(self.fields)
42-
table_txt = self.db.quoteId( (self.table.schemaName(), self.table.name) )
43-
44-
self.cursor = self.db._get_cursor()
45-
sql = u"SELECT %s FROM %s" % (fields_txt, table_txt)
46-
self.db._execute(self.cursor, sql)
47-
48-
def _sanitizeTableField(self, field):
49-
# get fields, ignore geometry columns
50-
if field.dataType.lower() == "geometry":
51-
return u"CASE WHEN %(fld)s IS NULL THEN NULL ELSE GeometryType(%(fld)s) END AS %(fld)s" % {'fld': self.db.quoteId(field.name)}
52-
elif field.dataType.lower() == "raster":
53-
return u"CASE WHEN %(fld)s IS NULL THEN NULL ELSE 'RASTER' END AS %(fld)s" % {'fld': self.db.quoteId(field.name)}
54-
return u"%s::text" % self.db.quoteId(field.name)
5527

56-
def _deleteCursor(self):
57-
self.db._close_cursor(self.cursor)
58-
self.cursor = None
59-
60-
def __del__(self):
61-
self.disconnect(self.table, SIGNAL("aboutToChange"), self._deleteCursor)
62-
self._deleteCursor()
63-
pass # print "PGTableModel.__del__"
64-
65-
def fetchMoreData(self, row_start):
66-
if not self.cursor:
67-
self._createCursor()
68-
69-
try:
70-
self.cursor.scroll(row_start, mode='absolute')
71-
except self.db.error_types():
72-
self._deleteCursor()
73-
return self.fetchMoreData(row_start)
74-
75-
self.resdata = self.cursor.fetchmany(self.fetchedCount)
76-
self.fetchedFrom = row_start
28+
class PGTableDataModel(TableDataModel):
29+
def __init__(self, table, parent=None):
30+
self.cursor = None
31+
TableDataModel.__init__(self, table, parent)
32+
33+
if self.table.rowCount is None:
34+
self.table.refreshRowCount()
35+
if self.table.rowCount is None:
36+
return
37+
38+
self.connect(self.table, SIGNAL("aboutToChange"), self._deleteCursor)
39+
self._createCursor()
40+
41+
def _createCursor(self):
42+
fields_txt = u", ".join(self.fields)
43+
table_txt = self.db.quoteId((self.table.schemaName(), self.table.name))
44+
45+
self.cursor = self.db._get_cursor()
46+
sql = u"SELECT %s FROM %s" % (fields_txt, table_txt)
47+
self.db._execute(self.cursor, sql)
48+
49+
def _sanitizeTableField(self, field):
50+
# get fields, ignore geometry columns
51+
if field.dataType.lower() == "geometry":
52+
return u"CASE WHEN %(fld)s IS NULL THEN NULL ELSE GeometryType(%(fld)s) END AS %(fld)s" % {
53+
'fld': self.db.quoteId(field.name)}
54+
elif field.dataType.lower() == "raster":
55+
return u"CASE WHEN %(fld)s IS NULL THEN NULL ELSE 'RASTER' END AS %(fld)s" % {
56+
'fld': self.db.quoteId(field.name)}
57+
return u"%s::text" % self.db.quoteId(field.name)
58+
59+
def _deleteCursor(self):
60+
self.db._close_cursor(self.cursor)
61+
self.cursor = None
62+
63+
def __del__(self):
64+
self.disconnect(self.table, SIGNAL("aboutToChange"), self._deleteCursor)
65+
self._deleteCursor()
66+
pass # print "PGTableModel.__del__"
67+
68+
def fetchMoreData(self, row_start):
69+
if not self.cursor:
70+
self._createCursor()
71+
72+
try:
73+
self.cursor.scroll(row_start, mode='absolute')
74+
except self.db.error_types():
75+
self._deleteCursor()
76+
return self.fetchMoreData(row_start)
77+
78+
self.resdata = self.cursor.fetchmany(self.fetchedCount)
79+
self.fetchedFrom = row_start
7780

7881

7982
class PGSqlResultModel(SqlResultModel):
80-
pass
83+
pass

‎python/plugins/db_manager/db_plugins/postgis/info_model.py

Lines changed: 195 additions & 167 deletions
Large diffs are not rendered by default.

‎python/plugins/db_manager/db_plugins/postgis/plugin.py

Lines changed: 242 additions & 227 deletions
Large diffs are not rendered by default.

‎python/plugins/db_manager/db_plugins/postgis/plugins/__init__.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,17 @@
2121
"""
2222

2323
import os
24+
2425
current_dir = os.path.dirname(__file__)
2526

27+
2628
def load(dbplugin, mainwindow):
27-
for name in os.listdir(current_dir):
28-
if not os.path.isdir( os.path.join( current_dir, name ) ):
29-
continue
30-
try:
31-
exec( u"from .%s import load" % name )
32-
except ImportError, e:
33-
continue
34-
35-
load(dbplugin, mainwindow)
29+
for name in os.listdir(current_dir):
30+
if not os.path.isdir(os.path.join(current_dir, name)):
31+
continue
32+
try:
33+
exec ( u"from .%s import load" % name )
34+
except ImportError, e:
35+
continue
36+
37+
load(dbplugin, mainwindow)

‎python/plugins/db_manager/db_plugins/postgis/plugins/qgis_topoview/__init__.py

Lines changed: 221 additions & 216 deletions
Large diffs are not rendered by default.

‎python/plugins/db_manager/db_plugins/postgis/plugins/versioning/__init__.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,9 @@
2727
# @param db is the selected database
2828
# @param mainwindow is the DBManager mainwindow
2929
def load(db, mainwindow):
30-
# add the action to the DBManager menu
31-
action = QAction( QIcon(), QApplication.translate("DBManagerPlugin", "&Versioning"), db )
32-
mainwindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Table"), run )
30+
# add the action to the DBManager menu
31+
action = QAction(QIcon(), QApplication.translate("DBManagerPlugin", "&Versioning"), db)
32+
mainwindow.registerAction(action, QApplication.translate("DBManagerPlugin", "&Table"), run)
3333

3434

3535
# The run function is called once the user clicks on the action TopoViewer
@@ -38,11 +38,12 @@ def load(db, mainwindow):
3838
# @param action is the clicked action on the DBManager menu/toolbar
3939
# @param mainwindow is the DBManager mainwindow
4040
def run(item, action, mainwindow):
41-
from .dlg_versioning import DlgVersioning
42-
dlg = DlgVersioning( item, mainwindow )
43-
44-
QApplication.restoreOverrideCursor()
45-
try:
46-
dlg.exec_()
47-
finally:
48-
QApplication.setOverrideCursor(Qt.WaitCursor)
41+
from .dlg_versioning import DlgVersioning
42+
43+
dlg = DlgVersioning(item, mainwindow)
44+
45+
QApplication.restoreOverrideCursor()
46+
try:
47+
dlg.exec_()
48+
finally:
49+
QApplication.setOverrideCursor(Qt.WaitCursor)

‎python/plugins/db_manager/db_plugins/postgis/plugins/versioning/dlg_versioning.py

Lines changed: 168 additions & 159 deletions
Large diffs are not rendered by default.

‎python/plugins/db_manager/db_plugins/postgis/sql_dictionary.py

Lines changed: 70 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -100,44 +100,81 @@
100100
"typeof", "upper", "zeroblob", "date", "datetime", "julianday", "strftime",
101101
"avg", "count", "group_concat", "sum", "total"
102102
]
103-
postgis_functions = [ # from http://www.postgis.org/docs/reference.html
104-
# 7.1. PostgreSQL PostGIS Types
105-
"box2d", "box3d", "box3d_extent", "geometry", "geometry_dump", "geography",
106-
# 7.2. Management Functions
107-
"addgeometrycolumn", "dropgeometrycolumn", "dropgeometrytable", "postgis_full_version", "postgis_geos_version", "postgis_libxml_version", "postgis_lib_build_date", "postgis_lib_version", "postgis_proj_version", "postgis_scripts_build_date", "postgis_scripts_installed", "postgis_scripts_released", "postgis_uses_stats", "postgis_version", "populate_geometry_columns", "probe_geometry_columns", "updategeometrysrid",
108-
# 7.3. Geometry Constructors
109-
"st_bdpolyfromtext", "st_bdmpolyfromtext", "st_geogfromtext", "st_geographyfromtext", "st_geogfromwkb", "st_geomcollfromtext", "st_geomfromewkb", "st_geomfromewkt", "st_geometryfromtext", "st_geomfromgml", "st_geomfromkml", "st_gmltosql", "st_geomfromtext", "st_geomfromwkb", "st_linefrommultipoint", "st_linefromtext", "st_linefromwkb", "st_linestringfromwkb", "st_makebox2d", "st_makebox3d", "st_makeline", "st_makeenvelope", "st_makepolygon", "st_makepoint", "st_makepointm", "st_mlinefromtext", "st_mpointfromtext", "st_mpolyfromtext", "st_point", "st_pointfromtext", "st_pointfromwkb", "st_polygon", "st_polygonfromtext", "st_wkbtosql", "st_wkttosql",
110-
# 7.4. Geometry Accessors
111-
"geometrytype", "st_boundary", "st_coorddim", "st_dimension", "st_endpoint", "st_envelope", "st_exteriorring", "st_geometryn", "st_geometrytype", "st_interiorringn", "st_isclosed", "st_isempty", "st_isring", "st_issimple", "st_isvalid", "st_isvalidreason", "st_m", "st_ndims", "st_npoints", "st_nrings", "st_numgeometries", "st_numinteriorrings", "st_numinteriorring", "st_numpoints", "st_pointn", "st_srid", "st_startpoint", "st_summary", "st_x", "st_y", "st_z", "st_zmflag",
112-
# 7.5. Geometry Editors
113-
"st_addpoint", "st_affine", "st_force_2d", "st_force_3d", "st_force_3dz", "st_force_3dm", "st_force_4d", "st_force_collection", "st_forcerhr", "st_linemerge", "st_collectionextract", "st_multi", "st_removepoint", "st_reverse", "st_rotate", "st_rotatex", "st_rotatey", "st_rotatez", "st_scale", "st_segmentize", "st_setpoint", "st_setsrid", "st_snaptogrid", "st_transform", "st_translate", "st_transscale",
114-
# 7.6. Geometry Outputs
115-
"st_asbinary", "st_asewkb", "st_asewkt", "st_asgeojson", "st_asgml", "st_ashexewkb", "st_askml", "st_assvg", "st_geohash", "st_astext",
116-
# 7.7. Operators
117-
# 7.8. Spatial Relationships and Measurements
118-
"st_area", "st_azimuth", "st_centroid", "st_closestpoint", "st_contains", "st_containsproperly", "st_covers", "st_coveredby", "st_crosses", "st_linecrossingdirection", "st_disjoint", "st_distance", "st_hausdorffdistance", "st_maxdistance", "st_distance_sphere", "st_distance_spheroid", "st_dfullywithin", "st_dwithin", "st_equals", "st_hasarc", "st_intersects", "st_length", "st_length2d", "st_length3d", "st_length_spheroid", "st_length2d_spheroid", "st_length3d_spheroid", "st_longestline", "st_orderingequals", "st_overlaps", "st_perimeter", "st_perimeter2d", "st_perimeter3d", "st_pointonsurface", "st_relate", "st_shortestline", "st_touches", "st_within",
119-
# 7.9. Geometry Processing Functions
120-
"st_buffer", "st_buildarea", "st_collect", "st_convexhull", "st_curvetoline", "st_difference", "st_dump", "st_dumppoints", "st_dumprings", "st_intersection", "st_linetocurve", "st_memunion", "st_minimumboundingcircle", "st_polygonize", "st_shift_longitude", "st_simplify", "st_simplifypreservetopology", "st_symdifference", "st_union",
121-
# 7.10. Linear Referencing
122-
"st_line_interpolate_point", "st_line_locate_point", "st_line_substring", "st_locate_along_measure", "st_locate_between_measures", "st_locatebetweenelevations", "st_addmeasure",
123-
# 7.11. Long Transactions Support
124-
"addauth", "checkauth", "disablelongtransactions", "enablelongtransactions", "lockrow", "unlockrows",
125-
# 7.12. Miscellaneous Functions
126-
"st_accum", "box2d", "box3d", "st_estimated_extent", "st_expand", "st_extent", "st_extent3d", "find_srid", "st_mem_size", "st_point_inside_circle", "st_xmax", "st_xmin", "st_ymax", "st_ymin", "st_zmax", "st_zmin",
127-
# 7.13. Exceptional Functions
128-
"postgis_addbbox", "postgis_dropbbox", "postgis_hasbbox"
103+
postgis_functions = [ # from http://www.postgis.org/docs/reference.html
104+
# 7.1. PostgreSQL PostGIS Types
105+
"box2d", "box3d", "box3d_extent", "geometry", "geometry_dump", "geography",
106+
# 7.2. Management Functions
107+
"addgeometrycolumn", "dropgeometrycolumn", "dropgeometrytable", "postgis_full_version",
108+
"postgis_geos_version", "postgis_libxml_version", "postgis_lib_build_date",
109+
"postgis_lib_version", "postgis_proj_version", "postgis_scripts_build_date",
110+
"postgis_scripts_installed", "postgis_scripts_released", "postgis_uses_stats", "postgis_version",
111+
"populate_geometry_columns", "probe_geometry_columns", "updategeometrysrid",
112+
# 7.3. Geometry Constructors
113+
"st_bdpolyfromtext", "st_bdmpolyfromtext", "st_geogfromtext", "st_geographyfromtext",
114+
"st_geogfromwkb", "st_geomcollfromtext", "st_geomfromewkb", "st_geomfromewkt",
115+
"st_geometryfromtext", "st_geomfromgml", "st_geomfromkml", "st_gmltosql", "st_geomfromtext",
116+
"st_geomfromwkb", "st_linefrommultipoint", "st_linefromtext", "st_linefromwkb",
117+
"st_linestringfromwkb", "st_makebox2d", "st_makebox3d", "st_makeline", "st_makeenvelope",
118+
"st_makepolygon", "st_makepoint", "st_makepointm", "st_mlinefromtext", "st_mpointfromtext",
119+
"st_mpolyfromtext", "st_point", "st_pointfromtext", "st_pointfromwkb", "st_polygon",
120+
"st_polygonfromtext", "st_wkbtosql", "st_wkttosql",
121+
# 7.4. Geometry Accessors
122+
"geometrytype", "st_boundary", "st_coorddim", "st_dimension", "st_endpoint", "st_envelope",
123+
"st_exteriorring", "st_geometryn", "st_geometrytype", "st_interiorringn", "st_isclosed",
124+
"st_isempty", "st_isring", "st_issimple", "st_isvalid", "st_isvalidreason", "st_m", "st_ndims",
125+
"st_npoints", "st_nrings", "st_numgeometries", "st_numinteriorrings", "st_numinteriorring",
126+
"st_numpoints", "st_pointn", "st_srid", "st_startpoint", "st_summary", "st_x", "st_y", "st_z",
127+
"st_zmflag",
128+
# 7.5. Geometry Editors
129+
"st_addpoint", "st_affine", "st_force_2d", "st_force_3d", "st_force_3dz", "st_force_3dm",
130+
"st_force_4d", "st_force_collection", "st_forcerhr", "st_linemerge", "st_collectionextract",
131+
"st_multi", "st_removepoint", "st_reverse", "st_rotate", "st_rotatex", "st_rotatey",
132+
"st_rotatez", "st_scale", "st_segmentize", "st_setpoint", "st_setsrid", "st_snaptogrid",
133+
"st_transform", "st_translate", "st_transscale",
134+
# 7.6. Geometry Outputs
135+
"st_asbinary", "st_asewkb", "st_asewkt", "st_asgeojson", "st_asgml", "st_ashexewkb", "st_askml",
136+
"st_assvg", "st_geohash", "st_astext",
137+
# 7.7. Operators
138+
# 7.8. Spatial Relationships and Measurements
139+
"st_area", "st_azimuth", "st_centroid", "st_closestpoint", "st_contains", "st_containsproperly",
140+
"st_covers", "st_coveredby", "st_crosses", "st_linecrossingdirection", "st_disjoint",
141+
"st_distance", "st_hausdorffdistance", "st_maxdistance", "st_distance_sphere",
142+
"st_distance_spheroid", "st_dfullywithin", "st_dwithin", "st_equals", "st_hasarc",
143+
"st_intersects", "st_length", "st_length2d", "st_length3d", "st_length_spheroid",
144+
"st_length2d_spheroid", "st_length3d_spheroid", "st_longestline", "st_orderingequals",
145+
"st_overlaps", "st_perimeter", "st_perimeter2d", "st_perimeter3d", "st_pointonsurface",
146+
"st_relate", "st_shortestline", "st_touches", "st_within",
147+
# 7.9. Geometry Processing Functions
148+
"st_buffer", "st_buildarea", "st_collect", "st_convexhull", "st_curvetoline", "st_difference",
149+
"st_dump", "st_dumppoints", "st_dumprings", "st_intersection", "st_linetocurve", "st_memunion",
150+
"st_minimumboundingcircle", "st_polygonize", "st_shift_longitude", "st_simplify",
151+
"st_simplifypreservetopology", "st_symdifference", "st_union",
152+
# 7.10. Linear Referencing
153+
"st_line_interpolate_point", "st_line_locate_point", "st_line_substring",
154+
"st_locate_along_measure", "st_locate_between_measures", "st_locatebetweenelevations",
155+
"st_addmeasure",
156+
# 7.11. Long Transactions Support
157+
"addauth", "checkauth", "disablelongtransactions", "enablelongtransactions", "lockrow",
158+
"unlockrows",
159+
# 7.12. Miscellaneous Functions
160+
"st_accum", "box2d", "box3d", "st_estimated_extent", "st_expand", "st_extent", "st_extent3d",
161+
"find_srid", "st_mem_size", "st_point_inside_circle", "st_xmax", "st_xmin", "st_ymax", "st_ymin",
162+
"st_zmax", "st_zmin",
163+
# 7.13. Exceptional Functions
164+
"postgis_addbbox", "postgis_dropbbox", "postgis_hasbbox"
129165
]
130166

131167
# constants
132-
constants = [ "null", "false", "true" ]
168+
constants = ["null", "false", "true"]
133169
postgis_constants = []
134170

171+
135172
def getSqlDictionary(spatial=True):
136-
k, c, f = list(keywords), list(constants), list(functions)
173+
k, c, f = list(keywords), list(constants), list(functions)
137174

138-
if spatial:
139-
k += postgis_keywords
140-
f += postgis_functions
141-
c += postgis_constants
175+
if spatial:
176+
k += postgis_keywords
177+
f += postgis_functions
178+
c += postgis_constants
142179

143-
return { 'keyword' : k, 'constant' : c, 'function' : f }
180+
return {'keyword': k, 'constant': c, 'function': f}

‎python/plugins/db_manager/db_plugins/spatialite/connector.py

Lines changed: 543 additions & 531 deletions
Large diffs are not rendered by default.

‎python/plugins/db_manager/db_plugins/spatialite/data_model.py

Lines changed: 26 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -22,39 +22,40 @@
2222

2323
from ..data_model import TableDataModel, SqlResultModel
2424

25+
2526
class SLTableDataModel(TableDataModel):
26-
def __init__(self, table, parent=None):
27-
TableDataModel.__init__(self, table, parent)
27+
def __init__(self, table, parent=None):
28+
TableDataModel.__init__(self, table, parent)
2829

29-
fields_txt = u", ".join(self.fields)
30-
table_txt = self.db.quoteId( (self.table.schemaName(), self.table.name) )
30+
fields_txt = u", ".join(self.fields)
31+
table_txt = self.db.quoteId((self.table.schemaName(), self.table.name))
3132

32-
# run query and get results
33-
sql = u"SELECT %s FROM %s" % (fields_txt, table_txt)
34-
c = self.db._get_cursor()
35-
self.db._execute(c, sql)
33+
# run query and get results
34+
sql = u"SELECT %s FROM %s" % (fields_txt, table_txt)
35+
c = self.db._get_cursor()
36+
self.db._execute(c, sql)
3637

37-
self.resdata = self.db._fetchall(c)
38-
c.close()
39-
del c
38+
self.resdata = self.db._fetchall(c)
39+
c.close()
40+
del c
4041

41-
self.fetchedFrom = 0
42-
self.fetchedCount = len(self.resdata)
42+
self.fetchedFrom = 0
43+
self.fetchedCount = len(self.resdata)
4344

4445

45-
def _sanitizeTableField(self, field):
46-
# get fields, ignore geometry columns
47-
dataType = field.dataType.upper()
48-
if dataType[:5] == "MULTI": dataType = dataType[5:]
49-
if dataType[-3:] == "25D": dataType = dataType[:-3]
50-
if dataType[-10:] == "COLLECTION": dataType = dataType[:-10]
51-
if dataType in ["POINT", "LINESTRING", "POLYGON", "GEOMETRY"]:
52-
return u'GeometryType(%s)' % self.db.quoteId(field.name)
53-
return self.db.quoteId(field.name)
46+
def _sanitizeTableField(self, field):
47+
# get fields, ignore geometry columns
48+
dataType = field.dataType.upper()
49+
if dataType[:5] == "MULTI": dataType = dataType[5:]
50+
if dataType[-3:] == "25D": dataType = dataType[:-3]
51+
if dataType[-10:] == "COLLECTION": dataType = dataType[:-10]
52+
if dataType in ["POINT", "LINESTRING", "POLYGON", "GEOMETRY"]:
53+
return u'GeometryType(%s)' % self.db.quoteId(field.name)
54+
return self.db.quoteId(field.name)
5455

55-
def rowCount(self, index=None):
56-
return self.fetchedCount
56+
def rowCount(self, index=None):
57+
return self.fetchedCount
5758

5859

5960
class SLSqlResultModel(SqlResultModel):
60-
pass
61+
pass

‎python/plugins/db_manager/db_plugins/spatialite/info_model.py

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -25,22 +25,23 @@
2525
from ..info_model import DatabaseInfo
2626
from ..html_elems import HtmlTable
2727

28+
2829
class SLDatabaseInfo(DatabaseInfo):
29-
def __init__(self, db):
30-
self.db = db
31-
32-
def connectionDetails(self):
33-
tbl = [
34-
(QApplication.translate("DBManagerPlugin","Filename:"), self.db.connector.dbname)
35-
]
36-
return HtmlTable( tbl )
37-
38-
def generalInfo(self):
39-
info = self.db.connector.getInfo()
40-
tbl = [
41-
(QApplication.translate("DBManagerPlugin","SQLite version:"), info[0])
42-
]
43-
return HtmlTable( tbl )
44-
45-
def privilegesDetails(self):
46-
return None
30+
def __init__(self, db):
31+
self.db = db
32+
33+
def connectionDetails(self):
34+
tbl = [
35+
(QApplication.translate("DBManagerPlugin", "Filename:"), self.db.connector.dbname)
36+
]
37+
return HtmlTable(tbl)
38+
39+
def generalInfo(self):
40+
info = self.db.connector.getInfo()
41+
tbl = [
42+
(QApplication.translate("DBManagerPlugin", "SQLite version:"), info[0])
43+
]
44+
return HtmlTable(tbl)
45+
46+
def privilegesDetails(self):
47+
return None

‎python/plugins/db_manager/db_plugins/spatialite/plugin.py

Lines changed: 164 additions & 155 deletions
Original file line numberDiff line numberDiff line change
@@ -27,222 +27,231 @@
2727
from PyQt4.QtGui import QIcon, QApplication, QAction
2828
from qgis.gui import QgsMessageBar
2929

30-
from ..plugin import DBPlugin, Database, Table, VectorTable, RasterTable, TableField, TableIndex, TableTrigger, InvalidDataException
30+
from ..plugin import DBPlugin, Database, Table, VectorTable, RasterTable, TableField, TableIndex, TableTrigger, \
31+
InvalidDataException
32+
3133
try:
32-
from . import resources_rc
34+
from . import resources_rc
3335
except ImportError:
34-
pass
35-
36+
pass
3637

3738

3839
def classFactory():
39-
return SpatiaLiteDBPlugin
40+
return SpatiaLiteDBPlugin
41+
4042

4143
class SpatiaLiteDBPlugin(DBPlugin):
44+
@classmethod
45+
def icon(self):
46+
return QIcon(":/db_manager/spatialite/icon")
4247

43-
@classmethod
44-
def icon(self):
45-
return QIcon(":/db_manager/spatialite/icon")
48+
@classmethod
49+
def typeName(self):
50+
return 'spatialite'
4651

47-
@classmethod
48-
def typeName(self):
49-
return 'spatialite'
52+
@classmethod
53+
def typeNameString(self):
54+
return 'SpatiaLite'
5055

51-
@classmethod
52-
def typeNameString(self):
53-
return 'SpatiaLite'
56+
@classmethod
57+
def providerName(self):
58+
return 'spatialite'
5459

55-
@classmethod
56-
def providerName(self):
57-
return 'spatialite'
60+
@classmethod
61+
def connectionSettingsKey(self):
62+
return '/SpatiaLite/connections'
5863

59-
@classmethod
60-
def connectionSettingsKey(self):
61-
return '/SpatiaLite/connections'
64+
def databasesFactory(self, connection, uri):
65+
return SLDatabase(connection, uri)
6266

63-
def databasesFactory(self, connection, uri):
64-
return SLDatabase(connection, uri)
67+
def connect(self, parent=None):
68+
conn_name = self.connectionName()
69+
settings = QSettings()
70+
settings.beginGroup(u"/%s/%s" % (self.connectionSettingsKey(), conn_name))
6571

66-
def connect(self, parent=None):
67-
conn_name = self.connectionName()
68-
settings = QSettings()
69-
settings.beginGroup( u"/%s/%s" % (self.connectionSettingsKey(), conn_name) )
72+
if not settings.contains("sqlitepath"): # non-existent entry?
73+
raise InvalidDataException(u'there is no defined database connection "%s".' % conn_name)
7074

71-
if not settings.contains( "sqlitepath" ): # non-existent entry?
72-
raise InvalidDataException( u'there is no defined database connection "%s".' % conn_name )
75+
database = settings.value("sqlitepath")
7376

74-
database = settings.value("sqlitepath")
77+
import qgis.core
7578

76-
import qgis.core
77-
uri = qgis.core.QgsDataSourceURI()
78-
uri.setDatabase(database)
79-
return self.connectToUri(uri)
79+
uri = qgis.core.QgsDataSourceURI()
80+
uri.setDatabase(database)
81+
return self.connectToUri(uri)
8082

8183

8284
class SLDatabase(Database):
83-
def __init__(self, connection, uri):
84-
Database.__init__(self, connection, uri)
85+
def __init__(self, connection, uri):
86+
Database.__init__(self, connection, uri)
8587

86-
def connectorsFactory(self, uri):
87-
return SpatiaLiteDBConnector(uri)
88+
def connectorsFactory(self, uri):
89+
return SpatiaLiteDBConnector(uri)
8890

8991

90-
def dataTablesFactory(self, row, db, schema=None):
91-
return SLTable(row, db, schema)
92+
def dataTablesFactory(self, row, db, schema=None):
93+
return SLTable(row, db, schema)
9294

93-
def vectorTablesFactory(self, row, db, schema=None):
94-
return SLVectorTable(row, db, schema)
95+
def vectorTablesFactory(self, row, db, schema=None):
96+
return SLVectorTable(row, db, schema)
9597

96-
def rasterTablesFactory(self, row, db, schema=None):
97-
return SLRasterTable(row, db, schema)
98+
def rasterTablesFactory(self, row, db, schema=None):
99+
return SLRasterTable(row, db, schema)
98100

99101

100-
def info(self):
101-
from .info_model import SLDatabaseInfo
102-
return SLDatabaseInfo(self)
102+
def info(self):
103+
from .info_model import SLDatabaseInfo
103104

104-
def sqlResultModel(self, sql, parent):
105-
from .data_model import SLSqlResultModel
106-
return SLSqlResultModel(self, sql, parent)
105+
return SLDatabaseInfo(self)
107106

107+
def sqlResultModel(self, sql, parent):
108+
from .data_model import SLSqlResultModel
108109

109-
def registerDatabaseActions(self, mainWindow):
110-
action = QAction(self.tr("Run &Vacuum"), self)
111-
mainWindow.registerAction( action, self.tr("&Database"), self.runVacuumActionSlot )
110+
return SLSqlResultModel(self, sql, parent)
112111

113-
Database.registerDatabaseActions(self, mainWindow)
114112

115-
def runVacuumActionSlot(self, item, action, parent):
116-
QApplication.restoreOverrideCursor()
117-
try:
118-
if not isinstance(item, (DBPlugin, Table)) or item.database() is None:
119-
parent.infoBar.pushMessage(self.tr("No database selected or you are not connected to it."), QgsMessageBar.INFO, parent.iface.messageTimeout())
120-
return
121-
finally:
122-
QApplication.setOverrideCursor(Qt.WaitCursor)
113+
def registerDatabaseActions(self, mainWindow):
114+
action = QAction(self.tr("Run &Vacuum"), self)
115+
mainWindow.registerAction(action, self.tr("&Database"), self.runVacuumActionSlot)
123116

124-
self.runVacuum()
117+
Database.registerDatabaseActions(self, mainWindow)
125118

126-
def runVacuum(self):
127-
self.database().aboutToChange()
128-
self.database().connector.runVacuum()
129-
self.database().refresh()
119+
def runVacuumActionSlot(self, item, action, parent):
120+
QApplication.restoreOverrideCursor()
121+
try:
122+
if not isinstance(item, (DBPlugin, Table)) or item.database() is None:
123+
parent.infoBar.pushMessage(self.tr("No database selected or you are not connected to it."),
124+
QgsMessageBar.INFO, parent.iface.messageTimeout())
125+
return
126+
finally:
127+
QApplication.setOverrideCursor(Qt.WaitCursor)
130128

129+
self.runVacuum()
131130

132-
def runAction(self, action):
133-
action = unicode(action)
131+
def runVacuum(self):
132+
self.database().aboutToChange()
133+
self.database().connector.runVacuum()
134+
self.database().refresh()
134135

135-
if action.startswith( "vacuum/" ):
136-
if action == "vacuum/run":
137-
self.runVacuum()
138-
return True
139136

140-
return Database.runAction(self, action)
137+
def runAction(self, action):
138+
action = unicode(action)
141139

140+
if action.startswith("vacuum/"):
141+
if action == "vacuum/run":
142+
self.runVacuum()
143+
return True
142144

143-
class SLTable(Table):
144-
def __init__(self, row, db, schema=None):
145-
Table.__init__(self, db, None)
146-
self.name, self.isView, self.isSysTable = row
145+
return Database.runAction(self, action)
147146

148147

149-
def tableFieldsFactory(self, row, table):
150-
return SLTableField(row, table)
148+
class SLTable(Table):
149+
def __init__(self, row, db, schema=None):
150+
Table.__init__(self, db, None)
151+
self.name, self.isView, self.isSysTable = row
151152

152-
def tableIndexesFactory(self, row, table):
153-
return SLTableIndex(row, table)
154153

155-
def tableTriggersFactory(self, row, table):
156-
return SLTableTrigger(row, table)
154+
def tableFieldsFactory(self, row, table):
155+
return SLTableField(row, table)
157156

157+
def tableIndexesFactory(self, row, table):
158+
return SLTableIndex(row, table)
158159

159-
def tableDataModel(self, parent):
160-
from .data_model import SLTableDataModel
161-
return SLTableDataModel(self, parent)
160+
def tableTriggersFactory(self, row, table):
161+
return SLTableTrigger(row, table)
162162

163163

164-
class SLVectorTable(SLTable, VectorTable):
165-
def __init__(self, row, db, schema=None):
166-
SLTable.__init__(self, row[:-5], db, schema)
167-
VectorTable.__init__(self, db, schema)
168-
# SpatiaLite does case-insensitive checks for table names, but the
169-
# SL provider didn't do the same in QGis < 1.9, so self.geomTableName
170-
# stores the table name like stored in the geometry_columns table
171-
self.geomTableName, self.geomColumn, self.geomType, self.geomDim, self.srid = row[-5:]
172-
173-
def uri(self):
174-
uri = self.database().uri()
175-
uri.setDataSource('', self.geomTableName, self.geomColumn)
176-
return uri
177-
178-
def hasSpatialIndex(self, geom_column=None):
179-
geom_column = geom_column if geom_column is not None else self.geomColumn
180-
return self.database().connector.hasSpatialIndex( (self.schemaName(), self.name), geom_column )
181-
182-
def createSpatialIndex(self, geom_column=None):
183-
self.aboutToChange()
184-
ret = VectorTable.createSpatialIndex(self, geom_column)
185-
if ret is not False:
186-
self.database().refresh()
187-
return ret
188-
189-
def deleteSpatialIndex(self, geom_column=None):
190-
self.aboutToChange()
191-
ret = VectorTable.deleteSpatialIndex(self, geom_column)
192-
if ret is not False:
193-
self.database().refresh()
194-
return ret
195-
196-
def refreshTableEstimatedExtent(self):
197-
return
164+
def tableDataModel(self, parent):
165+
from .data_model import SLTableDataModel
198166

167+
return SLTableDataModel(self, parent)
199168

200-
def runAction(self, action):
201-
if SLTable.runAction(self, action):
202-
return True
203-
return VectorTable.runAction(self, action)
169+
170+
class SLVectorTable(SLTable, VectorTable):
171+
def __init__(self, row, db, schema=None):
172+
SLTable.__init__(self, row[:-5], db, schema)
173+
VectorTable.__init__(self, db, schema)
174+
# SpatiaLite does case-insensitive checks for table names, but the
175+
# SL provider didn't do the same in QGis < 1.9, so self.geomTableName
176+
# stores the table name like stored in the geometry_columns table
177+
self.geomTableName, self.geomColumn, self.geomType, self.geomDim, self.srid = row[-5:]
178+
179+
def uri(self):
180+
uri = self.database().uri()
181+
uri.setDataSource('', self.geomTableName, self.geomColumn)
182+
return uri
183+
184+
def hasSpatialIndex(self, geom_column=None):
185+
geom_column = geom_column if geom_column is not None else self.geomColumn
186+
return self.database().connector.hasSpatialIndex((self.schemaName(), self.name), geom_column)
187+
188+
def createSpatialIndex(self, geom_column=None):
189+
self.aboutToChange()
190+
ret = VectorTable.createSpatialIndex(self, geom_column)
191+
if ret is not False:
192+
self.database().refresh()
193+
return ret
194+
195+
def deleteSpatialIndex(self, geom_column=None):
196+
self.aboutToChange()
197+
ret = VectorTable.deleteSpatialIndex(self, geom_column)
198+
if ret is not False:
199+
self.database().refresh()
200+
return ret
201+
202+
def refreshTableEstimatedExtent(self):
203+
return
204+
205+
206+
def runAction(self, action):
207+
if SLTable.runAction(self, action):
208+
return True
209+
return VectorTable.runAction(self, action)
204210

205211

206212
class SLRasterTable(SLTable, RasterTable):
207-
def __init__(self, row, db, schema=None):
208-
SLTable.__init__(self, row[:-3], db, schema)
209-
RasterTable.__init__(self, db, schema)
210-
self.prefixName, self.geomColumn, self.srid = row[-3:]
211-
self.geomType = 'RASTER'
213+
def __init__(self, row, db, schema=None):
214+
SLTable.__init__(self, row[:-3], db, schema)
215+
RasterTable.__init__(self, db, schema)
216+
self.prefixName, self.geomColumn, self.srid = row[-3:]
217+
self.geomType = 'RASTER'
212218

213-
#def info(self):
214-
#from .info_model import SLRasterTableInfo
215-
#return SLRasterTableInfo(self)
219+
# def info(self):
220+
#from .info_model import SLRasterTableInfo
221+
#return SLRasterTableInfo(self)
216222

217-
def gdalUri(self):
218-
uri = self.database().uri()
219-
gdalUri = u'RASTERLITE:%s,table=%s' % (uri.database(), self.prefixName)
220-
return gdalUri
223+
def gdalUri(self):
224+
uri = self.database().uri()
225+
gdalUri = u'RASTERLITE:%s,table=%s' % (uri.database(), self.prefixName)
226+
return gdalUri
221227

222-
def mimeUri(self):
223-
uri = u"raster:gdal:%s:%s" % (self.name, self.gdalUri())
224-
return uri
228+
def mimeUri(self):
229+
uri = u"raster:gdal:%s:%s" % (self.name, self.gdalUri())
230+
return uri
225231

226-
def toMapLayer(self):
227-
from qgis.core import QgsRasterLayer
228-
rl = QgsRasterLayer(self.gdalUri(), self.name)
229-
if rl.isValid():
230-
rl.setContrastEnhancementAlgorithm("StretchToMinimumMaximum")
231-
return rl
232+
def toMapLayer(self):
233+
from qgis.core import QgsRasterLayer
234+
235+
rl = QgsRasterLayer(self.gdalUri(), self.name)
236+
if rl.isValid():
237+
rl.setContrastEnhancementAlgorithm("StretchToMinimumMaximum")
238+
return rl
232239

233240

234241
class SLTableField(TableField):
235-
def __init__(self, row, table):
236-
TableField.__init__(self, table)
237-
self.num, self.name, self.dataType, self.notNull, self.default, self.primaryKey = row
238-
self.hasDefault = self.default
242+
def __init__(self, row, table):
243+
TableField.__init__(self, table)
244+
self.num, self.name, self.dataType, self.notNull, self.default, self.primaryKey = row
245+
self.hasDefault = self.default
246+
239247

240248
class SLTableIndex(TableIndex):
241-
def __init__(self, row, table):
242-
TableIndex.__init__(self, table)
243-
self.num, self.name, self.isUnique, self.columns = row
249+
def __init__(self, row, table):
250+
TableIndex.__init__(self, table)
251+
self.num, self.name, self.isUnique, self.columns = row
252+
244253

245254
class SLTableTrigger(TableTrigger):
246-
def __init__(self, row, table):
247-
TableTrigger.__init__(self, table)
248-
self.name, self.function = row
255+
def __init__(self, row, table):
256+
TableTrigger.__init__(self, table)
257+
self.name, self.function = row

‎python/plugins/db_manager/db_plugins/spatialite/sql_dictionary.py

Lines changed: 61 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -56,61 +56,72 @@
5656
"typeof", "upper", "zeroblob", "date", "datetime", "julianday", "strftime",
5757
"avg", "count", "group_concat", "sum", "total"
5858
]
59-
spatialite_functions = [ # from www.gaia-gis.it/spatialite-2.3.0/spatialite-sql-2.3.0.html
60-
# SQL math functions
61-
"abs", "acos", "asin", "atan", "cos", "cot", "degrees", "exp", "floor", "log", "log2", "log10", "pi", "radians", "round", "sign", "sin", "sqrt", "stddev_pop", "stddev_samp", "tan", "var_pop", "var_samp",
62-
# SQL utility functions for BLOB objects
63-
"iszipblob", "ispdfblob", "isgifblob", "ispngblob", "isjpegblob", "isexifblob", "isexifgpsblob", "geomfromexifgpsblob", "makepoint", "buildmbr", "buildcirclembr", "mbrminx", "mbrminy", "mbrmaxx", "mbrmaxy",
64-
# SQL functions for constructing a geometric object given its Well-known Text Representation
65-
"geomfromtext", "pointfromtext",
66-
# SQL functions for constructing a geometric object given its Well-known Binary Representation
67-
"geomfromwkb", "pointfromwkb",
68-
# SQL functions for obtaining the Well-known Text / Well-known Binary Representation of a geometric object
69-
"astext", "asbinary",
70-
# SQL functions supporting exotic geometric formats
71-
"assvg", "asfgf", "geomfromfgf",
72-
# SQL functions on type Geometry
73-
"dimension", "geometrytype", "srid", "setsrid", "isempty", "issimple", "isvalid", "boundary", "envelope",
74-
# SQL functions on type Point
75-
"x", "y",
76-
# SQL functions on type Curve [Linestring or Ring]
77-
"startpoint", "endpoint", "glength", "isclosed", "isring", "simplify", "simplifypreservetopology",
78-
# SQL functions on type LineString
79-
"numpoints", "pointn",
80-
# SQL functions on type Surface [Polygon or Ring]
81-
"centroid", "pointonsurface", "area",
82-
# SQL functions on type Polygon
83-
"exteriorring", "interiorringn",
84-
# SQL functions on type GeomCollection
85-
"numgeometries", "geometryn",
86-
# SQL functions that test approximative spatial relationships via MBRs
87-
"mbrequal", "mbrdisjoint", "mbrtouches", "mbrwithin", "mbroverlaps", "mbrintersects", "mbrcontains",
88-
# SQL functions that test spatial relationships
89-
"equals", "disjoint", "touches", "within", "overlaps", "crosses", "intersects", "contains", "relate",
90-
# SQL functions for distance relationships
91-
"distance",
92-
# SQL functions that implement spatial operators
93-
"intersection", "difference", "gunion", "gunion", "symdifference", "buffer", "convexhull",
94-
# SQL functions for coordinate transformations
95-
"transform",
96-
# SQL functions for Spatial-MetaData and Spatial-Index handling
97-
"initspatialmetadata", "addgeometrycolumn", "recovergeometrycolumn", "discardgeometrycolumn", "createspatialindex", "creatembrcache", "disablespatialindex",
98-
# SQL functions implementing FDO/OGR compatibily
99-
"checkspatialmetadata", "autofdostart", "autofdostop", "initfdospatialmetadata", "addfdogeometrycolumn", "recoverfdogeometrycolumn", "discardfdogeometrycolumn",
100-
# SQL functions for MbrCache-based queries
101-
"filtermbrwithin", "filtermbrcontains", "filtermbrintersects", "buildmbrfilter"
59+
spatialite_functions = [ # from www.gaia-gis.it/spatialite-2.3.0/spatialite-sql-2.3.0.html
60+
# SQL math functions
61+
"abs", "acos", "asin", "atan", "cos", "cot", "degrees", "exp", "floor", "log", "log2",
62+
"log10", "pi", "radians", "round", "sign", "sin", "sqrt", "stddev_pop", "stddev_samp", "tan",
63+
"var_pop", "var_samp",
64+
# SQL utility functions for BLOB objects
65+
"iszipblob", "ispdfblob", "isgifblob", "ispngblob", "isjpegblob", "isexifblob",
66+
"isexifgpsblob", "geomfromexifgpsblob", "makepoint", "buildmbr", "buildcirclembr", "mbrminx",
67+
"mbrminy", "mbrmaxx", "mbrmaxy",
68+
# SQL functions for constructing a geometric object given its Well-known Text Representation
69+
"geomfromtext", "pointfromtext",
70+
# SQL functions for constructing a geometric object given its Well-known Binary Representation
71+
"geomfromwkb", "pointfromwkb",
72+
# SQL functions for obtaining the Well-known Text / Well-known Binary Representation of a geometric object
73+
"astext", "asbinary",
74+
# SQL functions supporting exotic geometric formats
75+
"assvg", "asfgf", "geomfromfgf",
76+
# SQL functions on type Geometry
77+
"dimension", "geometrytype", "srid", "setsrid", "isempty", "issimple", "isvalid", "boundary",
78+
"envelope",
79+
# SQL functions on type Point
80+
"x", "y",
81+
# SQL functions on type Curve [Linestring or Ring]
82+
"startpoint", "endpoint", "glength", "isclosed", "isring", "simplify",
83+
"simplifypreservetopology",
84+
# SQL functions on type LineString
85+
"numpoints", "pointn",
86+
# SQL functions on type Surface [Polygon or Ring]
87+
"centroid", "pointonsurface", "area",
88+
# SQL functions on type Polygon
89+
"exteriorring", "interiorringn",
90+
# SQL functions on type GeomCollection
91+
"numgeometries", "geometryn",
92+
# SQL functions that test approximative spatial relationships via MBRs
93+
"mbrequal", "mbrdisjoint", "mbrtouches", "mbrwithin", "mbroverlaps", "mbrintersects",
94+
"mbrcontains",
95+
# SQL functions that test spatial relationships
96+
"equals", "disjoint", "touches", "within", "overlaps", "crosses", "intersects", "contains",
97+
"relate",
98+
# SQL functions for distance relationships
99+
"distance",
100+
# SQL functions that implement spatial operators
101+
"intersection", "difference", "gunion", "gunion", "symdifference", "buffer", "convexhull",
102+
# SQL functions for coordinate transformations
103+
"transform",
104+
# SQL functions for Spatial-MetaData and Spatial-Index handling
105+
"initspatialmetadata", "addgeometrycolumn", "recovergeometrycolumn", "discardgeometrycolumn",
106+
"createspatialindex", "creatembrcache", "disablespatialindex",
107+
# SQL functions implementing FDO/OGR compatibily
108+
"checkspatialmetadata", "autofdostart", "autofdostop", "initfdospatialmetadata",
109+
"addfdogeometrycolumn", "recoverfdogeometrycolumn", "discardfdogeometrycolumn",
110+
# SQL functions for MbrCache-based queries
111+
"filtermbrwithin", "filtermbrcontains", "filtermbrintersects", "buildmbrfilter"
102112
]
103113

104114
# constants
105-
constants = [ "null", "false", "true" ]
115+
constants = ["null", "false", "true"]
106116
spatialite_constants = []
107117

118+
108119
def getSqlDictionary(spatial=True):
109-
k, c, f = list(keywords), list(constants), list(functions)
120+
k, c, f = list(keywords), list(constants), list(functions)
110121

111-
if spatial:
112-
k += spatialite_keywords
113-
f += spatialite_functions
114-
c += spatialite_constants
122+
if spatial:
123+
k += spatialite_keywords
124+
f += spatialite_functions
125+
c += spatialite_constants
115126

116-
return { 'keyword' : k, 'constant' : c, 'function' : f }
127+
return {'keyword': k, 'constant': c, 'function': f}

‎python/plugins/db_manager/db_tree.py

Lines changed: 128 additions & 123 deletions
Original file line numberDiff line numberDiff line change
@@ -29,131 +29,136 @@
2929
from .db_model import DBModel
3030
from .db_plugins.plugin import DBPlugin, Schema, Table
3131

32-
class DBTree(QTreeView):
33-
def __init__(self, mainWindow):
34-
QTreeView.__init__(self, mainWindow)
35-
self.mainWindow = mainWindow
3632

37-
self.setModel( DBModel(self) )
38-
self.setHeaderHidden(True)
39-
self.setEditTriggers(QTreeView.EditKeyPressed|QTreeView.SelectedClicked)
33+
class DBTree(QTreeView):
34+
def __init__(self, mainWindow):
35+
QTreeView.__init__(self, mainWindow)
36+
self.mainWindow = mainWindow
4037

41-
self.setDragEnabled(True)
42-
self.setAcceptDrops(True)
43-
self.setDropIndicatorShown(True)
38+
self.setModel(DBModel(self))
39+
self.setHeaderHidden(True)
40+
self.setEditTriggers(QTreeView.EditKeyPressed | QTreeView.SelectedClicked)
4441

45-
self.connect(self.selectionModel(), SIGNAL("currentChanged(const QModelIndex&, const QModelIndex&)"), self.currentItemChanged)
46-
self.connect(self, SIGNAL("expanded(const QModelIndex&)"), self.itemChanged)
47-
self.connect(self, SIGNAL("collapsed(const QModelIndex&)"), self.itemChanged)
48-
self.connect(self.model(), SIGNAL("dataChanged(const QModelIndex&, const QModelIndex&)"), self.modelDataChanged)
49-
self.connect(self.model(), SIGNAL("notPopulated"), self.collapse)
42+
self.setDragEnabled(True)
43+
self.setAcceptDrops(True)
44+
self.setDropIndicatorShown(True)
5045

51-
def refreshItem(self, item=None):
52-
if item is None:
53-
item = self.currentItem()
54-
if item is None: return
55-
self.model().refreshItem(item)
56-
57-
def showSystemTables(self, show):
58-
pass
59-
60-
def currentItem(self):
61-
indexes = self.selectedIndexes()
62-
if len(indexes) <= 0:
63-
return
64-
return self.model().getItem(indexes[0])
65-
66-
67-
def currentDatabase(self):
68-
item = self.currentItem()
69-
if item is None: return
70-
71-
if isinstance(item, (DBPlugin, Schema, Table)):
72-
return item.database()
73-
return None
74-
75-
def currentSchema(self):
76-
item = self.currentItem()
77-
if item is None: return
78-
79-
if isinstance(item, (Schema, Table)):
80-
return item.schema()
81-
return None
82-
83-
def currentTable(self):
84-
item = self.currentItem()
85-
if item is None: return
86-
87-
if isinstance(item, Table):
88-
return item
89-
return None
90-
91-
92-
def itemChanged(self, index):
93-
self.setCurrentIndex(index)
94-
self.emit( SIGNAL('selectedItemChanged'), self.currentItem() )
95-
96-
def modelDataChanged(self, indexFrom, indexTo):
97-
self.itemChanged(indexTo)
98-
99-
def currentItemChanged(self, current, previous):
100-
self.itemChanged(current)
101-
102-
def contextMenuEvent(self, ev):
103-
index = self.indexAt( ev.pos() )
104-
if not index.isValid():
105-
return
106-
107-
if index != self.currentIndex():
108-
self.itemChanged(index)
109-
110-
item = self.currentItem()
111-
112-
menu = QMenu(self)
113-
114-
if isinstance(item, (Table, Schema)):
115-
menu.addAction(self.tr("Rename"), self.rename)
116-
menu.addAction(self.tr("Delete"), self.delete)
117-
118-
if isinstance(item, Table):
119-
menu.addSeparator()
120-
menu.addAction(self.tr("Add to canvas"), self.addLayer)
121-
122-
elif isinstance(item, DBPlugin) and item.database() is not None:
123-
menu.addAction(self.tr("Re-connect"), self.reconnect)
124-
125-
if not menu.isEmpty():
126-
menu.exec_(ev.globalPos())
127-
128-
menu.deleteLater()
129-
130-
def rename(self):
131-
index = self.currentIndex()
132-
item = self.model().getItem(index)
133-
if isinstance(item, (Table, Schema)):
134-
self.edit( index )
135-
136-
def delete(self):
137-
item = self.currentItem()
138-
if isinstance(item, (Table, Schema)):
139-
self.mainWindow.invokeCallback(item.database().deleteActionSlot)
140-
141-
def addLayer(self):
142-
table = self.currentTable()
143-
if table is not None:
144-
layer = table.toMapLayer()
145-
layers = QgsMapLayerRegistry.instance().addMapLayers([layer])
146-
if len(layers) != 1:
147-
QgsMessageLog.instance().logMessage( self.tr( "%1 is an invalid layer - not loaded" ).replace( "%1", layer.publicSource() ) )
148-
msgLabel = QLabel( self.tr( "%1 is an invalid layer and cannot be loaded. Please check the <a href=\"#messageLog\">message log</a> for further info." ).replace( "%1", layer.publicSource() ), self.mainWindow.infoBar )
149-
msgLabel.setWordWrap( True )
150-
self.connect( msgLabel, SIGNAL("linkActivated( QString )" ),
151-
self.mainWindow.iface.mainWindow().findChild( QWidget, "MessageLog" ), SLOT( "show()" ) )
152-
self.connect( msgLabel, SIGNAL("linkActivated( QString )" ),
153-
self.mainWindow.iface.mainWindow(), SLOT( "raise()" ) )
154-
self.mainWindow.infoBar.pushItem( QgsMessageBarItem( msgLabel, QgsMessageBar.WARNING ) )
46+
self.connect(self.selectionModel(), SIGNAL("currentChanged(const QModelIndex&, const QModelIndex&)"),
47+
self.currentItemChanged)
48+
self.connect(self, SIGNAL("expanded(const QModelIndex&)"), self.itemChanged)
49+
self.connect(self, SIGNAL("collapsed(const QModelIndex&)"), self.itemChanged)
50+
self.connect(self.model(), SIGNAL("dataChanged(const QModelIndex&, const QModelIndex&)"), self.modelDataChanged)
51+
self.connect(self.model(), SIGNAL("notPopulated"), self.collapse)
15552

156-
def reconnect(self):
157-
db = self.currentDatabase()
158-
if db is not None:
159-
self.mainWindow.invokeCallback(db.reconnectActionSlot)
53+
def refreshItem(self, item=None):
54+
if item is None:
55+
item = self.currentItem()
56+
if item is None: return
57+
self.model().refreshItem(item)
58+
59+
def showSystemTables(self, show):
60+
pass
61+
62+
def currentItem(self):
63+
indexes = self.selectedIndexes()
64+
if len(indexes) <= 0:
65+
return
66+
return self.model().getItem(indexes[0])
67+
68+
69+
def currentDatabase(self):
70+
item = self.currentItem()
71+
if item is None: return
72+
73+
if isinstance(item, (DBPlugin, Schema, Table)):
74+
return item.database()
75+
return None
76+
77+
def currentSchema(self):
78+
item = self.currentItem()
79+
if item is None: return
80+
81+
if isinstance(item, (Schema, Table)):
82+
return item.schema()
83+
return None
84+
85+
def currentTable(self):
86+
item = self.currentItem()
87+
if item is None: return
88+
89+
if isinstance(item, Table):
90+
return item
91+
return None
92+
93+
94+
def itemChanged(self, index):
95+
self.setCurrentIndex(index)
96+
self.emit(SIGNAL('selectedItemChanged'), self.currentItem())
97+
98+
def modelDataChanged(self, indexFrom, indexTo):
99+
self.itemChanged(indexTo)
100+
101+
def currentItemChanged(self, current, previous):
102+
self.itemChanged(current)
103+
104+
def contextMenuEvent(self, ev):
105+
index = self.indexAt(ev.pos())
106+
if not index.isValid():
107+
return
108+
109+
if index != self.currentIndex():
110+
self.itemChanged(index)
111+
112+
item = self.currentItem()
113+
114+
menu = QMenu(self)
115+
116+
if isinstance(item, (Table, Schema)):
117+
menu.addAction(self.tr("Rename"), self.rename)
118+
menu.addAction(self.tr("Delete"), self.delete)
119+
120+
if isinstance(item, Table):
121+
menu.addSeparator()
122+
menu.addAction(self.tr("Add to canvas"), self.addLayer)
123+
124+
elif isinstance(item, DBPlugin) and item.database() is not None:
125+
menu.addAction(self.tr("Re-connect"), self.reconnect)
126+
127+
if not menu.isEmpty():
128+
menu.exec_(ev.globalPos())
129+
130+
menu.deleteLater()
131+
132+
def rename(self):
133+
index = self.currentIndex()
134+
item = self.model().getItem(index)
135+
if isinstance(item, (Table, Schema)):
136+
self.edit(index)
137+
138+
def delete(self):
139+
item = self.currentItem()
140+
if isinstance(item, (Table, Schema)):
141+
self.mainWindow.invokeCallback(item.database().deleteActionSlot)
142+
143+
def addLayer(self):
144+
table = self.currentTable()
145+
if table is not None:
146+
layer = table.toMapLayer()
147+
layers = QgsMapLayerRegistry.instance().addMapLayers([layer])
148+
if len(layers) != 1:
149+
QgsMessageLog.instance().logMessage(
150+
self.tr("%1 is an invalid layer - not loaded").replace("%1", layer.publicSource()))
151+
msgLabel = QLabel(self.tr(
152+
"%1 is an invalid layer and cannot be loaded. Please check the <a href=\"#messageLog\">message log</a> for further info.").replace(
153+
"%1", layer.publicSource()), self.mainWindow.infoBar)
154+
msgLabel.setWordWrap(True)
155+
self.connect(msgLabel, SIGNAL("linkActivated( QString )"),
156+
self.mainWindow.iface.mainWindow().findChild(QWidget, "MessageLog"), SLOT("show()"))
157+
self.connect(msgLabel, SIGNAL("linkActivated( QString )"),
158+
self.mainWindow.iface.mainWindow(), SLOT("raise()"))
159+
self.mainWindow.infoBar.pushItem(QgsMessageBarItem(msgLabel, QgsMessageBar.WARNING))
160+
161+
def reconnect(self):
162+
db = self.currentDatabase()
163+
if db is not None:
164+
self.mainWindow.invokeCallback(db.reconnectActionSlot)

‎python/plugins/db_manager/dlg_add_geometry_column.py

Lines changed: 32 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -30,41 +30,42 @@
3030

3131
from .ui.ui_DlgAddGeometryColumn import Ui_DbManagerDlgAddGeometryColumn as Ui_Dialog
3232

33-
class DlgAddGeometryColumn(QDialog, Ui_Dialog):
3433

35-
GEOM_TYPES = ["POINT", "LINESTRING", "POLYGON", "MULTIPOINT", "MULTILINESTRING", "MULTIPOLYGON", "GEOMETRYCOLLECTION"]
34+
class DlgAddGeometryColumn(QDialog, Ui_Dialog):
35+
GEOM_TYPES = ["POINT", "LINESTRING", "POLYGON", "MULTIPOINT", "MULTILINESTRING", "MULTIPOLYGON",
36+
"GEOMETRYCOLLECTION"]
3637

37-
def __init__(self, parent=None, table=None, db=None):
38-
QDialog.__init__(self, parent)
39-
self.table = table
40-
self.db = self.table.database() if self.table and self.table.database() else db
41-
self.setupUi(self)
38+
def __init__(self, parent=None, table=None, db=None):
39+
QDialog.__init__(self, parent)
40+
self.table = table
41+
self.db = self.table.database() if self.table and self.table.database() else db
42+
self.setupUi(self)
4243

43-
self.connect(self.buttonBox, SIGNAL("accepted()"), self.createGeomColumn)
44+
self.connect(self.buttonBox, SIGNAL("accepted()"), self.createGeomColumn)
4445

45-
def createGeomColumn(self):
46-
""" first check whether everything's fine """
47-
if self.editName.text() == "":
48-
QMessageBox.critical(self, self.tr("DB Manager"), self.tr("field name must not be empty"))
49-
return
46+
def createGeomColumn(self):
47+
""" first check whether everything's fine """
48+
if self.editName.text() == "":
49+
QMessageBox.critical(self, self.tr("DB Manager"), self.tr("field name must not be empty"))
50+
return
5051

51-
name = self.editName.text()
52-
geom_type = self.GEOM_TYPES[ self.cboType.currentIndex() ]
53-
dim = self.spinDim.value()
54-
try:
55-
srid = int(self.editSrid.text())
56-
except ValueError:
57-
srid = -1
58-
createSpatialIndex = False
52+
name = self.editName.text()
53+
geom_type = self.GEOM_TYPES[self.cboType.currentIndex()]
54+
dim = self.spinDim.value()
55+
try:
56+
srid = int(self.editSrid.text())
57+
except ValueError:
58+
srid = -1
59+
createSpatialIndex = False
5960

60-
# now create the geometry column
61-
QApplication.setOverrideCursor(Qt.WaitCursor)
62-
try:
63-
self.table.addGeometryColumn(name, geom_type, srid, dim, createSpatialIndex)
64-
except DbError, e:
65-
DlgDbError.showError(e, self)
66-
return
67-
finally:
68-
QApplication.restoreOverrideCursor()
61+
# now create the geometry column
62+
QApplication.setOverrideCursor(Qt.WaitCursor)
63+
try:
64+
self.table.addGeometryColumn(name, geom_type, srid, dim, createSpatialIndex)
65+
except DbError, e:
66+
DlgDbError.showError(e, self)
67+
return
68+
finally:
69+
QApplication.restoreOverrideCursor()
6970

70-
self.accept()
71+
self.accept()

‎python/plugins/db_manager/dlg_create_constraint.py

Lines changed: 35 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -31,45 +31,46 @@
3131

3232
from .ui.ui_DlgCreateConstraint import Ui_DbManagerDlgCreateConstraint as Ui_Dialog
3333

34+
3435
class DlgCreateConstraint(QDialog, Ui_Dialog):
35-
def __init__(self, parent=None, table=None, db=None):
36-
QDialog.__init__(self, parent)
37-
self.table = table
38-
self.db = self.table.database() if self.table and self.table.database() else db
39-
self.setupUi(self)
36+
def __init__(self, parent=None, table=None, db=None):
37+
QDialog.__init__(self, parent)
38+
self.table = table
39+
self.db = self.table.database() if self.table and self.table.database() else db
40+
self.setupUi(self)
4041

41-
self.connect(self.buttonBox, SIGNAL("accepted()"), self.createConstraint)
42-
self.populateColumns()
42+
self.connect(self.buttonBox, SIGNAL("accepted()"), self.createConstraint)
43+
self.populateColumns()
4344

44-
def populateColumns(self):
45-
self.cboColumn.clear()
46-
for fld in self.table.fields():
47-
self.cboColumn.addItem(fld.name)
45+
def populateColumns(self):
46+
self.cboColumn.clear()
47+
for fld in self.table.fields():
48+
self.cboColumn.addItem(fld.name)
4849

4950

50-
def createConstraint(self):
51-
constr = self.getConstraint()
51+
def createConstraint(self):
52+
constr = self.getConstraint()
5253

53-
# now create the constraint
54-
QApplication.setOverrideCursor(Qt.WaitCursor)
55-
try:
56-
self.table.addConstraint(constr)
57-
except DbError, e:
58-
DlgDbError.showError(e, self)
59-
return
60-
finally:
61-
QApplication.restoreOverrideCursor()
54+
# now create the constraint
55+
QApplication.setOverrideCursor(Qt.WaitCursor)
56+
try:
57+
self.table.addConstraint(constr)
58+
except DbError, e:
59+
DlgDbError.showError(e, self)
60+
return
61+
finally:
62+
QApplication.restoreOverrideCursor()
6263

63-
self.accept()
64+
self.accept()
6465

65-
def getConstraint(self):
66-
constr = TableConstraint(self.table)
67-
constr.name = u""
68-
constr.type = TableConstraint.TypePrimaryKey if self.radPrimaryKey.isChecked() else TableConstraint.TypeUnique
69-
constr.columns = []
70-
column = self.cboColumn.currentText()
71-
for fld in self.table.fields():
72-
if fld.name == column:
73-
constr.columns.append( fld.num )
74-
break
75-
return constr
66+
def getConstraint(self):
67+
constr = TableConstraint(self.table)
68+
constr.name = u""
69+
constr.type = TableConstraint.TypePrimaryKey if self.radPrimaryKey.isChecked() else TableConstraint.TypeUnique
70+
constr.columns = []
71+
column = self.cboColumn.currentText()
72+
for fld in self.table.fields():
73+
if fld.name == column:
74+
constr.columns.append(fld.num)
75+
break
76+
return constr

‎python/plugins/db_manager/dlg_create_index.py

Lines changed: 50 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -31,53 +31,54 @@
3131

3232
from .ui.ui_DlgCreateIndex import Ui_DbManagerDlgCreateIndex as Ui_Dialog
3333

34+
3435
class DlgCreateIndex(QDialog, Ui_Dialog):
35-
def __init__(self, parent=None, table=None, db=None):
36-
QDialog.__init__(self, parent)
37-
self.table = table
38-
self.db = self.table.database() if self.table and self.table.database() else db
39-
self.setupUi(self)
40-
41-
self.connect(self.buttonBox, SIGNAL("accepted()"), self.createIndex)
42-
43-
self.connect(self.cboColumn, SIGNAL("currentIndexChanged(int)"), self.columnChanged)
44-
self.populateColumns()
45-
46-
47-
def populateColumns(self):
48-
self.cboColumn.clear()
49-
for fld in self.table.fields():
50-
self.cboColumn.addItem(fld.name)
51-
52-
def columnChanged(self):
53-
self.editName.setText(u"idx_%s_%s" % (self.table.name, self.cboColumn.currentText()))
54-
55-
56-
def createIndex(self):
57-
idx = self.getIndex()
58-
if idx.name == "":
59-
QMessageBox.critical(self, self.tr("Error"), self.tr("Please enter some name for the index"))
60-
return
61-
62-
# now create the index
63-
QApplication.setOverrideCursor(Qt.WaitCursor)
64-
try:
65-
self.table.addIndex(idx)
66-
except DbError, e:
67-
DlgDbError.showError(e, self)
68-
return
69-
finally:
70-
QApplication.restoreOverrideCursor()
71-
72-
self.accept()
73-
74-
def getIndex(self):
75-
idx = TableIndex(self.table)
76-
idx.name = self.editName.text()
77-
idx.columns = []
78-
colname = self.cboColumn.currentText()
79-
for fld in self.table.fields():
80-
if fld.name == colname:
81-
idx.columns.append( fld.num )
82-
break
83-
return idx
36+
def __init__(self, parent=None, table=None, db=None):
37+
QDialog.__init__(self, parent)
38+
self.table = table
39+
self.db = self.table.database() if self.table and self.table.database() else db
40+
self.setupUi(self)
41+
42+
self.connect(self.buttonBox, SIGNAL("accepted()"), self.createIndex)
43+
44+
self.connect(self.cboColumn, SIGNAL("currentIndexChanged(int)"), self.columnChanged)
45+
self.populateColumns()
46+
47+
48+
def populateColumns(self):
49+
self.cboColumn.clear()
50+
for fld in self.table.fields():
51+
self.cboColumn.addItem(fld.name)
52+
53+
def columnChanged(self):
54+
self.editName.setText(u"idx_%s_%s" % (self.table.name, self.cboColumn.currentText()))
55+
56+
57+
def createIndex(self):
58+
idx = self.getIndex()
59+
if idx.name == "":
60+
QMessageBox.critical(self, self.tr("Error"), self.tr("Please enter some name for the index"))
61+
return
62+
63+
# now create the index
64+
QApplication.setOverrideCursor(Qt.WaitCursor)
65+
try:
66+
self.table.addIndex(idx)
67+
except DbError, e:
68+
DlgDbError.showError(e, self)
69+
return
70+
finally:
71+
QApplication.restoreOverrideCursor()
72+
73+
self.accept()
74+
75+
def getIndex(self):
76+
idx = TableIndex(self.table)
77+
idx.name = self.editName.text()
78+
idx.columns = []
79+
colname = self.cboColumn.currentText()
80+
for fld in self.table.fields():
81+
if fld.name == colname:
82+
idx.columns.append(fld.num)
83+
break
84+
return idx

0 commit comments

Comments
 (0)
Please sign in to comment.