core.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391
  1. """
  2. This module provides the functionality to create the temporal
  3. SQL database and to establish a connection to the database.
  4. Usage:
  5. .. code-block:: python
  6. >>> import grass.temporal as tgis
  7. >>> # Create the temporal database
  8. >>> tgis.init()
  9. >>> # Establish a database connection
  10. >>> dbif, connected = tgis.init_dbif(None)
  11. >>> dbif.connect()
  12. >>> # Execute a SQL statement
  13. >>> dbif.execute_transaction("SELECT datetime(0, 'unixepoch', 'localtime');")
  14. >>> # Mogrify an SQL statement
  15. >>> dbif.mogrify_sql_statement(["SELECT name from raster_base where name = ?",
  16. ... ("precipitation",)])
  17. "SELECT name from raster_base where name = 'precipitation'"
  18. >>> dbif.close()
  19. (C) 2011-2014 by the GRASS Development Team
  20. This program is free software under the GNU General Public
  21. License (>=v2). Read the file COPYING that comes with GRASS
  22. for details.
  23. :author: Soeren Gebbert
  24. """
  25. #import traceback
  26. import os
  27. import sys
  28. import grass.script as gscript
  29. # i18N
  30. import gettext
  31. gettext.install('grasslibs', os.path.join(os.getenv("GISBASE"), 'locale'))
  32. if sys.version_info.major == 3:
  33. long = int
  34. from .c_libraries_interface import *
  35. from grass.pygrass import messages
  36. from grass.script.utils import decode, encode
  37. # Import all supported database backends
  38. # Ignore import errors since they are checked later
  39. try:
  40. import sqlite3
  41. except ImportError:
  42. pass
  43. # Postgresql is optional, existence is checked when needed
  44. try:
  45. import psycopg2
  46. import psycopg2.extras
  47. except:
  48. pass
  49. import atexit
  50. from datetime import datetime
  51. ###############################################################################
  52. def profile_function(func):
  53. """Profiling function provided by the temporal framework"""
  54. do_profiling = os.getenv("GRASS_TGIS_PROFILE")
  55. if do_profiling is "True" or do_profiling is "1":
  56. import cProfile, pstats
  57. try:
  58. import StringIO as io
  59. except ImportError:
  60. import io
  61. pr = cProfile.Profile()
  62. pr.enable()
  63. func()
  64. pr.disable()
  65. s = io.StringIO()
  66. sortby = 'cumulative'
  67. ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
  68. ps.print_stats()
  69. print(s.getvalue())
  70. else:
  71. func()
  72. # Global variable that defines the backend
  73. # of the temporal GIS
  74. # It can either be "sqlite" or "pg"
  75. tgis_backend = None
  76. def get_tgis_backend():
  77. """Return the temporal GIS backend as string
  78. :returns: either "sqlite" or "pg"
  79. """
  80. global tgis_backend
  81. return tgis_backend
  82. # Global variable that defines the database string
  83. # of the temporal GIS
  84. tgis_database = None
  85. def get_tgis_database():
  86. """Return the temporal database string specified with t.connect
  87. """
  88. global tgis_database
  89. return tgis_database
  90. # The version of the temporal framework
  91. # this value must be an integer larger than 0
  92. # Increase this value in case of backward incompatible changes in the TGIS API
  93. tgis_version = 2
  94. # The version of the temporal database since framework and database version
  95. # can differ this value must be an integer larger than 0
  96. # Increase this value in case of backward incompatible changes
  97. # temporal database SQL layout
  98. tgis_db_version = 2
  99. # We need to know the parameter style of the database backend
  100. tgis_dbmi_paramstyle = None
  101. def get_tgis_dbmi_paramstyle():
  102. """Return the temporal database backend parameter style
  103. :returns: "qmark" or ""
  104. """
  105. global tgis_dbmi_paramstyle
  106. return tgis_dbmi_paramstyle
  107. # We need to access the current mapset quite often in the framework, so we make
  108. # a global variable that will be initiated when init() is called
  109. current_mapset = None
  110. current_location = None
  111. current_gisdbase = None
  112. ###############################################################################
  113. def get_current_mapset():
  114. """Return the current mapset
  115. This is the fastest way to receive the current mapset.
  116. The current mapset is set by init() and stored in a global variable.
  117. This function provides access to this global variable.
  118. """
  119. global current_mapset
  120. return current_mapset
  121. ###############################################################################
  122. def get_current_location():
  123. """Return the current location
  124. This is the fastest way to receive the current location.
  125. The current location is set by init() and stored in a global variable.
  126. This function provides access to this global variable.
  127. """
  128. global current_location
  129. return current_location
  130. ###############################################################################
  131. def get_current_gisdbase():
  132. """Return the current gis database (gisdbase)
  133. This is the fastest way to receive the current gisdbase.
  134. The current gisdbase is set by init() and stored in a global variable.
  135. This function provides access to this global variable.
  136. """
  137. global current_gisdbase
  138. return current_gisdbase
  139. ###############################################################################
  140. # If this global variable is set True, then maps can only be registered in
  141. # space time datasets with the same mapset. In addition, only maps in the
  142. # current mapset can be inserted, updated or deleted from the temporal database.
  143. # Overwrite this global variable by: g.gisenv set="TGIS_DISABLE_MAPSET_CHECK=True"
  144. # ATTENTION: Be aware to face corrupted temporal database in case this global
  145. # variable is set to False. This feature is highly
  146. # experimental and violates the grass permission guidance.
  147. enable_mapset_check = True
  148. # If this global variable is set True, the timestamps of maps will be written
  149. # as textfiles for each map that will be inserted or updated in the temporal
  150. # database using the C-library timestamp interface.
  151. # Overwrite this global variable by: g.gisenv set="TGIS_DISABLE_TIMESTAMP_WRITE=True"
  152. # ATTENTION: Be aware to face corrupted temporal database in case this global
  153. # variable is set to False. This feature is highly
  154. # experimental and violates the grass permission guidance.
  155. enable_timestamp_write = True
  156. def get_enable_mapset_check():
  157. """Return True if the mapsets should be checked while insert, update,
  158. delete requests and space time dataset registration.
  159. If this global variable is set True, then maps can only be registered
  160. in space time datasets with the same mapset. In addition, only maps in
  161. the current mapset can be inserted, updated or deleted from the temporal
  162. database.
  163. Overwrite this global variable by: g.gisenv set="TGIS_DISABLE_MAPSET_CHECK=True"
  164. ..warning::
  165. Be aware to face corrupted temporal database in case this
  166. global variable is set to False. This feature is highly
  167. experimental and violates the grass permission guidance.
  168. """
  169. global enable_mapset_check
  170. return enable_mapset_check
  171. def get_enable_timestamp_write():
  172. """Return True if the map timestamps should be written to the spatial
  173. database metadata as well.
  174. If this global variable is set True, the timestamps of maps will be
  175. written as textfiles for each map that will be inserted or updated in
  176. the temporal database using the C-library timestamp interface.
  177. Overwrite this global variable by: g.gisenv set="TGIS_DISABLE_TIMESTAMP_WRITE=True"
  178. ..warning::
  179. Be aware that C-libraries can not access timestamp information if
  180. they are not written as spatial database metadata, hence modules
  181. that make use of timestamps using the C-library interface will not
  182. work with maps that were created without writing the timestamps.
  183. """
  184. global enable_timestamp_write
  185. return enable_timestamp_write
  186. ###############################################################################
  187. # The global variable that stores the PyGRASS Messenger object that
  188. # provides a fast and exit safe interface to the C-library message functions
  189. message_interface = None
  190. def _init_tgis_message_interface(raise_on_error=False):
  191. """Initiate the global message interface
  192. :param raise_on_error: If True raise a FatalError exception in case of
  193. a fatal error, call sys.exit(1) otherwise
  194. """
  195. global message_interface
  196. if message_interface is None:
  197. message_interface = messages.get_msgr(raise_on_error=raise_on_error)
  198. def get_tgis_message_interface():
  199. """Return the temporal GIS message interface which is of type
  200. grass.pygrass.message.Messenger()
  201. Use this message interface to print messages to stdout using the
  202. GRASS C-library messaging system.
  203. """
  204. global message_interface
  205. return message_interface
  206. ###############################################################################
  207. # The global variable that stores the C-library interface object that
  208. # provides a fast and exit safe interface to the C-library libgis,
  209. # libraster, libraster3d and libvector functions
  210. c_library_interface = None
  211. def _init_tgis_c_library_interface():
  212. """Set the global C-library interface variable that
  213. provides a fast and exit safe interface to the C-library libgis,
  214. libraster, libraster3d and libvector functions
  215. """
  216. global c_library_interface
  217. if c_library_interface is None:
  218. c_library_interface = CLibrariesInterface()
  219. def get_tgis_c_library_interface():
  220. """Return the C-library interface that
  221. provides a fast and exit safe interface to the C-library libgis,
  222. libraster, libraster3d and libvector functions
  223. """
  224. global c_library_interface
  225. return c_library_interface
  226. ###############################################################################
  227. # Set this variable True to raise a FatalError exception
  228. # in case a fatal error occurs using the messenger interface
  229. raise_on_error = False
  230. def set_raise_on_error(raise_exp=True):
  231. """Define behavior on fatal error, invoked using the tgis messenger
  232. interface (msgr.fatal())
  233. The messenger interface will be restarted using the new error policy
  234. :param raise_exp: True to raise a FatalError exception instead of calling
  235. sys.exit(1) when using the tgis messenger interface
  236. .. code-block:: python
  237. >>> import grass.temporal as tgis
  238. >>> tgis.init()
  239. >>> ignore = tgis.set_raise_on_error(False)
  240. >>> msgr = tgis.get_tgis_message_interface()
  241. >>> tgis.get_raise_on_error()
  242. False
  243. >>> msgr.fatal("Ohh no no no!")
  244. Traceback (most recent call last):
  245. File "__init__.py", line 239, in fatal
  246. sys.exit(1)
  247. SystemExit: 1
  248. >>> tgis.set_raise_on_error(True)
  249. False
  250. >>> msgr.fatal("Ohh no no no!")
  251. Traceback (most recent call last):
  252. File "__init__.py", line 241, in fatal
  253. raise FatalError(message)
  254. FatalError: Ohh no no no!
  255. :returns: current status
  256. """
  257. global raise_on_error
  258. tmp_raise = raise_on_error
  259. raise_on_error = raise_exp
  260. global message_interface
  261. if message_interface:
  262. message_interface.set_raise_on_error(raise_on_error)
  263. else:
  264. _init_tgis_message_interface(raise_on_error)
  265. return tmp_raise
  266. def get_raise_on_error():
  267. """Return True if a FatalError exception is raised instead of calling
  268. sys.exit(1) in case a fatal error was invoked with msgr.fatal()
  269. """
  270. global raise_on_error
  271. return raise_on_error
  272. ###############################################################################
  273. def get_tgis_version():
  274. """Get the version number of the temporal framework
  275. :returns: The version number of the temporal framework as string
  276. """
  277. global tgis_version
  278. return tgis_version
  279. ###############################################################################
  280. def get_tgis_db_version():
  281. """Get the version number of the temporal framework
  282. :returns: The version number of the temporal framework as string
  283. """
  284. global tgis_db_version
  285. return tgis_db_version
  286. ###############################################################################
  287. def get_tgis_metadata(dbif=None):
  288. """Return the tgis metadata table as a list of rows (dicts) or None if not
  289. present
  290. :param dbif: The database interface to be used
  291. :returns: The selected rows with key/value columns or None
  292. """
  293. dbif, connected = init_dbif(dbif)
  294. # Select metadata if the table is present
  295. try:
  296. statement = "SELECT * FROM tgis_metadata;\n"
  297. dbif.execute(statement)
  298. rows = dbif.fetchall()
  299. except:
  300. rows = None
  301. if connected:
  302. dbif.close()
  303. return rows
  304. ###############################################################################
  305. # The temporal database string set with t.connect
  306. # with substituted GRASS variables gisdbase, location and mapset
  307. tgis_database_string = None
  308. def get_tgis_database_string():
  309. """Return the preprocessed temporal database string
  310. This string is the temporal database string set with t.connect
  311. that was processed to substitue location, gisdbase and mapset
  312. variables.
  313. """
  314. global tgis_database_string
  315. return tgis_database_string
  316. ###############################################################################
  317. def get_sql_template_path():
  318. base = os.getenv("GISBASE")
  319. base_etc = os.path.join(base, "etc")
  320. return os.path.join(base_etc, "sql")
  321. ###############################################################################
  322. def stop_subprocesses():
  323. """Stop the messenger and C-interface subprocesses
  324. that are started by tgis.init()
  325. """
  326. global message_interface
  327. global c_library_interface
  328. if message_interface:
  329. message_interface.stop()
  330. if c_library_interface:
  331. c_library_interface.stop()
  332. # We register this function to be called at exit
  333. atexit.register(stop_subprocesses)
  334. def get_available_temporal_mapsets():
  335. """Return a list of of mapset names with temporal database driver and names
  336. that are accessible from the current mapset.
  337. :returns: A dictionary, mapset names are keys, the tuple (driver,
  338. database) are the values
  339. """
  340. global c_library_interface
  341. global message_interface
  342. mapsets = c_library_interface.available_mapsets()
  343. tgis_mapsets = {}
  344. for mapset in mapsets:
  345. mapset = mapset
  346. driver = c_library_interface.get_driver_name(mapset)
  347. database = c_library_interface.get_database_name(mapset)
  348. message_interface.debug(1, "get_available_temporal_mapsets: "\
  349. "\n mapset %s\n driver %s\n database %s"%(mapset,
  350. driver, database))
  351. if driver and database:
  352. # Check if the temporal sqlite database exists
  353. # We need to set non-existing databases in case the mapset is the current mapset
  354. # to create it
  355. if (driver == "sqlite" and os.path.exists(database)) or mapset == get_current_mapset() :
  356. tgis_mapsets[mapset] = (driver, database)
  357. # We need to warn if the connection is defined but the database does not
  358. # exists
  359. if driver == "sqlite" and not os.path.exists(database):
  360. message_interface.warning("Temporal database connection defined as:\n" + \
  361. database + "\nBut database file does not exist.")
  362. return tgis_mapsets
  363. ###############################################################################
  364. def init(raise_fatal_error=False):
  365. """This function set the correct database backend from GRASS environmental
  366. variables and creates the grass temporal database structure for raster,
  367. vector and raster3d maps as well as for the space-time datasets strds,
  368. str3ds and stvds in case it does not exist.
  369. Several global variables are initiated and the messenger and C-library
  370. interface subprocesses are spawned.
  371. Re-run this function in case the following GRASS variables change while
  372. the process runs:
  373. - MAPSET
  374. - LOCATION_NAME
  375. - GISDBASE
  376. - TGIS_DISABLE_MAPSET_CHECK
  377. - TGIS_DISABLE_TIMESTAMP_WRITE
  378. Re-run this function if the following t.connect variables change while
  379. the process runs:
  380. - temporal GIS driver (set by t.connect driver=)
  381. - temporal GIS database (set by t.connect database=)
  382. The following environmental variables are checked:
  383. - GRASS_TGIS_PROFILE (True, False, 1, 0)
  384. - GRASS_TGIS_RAISE_ON_ERROR (True, False, 1, 0)
  385. ..warning::
  386. This functions must be called before any spatio-temporal processing
  387. can be started
  388. :param raise_fatal_error: Set this True to assure that the init()
  389. function does not kill a persistent process
  390. like the GUI. If set True a
  391. grass.pygrass.messages.FatalError
  392. exception will be raised in case a fatal
  393. error occurs in the init process, otherwise
  394. sys.exit(1) will be called.
  395. """
  396. # We need to set the correct database backend and several global variables
  397. # from the GRASS mapset specific environment variables of g.gisenv and t.connect
  398. global tgis_backend
  399. global tgis_database
  400. global tgis_database_string
  401. global tgis_dbmi_paramstyle
  402. global raise_on_error
  403. global enable_mapset_check
  404. global enable_timestamp_write
  405. global current_mapset
  406. global current_location
  407. global current_gisdbase
  408. raise_on_error = raise_fatal_error
  409. # We must run t.connect at first to create the temporal database and to
  410. # get the environmental variables
  411. gscript.run_command("t.connect", flags="c")
  412. grassenv = gscript.gisenv()
  413. # Set the global variable for faster access
  414. current_mapset = grassenv["MAPSET"]
  415. current_location = grassenv["LOCATION_NAME"]
  416. current_gisdbase = grassenv["GISDBASE"]
  417. # Check environment variable GRASS_TGIS_RAISE_ON_ERROR
  418. if os.getenv("GRASS_TGIS_RAISE_ON_ERROR") == "True" or \
  419. os.getenv("GRASS_TGIS_RAISE_ON_ERROR") == "1":
  420. raise_on_error = True
  421. # Check if the script library raises on error,
  422. # if so we do the same
  423. if gscript.get_raise_on_error() is True:
  424. raise_on_error = True
  425. # Start the GRASS message interface server
  426. _init_tgis_message_interface(raise_on_error)
  427. # Start the C-library interface server
  428. _init_tgis_c_library_interface()
  429. msgr = get_tgis_message_interface()
  430. msgr.debug(1, "Initiate the temporal database")
  431. #"\n traceback:%s"%(str(" \n".join(traceback.format_stack()))))
  432. msgr.debug(1, ("Raise on error id: %s"%str(raise_on_error)))
  433. ciface = get_tgis_c_library_interface()
  434. driver_string = ciface.get_driver_name()
  435. database_string = ciface.get_database_name()
  436. # Set the mapset check and the timestamp write
  437. if "TGIS_DISABLE_MAPSET_CHECK" in grassenv:
  438. if gscript.encode(grassenv["TGIS_DISABLE_MAPSET_CHECK"]) == "True" or \
  439. gscript.encode(grassenv["TGIS_DISABLE_MAPSET_CHECK"]) == "1":
  440. enable_mapset_check = False
  441. msgr.warning("TGIS_DISABLE_MAPSET_CHECK is True")
  442. if "TGIS_DISABLE_TIMESTAMP_WRITE" in grassenv:
  443. if gscript.encode(grassenv["TGIS_DISABLE_TIMESTAMP_WRITE"]) == "True" or \
  444. gscript.encode(grassenv["TGIS_DISABLE_TIMESTAMP_WRITE"]) == "1":
  445. enable_timestamp_write = False
  446. msgr.warning("TGIS_DISABLE_TIMESTAMP_WRITE is True")
  447. if driver_string is not None and driver_string is not "":
  448. driver_string = decode(driver_string)
  449. if driver_string == "sqlite":
  450. tgis_backend = driver_string
  451. try:
  452. import sqlite3
  453. except ImportError:
  454. msgr.error("Unable to locate the sqlite SQL Python interface"
  455. " module sqlite3.")
  456. raise
  457. dbmi = sqlite3
  458. elif driver_string == "pg":
  459. tgis_backend = driver_string
  460. try:
  461. import psycopg2
  462. except ImportError:
  463. msgr.error("Unable to locate the Postgresql SQL Python "
  464. "interface module psycopg2.")
  465. raise
  466. dbmi = psycopg2
  467. else:
  468. msgr.fatal(_("Unable to initialize the temporal DBMI interface. "
  469. "Please use t.connect to specify the driver and the"
  470. " database string"))
  471. else:
  472. # Set the default sqlite3 connection in case nothing was defined
  473. gscript.run_command("t.connect", flags="d")
  474. driver_string = ciface.get_driver_name()
  475. database_string = ciface.get_database_name()
  476. tgis_backend = driver_string
  477. try:
  478. import sqlite3
  479. except ImportError:
  480. msgr.error("Unable to locate the sqlite SQL Python interface"
  481. " module sqlite3.")
  482. raise
  483. dbmi = sqlite3
  484. tgis_database_string = database_string
  485. # Set the parameter style
  486. tgis_dbmi_paramstyle = dbmi.paramstyle
  487. # We do not know if the database already exists
  488. db_exists = False
  489. dbif = SQLDatabaseInterfaceConnection()
  490. # Check if the database already exists
  491. if tgis_backend == "sqlite":
  492. # Check path of the sqlite database
  493. if os.path.exists(tgis_database_string):
  494. dbif.connect()
  495. # Check for raster_base table
  496. dbif.execute("SELECT name FROM sqlite_master WHERE type='table' "
  497. "AND name='raster_base';")
  498. name = dbif.fetchone()
  499. if name and name[0] == "raster_base":
  500. db_exists = True
  501. dbif.close()
  502. elif tgis_backend == "pg":
  503. # Connect to database
  504. dbif.connect()
  505. # Check for raster_base table
  506. dbif.execute("SELECT EXISTS(SELECT * FROM information_schema.tables "
  507. "WHERE table_name=%s)", ('raster_base',))
  508. if dbif.fetchone()[0]:
  509. db_exists = True
  510. backup_howto = "The format of your actual temporal database is not " \
  511. "supported any more.\nSolution: You need to export it by " \
  512. "restoring the GRASS GIS version used for creating this DB"\
  513. ". From there, create a backup of your temporal database "\
  514. "to avoid the loss of your temporal data.\nNotes: Use " \
  515. "t.rast.export and t.vect.export to make a backup of your" \
  516. " existing space time datasets.To safe the timestamps of" \
  517. " your existing maps and space time datasets, use " \
  518. "t.rast.list, t.vect.list and t.rast3d.list. "\
  519. "You can register the existing time stamped maps easily if"\
  520. " you export columns=id,start_time,end_time into text "\
  521. "files and use t.register to register them again in new" \
  522. " created space time datasets (t.create). After the backup"\
  523. " remove the existing temporal database, a new one will be"\
  524. " created automatically.\n"
  525. if db_exists is True:
  526. # Check the version of the temporal database
  527. dbif.close()
  528. dbif.connect()
  529. metadata = get_tgis_metadata(dbif)
  530. dbif.close()
  531. if metadata is None:
  532. msgr.fatal(_("Unable to receive temporal database metadata.\n"
  533. "Current temporal database info:%(info)s") % (
  534. {"info": get_database_info_string()}))
  535. for entry in metadata:
  536. if "tgis_version" in entry and entry[1] != str(get_tgis_version()):
  537. msgr.fatal(_("Unsupported temporal database: version mismatch."
  538. "\n %(backup)s Supported temporal API version is:"
  539. " %(api)i.\nPlease update your GRASS GIS "
  540. "installation.\nCurrent temporal database info:"
  541. "%(info)s") % ({"backup": backup_howto,
  542. "api": get_tgis_version(),
  543. "info": get_database_info_string()}))
  544. if "tgis_db_version" in entry and entry[1] != str(get_tgis_db_version()):
  545. msgr.fatal(_("Unsupported temporal database: version mismatch."
  546. "\n %(backup)sSupported temporal database version"
  547. " is: %(tdb)i\nCurrent temporal database info:"
  548. "%(info)s") % ({"backup": backup_howto,
  549. "tdb": get_tgis_version(),
  550. "info": get_database_info_string()}))
  551. return
  552. create_temporal_database(dbif)
  553. ###############################################################################
  554. def get_database_info_string():
  555. dbif = SQLDatabaseInterfaceConnection()
  556. info = "\nDBMI interface:..... " + str(dbif.get_dbmi().__name__)
  557. info += "\nTemporal database:.. " + str(get_tgis_database_string())
  558. return info
  559. ###############################################################################
  560. def create_temporal_database(dbif):
  561. """This function will create the temporal database
  562. It will create all tables and triggers that are needed to run
  563. the temporal GIS
  564. :param dbif: The database interface to be used
  565. """
  566. global tgis_backend
  567. global tgis_version
  568. global tgis_db_version
  569. global tgis_database_string
  570. template_path = get_sql_template_path()
  571. msgr = get_tgis_message_interface()
  572. # Read all SQL scripts and templates
  573. map_tables_template_sql = open(os.path.join(
  574. template_path, "map_tables_template.sql"), 'r').read()
  575. raster_metadata_sql = open(os.path.join(
  576. get_sql_template_path(), "raster_metadata_table.sql"), 'r').read()
  577. raster3d_metadata_sql = open(os.path.join(template_path,
  578. "raster3d_metadata_table.sql"),
  579. 'r').read()
  580. vector_metadata_sql = open(os.path.join(template_path,
  581. "vector_metadata_table.sql"),
  582. 'r').read()
  583. raster_views_sql = open(os.path.join(template_path, "raster_views.sql"),
  584. 'r').read()
  585. raster3d_views_sql = open(os.path.join(template_path,
  586. "raster3d_views.sql"), 'r').read()
  587. vector_views_sql = open(os.path.join(template_path, "vector_views.sql"),
  588. 'r').read()
  589. stds_tables_template_sql = open(os.path.join(template_path,
  590. "stds_tables_template.sql"),
  591. 'r').read()
  592. strds_metadata_sql = open(os.path.join(template_path,
  593. "strds_metadata_table.sql"),
  594. 'r').read()
  595. str3ds_metadata_sql = open(os.path.join(template_path,
  596. "str3ds_metadata_table.sql"),
  597. 'r').read()
  598. stvds_metadata_sql = open(os.path.join(template_path,
  599. "stvds_metadata_table.sql"),
  600. 'r').read()
  601. strds_views_sql = open(os.path.join(template_path, "strds_views.sql"),
  602. 'r').read()
  603. str3ds_views_sql = open(os.path.join(template_path, "str3ds_views.sql"),
  604. 'r').read()
  605. stvds_views_sql = open(os.path.join(template_path, "stvds_views.sql"),
  606. 'r').read()
  607. # Create the raster, raster3d and vector tables SQL statements
  608. raster_tables_sql = map_tables_template_sql.replace("GRASS_MAP", "raster")
  609. vector_tables_sql = map_tables_template_sql.replace("GRASS_MAP", "vector")
  610. raster3d_tables_sql = map_tables_template_sql.replace(
  611. "GRASS_MAP", "raster3d")
  612. # Create the space-time raster, raster3d and vector dataset tables
  613. # SQL statements
  614. strds_tables_sql = stds_tables_template_sql.replace("STDS", "strds")
  615. stvds_tables_sql = stds_tables_template_sql.replace("STDS", "stvds")
  616. str3ds_tables_sql = stds_tables_template_sql.replace("STDS", "str3ds")
  617. msgr.message(_("Creating temporal database: %s" % (str(tgis_database_string))))
  618. if tgis_backend == "sqlite":
  619. # We need to create the sqlite3 database path if it does not exist
  620. tgis_dir = os.path.dirname(tgis_database_string)
  621. if not os.path.exists(tgis_dir):
  622. try:
  623. os.makedirs(tgis_dir)
  624. except Exception as e:
  625. msgr.fatal(_("Unable to create SQLite temporal database\n"
  626. "Exception: %s\nPlease use t.connect to set a "
  627. "read- and writable temporal database path" % (e)))
  628. # Set up the trigger that takes care of
  629. # the correct deletion of entries across the different tables
  630. delete_trigger_sql = open(os.path.join(template_path,
  631. "sqlite3_delete_trigger.sql"),
  632. 'r').read()
  633. indexes_sql = open(os.path.join(template_path, "sqlite3_indexes.sql"),
  634. 'r').read()
  635. else:
  636. # Set up the trigger that takes care of
  637. # the correct deletion of entries across the different tables
  638. delete_trigger_sql = open(os.path.join(template_path,
  639. "postgresql_delete_trigger.sql"),
  640. 'r').read()
  641. indexes_sql = open(os.path.join(template_path,
  642. "postgresql_indexes.sql"), 'r').read()
  643. # Connect now to the database
  644. if dbif.connected is not True:
  645. dbif.connect()
  646. # Execute the SQL statements for sqlite
  647. # Create the global tables for the native grass datatypes
  648. dbif.execute_transaction(raster_tables_sql)
  649. dbif.execute_transaction(raster_metadata_sql)
  650. dbif.execute_transaction(raster_views_sql)
  651. dbif.execute_transaction(vector_tables_sql)
  652. dbif.execute_transaction(vector_metadata_sql)
  653. dbif.execute_transaction(vector_views_sql)
  654. dbif.execute_transaction(raster3d_tables_sql)
  655. dbif.execute_transaction(raster3d_metadata_sql)
  656. dbif.execute_transaction(raster3d_views_sql)
  657. # Create the tables for the new space-time datatypes
  658. dbif.execute_transaction(strds_tables_sql)
  659. dbif.execute_transaction(strds_metadata_sql)
  660. dbif.execute_transaction(strds_views_sql)
  661. dbif.execute_transaction(stvds_tables_sql)
  662. dbif.execute_transaction(stvds_metadata_sql)
  663. dbif.execute_transaction(stvds_views_sql)
  664. dbif.execute_transaction(str3ds_tables_sql)
  665. dbif.execute_transaction(str3ds_metadata_sql)
  666. dbif.execute_transaction(str3ds_views_sql)
  667. # The delete trigger
  668. dbif.execute_transaction(delete_trigger_sql)
  669. # The indexes
  670. dbif.execute_transaction(indexes_sql)
  671. # Create the tgis metadata table to store the database
  672. # initial configuration
  673. # The metadata table content
  674. metadata = {}
  675. metadata["tgis_version"] = tgis_version
  676. metadata["tgis_db_version"] = tgis_db_version
  677. metadata["creation_time"] = datetime.today()
  678. _create_tgis_metadata_table(metadata, dbif)
  679. dbif.close()
  680. ###############################################################################
  681. def _create_tgis_metadata_table(content, dbif=None):
  682. """!Create the temporal gis metadata table which stores all metadata
  683. information about the temporal database.
  684. :param content: The dictionary that stores the key:value metadata
  685. that should be stored in the metadata table
  686. :param dbif: The database interface to be used
  687. """
  688. dbif, connected = init_dbif(dbif)
  689. statement = "CREATE TABLE tgis_metadata (key VARCHAR NOT NULL, value VARCHAR);\n";
  690. dbif.execute_transaction(statement)
  691. for key in content.keys():
  692. statement = "INSERT INTO tgis_metadata (key, value) VALUES " + \
  693. "(\'%s\' , \'%s\');\n" % (str(key), str(content[key]))
  694. dbif.execute_transaction(statement)
  695. if connected:
  696. dbif.close()
  697. ###############################################################################
  698. class SQLDatabaseInterfaceConnection(object):
  699. def __init__(self):
  700. self.tgis_mapsets = get_available_temporal_mapsets()
  701. self.current_mapset = get_current_mapset()
  702. self.connections = {}
  703. self.connected = False
  704. self.unique_connections = {}
  705. for mapset in self.tgis_mapsets.keys():
  706. driver, dbstring = self.tgis_mapsets[mapset]
  707. if dbstring not in self.unique_connections.keys():
  708. self.unique_connections[dbstring] = DBConnection(backend=driver,
  709. dbstring=dbstring)
  710. self.connections[mapset] = self.unique_connections[dbstring]
  711. self.msgr = get_tgis_message_interface()
  712. def get_dbmi(self, mapset=None):
  713. if mapset is None:
  714. mapset = self.current_mapset
  715. mapset = decode(mapset)
  716. return self.connections[mapset].dbmi
  717. def rollback(self, mapset=None):
  718. """
  719. Roll back the last transaction. This must be called
  720. in case a new query should be performed after a db error.
  721. This is only relevant for postgresql database.
  722. """
  723. if mapset is None:
  724. mapset = self.current_mapset
  725. def connect(self):
  726. """Connect to the DBMI to execute SQL statements
  727. Supported backends are sqlite3 and postgresql
  728. """
  729. for mapset in self.tgis_mapsets.keys():
  730. driver, dbstring = self.tgis_mapsets[mapset]
  731. conn = self.connections[mapset]
  732. if conn.is_connected() is False:
  733. conn.connect(dbstring)
  734. self.connected = True
  735. def is_connected(self):
  736. return self.connected
  737. def close(self):
  738. """Close the DBMI connection
  739. There may be several temporal databases in a location, hence
  740. close all temporal databases that have been opened.
  741. """
  742. for key in self.unique_connections.keys():
  743. self.unique_connections[key].close()
  744. self.connected = False
  745. def mogrify_sql_statement(self, content, mapset=None):
  746. """Return the SQL statement and arguments as executable SQL string
  747. :param content: The content as tuple with two entries, the first
  748. entry is the SQL statement with DBMI specific
  749. place holder (?), the second entry is the argument
  750. list that should substitute the place holder.
  751. :param mapset: The mapset of the abstract dataset or temporal
  752. database location, if None the current mapset
  753. will be used
  754. """
  755. if mapset is None:
  756. mapset = self.current_mapset
  757. mapset = decode(mapset)
  758. if mapset not in self.tgis_mapsets.keys():
  759. self.msgr.fatal(_("Unable to mogrify sql statement. " +
  760. self._create_mapset_error_message(mapset)))
  761. return self.connections[mapset].mogrify_sql_statement(content)
  762. def check_table(self, table_name, mapset=None):
  763. """Check if a table exists in the temporal database
  764. :param table_name: The name of the table to be checked for existence
  765. :param mapset: The mapset of the abstract dataset or temporal
  766. database location, if None the current mapset
  767. will be used
  768. :returns: True if the table exists, False otherwise
  769. TODO:
  770. There may be several temporal databases in a location, hence
  771. the mapset is used to query the correct temporal database.
  772. """
  773. if mapset is None:
  774. mapset = self.current_mapset
  775. mapset = decode(mapset)
  776. if mapset not in self.tgis_mapsets.keys():
  777. self.msgr.fatal(_("Unable to check table. " +
  778. self._create_mapset_error_message(mapset)))
  779. return self.connections[mapset].check_table(table_name)
  780. def execute(self, statement, args=None, mapset=None):
  781. """
  782. :param mapset: The mapset of the abstract dataset or temporal
  783. database location, if None the current mapset
  784. will be used
  785. """
  786. if mapset is None:
  787. mapset = self.current_mapset
  788. mapset = decode(mapset)
  789. if mapset not in self.tgis_mapsets.keys():
  790. self.msgr.fatal(_("Unable to execute sql statement. " +
  791. self._create_mapset_error_message(mapset)))
  792. return self.connections[mapset].execute(statement, args)
  793. def fetchone(self, mapset=None):
  794. if mapset is None:
  795. mapset = self.current_mapset
  796. mapset = decode(mapset)
  797. if mapset not in self.tgis_mapsets.keys():
  798. self.msgr.fatal(_("Unable to fetch one. " +
  799. self._create_mapset_error_message(mapset)))
  800. return self.connections[mapset].fetchone()
  801. def fetchall(self, mapset=None):
  802. if mapset is None:
  803. mapset = self.current_mapset
  804. mapset = decode(mapset)
  805. if mapset not in self.tgis_mapsets.keys():
  806. self.msgr.fatal(_("Unable to fetch all. " +
  807. self._create_mapset_error_message(mapset)))
  808. return self.connections[mapset].fetchall()
  809. def execute_transaction(self, statement, mapset=None):
  810. """Execute a transactional SQL statement
  811. The BEGIN and END TRANSACTION statements will be added automatically
  812. to the sql statement
  813. :param statement: The executable SQL statement or SQL script
  814. """
  815. if mapset is None:
  816. mapset = self.current_mapset
  817. mapset = decode(mapset)
  818. if mapset not in self.tgis_mapsets.keys():
  819. self.msgr.fatal(_("Unable to execute transaction. " +
  820. self._create_mapset_error_message(mapset)))
  821. return self.connections[mapset].execute_transaction(statement)
  822. def _create_mapset_error_message(self, mapset):
  823. return("You have no permission to "
  824. "access mapset <%(mapset)s>, or "
  825. "mapset <%(mapset)s> has no temporal database. "
  826. "Accessible mapsets are: <%(mapsets)s>" % \
  827. {"mapset": decode(mapset),
  828. "mapsets":','.join(self.tgis_mapsets.keys())})
  829. ###############################################################################
  830. class DBConnection(object):
  831. """This class represents the database interface connection
  832. and provides access to the chosen backend modules.
  833. The following DBMS are supported:
  834. - sqlite via the sqlite3 standard library
  835. - postgresql via psycopg2
  836. """
  837. def __init__(self, backend=None, dbstring=None):
  838. """ Constructor of a database connection
  839. param backend:The database backend sqlite or pg
  840. param dbstring: The database connection string
  841. """
  842. self.connected = False
  843. if backend is None:
  844. global tgis_backend
  845. if decode(tgis_backend) == "sqlite":
  846. self.dbmi = sqlite3
  847. else:
  848. self.dbmi = psycopg2
  849. else:
  850. if decode(backend) == "sqlite":
  851. self.dbmi = sqlite3
  852. else:
  853. self.dbmi = psycopg2
  854. if dbstring is None:
  855. global tgis_database_string
  856. self.dbstring = tgis_database_string
  857. self.dbstring = dbstring
  858. self.msgr = get_tgis_message_interface()
  859. self.msgr.debug(1, "DBConnection constructor:"\
  860. "\n backend: %s"\
  861. "\n dbstring: %s"%(backend, self.dbstring))
  862. #"\n traceback:%s"%(backend, self.dbstring,
  863. #str(" \n".join(traceback.format_stack()))))
  864. def __del__(self):
  865. if self.connected is True:
  866. self.close()
  867. def is_connected(self):
  868. return self.connected
  869. def rollback(self):
  870. """
  871. Roll back the last transaction. This must be called
  872. in case a new query should be performed after a db error.
  873. This is only relevant for postgresql database.
  874. """
  875. if self.dbmi.__name__ == "psycopg2":
  876. if self.connected:
  877. self.connection.rollback()
  878. def connect(self, dbstring=None):
  879. """Connect to the DBMI to execute SQL statements
  880. Supported backends are sqlite3 and postgresql
  881. param dbstring: The database connection string
  882. """
  883. # Connection in the current mapset
  884. if dbstring is None:
  885. dbstring = self.dbstring
  886. dbstring = decode(dbstring)
  887. try:
  888. if self.dbmi.__name__ == "sqlite3":
  889. self.connection = self.dbmi.connect(dbstring,
  890. detect_types=self.dbmi.PARSE_DECLTYPES | self.dbmi.PARSE_COLNAMES)
  891. self.connection.row_factory = self.dbmi.Row
  892. self.connection.isolation_level = None
  893. self.connection.text_factory = str
  894. self.cursor = self.connection.cursor()
  895. self.cursor.execute("PRAGMA synchronous = OFF")
  896. self.cursor.execute("PRAGMA journal_mode = MEMORY")
  897. elif self.dbmi.__name__ == "psycopg2":
  898. self.connection = self.dbmi.connect(dbstring)
  899. #self.connection.set_isolation_level(dbmi.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
  900. self.cursor = self.connection.cursor(
  901. cursor_factory=self.dbmi.extras.DictCursor)
  902. self.connected = True
  903. except Exception as e:
  904. self.msgr.fatal(_("Unable to connect to %(db)s database: "
  905. "%(string)s\nException: \"%(ex)s\"\nPlease use"
  906. " t.connect to set a read- and writable "
  907. "temporal database backend") % (
  908. {"db": self.dbmi.__name__,
  909. "string": tgis_database_string, "ex": e, }))
  910. def close(self):
  911. """Close the DBMI connection
  912. TODO:
  913. There may be several temporal databases in a location, hence
  914. close all temporal databases that have been opened. Use a dictionary
  915. to manage different connections.
  916. """
  917. self.connection.commit()
  918. self.cursor.close()
  919. self.connected = False
  920. def mogrify_sql_statement(self, content):
  921. """Return the SQL statement and arguments as executable SQL string
  922. TODO:
  923. Use the mapset argument to identify the correct database driver
  924. :param content: The content as tuple with two entries, the first
  925. entry is the SQL statement with DBMI specific
  926. place holder (?), the second entry is the argument
  927. list that should substitute the place holder.
  928. :param mapset: The mapset of the abstract dataset or temporal
  929. database location, if None the current mapset
  930. will be used
  931. Usage:
  932. .. code-block:: python
  933. >>> init()
  934. >>> dbif = SQLDatabaseInterfaceConnection()
  935. >>> dbif.mogrify_sql_statement(["SELECT ctime FROM raster_base WHERE id = ?",
  936. ... ["soil@PERMANENT",]])
  937. "SELECT ctime FROM raster_base WHERE id = 'soil@PERMANENT'"
  938. """
  939. sql = content[0]
  940. args = content[1]
  941. if self.dbmi.__name__ == "psycopg2":
  942. if len(args) == 0:
  943. return sql
  944. else:
  945. if self.connected:
  946. try:
  947. return self.cursor.mogrify(sql, args)
  948. except Exception as exc:
  949. print(sql, args)
  950. raise exc
  951. else:
  952. self.connect()
  953. statement = self.cursor.mogrify(sql, args)
  954. self.close()
  955. return statement
  956. elif self.dbmi.__name__ == "sqlite3":
  957. if len(args) == 0:
  958. return sql
  959. else:
  960. # Unfortunately as sqlite does not support
  961. # the transformation of sql strings and qmarked or
  962. # named arguments we must make our hands dirty
  963. # and do it by ourself. :(
  964. # Doors are open for SQL injection because of the
  965. # limited python sqlite3 implementation!!!
  966. pos = 0
  967. count = 0
  968. maxcount = 100
  969. statement = sql
  970. while count < maxcount:
  971. pos = statement.find("?", pos + 1)
  972. if pos == -1:
  973. break
  974. if args[count] is None:
  975. statement = "%sNULL%s" % (statement[0:pos],
  976. statement[pos + 1:])
  977. elif isinstance(args[count], (int, long)):
  978. statement = "%s%d%s" % (statement[0:pos], args[count],
  979. statement[pos + 1:])
  980. elif isinstance(args[count], float):
  981. statement = "%s%f%s" % (statement[0:pos], args[count],
  982. statement[pos + 1:])
  983. elif isinstance(args[count], datetime):
  984. statement = "%s\'%s\'%s" % (statement[0:pos], str(args[count]),
  985. statement[pos + 1:])
  986. else:
  987. # Default is a string, this works for datetime
  988. # objects too
  989. statement = "%s\'%s\'%s" % (statement[0:pos],
  990. str(args[count]),
  991. str(statement[pos + 1:]))
  992. count += 1
  993. return statement
  994. def check_table(self, table_name):
  995. """Check if a table exists in the temporal database
  996. :param table_name: The name of the table to be checked for existence
  997. :param mapset: The mapset of the abstract dataset or temporal
  998. database location, if None the current mapset
  999. will be used
  1000. :returns: True if the table exists, False otherwise
  1001. TODO:
  1002. There may be several temporal databases in a location, hence
  1003. the mapset is used to query the correct temporal database.
  1004. """
  1005. table_exists = False
  1006. connected = False
  1007. if not self.connected:
  1008. self.connect()
  1009. connected = True
  1010. # Check if the database already exists
  1011. if self.dbmi.__name__ == "sqlite3":
  1012. self.cursor.execute("SELECT name FROM sqlite_master WHERE "
  1013. "type='table' AND name='%s';" % table_name)
  1014. name = self.cursor.fetchone()
  1015. if name and name[0] == table_name:
  1016. table_exists = True
  1017. else:
  1018. # Check for raster_base table
  1019. self.cursor.execute("SELECT EXISTS(SELECT * FROM information_schema.tables "
  1020. "WHERE table_name=%s)", ('%s' % table_name,))
  1021. if self.cursor.fetchone()[0]:
  1022. table_exists = True
  1023. if connected:
  1024. self.close()
  1025. return table_exists
  1026. def execute(self, statement, args=None):
  1027. """Execute a SQL statement
  1028. :param statement: The executable SQL statement or SQL script
  1029. """
  1030. connected = False
  1031. if not self.connected:
  1032. self.connect()
  1033. connected = True
  1034. try:
  1035. if args:
  1036. self.cursor.execute(statement, args)
  1037. else:
  1038. self.cursor.execute(statement)
  1039. except:
  1040. if connected:
  1041. self.close()
  1042. self.msgr.error(_("Unable to execute :\n %(sql)s" %
  1043. {"sql": statement}))
  1044. raise
  1045. if connected:
  1046. self.close()
  1047. def fetchone(self):
  1048. if self.connected:
  1049. return self.cursor.fetchone()
  1050. return None
  1051. def fetchall(self):
  1052. if self.connected:
  1053. return self.cursor.fetchall()
  1054. return None
  1055. def execute_transaction(self, statement, mapset=None):
  1056. """Execute a transactional SQL statement
  1057. The BEGIN and END TRANSACTION statements will be added automatically
  1058. to the sql statement
  1059. :param statement: The executable SQL statement or SQL script
  1060. """
  1061. connected = False
  1062. if not self.connected:
  1063. self.connect()
  1064. connected = True
  1065. sql_script = ""
  1066. sql_script += "BEGIN TRANSACTION;\n"
  1067. sql_script += statement
  1068. sql_script += "END TRANSACTION;"
  1069. try:
  1070. if self.dbmi.__name__ == "sqlite3":
  1071. self.cursor.executescript(statement)
  1072. else:
  1073. self.cursor.execute(statement)
  1074. self.connection.commit()
  1075. except:
  1076. if connected:
  1077. self.close()
  1078. self.msgr.error(_("Unable to execute transaction:\n %(sql)s" %
  1079. {"sql": statement}))
  1080. raise
  1081. if connected:
  1082. self.close()
  1083. ###############################################################################
  1084. def init_dbif(dbif):
  1085. """This method checks if the database interface connection exists,
  1086. if not a new one will be created, connected and True will be returned.
  1087. If the database interface exists but is connected, the connection will
  1088. be established.
  1089. :returns: the tuple (dbif, True|False)
  1090. Usage code sample:
  1091. .. code-block:: python
  1092. dbif, connect = tgis.init_dbif(None)
  1093. sql = dbif.mogrify_sql_statement(["SELECT * FROM raster_base WHERE ? = ?"],
  1094. ["id", "soil@PERMANENT"])
  1095. dbif.execute_transaction(sql)
  1096. if connect:
  1097. dbif.close()
  1098. """
  1099. if dbif is None:
  1100. dbif = SQLDatabaseInterfaceConnection()
  1101. dbif.connect()
  1102. return dbif, True
  1103. elif dbif.is_connected() is False:
  1104. dbif.connect()
  1105. return dbif, True
  1106. return dbif, False
  1107. ###############################################################################
  1108. if __name__ == "__main__":
  1109. import doctest
  1110. doctest.testmod()