core.py 50 KB

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