core.py 53 KB

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