core.py 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  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. 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 = "Your temporal database format is not supported any more. "\
  457. "Unfortunately you have to restore your previous grass version "\
  458. "to make a backup of your existing temporal database and to avoid the loss of your temporal data. "\
  459. "You can use t.rast.export and t.vect.export to make a backup of your existing space time datasets. "\
  460. "Use t.rast.list, t.vect.list and t.rast3d.list to safe the time "\
  461. "stamps of your existing maps and space time datasets. "\
  462. "You can register the exitsing time stamped maps easily if you write 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. "
  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 receiving 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 installation to the latest svn version.\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(_("Create 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. os.makedirs(tgis_dir)
  558. # Set up the trigger that takes care of
  559. # the correct deletion of entries across the different tables
  560. delete_trigger_sql = open(os.path.join(template_path,
  561. "sqlite3_delete_trigger.sql"),
  562. 'r').read()
  563. indexes_sql = open(os.path.join(template_path, "sqlite3_indexes.sql"), 'r').read()
  564. else:
  565. # Set up the trigger that takes care of
  566. # the correct deletion of entries across the different tables
  567. delete_trigger_sql = open(os.path.join(template_path,
  568. "postgresql_delete_trigger.sql"),
  569. 'r').read()
  570. indexes_sql = open(os.path.join(template_path, "postgresql_indexes.sql"), 'r').read()
  571. # Connect now to the database
  572. if not dbif.connected:
  573. dbif.connect()
  574. # Execute the SQL statements for sqlite
  575. # Create the global tables for the native grass datatypes
  576. dbif.execute_transaction(raster_tables_sql)
  577. dbif.execute_transaction(raster_metadata_sql)
  578. dbif.execute_transaction(raster_views_sql)
  579. dbif.execute_transaction(vector_tables_sql)
  580. dbif.execute_transaction(vector_metadata_sql)
  581. dbif.execute_transaction(vector_views_sql)
  582. dbif.execute_transaction(raster3d_tables_sql)
  583. dbif.execute_transaction(raster3d_metadata_sql)
  584. dbif.execute_transaction(raster3d_views_sql)
  585. # Create the tables for the new space-time datatypes
  586. dbif.execute_transaction(strds_tables_sql)
  587. dbif.execute_transaction(strds_metadata_sql)
  588. dbif.execute_transaction(strds_views_sql)
  589. dbif.execute_transaction(stvds_tables_sql)
  590. dbif.execute_transaction(stvds_metadata_sql)
  591. dbif.execute_transaction(stvds_views_sql)
  592. dbif.execute_transaction(str3ds_tables_sql)
  593. dbif.execute_transaction(str3ds_metadata_sql)
  594. dbif.execute_transaction(str3ds_views_sql)
  595. # The delete trigger
  596. dbif.execute_transaction(delete_trigger_sql)
  597. # The indexes
  598. dbif.execute_transaction(indexes_sql)
  599. # Create the tgis metadata table to store the database
  600. # initial configuration
  601. # The metadata table content
  602. metadata = {}
  603. metadata["tgis_version"] = tgis_version
  604. metadata["tgis_db_version"] = tgis_db_version
  605. metadata["creation_time"] = datetime.today()
  606. _create_tgis_metadata_table(metadata, dbif)
  607. dbif.close()
  608. ###############################################################################
  609. def _create_tgis_metadata_table(content, dbif=None):
  610. """!Create the temporal gis metadata table which stores all metadata
  611. information about the temporal database.
  612. @param content The dictionary that stores the key:value metadata
  613. that should be stored in the metadata table
  614. @param dbif The database interface to be used
  615. """
  616. dbif, connected = init_dbif(dbif)
  617. statement = "CREATE TABLE tgis_metadata (key VARCHAR NOT NULL, value VARCHAR);\n";
  618. dbif.execute_transaction(statement)
  619. for key in content.keys():
  620. statement = "INSERT INTO tgis_metadata (key, value) VALUES " + \
  621. "(\'%s\' , \'%s\');\n"%(str(key), str(content[key]))
  622. dbif.execute_transaction(statement)
  623. if connected:
  624. dbif.close()
  625. ###############################################################################
  626. class SQLDatabaseInterfaceConnection():
  627. """!This class represents the database interface connection
  628. and provides access to the chisen backend modules.
  629. The following DBMS are supported:
  630. - sqlite via the sqlite3 standard library
  631. - postgresql via psycopg2
  632. """
  633. def __init__(self):
  634. self.connected = False
  635. global tgis_backend
  636. if tgis_backend == "sqlite":
  637. self.dbmi = sqlite3
  638. else:
  639. self.dbmi = psycopg2
  640. self.msgr = get_tgis_message_interface()
  641. self.msgr.debug(1, "SQLDatabaseInterfaceConnection constructor")
  642. def __del__(self):
  643. if self.connected is True:
  644. self.close()
  645. def rollback(self):
  646. """
  647. Roll back the last transaction. This must be called
  648. in case a new query should be performed after a db error.
  649. This is only relevant for postgresql database.
  650. """
  651. if self.dbmi.__name__ == "psycopg2":
  652. if self.connected:
  653. self.connection.rollback()
  654. def connect(self):
  655. """!Connect to the DBMI to execute SQL statements
  656. Supported backends are sqlite3 and postgresql
  657. """
  658. global tgis_database_string
  659. if self.dbmi.__name__ == "sqlite3":
  660. self.connection = self.dbmi.connect(tgis_database_string,
  661. detect_types = self.dbmi.PARSE_DECLTYPES | self.dbmi.PARSE_COLNAMES)
  662. self.connection.row_factory = self.dbmi.Row
  663. self.connection.isolation_level = None
  664. self.cursor = self.connection.cursor()
  665. self.cursor.execute("PRAGMA synchronous = OFF")
  666. self.cursor.execute("PRAGMA journal_mode = MEMORY")
  667. elif self.dbmi.__name__ == "psycopg2":
  668. self.connection = self.dbmi.connect(tgis_database_string)
  669. #self.connection.set_isolation_level(dbmi.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
  670. self.cursor = self.connection.cursor(
  671. cursor_factory = self.dbmi.extras.DictCursor)
  672. self.connected = True
  673. def close(self):
  674. """!Close the DBMI connection"""
  675. self.connection.commit()
  676. self.cursor.close()
  677. self.connected = False
  678. def mogrify_sql_statement(self, content):
  679. """!Return the SQL statement and arguments as executable SQL string
  680. @param content The content as tuple with two entries, the first
  681. entry is the SQL statement with DBMI specific
  682. place holder (?), the second entry is the argument
  683. list that should substitue the place holder.
  684. Usage:
  685. @code
  686. >>> init()
  687. >>> dbif = SQLDatabaseInterfaceConnection()
  688. >>> dbif.mogrify_sql_statement(["SELECT ctime FROM raster_base WHERE id = ?",
  689. ... ["soil@PERMANENT",]])
  690. "SELECT ctime FROM raster_base WHERE id = 'soil@PERMANENT'"
  691. @endcode
  692. """
  693. sql = content[0]
  694. args = content[1]
  695. if self.dbmi.__name__ == "psycopg2":
  696. if len(args) == 0:
  697. return sql
  698. else:
  699. if self.connected:
  700. try:
  701. return self.cursor.mogrify(sql, args)
  702. except:
  703. print sql, args
  704. raise
  705. else:
  706. self.connect()
  707. statement = self.cursor.mogrify(sql, args)
  708. self.close()
  709. return statement
  710. elif self.dbmi.__name__ == "sqlite3":
  711. if len(args) == 0:
  712. return sql
  713. else:
  714. # Unfortunately as sqlite does not support
  715. # the transformation of sql strings and qmarked or
  716. # named arguments we must make our hands dirty
  717. # and do it by ourself. :(
  718. # Doors are open for SQL injection because of the
  719. # limited python sqlite3 implementation!!!
  720. pos = 0
  721. count = 0
  722. maxcount = 100
  723. statement = sql
  724. while count < maxcount:
  725. pos = statement.find("?", pos + 1)
  726. if pos == -1:
  727. break
  728. if args[count] is None:
  729. statement = "%sNULL%s" % (statement[0:pos],
  730. statement[pos + 1:])
  731. elif isinstance(args[count], (int, long)):
  732. statement = "%s%d%s" % (statement[0:pos], args[count],
  733. statement[pos + 1:])
  734. elif isinstance(args[count], float):
  735. statement = "%s%f%s" % (statement[0:pos], args[count],
  736. statement[pos + 1:])
  737. else:
  738. # Default is a string, this works for datetime
  739. # objects too
  740. statement = "%s\'%s\'%s" % (statement[0:pos],
  741. str(args[count]),
  742. statement[pos + 1:])
  743. count += 1
  744. return statement
  745. def check_table(self, table_name):
  746. """!Check if a table exists in the temporal database
  747. @param table_name The name of the table to be checked for existance
  748. @return True if the table exists, False otherwise
  749. """
  750. table_exists = False
  751. connected = False
  752. if not self.connected:
  753. self.connect()
  754. connected = True
  755. # Check if the database already exists
  756. if self.dbmi.__name__ == "sqlite3":
  757. self.cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='%s';"%table_name)
  758. name = self.cursor.fetchone()
  759. if name and name[0] == table_name:
  760. table_exists = True
  761. else:
  762. # Check for raster_base table
  763. self.cursor.execute("SELECT EXISTS(SELECT * FROM information_schema.tables "
  764. "WHERE table_name=%s)", ('%s'%table_name,))
  765. if self.cursor.fetchone()[0]:
  766. table_exists = True
  767. if connected:
  768. self.close()
  769. return table_exists
  770. def execute_transaction(self, statement):
  771. """!Execute a transactional SQL statement
  772. The BEGIN and END TRANSACTION statements will be added automatically
  773. to the sql statement
  774. @param statement The executable SQL statement or SQL script
  775. """
  776. connected = False
  777. if not self.connected:
  778. self.connect()
  779. connected = True
  780. sql_script = ""
  781. sql_script += "BEGIN TRANSACTION;\n"
  782. sql_script += statement
  783. sql_script += "END TRANSACTION;"
  784. try:
  785. if self.dbmi.__name__ == "sqlite3":
  786. self.cursor.executescript(statement)
  787. else:
  788. self.cursor.execute(statement)
  789. self.connection.commit()
  790. except:
  791. if connected:
  792. self.close()
  793. self.msgr.error(_("Unable to execute transaction:\n %(sql)s" % {"sql":statement}))
  794. raise
  795. if connected:
  796. self.close()
  797. ###############################################################################
  798. def init_dbif(dbif):
  799. """!This method checks if the database interface connection exists,
  800. if not a new one will be created, connected and True will be returned.
  801. If the database interface exists but is connected, the connection will be established.
  802. @return the tuple (dbif, True|False)
  803. Usage code sample:
  804. @code
  805. dbif, connect = tgis.init_dbif(None)
  806. sql = dbif.mogrify_sql_statement(["SELECT * FROM raster_base WHERE ? = ?"],
  807. ["id", "soil@PERMANENT"])
  808. dbif.execute_transaction(sql)
  809. if connect:
  810. dbif.close()
  811. @endcode
  812. """
  813. if dbif is None:
  814. dbif = SQLDatabaseInterfaceConnection()
  815. dbif.connect()
  816. return dbif, True
  817. elif dbif.connected is False:
  818. dbif.connect()
  819. return dbif, True
  820. return dbif, False
  821. ###############################################################################
  822. if __name__ == "__main__":
  823. import doctest
  824. doctest.testmod()