core.py 50 KB

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