core.py 50 KB

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