core.py 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460
  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. from .c_libraries_interface import *
  30. from grass.pygrass import messages
  31. from grass.script.utils import decode, encode
  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, 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 = 3
  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, skip_db_version_check=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. :param skip_db_version_check: Set this True to skip mismatch temporal
  393. database version check.
  394. Recommended to be used only for
  395. upgrade_temporal_database().
  396. """
  397. # We need to set the correct database backend and several global variables
  398. # from the GRASS mapset specific environment variables of g.gisenv and t.connect
  399. global tgis_backend
  400. global tgis_database
  401. global tgis_database_string
  402. global tgis_dbmi_paramstyle
  403. global tgis_db_version
  404. global raise_on_error
  405. global enable_mapset_check
  406. global enable_timestamp_write
  407. global current_mapset
  408. global current_location
  409. global current_gisdbase
  410. raise_on_error = raise_fatal_error
  411. # We must run t.connect at first to create the temporal database and to
  412. # get the environmental variables
  413. gscript.run_command("t.connect", flags="c")
  414. grassenv = gscript.gisenv()
  415. # Set the global variable for faster access
  416. current_mapset = grassenv["MAPSET"]
  417. current_location = grassenv["LOCATION_NAME"]
  418. current_gisdbase = grassenv["GISDBASE"]
  419. # Check environment variable GRASS_TGIS_RAISE_ON_ERROR
  420. if os.getenv("GRASS_TGIS_RAISE_ON_ERROR") == "True" or \
  421. os.getenv("GRASS_TGIS_RAISE_ON_ERROR") == "1":
  422. raise_on_error = True
  423. # Check if the script library raises on error,
  424. # if so we do the same
  425. if gscript.get_raise_on_error() is True:
  426. raise_on_error = True
  427. # Start the GRASS message interface server
  428. _init_tgis_message_interface(raise_on_error)
  429. # Start the C-library interface server
  430. _init_tgis_c_library_interface()
  431. msgr = get_tgis_message_interface()
  432. msgr.debug(1, "Initiate the temporal database")
  433. msgr.debug(1, ("Raise on error id: %s"%str(raise_on_error)))
  434. ciface = get_tgis_c_library_interface()
  435. driver_string = ciface.get_driver_name()
  436. database_string = ciface.get_database_name()
  437. # Set the mapset check and the timestamp write
  438. if "TGIS_DISABLE_MAPSET_CHECK" in grassenv:
  439. if gscript.encode(grassenv["TGIS_DISABLE_MAPSET_CHECK"]) == "True" or \
  440. gscript.encode(grassenv["TGIS_DISABLE_MAPSET_CHECK"]) == "1":
  441. enable_mapset_check = False
  442. msgr.warning("TGIS_DISABLE_MAPSET_CHECK is True")
  443. if "TGIS_DISABLE_TIMESTAMP_WRITE" in grassenv:
  444. if gscript.encode(grassenv["TGIS_DISABLE_TIMESTAMP_WRITE"]) == "True" or \
  445. gscript.encode(grassenv["TGIS_DISABLE_TIMESTAMP_WRITE"]) == "1":
  446. enable_timestamp_write = False
  447. msgr.warning("TGIS_DISABLE_TIMESTAMP_WRITE is True")
  448. if driver_string is not None and driver_string != "":
  449. driver_string = decode(driver_string)
  450. if driver_string == "sqlite":
  451. tgis_backend = driver_string
  452. try:
  453. import sqlite3
  454. except ImportError:
  455. msgr.error("Unable to locate the sqlite SQL Python interface"
  456. " module sqlite3.")
  457. raise
  458. dbmi = sqlite3
  459. elif driver_string == "pg":
  460. tgis_backend = driver_string
  461. try:
  462. import psycopg2
  463. except ImportError:
  464. msgr.error("Unable to locate the Postgresql SQL Python "
  465. "interface module psycopg2.")
  466. raise
  467. dbmi = psycopg2
  468. else:
  469. msgr.fatal(_("Unable to initialize the temporal DBMI interface. "
  470. "Please use t.connect to specify the driver and the"
  471. " database string"))
  472. else:
  473. # Set the default sqlite3 connection in case nothing was defined
  474. gscript.run_command("t.connect", flags="d")
  475. driver_string = ciface.get_driver_name()
  476. database_string = ciface.get_database_name()
  477. tgis_backend = driver_string
  478. try:
  479. import sqlite3
  480. except ImportError:
  481. msgr.error("Unable to locate the sqlite SQL Python interface"
  482. " module sqlite3.")
  483. raise
  484. dbmi = sqlite3
  485. tgis_database_string = database_string
  486. # Set the parameter style
  487. tgis_dbmi_paramstyle = dbmi.paramstyle
  488. # We do not know if the database already exists
  489. db_exists = False
  490. dbif = SQLDatabaseInterfaceConnection()
  491. # Check if the database already exists
  492. if tgis_backend == "sqlite":
  493. # Check path of the sqlite database
  494. if os.path.exists(tgis_database_string):
  495. dbif.connect()
  496. # Check for raster_base table
  497. dbif.execute("SELECT name FROM sqlite_master WHERE type='table' "
  498. "AND name='raster_base';")
  499. name = dbif.fetchone()
  500. if name and name[0] == "raster_base":
  501. db_exists = True
  502. dbif.close()
  503. elif tgis_backend == "pg":
  504. # Connect to database
  505. dbif.connect()
  506. # Check for raster_base table
  507. dbif.execute("SELECT EXISTS(SELECT * FROM information_schema.tables "
  508. "WHERE table_name=%s)", ('raster_base',))
  509. if dbif.fetchone()[0]:
  510. db_exists = True
  511. backup_howto = _("The format of your actual temporal database is not " \
  512. "supported any more.\n" \
  513. "Please create a backup of your temporal database "\
  514. "to avoid lossing data.\nSOLUTION: ")
  515. if tgis_db_version > 2:
  516. backup_howto += _("Run t.upgrade command installed from " \
  517. "GRASS Addons in order to upgrade your temporal database.\n")
  518. else:
  519. backup_howto += _("You need to export it by " \
  520. "restoring the GRASS GIS version used for creating this DB."\
  521. "Notes: Use t.rast.export and t.vect.export "\
  522. "to make a backup of your" \
  523. " existing space time datasets. To save the timestamps of" \
  524. " your existing maps and space time datasets, use " \
  525. "t.rast.list, t.vect.list and t.rast3d.list. "\
  526. "You can register the existing time stamped maps easily if"\
  527. " you export columns=id,start_time,end_time into text "\
  528. "files and use t.register to register them again in new" \
  529. " created space time datasets (t.create). After the backup"\
  530. " remove the existing temporal database, a new one will be"\
  531. " created automatically.\n")
  532. if db_exists is True:
  533. dbif.close()
  534. if skip_db_version_check is True:
  535. return
  536. # Check the version of the temporal database
  537. dbif.connect()
  538. metadata = get_tgis_metadata(dbif)
  539. dbif.close()
  540. if metadata is None:
  541. msgr.fatal(_("Unable to receive temporal database metadata.\n"
  542. "Current temporal database info:%(info)s") % (
  543. {"info": get_database_info_string()}))
  544. for entry in metadata:
  545. if "tgis_version" in entry and entry[1] != str(get_tgis_version()):
  546. msgr.fatal(_("Unsupported temporal database: version mismatch."
  547. "\n %(backup)s Supported temporal API version is:"
  548. " %(api)i.\nPlease update your GRASS GIS "
  549. "installation.\nCurrent temporal database info:"
  550. "%(info)s") % ({"backup": backup_howto,
  551. "api": get_tgis_version(),
  552. "info": get_database_info_string()}))
  553. if "tgis_db_version" in entry and entry[1] != str(get_tgis_db_version()):
  554. msgr.fatal(_("Unsupported temporal database: version mismatch."
  555. "\n %(backup)sSupported temporal database version"
  556. " is: %(tdb)i\nCurrent temporal database info:"
  557. "%(info)s") % ({"backup": backup_howto,
  558. "tdb": get_tgis_version(),
  559. "info": get_database_info_string()}))
  560. return
  561. create_temporal_database(dbif)
  562. ###############################################################################
  563. def get_database_info_string():
  564. dbif = SQLDatabaseInterfaceConnection()
  565. info = "\nDBMI interface:..... " + str(dbif.get_dbmi().__name__)
  566. info += "\nTemporal database:.. " + str(get_tgis_database_string())
  567. return info
  568. ###############################################################################
  569. def _create_temporal_database_views(dbif):
  570. """Create all views in the temporal database (internal use only)
  571. Used by create_temporal_database() and upgrade_temporal_database().
  572. :param dbif: The database interface to be used
  573. """
  574. template_path = get_sql_template_path()
  575. for sql_filename in ("raster_views",
  576. "raster3d_views",
  577. "vector_views",
  578. "strds_views",
  579. "str3ds_views",
  580. "stvds_views"):
  581. sql_filepath = open(os.path.join(template_path,
  582. sql_filename + '.sql'),
  583. 'r').read()
  584. dbif.execute_transaction(sql_filepath)
  585. def create_temporal_database(dbif):
  586. """This function will create the temporal database
  587. It will create all tables and triggers that are needed to run
  588. the temporal GIS
  589. :param dbif: The database interface to be used
  590. """
  591. global tgis_backend
  592. global tgis_version
  593. global tgis_db_version
  594. global tgis_database_string
  595. template_path = get_sql_template_path()
  596. msgr = get_tgis_message_interface()
  597. # Read all SQL scripts and templates
  598. map_tables_template_sql = open(os.path.join(
  599. template_path, "map_tables_template.sql"), 'r').read()
  600. raster_metadata_sql = open(os.path.join(
  601. get_sql_template_path(), "raster_metadata_table.sql"), 'r').read()
  602. raster3d_metadata_sql = open(os.path.join(template_path,
  603. "raster3d_metadata_table.sql"),
  604. 'r').read()
  605. vector_metadata_sql = open(os.path.join(template_path,
  606. "vector_metadata_table.sql"),
  607. 'r').read()
  608. stds_tables_template_sql = open(os.path.join(template_path,
  609. "stds_tables_template.sql"),
  610. 'r').read()
  611. strds_metadata_sql = open(os.path.join(template_path,
  612. "strds_metadata_table.sql"),
  613. 'r').read()
  614. str3ds_metadata_sql = open(os.path.join(template_path,
  615. "str3ds_metadata_table.sql"),
  616. 'r').read()
  617. stvds_metadata_sql = open(os.path.join(template_path,
  618. "stvds_metadata_table.sql"),
  619. 'r').read()
  620. # Create the raster, raster3d and vector tables SQL statements
  621. raster_tables_sql = map_tables_template_sql.replace("GRASS_MAP", "raster")
  622. vector_tables_sql = map_tables_template_sql.replace("GRASS_MAP", "vector")
  623. raster3d_tables_sql = map_tables_template_sql.replace(
  624. "GRASS_MAP", "raster3d")
  625. # Create the space-time raster, raster3d and vector dataset tables
  626. # SQL statements
  627. strds_tables_sql = stds_tables_template_sql.replace("STDS", "strds")
  628. stvds_tables_sql = stds_tables_template_sql.replace("STDS", "stvds")
  629. str3ds_tables_sql = stds_tables_template_sql.replace("STDS", "str3ds")
  630. msgr.message(_("Creating temporal database: %s" % (str(tgis_database_string))))
  631. if tgis_backend == "sqlite":
  632. # We need to create the sqlite3 database path if it does not exist
  633. tgis_dir = os.path.dirname(tgis_database_string)
  634. if not os.path.exists(tgis_dir):
  635. try:
  636. os.makedirs(tgis_dir)
  637. except Exception as e:
  638. msgr.fatal(_("Unable to create SQLite temporal database\n"
  639. "Exception: %s\nPlease use t.connect to set a "
  640. "read- and writable temporal database path" % (e)))
  641. # Set up the trigger that takes care of
  642. # the correct deletion of entries across the different tables
  643. delete_trigger_sql = open(os.path.join(template_path,
  644. "sqlite3_delete_trigger.sql"),
  645. 'r').read()
  646. indexes_sql = open(os.path.join(template_path, "sqlite3_indexes.sql"),
  647. 'r').read()
  648. else:
  649. # Set up the trigger that takes care of
  650. # the correct deletion of entries across the different tables
  651. delete_trigger_sql = open(os.path.join(template_path,
  652. "postgresql_delete_trigger.sql"),
  653. 'r').read()
  654. indexes_sql = open(os.path.join(template_path,
  655. "postgresql_indexes.sql"), 'r').read()
  656. # Connect now to the database
  657. if dbif.connected is not True:
  658. dbif.connect()
  659. # Execute the SQL statements
  660. # Create the global tables for the native grass datatypes
  661. dbif.execute_transaction(raster_tables_sql)
  662. dbif.execute_transaction(raster_metadata_sql)
  663. dbif.execute_transaction(vector_tables_sql)
  664. dbif.execute_transaction(vector_metadata_sql)
  665. dbif.execute_transaction(raster3d_tables_sql)
  666. dbif.execute_transaction(raster3d_metadata_sql)
  667. # Create the tables for the new space-time datatypes
  668. dbif.execute_transaction(strds_tables_sql)
  669. dbif.execute_transaction(strds_metadata_sql)
  670. dbif.execute_transaction(stvds_tables_sql)
  671. dbif.execute_transaction(stvds_metadata_sql)
  672. dbif.execute_transaction(str3ds_tables_sql)
  673. dbif.execute_transaction(str3ds_metadata_sql)
  674. # Create views
  675. _create_temporal_database_views(dbif)
  676. # The delete trigger
  677. dbif.execute_transaction(delete_trigger_sql)
  678. # The indexes
  679. dbif.execute_transaction(indexes_sql)
  680. # Create the tgis metadata table to store the database
  681. # initial configuration
  682. # The metadata table content
  683. metadata = {}
  684. metadata["tgis_version"] = tgis_version
  685. metadata["tgis_db_version"] = tgis_db_version
  686. metadata["creation_time"] = datetime.today()
  687. _create_tgis_metadata_table(metadata, dbif)
  688. dbif.close()
  689. ###############################################################################
  690. def upgrade_temporal_database(dbif):
  691. """This function will upgrade the temporal database if needed.
  692. It will update all tables and triggers that are requested by
  693. currently supported TGIS DB version.
  694. :param dbif: The database interface to be used
  695. """
  696. global tgis_database_string
  697. global tgis_db_version
  698. metadata = get_tgis_metadata(dbif)
  699. msgr = get_tgis_message_interface()
  700. if metadata is None:
  701. msgr.fatal(_("Unable to receive temporal database metadata.\n"
  702. "Current temporal database info:%(info)s") % (
  703. {"info": get_database_info_string()}))
  704. upgrade_db_from = None
  705. for entry in metadata:
  706. if "tgis_db_version" in entry and entry[1] != str(tgis_db_version):
  707. upgrade_db_from = entry[1]
  708. break
  709. if upgrade_db_from is None:
  710. msgr.message(_("Temporal database is up-to-date. Operation canceled"))
  711. dbif.close()
  712. return
  713. template_path = get_sql_template_path()
  714. try:
  715. upgrade_db_sql = open(os.path.join(
  716. template_path,
  717. "upgrade_db_%s_to_%s.sql" % (upgrade_db_from, tgis_db_version)),
  718. 'r').read()
  719. except FileNotFoundError:
  720. msgr.fatal(_("Unsupported TGIS DB upgrade scenario: from version %s to %s") % \
  721. (upgrade_db_from, tgis_db_version))
  722. drop_views_sql = open(
  723. os.path.join(template_path, "drop_views.sql"),
  724. 'r').read()
  725. msgr.message(
  726. _("Upgrading temporal database <%s> from version %s to %s...") % \
  727. (tgis_database_string, upgrade_db_from, tgis_db_version))
  728. # Drop views
  729. dbif.execute_transaction(drop_views_sql)
  730. # Perform upgrade
  731. dbif.execute_transaction(upgrade_db_sql)
  732. # Recreate views
  733. _create_temporal_database_views(dbif)
  734. dbif.close()
  735. ###############################################################################
  736. def _create_tgis_metadata_table(content, dbif=None):
  737. """!Create the temporal gis metadata table which stores all metadata
  738. information about the temporal database.
  739. :param content: The dictionary that stores the key:value metadata
  740. that should be stored in the metadata table
  741. :param dbif: The database interface to be used
  742. """
  743. dbif, connected = init_dbif(dbif)
  744. statement = "CREATE TABLE tgis_metadata (key VARCHAR NOT NULL, value VARCHAR);\n"
  745. dbif.execute_transaction(statement)
  746. for key in content.keys():
  747. statement = "INSERT INTO tgis_metadata (key, value) VALUES " + \
  748. "(\'%s\' , \'%s\');\n" % (str(key), str(content[key]))
  749. dbif.execute_transaction(statement)
  750. if connected:
  751. dbif.close()
  752. ###############################################################################
  753. class SQLDatabaseInterfaceConnection(object):
  754. def __init__(self):
  755. self.tgis_mapsets = get_available_temporal_mapsets()
  756. self.current_mapset = get_current_mapset()
  757. self.connections = {}
  758. self.connected = False
  759. self.unique_connections = {}
  760. for mapset in self.tgis_mapsets.keys():
  761. driver, dbstring = self.tgis_mapsets[mapset]
  762. if dbstring not in self.unique_connections.keys():
  763. self.unique_connections[dbstring] = DBConnection(backend=driver,
  764. dbstring=dbstring)
  765. self.connections[mapset] = self.unique_connections[dbstring]
  766. self.msgr = get_tgis_message_interface()
  767. def get_dbmi(self, mapset=None):
  768. if mapset is None:
  769. mapset = self.current_mapset
  770. mapset = decode(mapset)
  771. return self.connections[mapset].dbmi
  772. def rollback(self, mapset=None):
  773. """
  774. Roll back the last transaction. This must be called
  775. in case a new query should be performed after a db error.
  776. This is only relevant for postgresql database.
  777. """
  778. if mapset is None:
  779. mapset = self.current_mapset
  780. def connect(self):
  781. """Connect to the DBMI to execute SQL statements
  782. Supported backends are sqlite3 and postgresql
  783. """
  784. for mapset in self.tgis_mapsets.keys():
  785. driver, dbstring = self.tgis_mapsets[mapset]
  786. conn = self.connections[mapset]
  787. if conn.is_connected() is False:
  788. conn.connect(dbstring)
  789. self.connected = True
  790. def is_connected(self):
  791. return self.connected
  792. def close(self):
  793. """Close the DBMI connection
  794. There may be several temporal databases in a location, hence
  795. close all temporal databases that have been opened.
  796. """
  797. for key in self.unique_connections.keys():
  798. self.unique_connections[key].close()
  799. self.connected = False
  800. def mogrify_sql_statement(self, content, mapset=None):
  801. """Return the SQL statement and arguments as executable SQL string
  802. :param content: The content as tuple with two entries, the first
  803. entry is the SQL statement with DBMI specific
  804. place holder (?), the second entry is the argument
  805. list that should substitute the place holder.
  806. :param mapset: The mapset of the abstract dataset or temporal
  807. database location, if None the current mapset
  808. will be used
  809. """
  810. if mapset is None:
  811. mapset = self.current_mapset
  812. mapset = decode(mapset)
  813. if mapset not in self.tgis_mapsets.keys():
  814. self.msgr.fatal(_("Unable to mogrify sql statement. " +
  815. self._create_mapset_error_message(mapset)))
  816. return self.connections[mapset].mogrify_sql_statement(content)
  817. def check_table(self, table_name, mapset=None):
  818. """Check if a table exists in the temporal database
  819. :param table_name: The name of the table to be checked for existence
  820. :param mapset: The mapset of the abstract dataset or temporal
  821. database location, if None the current mapset
  822. will be used
  823. :returns: True if the table exists, False otherwise
  824. TODO:
  825. There may be several temporal databases in a location, hence
  826. the mapset is used to query the correct temporal database.
  827. """
  828. if mapset is None:
  829. mapset = self.current_mapset
  830. mapset = decode(mapset)
  831. if mapset not in self.tgis_mapsets.keys():
  832. self.msgr.fatal(_("Unable to check table. " +
  833. self._create_mapset_error_message(mapset)))
  834. return self.connections[mapset].check_table(table_name)
  835. def execute(self, statement, args=None, mapset=None):
  836. """
  837. :param mapset: The mapset of the abstract dataset or temporal
  838. database location, if None the current mapset
  839. will be used
  840. """
  841. if mapset is None:
  842. mapset = self.current_mapset
  843. mapset = decode(mapset)
  844. if mapset not in self.tgis_mapsets.keys():
  845. self.msgr.fatal(_("Unable to execute sql statement. " +
  846. self._create_mapset_error_message(mapset)))
  847. return self.connections[mapset].execute(statement, args)
  848. def fetchone(self, mapset=None):
  849. if mapset is None:
  850. mapset = self.current_mapset
  851. mapset = decode(mapset)
  852. if mapset not in self.tgis_mapsets.keys():
  853. self.msgr.fatal(_("Unable to fetch one. " +
  854. self._create_mapset_error_message(mapset)))
  855. return self.connections[mapset].fetchone()
  856. def fetchall(self, mapset=None):
  857. if mapset is None:
  858. mapset = self.current_mapset
  859. mapset = decode(mapset)
  860. if mapset not in self.tgis_mapsets.keys():
  861. self.msgr.fatal(_("Unable to fetch all. " +
  862. self._create_mapset_error_message(mapset)))
  863. return self.connections[mapset].fetchall()
  864. def execute_transaction(self, statement, mapset=None):
  865. """Execute a transactional SQL statement
  866. The BEGIN and END TRANSACTION statements will be added automatically
  867. to the sql statement
  868. :param statement: The executable SQL statement or SQL script
  869. """
  870. if mapset is None:
  871. mapset = self.current_mapset
  872. mapset = decode(mapset)
  873. if mapset not in self.tgis_mapsets.keys():
  874. self.msgr.fatal(_("Unable to execute transaction. " +
  875. self._create_mapset_error_message(mapset)))
  876. return self.connections[mapset].execute_transaction(statement)
  877. def _create_mapset_error_message(self, mapset):
  878. return("You have no permission to "
  879. "access mapset <%(mapset)s>, or "
  880. "mapset <%(mapset)s> has no temporal database. "
  881. "Accessible mapsets are: <%(mapsets)s>" % \
  882. {"mapset": decode(mapset),
  883. "mapsets":','.join(self.tgis_mapsets.keys())})
  884. ###############################################################################
  885. class DBConnection(object):
  886. """This class represents the database interface connection
  887. and provides access to the chosen backend modules.
  888. The following DBMS are supported:
  889. - sqlite via the sqlite3 standard library
  890. - postgresql via psycopg2
  891. """
  892. def __init__(self, backend=None, dbstring=None):
  893. """ Constructor of a database connection
  894. param backend:The database backend sqlite or pg
  895. param dbstring: The database connection string
  896. """
  897. self.connected = False
  898. if backend is None:
  899. global tgis_backend
  900. if decode(tgis_backend) == "sqlite":
  901. self.dbmi = sqlite3
  902. else:
  903. self.dbmi = psycopg2
  904. else:
  905. if decode(backend) == "sqlite":
  906. self.dbmi = sqlite3
  907. else:
  908. self.dbmi = psycopg2
  909. if dbstring is None:
  910. global tgis_database_string
  911. self.dbstring = tgis_database_string
  912. self.dbstring = dbstring
  913. self.msgr = get_tgis_message_interface()
  914. self.msgr.debug(1, "DBConnection constructor:"\
  915. "\n backend: %s"\
  916. "\n dbstring: %s"%(backend, self.dbstring))
  917. def __del__(self):
  918. if self.connected is True:
  919. self.close()
  920. def is_connected(self):
  921. return self.connected
  922. def rollback(self):
  923. """
  924. Roll back the last transaction. This must be called
  925. in case a new query should be performed after a db error.
  926. This is only relevant for postgresql database.
  927. """
  928. if self.dbmi.__name__ == "psycopg2":
  929. if self.connected:
  930. self.connection.rollback()
  931. def connect(self, dbstring=None):
  932. """Connect to the DBMI to execute SQL statements
  933. Supported backends are sqlite3 and postgresql
  934. param dbstring: The database connection string
  935. """
  936. # Connection in the current mapset
  937. if dbstring is None:
  938. dbstring = self.dbstring
  939. dbstring = decode(dbstring)
  940. try:
  941. if self.dbmi.__name__ == "sqlite3":
  942. self.connection = self.dbmi.connect(dbstring,
  943. detect_types=self.dbmi.PARSE_DECLTYPES | self.dbmi.PARSE_COLNAMES)
  944. self.connection.row_factory = self.dbmi.Row
  945. self.connection.isolation_level = None
  946. self.connection.text_factory = str
  947. self.cursor = self.connection.cursor()
  948. self.cursor.execute("PRAGMA synchronous = OFF")
  949. self.cursor.execute("PRAGMA journal_mode = MEMORY")
  950. elif self.dbmi.__name__ == "psycopg2":
  951. self.connection = self.dbmi.connect(dbstring)
  952. #self.connection.set_isolation_level(dbmi.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
  953. self.cursor = self.connection.cursor(
  954. cursor_factory=self.dbmi.extras.DictCursor)
  955. self.connected = True
  956. except Exception as e:
  957. self.msgr.fatal(_("Unable to connect to %(db)s database: "
  958. "%(string)s\nException: \"%(ex)s\"\nPlease use"
  959. " t.connect to set a read- and writable "
  960. "temporal database backend") % (
  961. {"db": self.dbmi.__name__,
  962. "string": tgis_database_string, "ex": e, }))
  963. def close(self):
  964. """Close the DBMI connection
  965. TODO:
  966. There may be several temporal databases in a location, hence
  967. close all temporal databases that have been opened. Use a dictionary
  968. to manage different connections.
  969. """
  970. self.connection.commit()
  971. self.cursor.close()
  972. self.connected = False
  973. def mogrify_sql_statement(self, content):
  974. """Return the SQL statement and arguments as executable SQL string
  975. TODO:
  976. Use the mapset argument to identify the correct database driver
  977. :param content: The content as tuple with two entries, the first
  978. entry is the SQL statement with DBMI specific
  979. place holder (?), the second entry is the argument
  980. list that should substitute the place holder.
  981. :param mapset: The mapset of the abstract dataset or temporal
  982. database location, if None the current mapset
  983. will be used
  984. Usage:
  985. .. code-block:: python
  986. >>> init()
  987. >>> dbif = SQLDatabaseInterfaceConnection()
  988. >>> dbif.mogrify_sql_statement(["SELECT ctime FROM raster_base WHERE id = ?",
  989. ... ["soil@PERMANENT",]])
  990. "SELECT ctime FROM raster_base WHERE id = 'soil@PERMANENT'"
  991. """
  992. sql = content[0]
  993. args = content[1]
  994. if self.dbmi.__name__ == "psycopg2":
  995. if len(args) == 0:
  996. return sql
  997. else:
  998. if self.connected:
  999. try:
  1000. return self.cursor.mogrify(sql, args)
  1001. except Exception as exc:
  1002. print(sql, args)
  1003. raise exc
  1004. else:
  1005. self.connect()
  1006. statement = self.cursor.mogrify(sql, args)
  1007. self.close()
  1008. return statement
  1009. elif self.dbmi.__name__ == "sqlite3":
  1010. if len(args) == 0:
  1011. return sql
  1012. else:
  1013. # Unfortunately as sqlite does not support
  1014. # the transformation of sql strings and qmarked or
  1015. # named arguments we must make our hands dirty
  1016. # and do it by ourself. :(
  1017. # Doors are open for SQL injection because of the
  1018. # limited python sqlite3 implementation!!!
  1019. pos = 0
  1020. count = 0
  1021. maxcount = 100
  1022. statement = sql
  1023. while count < maxcount:
  1024. pos = statement.find("?", pos + 1)
  1025. if pos == -1:
  1026. break
  1027. if args[count] is None:
  1028. statement = "%sNULL%s" % (statement[0:pos],
  1029. statement[pos + 1:])
  1030. elif isinstance(args[count], (int, long)):
  1031. statement = "%s%d%s" % (statement[0:pos], args[count],
  1032. statement[pos + 1:])
  1033. elif isinstance(args[count], float):
  1034. statement = "%s%f%s" % (statement[0:pos], args[count],
  1035. statement[pos + 1:])
  1036. elif isinstance(args[count], datetime):
  1037. statement = "%s\'%s\'%s" % (statement[0:pos], str(args[count]),
  1038. statement[pos + 1:])
  1039. else:
  1040. # Default is a string, this works for datetime
  1041. # objects too
  1042. statement = "%s\'%s\'%s" % (statement[0:pos],
  1043. str(args[count]),
  1044. statement[pos + 1:])
  1045. count += 1
  1046. return statement
  1047. def check_table(self, table_name):
  1048. """Check if a table exists in the temporal database
  1049. :param table_name: The name of the table to be checked for existence
  1050. :param mapset: The mapset of the abstract dataset or temporal
  1051. database location, if None the current mapset
  1052. will be used
  1053. :returns: True if the table exists, False otherwise
  1054. TODO:
  1055. There may be several temporal databases in a location, hence
  1056. the mapset is used to query the correct temporal database.
  1057. """
  1058. table_exists = False
  1059. connected = False
  1060. if not self.connected:
  1061. self.connect()
  1062. connected = True
  1063. # Check if the database already exists
  1064. if self.dbmi.__name__ == "sqlite3":
  1065. self.cursor.execute("SELECT name FROM sqlite_master WHERE "
  1066. "type='table' AND name='%s';" % table_name)
  1067. name = self.cursor.fetchone()
  1068. if name and name[0] == table_name:
  1069. table_exists = True
  1070. else:
  1071. # Check for raster_base table
  1072. self.cursor.execute("SELECT EXISTS(SELECT * FROM information_schema.tables "
  1073. "WHERE table_name=%s)", ('%s' % table_name,))
  1074. if self.cursor.fetchone()[0]:
  1075. table_exists = True
  1076. if connected:
  1077. self.close()
  1078. return table_exists
  1079. def execute(self, statement, args=None):
  1080. """Execute a SQL statement
  1081. :param statement: The executable SQL statement or SQL script
  1082. """
  1083. connected = False
  1084. if not self.connected:
  1085. self.connect()
  1086. connected = True
  1087. try:
  1088. if args:
  1089. self.cursor.execute(statement, args)
  1090. else:
  1091. self.cursor.execute(statement)
  1092. except:
  1093. if connected:
  1094. self.close()
  1095. self.msgr.error(_("Unable to execute :\n %(sql)s" %
  1096. {"sql": statement}))
  1097. raise
  1098. if connected:
  1099. self.close()
  1100. def fetchone(self):
  1101. if self.connected:
  1102. return self.cursor.fetchone()
  1103. return None
  1104. def fetchall(self):
  1105. if self.connected:
  1106. return self.cursor.fetchall()
  1107. return None
  1108. def execute_transaction(self, statement, mapset=None):
  1109. """Execute a transactional SQL statement
  1110. The BEGIN and END TRANSACTION statements will be added automatically
  1111. to the sql statement
  1112. :param statement: The executable SQL statement or SQL script
  1113. """
  1114. connected = False
  1115. if not self.connected:
  1116. self.connect()
  1117. connected = True
  1118. sql_script = ""
  1119. sql_script += "BEGIN TRANSACTION;\n"
  1120. sql_script += statement
  1121. sql_script += "END TRANSACTION;"
  1122. try:
  1123. if self.dbmi.__name__ == "sqlite3":
  1124. self.cursor.executescript(statement)
  1125. else:
  1126. self.cursor.execute(statement)
  1127. self.connection.commit()
  1128. except:
  1129. if connected:
  1130. self.close()
  1131. self.msgr.error(_("Unable to execute transaction:\n %(sql)s" %
  1132. {"sql": statement}))
  1133. raise
  1134. if connected:
  1135. self.close()
  1136. ###############################################################################
  1137. def init_dbif(dbif):
  1138. """This method checks if the database interface connection exists,
  1139. if not a new one will be created, connected and True will be returned.
  1140. If the database interface exists but is connected, the connection will
  1141. be established.
  1142. :returns: the tuple (dbif, True|False)
  1143. Usage code sample:
  1144. .. code-block:: python
  1145. dbif, connect = tgis.init_dbif(None)
  1146. sql = dbif.mogrify_sql_statement(["SELECT * FROM raster_base WHERE ? = ?"],
  1147. ["id", "soil@PERMANENT"])
  1148. dbif.execute_transaction(sql)
  1149. if connect:
  1150. dbif.close()
  1151. """
  1152. if dbif is None:
  1153. dbif = SQLDatabaseInterfaceConnection()
  1154. dbif.connect()
  1155. return dbif, True
  1156. elif dbif.is_connected() is False:
  1157. dbif.connect()
  1158. return dbif, True
  1159. return dbif, False
  1160. ###############################################################################
  1161. if __name__ == "__main__":
  1162. import doctest
  1163. doctest.testmod()