core.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  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=3
  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.Messenger(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 behaviour 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():
  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. """
  345. # We need to set the correct database backend and several global variables
  346. # from the GRASS mapset specific environment variables of g.gisenv and t.connect
  347. global tgis_backend
  348. global tgis_database
  349. global tgis_database_string
  350. global tgis_dbmi_paramstyle
  351. global raise_on_error
  352. global enable_mapset_check
  353. global enable_timestamp_write
  354. global current_mapset
  355. global current_location
  356. global current_gisdbase
  357. # We must run t.connect at first to create the temporal database and to
  358. # get the environmental variables
  359. core.run_command("t.connect", flags="c")
  360. kv = core.parse_command("t.connect", flags="pg")
  361. grassenv = core.gisenv()
  362. raise_on_error = False
  363. # Set the global variable for faster access
  364. current_mapset = grassenv["MAPSET"]
  365. current_location = grassenv["LOCATION_NAME"]
  366. current_gisdbase = grassenv["GISDBASE"]
  367. # Check environment variable GRASS_TGIS_RAISE_ON_ERROR
  368. if os.getenv("GRASS_TGIS_RAISE_ON_ERROR") is "True" or os.getenv("GRASS_TGIS_RAISE_ON_ERROR") is "1":
  369. raise_on_error = True
  370. # Check if the script library raises on error,
  371. # if so we do the same
  372. if core.get_raise_on_error() is True:
  373. raise_on_error = True
  374. # Start the GRASS message interface server
  375. _init_tgis_message_interface(raise_on_error)
  376. # Start the C-library interface server
  377. _init_tgis_c_library_interface()
  378. msgr = get_tgis_message_interface()
  379. msgr.debug(1, "Inititate the temporal database")
  380. # Set the mapset check and the timestamp write
  381. if grassenv.has_key("TGIS_DISABLE_MAPSET_CHECK"):
  382. if grassenv["TGIS_DISABLE_MAPSET_CHECK"] == "True" or grassenv["TGIS_DISABLE_MAPSET_CHECK"] == "1":
  383. enable_mapset_check = False
  384. msgr.warning("TGIS_DISABLE_MAPSET_CHECK is True")
  385. if grassenv.has_key("TGIS_DISABLE_TIMESTAMP_WRITE"):
  386. if grassenv["TGIS_DISABLE_TIMESTAMP_WRITE"] == "True" or grassenv["TGIS_DISABLE_TIMESTAMP_WRITE"] == "1":
  387. enable_timestamp_write = False
  388. msgr.warning("TGIS_DISABLE_TIMESTAMP_WRITE is True")
  389. if "driver" in kv:
  390. if kv["driver"] == "sqlite":
  391. tgis_backend = kv["driver"]
  392. try:
  393. import sqlite3
  394. except ImportError:
  395. msgr.error("Unable to locate the sqlite SQL Python interface module sqlite3.")
  396. raise
  397. dbmi = sqlite3
  398. elif kv["driver"] == "pg":
  399. tgis_backend = kv["driver"]
  400. try:
  401. import psycopg2
  402. except ImportError:
  403. msgr.error("Unable to locate the Postgresql SQL Python interface module psycopg2.")
  404. raise
  405. dbmi = psycopg2
  406. else:
  407. msgr.fatal(_("Unable to initialize the temporal DBMI interface. Use "
  408. "t.connect to specify the driver and the database string"))
  409. dbmi = sqlite3
  410. else:
  411. # Set the default sqlite3 connection in case nothing was defined
  412. core.run_command("t.connect", flags="d")
  413. kv = core.parse_command("t.connect", flags="pg")
  414. tgis_backend = kv["driver"]
  415. # Database string from t.connect -pg
  416. tgis_database = kv["database"]
  417. # Set the parameter style
  418. tgis_dbmi_paramstyle = dbmi.paramstyle
  419. # Create the temporal database string
  420. if tgis_backend == "sqlite":
  421. # We substitute GRASS variables if they are located in the database string
  422. # This behavior is in conjunction with db.connect
  423. tgis_database_string = tgis_database
  424. tgis_database_string = tgis_database_string.replace("$GISDBASE", current_gisdbase)
  425. tgis_database_string = tgis_database_string.replace("$LOCATION_NAME", current_location)
  426. tgis_database_string = tgis_database_string.replace("$MAPSET", current_mapset)
  427. elif tgis_backend == "pg":
  428. tgis_database_string = tgis_database
  429. # We do not know if the database already exists
  430. db_exists = False
  431. dbif = SQLDatabaseInterfaceConnection()
  432. # Check if the database already exists
  433. if tgis_backend == "sqlite":
  434. # Check path of the sqlite database
  435. if os.path.exists(tgis_database_string):
  436. dbif.connect()
  437. # Check for raster_base table
  438. dbif.cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='raster_base';")
  439. name = dbif.cursor.fetchone()
  440. if name and name[0] == "raster_base":
  441. db_exists = True
  442. dbif.close()
  443. elif tgis_backend == "pg":
  444. # Connect to database
  445. dbif.connect()
  446. # Check for raster_base table
  447. dbif.cursor.execute("SELECT EXISTS(SELECT * FROM information_schema.tables "
  448. "WHERE table_name=%s)", ('raster_base',))
  449. if dbif.cursor.fetchone()[0]:
  450. db_exists = True
  451. if db_exists == True:
  452. # Check the version of the temporal database
  453. dbif.close()
  454. dbif.connect()
  455. metadata = get_tgis_metadata(dbif)
  456. dbif.close()
  457. if metadata is None:
  458. msgr.fatal(_("Unable to receiving temporal database metadata.\n"
  459. "Your temporal database is not supported.\n"
  460. "Please remove your temporal database. A new one will be cerated automatically.\n"
  461. "Current temporal database info:%(info)s")%({"info":get_database_info_string()}))
  462. for entry in metadata:
  463. if "tgis_version" in entry and entry[1] != str(get_tgis_version()):
  464. msgr.fatal(_("Unsupported temporal database. Version mismatch.\n"
  465. "Supported temporal API version is: %(api)i.\n"
  466. "Please update your GRASS installation to the latest svn version.\n"
  467. "Current temporal database info:%(info)s")%({"api":get_tgis_version(),
  468. "info":get_database_info_string()}))
  469. if "tgis_db_version" in entry and entry[1] != str(get_tgis_db_version()):
  470. msgr.fatal(_("Unsupported temporal database. Version mismatch.\n"
  471. "Supported temporal database version is: %(tdb)i\n"
  472. "Please remove your old temporal database. \n"
  473. "A new one will be created automatically.\n"
  474. "Current temporal database info:%(info)s")%({"tdb":get_tgis_version(),
  475. "info":get_database_info_string()}))
  476. return
  477. create_temporal_database(dbif)
  478. ###############################################################################
  479. def get_database_info_string():
  480. dbif = SQLDatabaseInterfaceConnection()
  481. info = "\nDBMI interface:..... " + str(dbif.dbmi.__name__)
  482. info += "\nTemporal database:.. " + str( get_tgis_database_string())
  483. return info
  484. ###############################################################################
  485. def create_temporal_database(dbif):
  486. """!This function will create the temporal database
  487. It will create all tables and triggers that are needed to run
  488. the temporal GIS
  489. @param dbif The database interface to be used
  490. """
  491. global tgis_backend
  492. global tgis_version
  493. global tgis_db_version
  494. global tgis_database_string
  495. template_path = get_sql_template_path()
  496. msgr = get_tgis_message_interface()
  497. # Read all SQL scripts and templates
  498. map_tables_template_sql = open(os.path.join(
  499. template_path, "map_tables_template.sql"), 'r').read()
  500. raster_metadata_sql = open(os.path.join(
  501. get_sql_template_path(), "raster_metadata_table.sql"), 'r').read()
  502. raster3d_metadata_sql = open(os.path.join(template_path,
  503. "raster3d_metadata_table.sql"),
  504. 'r').read()
  505. vector_metadata_sql = open(os.path.join(template_path,
  506. "vector_metadata_table.sql"),
  507. 'r').read()
  508. raster_views_sql = open(os.path.join(template_path, "raster_views.sql"),
  509. 'r').read()
  510. raster3d_views_sql = open(os.path.join(template_path,
  511. "raster3d_views.sql"), 'r').read()
  512. vector_views_sql = open(os.path.join(template_path, "vector_views.sql"),
  513. 'r').read()
  514. stds_tables_template_sql = open(os.path.join(template_path,
  515. "stds_tables_template.sql"),
  516. 'r').read()
  517. strds_metadata_sql = open(os.path.join(template_path,
  518. "strds_metadata_table.sql"),
  519. 'r').read()
  520. str3ds_metadata_sql = open(os.path.join(template_path,
  521. "str3ds_metadata_table.sql"),
  522. 'r').read()
  523. stvds_metadata_sql = open(os.path.join(template_path,
  524. "stvds_metadata_table.sql"),
  525. 'r').read()
  526. strds_views_sql = open(os.path.join(template_path, "strds_views.sql"),
  527. 'r').read()
  528. str3ds_views_sql = open(os.path.join(template_path, "str3ds_views.sql"),
  529. 'r').read()
  530. stvds_views_sql = open(os.path.join(template_path, "stvds_views.sql"),
  531. 'r').read()
  532. # Create the raster, raster3d and vector tables SQL statements
  533. raster_tables_sql = map_tables_template_sql.replace("GRASS_MAP", "raster")
  534. vector_tables_sql = map_tables_template_sql.replace("GRASS_MAP", "vector")
  535. raster3d_tables_sql = map_tables_template_sql.replace(
  536. "GRASS_MAP", "raster3d")
  537. # Create the space-time raster, raster3d and vector dataset tables
  538. # SQL statements
  539. strds_tables_sql = stds_tables_template_sql.replace("STDS", "strds")
  540. stvds_tables_sql = stds_tables_template_sql.replace("STDS", "stvds")
  541. str3ds_tables_sql = stds_tables_template_sql.replace("STDS", "str3ds")
  542. msgr.message(_("Create temporal database: %s" % (tgis_database_string)))
  543. if tgis_backend == "sqlite":
  544. # We need to create the sqlite3 database path if it does not exists
  545. tgis_dir = os.path.dirname(tgis_database_string)
  546. if not os.path.exists(tgis_dir):
  547. os.makedirs(tgis_dir)
  548. # Set up the trigger that takes care of
  549. # the correct deletion of entries across the different tables
  550. delete_trigger_sql = open(os.path.join(template_path,
  551. "sqlite3_delete_trigger.sql"),
  552. 'r').read()
  553. indexes_sql = open(os.path.join(template_path, "sqlite3_indexes.sql"), 'r').read()
  554. else:
  555. # Set up the trigger that takes care of
  556. # the correct deletion of entries across the different tables
  557. delete_trigger_sql = open(os.path.join(template_path,
  558. "postgresql_delete_trigger.sql"),
  559. 'r').read()
  560. indexes_sql = open(os.path.join(template_path, "postgresql_indexes.sql"), 'r').read()
  561. # Connect now to the database
  562. if not dbif.connected:
  563. dbif.connect()
  564. # Execute the SQL statements for sqlite
  565. # Create the global tables for the native grass datatypes
  566. dbif.execute_transaction(raster_tables_sql)
  567. dbif.execute_transaction(raster_metadata_sql)
  568. dbif.execute_transaction(raster_views_sql)
  569. dbif.execute_transaction(vector_tables_sql)
  570. dbif.execute_transaction(vector_metadata_sql)
  571. dbif.execute_transaction(vector_views_sql)
  572. dbif.execute_transaction(raster3d_tables_sql)
  573. dbif.execute_transaction(raster3d_metadata_sql)
  574. dbif.execute_transaction(raster3d_views_sql)
  575. # Create the tables for the new space-time datatypes
  576. dbif.execute_transaction(strds_tables_sql)
  577. dbif.execute_transaction(strds_metadata_sql)
  578. dbif.execute_transaction(strds_views_sql)
  579. dbif.execute_transaction(stvds_tables_sql)
  580. dbif.execute_transaction(stvds_metadata_sql)
  581. dbif.execute_transaction(stvds_views_sql)
  582. dbif.execute_transaction(str3ds_tables_sql)
  583. dbif.execute_transaction(str3ds_metadata_sql)
  584. dbif.execute_transaction(str3ds_views_sql)
  585. # The delete trigger
  586. dbif.execute_transaction(delete_trigger_sql)
  587. # The indexes
  588. dbif.execute_transaction(indexes_sql)
  589. # Create the tgis metadata table to store the database
  590. # initial configuration
  591. # The metadata table content
  592. metadata = {}
  593. metadata["tgis_version"] = tgis_version
  594. metadata["tgis_db_version"] = tgis_db_version
  595. metadata["creation_time"] = datetime.today()
  596. _create_tgis_metadata_table(metadata, dbif)
  597. dbif.close()
  598. ###############################################################################
  599. def _create_tgis_metadata_table(content, dbif=None):
  600. """!Create the temporal gis metadata table which stores all metadata
  601. information about the temporal database.
  602. @param content The dictionary that stores the key:value metadata
  603. that should be stored in the metadata table
  604. @param dbif The database interface to be used
  605. """
  606. dbif, connected = init_dbif(dbif)
  607. statement = "CREATE TABLE tgis_metadata (key VARCHAR NOT NULL, value VARCHAR);\n";
  608. dbif.execute_transaction(statement)
  609. for key in content.keys():
  610. statement = "INSERT INTO tgis_metadata (key, value) VALUES " + \
  611. "(\'%s\' , \'%s\');\n"%(str(key), str(content[key]))
  612. dbif.execute_transaction(statement)
  613. if connected:
  614. dbif.close()
  615. ###############################################################################
  616. class SQLDatabaseInterfaceConnection():
  617. """!This class represents the database interface connection
  618. and provides access to the chisen backend modules.
  619. The following DBMS are supported:
  620. - sqlite via the sqlite3 standard library
  621. - postgresql via psycopg2
  622. """
  623. def __init__(self):
  624. self.connected = False
  625. global tgis_backend
  626. if tgis_backend == "sqlite":
  627. self.dbmi = sqlite3
  628. else:
  629. self.dbmi = psycopg2
  630. self.msgr = get_tgis_message_interface()
  631. self.msgr.debug(1, "SQLDatabaseInterfaceConnection constructor")
  632. def __del__(self):
  633. if self.connected is True:
  634. self.close()
  635. def rollback(self):
  636. """
  637. Roll back the last transaction. This must be called
  638. in case a new query should be performed after a db error.
  639. This is only relevant for postgresql database.
  640. """
  641. if self.dbmi.__name__ == "psycopg2":
  642. if self.connected:
  643. self.connection.rollback()
  644. def connect(self):
  645. """!Connect to the DBMI to execute SQL statements
  646. Supported backends are sqlite3 and postgresql
  647. """
  648. global tgis_database_string
  649. if self.dbmi.__name__ == "sqlite3":
  650. self.connection = self.dbmi.connect(tgis_database_string,
  651. detect_types = self.dbmi.PARSE_DECLTYPES | self.dbmi.PARSE_COLNAMES)
  652. self.connection.row_factory = self.dbmi.Row
  653. self.connection.isolation_level = None
  654. self.cursor = self.connection.cursor()
  655. self.cursor.execute("PRAGMA synchronous = OFF")
  656. self.cursor.execute("PRAGMA journal_mode = MEMORY")
  657. elif self.dbmi.__name__ == "psycopg2":
  658. self.connection = self.dbmi.connect(tgis_database_string)
  659. #self.connection.set_isolation_level(dbmi.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
  660. self.cursor = self.connection.cursor(
  661. cursor_factory = self.dbmi.extras.DictCursor)
  662. self.connected = True
  663. def close(self):
  664. """!Close the DBMI connection"""
  665. self.connection.commit()
  666. self.cursor.close()
  667. self.connected = False
  668. def mogrify_sql_statement(self, content):
  669. """!Return the SQL statement and arguments as executable SQL string
  670. @param content The content as tuple with two entries, the first
  671. entry is the SQL statement with DBMI specific
  672. place holder (?), the second entry is the argument
  673. list that should substitue the place holder.
  674. Usage:
  675. @code
  676. >>> init()
  677. >>> dbif = SQLDatabaseInterfaceConnection()
  678. >>> dbif.mogrify_sql_statement(["SELECT ctime FROM raster_base WHERE id = ?",
  679. ... ["soil@PERMANENT",]])
  680. "SELECT ctime FROM raster_base WHERE id = 'soil@PERMANENT'"
  681. @endcode
  682. """
  683. sql = content[0]
  684. args = content[1]
  685. if self.dbmi.__name__ == "psycopg2":
  686. if len(args) == 0:
  687. return sql
  688. else:
  689. if self.connected:
  690. try:
  691. return self.cursor.mogrify(sql, args)
  692. except:
  693. print sql, args
  694. raise
  695. else:
  696. self.connect()
  697. statement = self.cursor.mogrify(sql, args)
  698. self.close()
  699. return statement
  700. elif self.dbmi.__name__ == "sqlite3":
  701. if len(args) == 0:
  702. return sql
  703. else:
  704. # Unfortunately as sqlite does not support
  705. # the transformation of sql strings and qmarked or
  706. # named arguments we must make our hands dirty
  707. # and do it by ourself. :(
  708. # Doors are open for SQL injection because of the
  709. # limited python sqlite3 implementation!!!
  710. pos = 0
  711. count = 0
  712. maxcount = 100
  713. statement = sql
  714. while count < maxcount:
  715. pos = statement.find("?", pos + 1)
  716. if pos == -1:
  717. break
  718. if args[count] is None:
  719. statement = "%sNULL%s" % (statement[0:pos],
  720. statement[pos + 1:])
  721. elif isinstance(args[count], (int, long)):
  722. statement = "%s%d%s" % (statement[0:pos], args[count],
  723. statement[pos + 1:])
  724. elif isinstance(args[count], float):
  725. statement = "%s%f%s" % (statement[0:pos], args[count],
  726. statement[pos + 1:])
  727. else:
  728. # Default is a string, this works for datetime
  729. # objects too
  730. statement = "%s\'%s\'%s" % (statement[0:pos],
  731. str(args[count]),
  732. statement[pos + 1:])
  733. count += 1
  734. return statement
  735. def check_table(self, table_name):
  736. """!Check if a table exists in the temporal database
  737. @param table_name The name of the table to be checked for existance
  738. @return True if the table exists, False otherwise
  739. """
  740. table_exists = False
  741. connected = False
  742. if not self.connected:
  743. self.connect()
  744. connected = True
  745. # Check if the database already exists
  746. if self.dbmi.__name__ == "sqlite3":
  747. self.cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='%s';"%table_name)
  748. name = self.cursor.fetchone()
  749. if name and name[0] == table_name:
  750. table_exists = True
  751. else:
  752. # Check for raster_base table
  753. self.cursor.execute("SELECT EXISTS(SELECT * FROM information_schema.tables "
  754. "WHERE table_name=%s)", ('%s'%table_name,))
  755. if self.cursor.fetchone()[0]:
  756. table_exists = True
  757. if connected:
  758. self.close()
  759. return table_exists
  760. def execute_transaction(self, statement):
  761. """!Execute a transactional SQL statement
  762. The BEGIN and END TRANSACTION statements will be added automatically
  763. to the sql statement
  764. @param statement The executable SQL statement or SQL script
  765. """
  766. connected = False
  767. if not self.connected:
  768. self.connect()
  769. connected = True
  770. sql_script = ""
  771. sql_script += "BEGIN TRANSACTION;\n"
  772. sql_script += statement
  773. sql_script += "END TRANSACTION;"
  774. try:
  775. if self.dbmi.__name__ == "sqlite3":
  776. self.cursor.executescript(statement)
  777. else:
  778. self.cursor.execute(statement)
  779. self.connection.commit()
  780. except:
  781. if connected:
  782. self.close()
  783. self.msgr.error(_("Unable to execute transaction:\n %(sql)s" % {"sql":statement}))
  784. raise
  785. if connected:
  786. self.close()
  787. ###############################################################################
  788. def init_dbif(dbif):
  789. """!This method checks if the database interface connection exists,
  790. if not a new one will be created, connected and True will be returned.
  791. If the database interface exists but is connected, the connection will be established.
  792. @return the tuple (dbif, True|False)
  793. Usage code sample:
  794. @code
  795. dbif, connect = tgis.init_dbif(None)
  796. sql = dbif.mogrify_sql_statement(["SELECT * FROM raster_base WHERE ? = ?"],
  797. ["id", "soil@PERMANENT"])
  798. dbif.execute_transaction(sql)
  799. if connect:
  800. dbif.close()
  801. @endcode
  802. """
  803. if dbif is None:
  804. dbif = SQLDatabaseInterfaceConnection()
  805. dbif.connect()
  806. return dbif, True
  807. elif dbif.connected is False:
  808. dbif.connect()
  809. return dbif, True
  810. return dbif, False
  811. ###############################################################################
  812. if __name__ == "__main__":
  813. import doctest
  814. doctest.testmod()