core.py 41 KB

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