core.py 50 KB

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