core.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  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 not None:
  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.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. def get_tgis_version():
  215. """!Get the verion number of the temporal framework
  216. @return The version number of the temporal framework as string
  217. """
  218. global tgis_version
  219. return tgis_version
  220. ###############################################################################
  221. def get_tgis_db_version():
  222. """!Get the verion number of the temporal framework
  223. @return The version number of the temporal framework as string
  224. """
  225. global tgis_db_version
  226. return tgis_db_version
  227. ###############################################################################
  228. def get_tgis_metadata(dbif=None):
  229. """!Return the tgis metadata table as a list of rows (dicts)
  230. or None if not present
  231. @param dbif The database interface to be used
  232. @return The selected rows with key/value comumns or None
  233. """
  234. dbif, connected = init_dbif(dbif)
  235. # Select metadata if the table is present
  236. try:
  237. statement = "SELECT * FROM tgis_metadata;\n"
  238. dbif.cursor.execute(statement)
  239. rows = dbif.cursor.fetchall()
  240. except:
  241. rows = None
  242. if connected:
  243. dbif.close()
  244. return rows
  245. ###############################################################################
  246. # The temporal database string set with t.connect
  247. # with substituted GRASS variables gisdbase, location and mapset
  248. tgis_database_string = None
  249. def get_tgis_database_string():
  250. """!Return the preprocessed temporal database string
  251. This string is the temporal database string set with t.connect
  252. that was processed to substitue location, gisdbase and mapset
  253. varibales.
  254. """
  255. global tgis_database_string
  256. return tgis_database_string
  257. ###############################################################################
  258. def get_sql_template_path():
  259. base = os.getenv("GISBASE")
  260. base_etc = os.path.join(base, "etc")
  261. return os.path.join(base_etc, "sql")
  262. ###############################################################################
  263. def stop_subprocesses():
  264. """!Stop the messenger and C-interface subprocesses
  265. that are started by tgis.init()
  266. """
  267. global message_interface
  268. global c_library_interface
  269. if message_interface:
  270. message_interface.stop()
  271. if c_library_interface:
  272. c_library_interface.stop()
  273. # We register this function to be called at exit
  274. atexit.register(stop_subprocesses)
  275. ###############################################################################
  276. def init():
  277. """!This function set the correct database backend from GRASS environmental variables
  278. and creates the grass temporal database structure for raster,
  279. vector and raster3d maps as well as for the space-time datasets strds,
  280. str3ds and stvds in case it does not exists.
  281. Several global variables are initiated and the messenger and C-library interface
  282. subprocesses are spawned.
  283. Re-run this function in case the following GRASS variables change while the process runs:
  284. - MAPSET
  285. - LOCATION_NAME
  286. - GISDBASE
  287. - TGIS_RAISE_ON_ERROR
  288. - TGIS_DISABLE_MAPSET_CHECK
  289. - TGIS_DISABLE_TIMESTAMP_WRITE
  290. Re-run the script if the following t.connect variables change while the process runs:
  291. - temporal GIS driver (set by t.connect driver=)
  292. - temporal GIS database (set by t.connect database=)
  293. The following environmental variables are checked:
  294. - GRASS_TGIS_PROFILE
  295. ATTENTION: This functions must be called before any spatio-temporal processing
  296. can be started
  297. """
  298. # We need to set the correct database backend and several global variables
  299. # from the GRASS mapset specific environment variables of g.gisenv and t.connect
  300. global tgis_backend
  301. global tgis_database
  302. global tgis_database_string
  303. global tgis_dbmi_paramstyle
  304. global enable_mapset_check
  305. global enable_timestamp_write
  306. global current_mapset
  307. global current_location
  308. global current_gisdbase
  309. # We must run t.connect at first to create the temporal database and to
  310. # get the environmental variables
  311. core.run_command("t.connect", flags="c")
  312. kv = core.parse_command("t.connect", flags="pg")
  313. grassenv = core.gisenv()
  314. raise_on_error = False
  315. # Set the global variable for faster access
  316. current_mapset = grassenv["MAPSET"]
  317. current_location = grassenv["LOCATION_NAME"]
  318. current_gisdbase = grassenv["GISDBASE"]
  319. # Check the g.gisenv variable TGIS_RAISE_ON_ERROR
  320. if grassenv.has_key("TGIS_RAISE_ON_ERROR"):
  321. if grassenv["TGIS_RAISE_ON_ERROR"] == "True" or grassenv["TGIS_RAISE_ON_ERROR"] == "1":
  322. raise_on_error = True
  323. # Start the GRASS message interface server
  324. _init_tgis_message_interface(raise_on_error)
  325. # Start the C-library interface server
  326. _init_tgis_c_library_interface()
  327. msgr = get_tgis_message_interface()
  328. msgr.debug(1, "Inititate the temporal database")
  329. if raise_on_error is True:
  330. msgr.warning("TGIS_RAISE_ON_ERROR is True")
  331. # Set the mapset check and the timestamp write
  332. if grassenv.has_key("TGIS_DISABLE_MAPSET_CHECK"):
  333. if grassenv["TGIS_DISABLE_MAPSET_CHECK"] == "True" or grassenv["TGIS_DISABLE_MAPSET_CHECK"] == "1":
  334. enable_mapset_check = False
  335. msgr.warning("TGIS_DISABLE_MAPSET_CHECK is True")
  336. if grassenv.has_key("TGIS_DISABLE_TIMESTAMP_WRITE"):
  337. if grassenv["TGIS_DISABLE_TIMESTAMP_WRITE"] == "True" or grassenv["TGIS_DISABLE_TIMESTAMP_WRITE"] == "1":
  338. enable_timestamp_write = False
  339. msgr.warning("TGIS_DISABLE_TIMESTAMP_WRITE is True")
  340. if "driver" in kv:
  341. if kv["driver"] == "sqlite":
  342. tgis_backend = kv["driver"]
  343. try:
  344. import sqlite3
  345. except ImportError:
  346. msgr.error("Unable to locate the sqlite SQL Python interface module sqlite3.")
  347. raise
  348. dbmi = sqlite3
  349. elif kv["driver"] == "pg":
  350. tgis_backend = kv["driver"]
  351. try:
  352. import psycopg2
  353. except ImportError:
  354. msgr.error("Unable to locate the Postgresql SQL Python interface module psycopg2.")
  355. raise
  356. dbmi = psycopg2
  357. else:
  358. msgr.fatal(_("Unable to initialize the temporal DBMI interface. Use "
  359. "t.connect to specify the driver and the database string"))
  360. dbmi = sqlite3
  361. else:
  362. # Set the default sqlite3 connection in case nothing was defined
  363. core.run_command("t.connect", flags="d")
  364. kv = core.parse_command("t.connect", flags="pg")
  365. tgis_backend = kv["driver"]
  366. # Database string from t.connect -pg
  367. tgis_database = kv["database"]
  368. # Set the parameter style
  369. tgis_dbmi_paramstyle = dbmi.paramstyle
  370. # Create the temporal database string
  371. if tgis_backend == "sqlite":
  372. # We substitute GRASS variables if they are located in the database string
  373. # This behavior is in conjunction with db.connect
  374. tgis_database_string = tgis_database
  375. tgis_database_string = tgis_database_string.replace("$GISDBASE", current_gisdbase)
  376. tgis_database_string = tgis_database_string.replace("$LOCATION_NAME", current_location)
  377. tgis_database_string = tgis_database_string.replace("$MAPSET", current_mapset)
  378. elif tgis_backend == "pg":
  379. tgis_database_string = tgis_database
  380. # We do not know if the database already exists
  381. db_exists = False
  382. dbif = SQLDatabaseInterfaceConnection()
  383. # Check if the database already exists
  384. if tgis_backend == "sqlite":
  385. # Check path of the sqlite database
  386. if os.path.exists(tgis_database_string):
  387. dbif.connect()
  388. # Check for raster_base table
  389. dbif.cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='raster_base';")
  390. name = dbif.cursor.fetchone()
  391. if name and name[0] == "raster_base":
  392. db_exists = True
  393. dbif.close()
  394. elif tgis_backend == "pg":
  395. # Connect to database
  396. dbif.connect()
  397. # Check for raster_base table
  398. dbif.cursor.execute("SELECT EXISTS(SELECT * FROM information_schema.tables "
  399. "WHERE table_name=%s)", ('raster_base',))
  400. if dbif.cursor.fetchone()[0]:
  401. db_exists = True
  402. if db_exists == True:
  403. # Check the version of the temporal database
  404. # This version works only with database of version 2
  405. dbif.close()
  406. dbif.connect()
  407. metadata = get_tgis_metadata(dbif)
  408. dbif.close()
  409. if metadata is None:
  410. msgr.fatal(_("Unable to receiving temporal database metadata. Your temporal database is not supported."))
  411. for entry in metadata:
  412. if "tgis_version" in entry and entry[1] != str(get_tgis_version()):
  413. msgr.fatal(_("Unsupported temporal database. Version mismatch.\n"
  414. "Supported temporal API version is: %(api)i")%({"api":get_tgis_version()}))
  415. if "tgis_db_version" in entry and entry[1] != str(get_tgis_db_version()):
  416. msgr.fatal(_("Unsupported temporal database. Version mismatch.\n"
  417. "Supported temporal database version is: %(tdb)i")%( {"tdb":get_tgis_db_version()}))
  418. return
  419. create_temporal_database(dbif)
  420. ###############################################################################
  421. def create_temporal_database(dbif):
  422. """!This function will create the temporal database
  423. It will create all tables and triggers that are needed to run
  424. the temporal GIS
  425. @param dbif The database interface to be used
  426. """
  427. global tgis_backend
  428. global tgis_version
  429. global tgis_db_version
  430. global tgis_database_string
  431. template_path = get_sql_template_path()
  432. msgr = get_tgis_message_interface()
  433. # Read all SQL scripts and templates
  434. map_tables_template_sql = open(os.path.join(
  435. template_path, "map_tables_template.sql"), 'r').read()
  436. raster_metadata_sql = open(os.path.join(
  437. get_sql_template_path(), "raster_metadata_table.sql"), 'r').read()
  438. raster3d_metadata_sql = open(os.path.join(template_path,
  439. "raster3d_metadata_table.sql"),
  440. 'r').read()
  441. vector_metadata_sql = open(os.path.join(template_path,
  442. "vector_metadata_table.sql"),
  443. 'r').read()
  444. raster_views_sql = open(os.path.join(template_path, "raster_views.sql"),
  445. 'r').read()
  446. raster3d_views_sql = open(os.path.join(template_path,
  447. "raster3d_views.sql"), 'r').read()
  448. vector_views_sql = open(os.path.join(template_path, "vector_views.sql"),
  449. 'r').read()
  450. stds_tables_template_sql = open(os.path.join(template_path,
  451. "stds_tables_template.sql"),
  452. 'r').read()
  453. strds_metadata_sql = open(os.path.join(template_path,
  454. "strds_metadata_table.sql"),
  455. 'r').read()
  456. str3ds_metadata_sql = open(os.path.join(template_path,
  457. "str3ds_metadata_table.sql"),
  458. 'r').read()
  459. stvds_metadata_sql = open(os.path.join(template_path,
  460. "stvds_metadata_table.sql"),
  461. 'r').read()
  462. strds_views_sql = open(os.path.join(template_path, "strds_views.sql"),
  463. 'r').read()
  464. str3ds_views_sql = open(os.path.join(template_path, "str3ds_views.sql"),
  465. 'r').read()
  466. stvds_views_sql = open(os.path.join(template_path, "stvds_views.sql"),
  467. 'r').read()
  468. # Create the raster, raster3d and vector tables SQL statements
  469. raster_tables_sql = map_tables_template_sql.replace("GRASS_MAP", "raster")
  470. vector_tables_sql = map_tables_template_sql.replace("GRASS_MAP", "vector")
  471. raster3d_tables_sql = map_tables_template_sql.replace(
  472. "GRASS_MAP", "raster3d")
  473. # Create the space-time raster, raster3d and vector dataset tables
  474. # SQL statements
  475. strds_tables_sql = stds_tables_template_sql.replace("STDS", "strds")
  476. stvds_tables_sql = stds_tables_template_sql.replace("STDS", "stvds")
  477. str3ds_tables_sql = stds_tables_template_sql.replace("STDS", "str3ds")
  478. msgr.message(_("Create temporal database: %s" % (tgis_database_string)))
  479. if tgis_backend == "sqlite":
  480. # We need to create the sqlite3 database path if it does not exists
  481. tgis_dir = os.path.dirname(tgis_database_string)
  482. if not os.path.exists(tgis_dir):
  483. os.makedirs(tgis_dir)
  484. # Set up the trigger that takes care of
  485. # the correct deletion of entries across the different tables
  486. delete_trigger_sql = open(os.path.join(template_path,
  487. "sqlite3_delete_trigger.sql"),
  488. 'r').read()
  489. indexes_sql = open(os.path.join(template_path, "sqlite3_indexes.sql"), 'r').read()
  490. else:
  491. # Set up the trigger that takes care of
  492. # the correct deletion of entries across the different tables
  493. delete_trigger_sql = open(os.path.join(template_path,
  494. "postgresql_delete_trigger.sql"),
  495. 'r').read()
  496. indexes_sql = open(os.path.join(template_path, "postgresql_indexes.sql"), 'r').read()
  497. # Connect now to the database
  498. if not dbif.connected:
  499. dbif.connect()
  500. # Execute the SQL statements for sqlite
  501. # Create the global tables for the native grass datatypes
  502. dbif.execute_transaction(raster_tables_sql)
  503. dbif.execute_transaction(raster_metadata_sql)
  504. dbif.execute_transaction(raster_views_sql)
  505. dbif.execute_transaction(vector_tables_sql)
  506. dbif.execute_transaction(vector_metadata_sql)
  507. dbif.execute_transaction(vector_views_sql)
  508. dbif.execute_transaction(raster3d_tables_sql)
  509. dbif.execute_transaction(raster3d_metadata_sql)
  510. dbif.execute_transaction(raster3d_views_sql)
  511. # Create the tables for the new space-time datatypes
  512. dbif.execute_transaction(strds_tables_sql)
  513. dbif.execute_transaction(strds_metadata_sql)
  514. dbif.execute_transaction(strds_views_sql)
  515. dbif.execute_transaction(stvds_tables_sql)
  516. dbif.execute_transaction(stvds_metadata_sql)
  517. dbif.execute_transaction(stvds_views_sql)
  518. dbif.execute_transaction(str3ds_tables_sql)
  519. dbif.execute_transaction(str3ds_metadata_sql)
  520. dbif.execute_transaction(str3ds_views_sql)
  521. # The delete trigger
  522. dbif.execute_transaction(delete_trigger_sql)
  523. # The indexes
  524. dbif.execute_transaction(indexes_sql)
  525. # Create the tgis metadata table to store the database
  526. # initial configuration
  527. # The metadata table content
  528. metadata = {}
  529. metadata["tgis_version"] = tgis_version
  530. metadata["tgis_db_version"] = tgis_db_version
  531. metadata["creation_time"] = datetime.today()
  532. _create_tgis_metadata_table(metadata, dbif)
  533. dbif.close()
  534. ###############################################################################
  535. def _create_tgis_metadata_table(content, dbif=None):
  536. """!Create the temporal gis metadata table which stores all metadata
  537. information about the temporal database.
  538. @param content The dictionary that stores the key:value metadata
  539. that should be stored in the metadata table
  540. @param dbif The database interface to be used
  541. """
  542. dbif, connected = init_dbif(dbif)
  543. statement = "CREATE TABLE tgis_metadata (key VARCHAR NOT NULL, value VARCHAR);\n";
  544. dbif.execute_transaction(statement)
  545. for key in content.keys():
  546. statement = "INSERT INTO tgis_metadata (key, value) VALUES " + \
  547. "(\'%s\' , \'%s\');\n"%(str(key), str(content[key]))
  548. dbif.execute_transaction(statement)
  549. if connected:
  550. dbif.close()
  551. ###############################################################################
  552. class SQLDatabaseInterfaceConnection():
  553. """!This class represents the database interface connection
  554. and provides access to the chisen backend modules.
  555. The following DBMS are supported:
  556. - sqlite via the sqlite3 standard library
  557. - postgresql via psycopg2
  558. """
  559. def __init__(self):
  560. self.connected = False
  561. global tgis_backend
  562. if tgis_backend == "sqlite":
  563. self.dbmi = sqlite3
  564. else:
  565. self.dbmi = psycopg2
  566. self.msgr = get_tgis_message_interface()
  567. self.msgr.debug(1, "SQLDatabaseInterfaceConnection constructor")
  568. def __del__(self):
  569. if self.connected is True:
  570. self.close()
  571. def rollback(self):
  572. """
  573. Roll back the last transaction. This must be called
  574. in case a new query should be performed after a db error.
  575. This is only relevant for postgresql database.
  576. """
  577. if self.dbmi.__name__ == "psycopg2":
  578. if self.connected:
  579. self.connection.rollback()
  580. def connect(self):
  581. """!Connect to the DBMI to execute SQL statements
  582. Supported backends are sqlite3 and postgresql
  583. """
  584. global tgis_database_string
  585. if self.dbmi.__name__ == "sqlite3":
  586. self.connection = self.dbmi.connect(tgis_database_string,
  587. detect_types = self.dbmi.PARSE_DECLTYPES | self.dbmi.PARSE_COLNAMES)
  588. self.connection.row_factory = self.dbmi.Row
  589. self.connection.isolation_level = None
  590. self.cursor = self.connection.cursor()
  591. self.cursor.execute("PRAGMA synchronous = OFF")
  592. self.cursor.execute("PRAGMA journal_mode = MEMORY")
  593. elif self.dbmi.__name__ == "psycopg2":
  594. self.connection = self.dbmi.connect(tgis_database_string)
  595. #self.connection.set_isolation_level(dbmi.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
  596. self.cursor = self.connection.cursor(
  597. cursor_factory = self.dbmi.extras.DictCursor)
  598. self.connected = True
  599. def close(self):
  600. """!Close the DBMI connection"""
  601. self.connection.commit()
  602. self.cursor.close()
  603. self.connected = False
  604. def mogrify_sql_statement(self, content):
  605. """!Return the SQL statement and arguments as executable SQL string
  606. @param content The content as tuple with two entries, the first
  607. entry is the SQL statement with DBMI specific
  608. place holder (?), the second entry is the argument
  609. list that should substitue the place holder.
  610. Usage:
  611. @code
  612. >>> init()
  613. >>> dbif = SQLDatabaseInterfaceConnection()
  614. >>> dbif.mogrify_sql_statement(["SELECT ctime FROM raster_base WHERE id = ?",
  615. ... ["soil@PERMANENT",]])
  616. "SELECT ctime FROM raster_base WHERE id = 'soil@PERMANENT'"
  617. @endcode
  618. """
  619. sql = content[0]
  620. args = content[1]
  621. if self.dbmi.__name__ == "psycopg2":
  622. if len(args) == 0:
  623. return sql
  624. else:
  625. if self.connected:
  626. try:
  627. return self.cursor.mogrify(sql, args)
  628. except:
  629. print sql, args
  630. raise
  631. else:
  632. self.connect()
  633. statement = self.cursor.mogrify(sql, args)
  634. self.close()
  635. return statement
  636. elif self.dbmi.__name__ == "sqlite3":
  637. if len(args) == 0:
  638. return sql
  639. else:
  640. # Unfortunately as sqlite does not support
  641. # the transformation of sql strings and qmarked or
  642. # named arguments we must make our hands dirty
  643. # and do it by ourself. :(
  644. # Doors are open for SQL injection because of the
  645. # limited python sqlite3 implementation!!!
  646. pos = 0
  647. count = 0
  648. maxcount = 100
  649. statement = sql
  650. while count < maxcount:
  651. pos = statement.find("?", pos + 1)
  652. if pos == -1:
  653. break
  654. if args[count] is None:
  655. statement = "%sNULL%s" % (statement[0:pos],
  656. statement[pos + 1:])
  657. elif isinstance(args[count], (int, long)):
  658. statement = "%s%d%s" % (statement[0:pos], args[count],
  659. statement[pos + 1:])
  660. elif isinstance(args[count], float):
  661. statement = "%s%f%s" % (statement[0:pos], args[count],
  662. statement[pos + 1:])
  663. else:
  664. # Default is a string, this works for datetime
  665. # objects too
  666. statement = "%s\'%s\'%s" % (statement[0:pos],
  667. str(args[count]),
  668. statement[pos + 1:])
  669. count += 1
  670. return statement
  671. def check_table(self, table_name):
  672. """!Check if a table exists in the temporal database
  673. @param table_name The name of the table to be checked for existance
  674. @return True if the table exists, False otherwise
  675. """
  676. table_exists = False
  677. connected = False
  678. if not self.connected:
  679. self.connect()
  680. connected = True
  681. # Check if the database already exists
  682. if self.dbmi.__name__ == "sqlite3":
  683. self.cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='%s';"%table_name)
  684. name = self.cursor.fetchone()
  685. if name and name[0] == table_name:
  686. table_exists = True
  687. else:
  688. # Check for raster_base table
  689. self.cursor.execute("SELECT EXISTS(SELECT * FROM information_schema.tables "
  690. "WHERE table_name=%s)", ('%s'%table_name,))
  691. if self.cursor.fetchone()[0]:
  692. table_exists = True
  693. if connected:
  694. self.close()
  695. return table_exists
  696. def execute_transaction(self, statement):
  697. """!Execute a transactional SQL statement
  698. The BEGIN and END TRANSACTION statements will be added automatically
  699. to the sql statement
  700. @param statement The executable SQL statement or SQL script
  701. """
  702. connected = False
  703. if not self.connected:
  704. self.connect()
  705. connected = True
  706. sql_script = ""
  707. sql_script += "BEGIN TRANSACTION;\n"
  708. sql_script += statement
  709. sql_script += "END TRANSACTION;"
  710. try:
  711. if self.dbmi.__name__ == "sqlite3":
  712. self.cursor.executescript(statement)
  713. else:
  714. self.cursor.execute(statement)
  715. self.connection.commit()
  716. except:
  717. if connected:
  718. self.close()
  719. self.msgr.error(_("Unable to execute transaction:\n %(sql)s" % {"sql":statement}))
  720. raise
  721. if connected:
  722. self.close()
  723. ###############################################################################
  724. def init_dbif(dbif):
  725. """!This method checks if the database interface connection exists,
  726. if not a new one will be created, connected and True will be returned.
  727. If the database interface exists but is connected, the connection will be established.
  728. @return the tuple (dbif, True|False)
  729. Usage code sample:
  730. @code
  731. dbif, connect = tgis.init_dbif(None)
  732. sql = dbif.mogrify_sql_statement(["SELECT * FROM raster_base WHERE ? = ?"],
  733. ["id", "soil@PERMANENT"])
  734. dbif.execute_transaction(sql)
  735. if connect:
  736. dbif.close()
  737. @endcode
  738. """
  739. if dbif is None:
  740. dbif = SQLDatabaseInterfaceConnection()
  741. dbif.connect()
  742. return dbif, True
  743. elif dbif.connected is False:
  744. dbif.connect()
  745. return dbif, True
  746. return dbif, False
  747. ###############################################################################
  748. if __name__ == "__main__":
  749. import doctest
  750. doctest.testmod()