core.py 39 KB

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