File: core.py

package info (click to toggle)
grass 7.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 135,976 kB
  • ctags: 44,148
  • sloc: ansic: 410,300; python: 166,939; cpp: 34,819; sh: 9,358; makefile: 6,618; xml: 3,551; sql: 769; lex: 519; yacc: 450; asm: 387; perl: 282; sed: 17; objc: 7
file content (1368 lines) | stat: -rw-r--r-- 50,723 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
"""
This module provides the functionality to create the temporal
SQL database and to establish a connection to the database.

Usage:

.. code-block:: python

    >>> import grass.temporal as tgis
    >>> # Create the temporal database
    >>> tgis.init()
    >>> # Establish a database connection
    >>> dbif, connected = tgis.init_dbif(None)
    >>> dbif.connect()
    >>> # Execute a SQL statement
    >>> dbif.execute_transaction("SELECT datetime(0, 'unixepoch', 'localtime');")
    >>> # Mogrify an SQL statement
    >>> dbif.mogrify_sql_statement(["SELECT name from raster_base where name = ?",
    ... ("precipitation",)])
    "SELECT name from raster_base where name = 'precipitation'"
    >>> dbif.close()


(C) 2011-2014 by the GRASS Development Team
This program is free software under the GNU General Public
License (>=v2). Read the file COPYING that comes with GRASS
for details.

:author: Soeren Gebbert
"""
#import traceback
import os
# i18N
import gettext
gettext.install('grasslibs', os.path.join(os.getenv("GISBASE"), 'locale'))

try:
    from builtins import long
except ImportError:
    # python3
    long = int

import grass.script as gscript
from datetime import datetime
from .c_libraries_interface import *
from grass.pygrass import messages
# Import all supported database backends
# Ignore import errors since they are checked later
try:
    import sqlite3
except ImportError:
    pass
# Postgresql is optional, existence is checked when needed
try:
    import psycopg2
    import psycopg2.extras
except:
    pass

import atexit

###############################################################################


def profile_function(func):
    """Profiling function provided by the temporal framework"""
    do_profiling = os.getenv("GRASS_TGIS_PROFILE")

    if do_profiling is "True" or do_profiling is "1":
        import cProfile, pstats
        try:
            import StringIO as io
        except ImportError:
            import io
        pr = cProfile.Profile()
        pr.enable()
        func()
        pr.disable()
        s = io.StringIO()
        sortby = 'cumulative'
        ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
        ps.print_stats()
        print(s.getvalue())
    else:
        func()

# Global variable that defines the backend
# of the temporal GIS
# It can either be "sqlite" or "pg"
tgis_backend = None


def get_tgis_backend():
    """Return the temporal GIS backend as string

       :returns: either "sqlite" or "pg"
    """
    global tgis_backend
    return tgis_backend

# Global variable that defines the database string
# of the temporal GIS
tgis_database = None


def get_tgis_database():
    """Return the temporal database string specified with t.connect
    """
    global tgis_database
    return tgis_database

# The version of the temporal framework
# this value must be an integer larger than 0
# Increase this value in case of backward incompatible changes in the TGIS API
tgis_version = 2
# The version of the temporal database since framework and database version
# can differ this value must be an integer larger than 0
# Increase this value in case of backward incompatible changes
# temporal database SQL layout
tgis_db_version = 2

# We need to know the parameter style of the database backend
tgis_dbmi_paramstyle = None


def get_tgis_dbmi_paramstyle():
    """Return the temporal database backend parameter style

       :returns: "qmark" or ""
    """
    global tgis_dbmi_paramstyle
    return tgis_dbmi_paramstyle

# We need to access the current mapset quite often in the framework, so we make
# a global variable that will be initiated when init() is called
current_mapset = None
current_location = None
current_gisdbase = None

###############################################################################


def get_current_mapset():
    """Return the current mapset

       This is the fastest way to receive the current mapset.
       The current mapset is set by init() and stored in a global variable.
       This function provides access to this global variable.
    """
    global current_mapset
    return current_mapset

###############################################################################


def get_current_location():
    """Return the current location

       This is the fastest way to receive the current location.
       The current location is set by init() and stored in a global variable.
       This function provides access to this global variable.
    """
    global current_location
    return current_location

###############################################################################


def get_current_gisdbase():
    """Return the current gis database (gisdbase)

       This is the fastest way to receive the current gisdbase.
       The current gisdbase is set by init() and stored in a global variable.
       This function provides access to this global variable.
    """
    global current_gisdbase
    return current_gisdbase

###############################################################################

# If this global variable is set True, then maps can only be registered in
# space time datasets with the same mapset. In addition, only maps in the
# current mapset can be inserted, updated or deleted from the temporal database.
# Overwrite this global variable by: g.gisenv set="TGIS_DISABLE_MAPSET_CHECK=True"
# ATTENTION: Be aware to face corrupted temporal database in case this global
#            variable is set to False. This feature is highly
#            experimental and violates the grass permission guidance.
enable_mapset_check = True
# If this global variable is set True, the timestamps of maps will be written
# as textfiles for each map that will be inserted or updated in the temporal
# database using the C-library timestamp interface.
# Overwrite this global variable by: g.gisenv set="TGIS_DISABLE_TIMESTAMP_WRITE=True"
# ATTENTION: Be aware to face corrupted temporal database in case this global
#            variable is set to False. This feature is highly
#            experimental and violates the grass permission guidance.
enable_timestamp_write = True


def get_enable_mapset_check():
    """Return True if the mapsets should be checked while insert, update,
       delete requests and space time dataset registration.

       If this global variable is set True, then maps can only be registered
       in space time datasets with the same mapset. In addition, only maps in
       the current mapset can be inserted, updated or deleted from the temporal
       database.
       Overwrite this global variable by: g.gisenv set="TGIS_DISABLE_MAPSET_CHECK=True"

       ..warning::

           Be aware to face corrupted temporal database in case this
           global variable is set to False. This feature is highly
           experimental and violates the grass permission guidance.

    """
    global enable_mapset_check
    return enable_mapset_check


def get_enable_timestamp_write():
    """Return True if the map timestamps should be written to the spatial
       database metadata as well.

       If this global variable is set True, the timestamps of maps will be
       written as textfiles for each map that will be inserted or updated in
       the temporal database using the C-library timestamp interface.
       Overwrite this global variable by: g.gisenv set="TGIS_DISABLE_TIMESTAMP_WRITE=True"

       ..warning::

           Be aware that C-libraries can not access timestamp information if
           they are not written as spatial database metadata, hence modules
           that make use of timestamps using the C-library interface will not
           work with maps that were created without writing the timestamps.
    """
    global enable_timestamp_write
    return enable_timestamp_write

###############################################################################

# The global variable that stores the PyGRASS Messenger object that
# provides a fast and exit safe interface to the C-library message functions
message_interface = None


def _init_tgis_message_interface(raise_on_error=False):
    """Initiate the global message interface

       :param raise_on_error: If True raise a FatalError exception in case of
                              a fatal error, call sys.exit(1) otherwise
    """
    global message_interface
    if message_interface is None:
        message_interface = messages.get_msgr(raise_on_error=raise_on_error)


def get_tgis_message_interface():
    """Return the temporal GIS message interface which is of type
       grass.pygrass.message.Messenger()

       Use this message interface to print messages to stdout using the
       GRASS C-library messaging system.
    """
    global message_interface
    return message_interface

###############################################################################

# The global variable that stores the C-library interface object that
# provides a fast and exit safe interface to the C-library libgis,
# libraster, libraster3d and libvector functions
c_library_interface = None


def _init_tgis_c_library_interface():
    """Set the global C-library interface variable that
       provides a fast and exit safe interface to the C-library libgis,
       libraster, libraster3d and libvector functions
    """
    global c_library_interface
    if c_library_interface is None:
        c_library_interface = CLibrariesInterface()


def get_tgis_c_library_interface():
    """Return the C-library interface that
       provides a fast and exit safe interface to the C-library libgis,
       libraster, libraster3d and libvector functions
    """
    global c_library_interface
    return c_library_interface

###############################################################################

# Set this variable True to raise a FatalError exception
# in case a fatal error occurs using the messenger interface
raise_on_error = False


def set_raise_on_error(raise_exp=True):
    """Define behavior on fatal error, invoked using the tgis messenger
    interface (msgr.fatal())

    The messenger interface will be restarted using the new error policy

    :param raise_exp: True to raise a FatalError exception instead of calling
                      sys.exit(1) when using the tgis messenger interface

    .. code-block:: python

        >>> import grass.temporal as tgis
        >>> tgis.init()
        >>> ignore = tgis.set_raise_on_error(False)
        >>> msgr = tgis.get_tgis_message_interface()
        >>> tgis.get_raise_on_error()
        False
        >>> msgr.fatal("Ohh no no no!")
        Traceback (most recent call last):
          File "__init__.py", line 239, in fatal
            sys.exit(1)
        SystemExit: 1

        >>> tgis.set_raise_on_error(True)
        False
        >>> msgr.fatal("Ohh no no no!")
        Traceback (most recent call last):
          File "__init__.py", line 241, in fatal
            raise FatalError(message)
        FatalError: Ohh no no no!

    :returns: current status
    """
    global raise_on_error
    tmp_raise = raise_on_error
    raise_on_error = raise_exp

    global message_interface
    if message_interface:
        message_interface.set_raise_on_error(raise_on_error)
    else:
        _init_tgis_message_interface(raise_on_error)

    return tmp_raise


def get_raise_on_error():
    """Return True if a FatalError exception is raised instead of calling
       sys.exit(1) in case a fatal error was invoked with msgr.fatal()
    """
    global raise_on_error
    return raise_on_error


###############################################################################


def get_tgis_version():
    """Get the version number of the temporal framework
       :returns: The version number of the temporal framework as string
    """
    global tgis_version
    return tgis_version

###############################################################################


def get_tgis_db_version():
    """Get the version number of the temporal framework
       :returns: The version number of the temporal framework as string
    """
    global tgis_db_version
    return tgis_db_version

###############################################################################


def get_tgis_metadata(dbif=None):
    """Return the tgis metadata table as a list of rows (dicts) or None if not
       present

       :param dbif: The database interface to be used
       :returns: The selected rows with key/value columns or None
    """

    dbif, connected = init_dbif(dbif)

    # Select metadata if the table is present
    try:
        statement = "SELECT * FROM tgis_metadata;\n"
        dbif.execute(statement)
        rows = dbif.fetchall()
    except:
        rows = None

    if connected:
        dbif.close()

    return rows

###############################################################################

# The temporal database string set with t.connect
# with substituted GRASS variables gisdbase, location and mapset
tgis_database_string = None


def get_tgis_database_string():
    """Return the preprocessed temporal database string

       This string is the temporal database string set with t.connect
       that was processed to substitue location, gisdbase and mapset
       variables.
    """
    global tgis_database_string
    return tgis_database_string

###############################################################################


def get_sql_template_path():
    base = os.getenv("GISBASE")
    base_etc = os.path.join(base, "etc")
    return os.path.join(base_etc, "sql")

###############################################################################


def stop_subprocesses():
    """Stop the messenger and C-interface subprocesses
       that are started by tgis.init()
    """
    global message_interface
    global c_library_interface
    if message_interface:
        message_interface.stop()
    if c_library_interface:
        c_library_interface.stop()

# We register this function to be called at exit
atexit.register(stop_subprocesses)


def get_available_temporal_mapsets():
    """Return a list of of mapset names with temporal database driver and names
        that are accessible from the current mapset.

        :returns: A dictionary, mapset names are keys, the tuple (driver,
                  database) are the values
    """
    global c_library_interface
    global message_interface

    mapsets = c_library_interface.available_mapsets()

    tgis_mapsets = {}

    for mapset in mapsets:
        driver = c_library_interface.get_driver_name(mapset)
        database = c_library_interface.get_database_name(mapset)
        
        message_interface.debug(1, "get_available_temporal_mapsets: "\
                                   "\n  mapset %s\n  driver %s\n  database %s"%(mapset,
                                   driver, database))

        if driver and database:
            # Check if the temporal sqlite database exists
            # We need to set non-existing databases in case the mapset is the current mapset
            # to create it
            if (driver == "sqlite" and os.path.exists(database)) or mapset == get_current_mapset() :
                tgis_mapsets[mapset] = (driver,  database)

            # We need to warn if the connection is defined but the database does not
            # exists
            if driver == "sqlite" and not os.path.exists(database):
                message_interface.warning("Temporal database connection defined as:\n" + \
                                          database + "\nBut database file does not exist.")

    return tgis_mapsets

###############################################################################


def init(raise_fatal_error=False):
    """This function set the correct database backend from GRASS environmental
       variables and creates the grass temporal database structure for raster,
       vector and raster3d maps as well as for the space-time datasets strds,
       str3ds and stvds in case it does not exist.

       Several global variables are initiated and the messenger and C-library
       interface subprocesses are spawned.

       Re-run this function in case the following GRASS variables change while
       the process runs:

       - MAPSET
       - LOCATION_NAME
       - GISDBASE
       - TGIS_DISABLE_MAPSET_CHECK
       - TGIS_DISABLE_TIMESTAMP_WRITE

       Re-run this function if the following t.connect variables change while
       the process runs:

       - temporal GIS driver (set by t.connect driver=)
       - temporal GIS database (set by t.connect database=)

       The following environmental variables are checked:

        - GRASS_TGIS_PROFILE (True, False, 1, 0)
        - GRASS_TGIS_RAISE_ON_ERROR (True, False, 1, 0)

        ..warning::

            This functions must be called before any spatio-temporal processing
            can be started

        :param raise_fatal_error: Set this True to assure that the init()
                                  function does not kill a persistent process
                                  like the GUI. If set True a
                                  grass.pygrass.messages.FatalError
                                  exception will be raised in case a fatal
                                  error occurs in the init process, otherwise
                                  sys.exit(1) will be called.
    """
    # We need to set the correct database backend and several global variables
    # from the GRASS mapset specific environment variables of g.gisenv and t.connect
    global tgis_backend
    global tgis_database
    global tgis_database_string
    global tgis_dbmi_paramstyle
    global raise_on_error
    global enable_mapset_check
    global enable_timestamp_write
    global current_mapset
    global current_location
    global current_gisdbase

    raise_on_error = raise_fatal_error

    # We must run t.connect at first to create the temporal database and to
    # get the environmental variables
    gscript.run_command("t.connect", flags="c")
    grassenv = gscript.gisenv()

    # Set the global variable for faster access
    current_mapset = grassenv["MAPSET"]
    current_location = grassenv["LOCATION_NAME"]
    current_gisdbase = grassenv["GISDBASE"]

    # Check environment variable GRASS_TGIS_RAISE_ON_ERROR
    if os.getenv("GRASS_TGIS_RAISE_ON_ERROR") == "True" or \
       os.getenv("GRASS_TGIS_RAISE_ON_ERROR") == "1":
        raise_on_error = True

    # Check if the script library raises on error,
    # if so we do the same
    if gscript.get_raise_on_error() is True:
        raise_on_error = True

    # Start the GRASS message interface server
    _init_tgis_message_interface(raise_on_error)
    # Start the C-library interface server
    _init_tgis_c_library_interface()
    msgr = get_tgis_message_interface()
    msgr.debug(1, "Initiate the temporal database")
                  #"\n  traceback:%s"%(str("  \n".join(traceback.format_stack()))))

    ciface = get_tgis_c_library_interface()
    driver_string = ciface.get_driver_name()
    database_string = ciface.get_database_name()

    # Set the mapset check and the timestamp write
    if "TGIS_DISABLE_MAPSET_CHECK" in grassenv:
        if grassenv["TGIS_DISABLE_MAPSET_CHECK"] == "True" or \
           grassenv["TGIS_DISABLE_MAPSET_CHECK"] == "1":
            enable_mapset_check = False
            msgr.warning("TGIS_DISABLE_MAPSET_CHECK is True")

    if "TGIS_DISABLE_TIMESTAMP_WRITE" in grassenv:
        if grassenv["TGIS_DISABLE_TIMESTAMP_WRITE"] == "True" or \
           grassenv["TGIS_DISABLE_TIMESTAMP_WRITE"] == "1":
            enable_timestamp_write = False
            msgr.warning("TGIS_DISABLE_TIMESTAMP_WRITE is True")

    if driver_string is not None and driver_string is not "":
        if driver_string == "sqlite":
            tgis_backend = driver_string
            try:
                import sqlite3
            except ImportError:
                msgr.error("Unable to locate the sqlite SQL Python interface"
                           " module sqlite3.")
                raise
            dbmi = sqlite3
        elif driver_string == "pg":
            tgis_backend = driver_string
            try:
                import psycopg2
            except ImportError:
                msgr.error("Unable to locate the Postgresql SQL Python "
                           "interface module psycopg2.")
                raise
            dbmi = psycopg2
        else:
            msgr.fatal(_("Unable to initialize the temporal DBMI interface. "
                         "Please use t.connect to specify the driver and the"
                         " database string"))
    else:
        # Set the default sqlite3 connection in case nothing was defined
        gscript.run_command("t.connect", flags="d")
        driver_string = ciface.get_driver_name()
        database_string = ciface.get_database_name()
        tgis_backend = driver_string
        dbmi = sqlite3

    tgis_database_string = database_string
    # Set the parameter style
    tgis_dbmi_paramstyle = dbmi.paramstyle

    # We do not know if the database already exists
    db_exists = False
    dbif = SQLDatabaseInterfaceConnection()

    # Check if the database already exists
    if tgis_backend == "sqlite":
        # Check path of the sqlite database
        if os.path.exists(tgis_database_string):
            dbif.connect()
            # Check for raster_base table
            dbif.execute("SELECT name FROM sqlite_master WHERE type='table' "
                         "AND name='raster_base';")
            name = dbif.fetchone()
            if name and name[0] == "raster_base":
                db_exists = True
            dbif.close()
    elif tgis_backend == "pg":
        # Connect to database
        dbif.connect()
        # Check for raster_base table
        dbif.execute("SELECT EXISTS(SELECT * FROM information_schema.tables "
                     "WHERE table_name=%s)", ('raster_base',))
        if dbif.fetchone()[0]:
            db_exists = True

    backup_howto = "The format of your actual temporal database is not " \
                   "supported any more.\nSolution: You need to export it by " \
                   "restoring the GRASS GIS version used for creating this DB"\
                   ". From there, create a backup of your temporal database "\
                   "to avoid the loss of your temporal data.\nNotes: Use " \
                   "t.rast.export and t.vect.export to make a backup of your" \
                   " existing space time datasets.To safe the timestamps of" \
                   " your existing maps and space time datasets, use " \
                   "t.rast.list, t.vect.list and t.rast3d.list. "\
                   "You can register the existing time stamped maps easily if"\
                   " you export columns=id,start_time,end_time into text "\
                   "files and use t.register to register them again in new" \
                   " created space time datasets (t.create). After the backup"\
                   " remove the existing temporal database, a new one will be"\
                   " created automatically.\n"

    if db_exists is True:
        # Check the version of the temporal database
        dbif.close()
        dbif.connect()
        metadata = get_tgis_metadata(dbif)
        dbif.close()
        if metadata is None:
            msgr.fatal(_("Unable to receive temporal database metadata.\n"
                         "Current temporal database info:%(info)s") % (
                       {"info": get_database_info_string()}))
        for entry in metadata:
            if "tgis_version" in entry and entry[1] != str(get_tgis_version()):
                msgr.fatal(_("Unsupported temporal database: version mismatch."
                             "\n %(backup)s Supported temporal API version is:"
                             " %(api)i.\nPlease update your GRASS GIS "
                             "installation.\nCurrent temporal database info:"
                             "%(info)s") % ({"backup": backup_howto,
                                             "api": get_tgis_version(),
                                             "info": get_database_info_string()}))
            if "tgis_db_version" in entry and entry[1] != str(get_tgis_db_version()):
                msgr.fatal(_("Unsupported temporal database: version mismatch."
                             "\n %(backup)sSupported temporal database version"
                             " is: %(tdb)i\nCurrent temporal database info:"
                             "%(info)s") % ({"backup": backup_howto,
                                             "tdb": get_tgis_version(),
                                             "info": get_database_info_string()}))
        return

    create_temporal_database(dbif)

###############################################################################


def get_database_info_string():
    dbif = SQLDatabaseInterfaceConnection()

    info = "\nDBMI interface:..... " + str(dbif.get_dbmi().__name__)
    info += "\nTemporal database:.. " + str(get_tgis_database_string())
    return info

###############################################################################


def create_temporal_database(dbif):
    """This function will create the temporal database

       It will create all tables and triggers that are needed to run
       the temporal GIS

       :param dbif: The database interface to be used
    """
    global tgis_backend
    global tgis_version
    global tgis_db_version
    global tgis_database_string

    template_path = get_sql_template_path()
    msgr = get_tgis_message_interface()

    # Read all SQL scripts and templates
    map_tables_template_sql = open(os.path.join(
        template_path, "map_tables_template.sql"), 'r').read()
    raster_metadata_sql = open(os.path.join(
        get_sql_template_path(), "raster_metadata_table.sql"), 'r').read()
    raster3d_metadata_sql = open(os.path.join(template_path,
                                              "raster3d_metadata_table.sql"),
                                 'r').read()
    vector_metadata_sql = open(os.path.join(template_path,
                                            "vector_metadata_table.sql"),
                               'r').read()
    raster_views_sql = open(os.path.join(template_path, "raster_views.sql"),
                            'r').read()
    raster3d_views_sql = open(os.path.join(template_path,
                                           "raster3d_views.sql"), 'r').read()
    vector_views_sql = open(os.path.join(template_path, "vector_views.sql"),
                            'r').read()

    stds_tables_template_sql = open(os.path.join(template_path,
                                                 "stds_tables_template.sql"),
                                    'r').read()
    strds_metadata_sql = open(os.path.join(template_path,
                                           "strds_metadata_table.sql"),
                              'r').read()
    str3ds_metadata_sql = open(os.path.join(template_path,
                                            "str3ds_metadata_table.sql"),
                               'r').read()
    stvds_metadata_sql = open(os.path.join(template_path,
                                           "stvds_metadata_table.sql"),
                              'r').read()
    strds_views_sql = open(os.path.join(template_path, "strds_views.sql"),
                           'r').read()
    str3ds_views_sql = open(os.path.join(template_path, "str3ds_views.sql"),
                            'r').read()
    stvds_views_sql = open(os.path.join(template_path, "stvds_views.sql"),
                           'r').read()

    # Create the raster, raster3d and vector tables SQL statements
    raster_tables_sql = map_tables_template_sql.replace("GRASS_MAP", "raster")
    vector_tables_sql = map_tables_template_sql.replace("GRASS_MAP", "vector")
    raster3d_tables_sql = map_tables_template_sql.replace(
        "GRASS_MAP", "raster3d")

    # Create the space-time raster, raster3d and vector dataset tables
    # SQL statements
    strds_tables_sql = stds_tables_template_sql.replace("STDS", "strds")
    stvds_tables_sql = stds_tables_template_sql.replace("STDS", "stvds")
    str3ds_tables_sql = stds_tables_template_sql.replace("STDS", "str3ds")

    msgr.message(_("Creating temporal database: %s" % (str(tgis_database_string))))

    if tgis_backend == "sqlite":
        # We need to create the sqlite3 database path if it does not exist
        tgis_dir = os.path.dirname(tgis_database_string)
        if not os.path.exists(tgis_dir):
            try:
                os.makedirs(tgis_dir)
            except Exception as e:
                msgr.fatal(_("Unable to create SQLite temporal database\n"
                             "Exception: %s\nPlease use t.connect to set a "
                             "read- and writable temporal database path" % (e)))

        # Set up the trigger that takes care of
        # the correct deletion of entries across the different tables
        delete_trigger_sql = open(os.path.join(template_path,
                                               "sqlite3_delete_trigger.sql"),
                                  'r').read()
        indexes_sql = open(os.path.join(template_path, "sqlite3_indexes.sql"),
                           'r').read()
    else:
        # Set up the trigger that takes care of
        # the correct deletion of entries across the different tables
        delete_trigger_sql = open(os.path.join(template_path,
                                               "postgresql_delete_trigger.sql"),
                                  'r').read()
        indexes_sql = open(os.path.join(template_path,
                                        "postgresql_indexes.sql"), 'r').read()

    # Connect now to the database
    if dbif.connected is not True:
        dbif.connect()

    # Execute the SQL statements for sqlite
    # Create the global tables for the native grass datatypes
    dbif.execute_transaction(raster_tables_sql)
    dbif.execute_transaction(raster_metadata_sql)
    dbif.execute_transaction(raster_views_sql)
    dbif.execute_transaction(vector_tables_sql)
    dbif.execute_transaction(vector_metadata_sql)
    dbif.execute_transaction(vector_views_sql)
    dbif.execute_transaction(raster3d_tables_sql)
    dbif.execute_transaction(raster3d_metadata_sql)
    dbif.execute_transaction(raster3d_views_sql)
    # Create the tables for the new space-time datatypes
    dbif.execute_transaction(strds_tables_sql)
    dbif.execute_transaction(strds_metadata_sql)
    dbif.execute_transaction(strds_views_sql)
    dbif.execute_transaction(stvds_tables_sql)
    dbif.execute_transaction(stvds_metadata_sql)
    dbif.execute_transaction(stvds_views_sql)
    dbif.execute_transaction(str3ds_tables_sql)
    dbif.execute_transaction(str3ds_metadata_sql)
    dbif.execute_transaction(str3ds_views_sql)

    # The delete trigger
    dbif.execute_transaction(delete_trigger_sql)
    # The indexes
    dbif.execute_transaction(indexes_sql)

    # Create the tgis metadata table to store the database
    # initial configuration
    # The metadata table content
    metadata = {}
    metadata["tgis_version"] = tgis_version
    metadata["tgis_db_version"] = tgis_db_version
    metadata["creation_time"] = datetime.today()
    _create_tgis_metadata_table(metadata, dbif)

    dbif.close()

###############################################################################


def _create_tgis_metadata_table(content, dbif=None):
    """!Create the temporal gis metadata table which stores all metadata
       information about the temporal database.

       :param content: The dictionary that stores the key:value metadata
                      that should be stored in the metadata table
       :param dbif: The database interface to be used
    """
    dbif, connected = init_dbif(dbif)
    statement = "CREATE TABLE tgis_metadata (key VARCHAR NOT NULL, value VARCHAR);\n";
    dbif.execute_transaction(statement)

    for key in content.keys():
        statement = "INSERT INTO tgis_metadata (key, value) VALUES " + \
                    "(\'%s\' , \'%s\');\n" % (str(key), str(content[key]))
        dbif.execute_transaction(statement)

    if connected:
        dbif.close()

###############################################################################


class SQLDatabaseInterfaceConnection(object):
    def __init__(self):
        self.tgis_mapsets = get_available_temporal_mapsets()
        self.current_mapset = get_current_mapset()
        self.connections = {}
        self.connected = False

        self.unique_connections = {}

        for mapset in self.tgis_mapsets.keys():
            driver,  dbstring = self.tgis_mapsets[mapset]

            if dbstring not in self.unique_connections.keys():
                self.unique_connections[dbstring] = DBConnection(backend=driver,
                                                                 dbstring=dbstring)

            self.connections[mapset] = self.unique_connections[dbstring]

        self.msgr = get_tgis_message_interface()

    def get_dbmi(self,  mapset=None):
        if mapset is None:
            mapset = self.current_mapset
        return self.connections[mapset].dbmi

    def rollback(self,  mapset=None):
        """
            Roll back the last transaction. This must be called
            in case a new query should be performed after a db error.

            This is only relevant for postgresql database.
        """
        if mapset is None:
            mapset = self.current_mapset

    def connect(self):
        """Connect to the DBMI to execute SQL statements

           Supported backends are sqlite3 and postgresql
        """
        for mapset in self.tgis_mapsets.keys():
            driver,  dbstring = self.tgis_mapsets[mapset]
            conn = self.connections[mapset]
            if conn.is_connected() is False:
                conn.connect(dbstring)

        self.connected = True

    def is_connected(self):
        return self.connected

    def close(self):
        """Close the DBMI connection

           There may be several temporal databases in a location, hence
           close all temporal databases that have been opened.
        """
        for key in self.unique_connections.keys():
            self.unique_connections[key].close()

        self.connected = False

    def mogrify_sql_statement(self, content, mapset=None):
        """Return the SQL statement and arguments as executable SQL string

           :param content: The content as tuple with two entries, the first
                           entry is the SQL statement with DBMI specific
                           place holder (?), the second entry is the argument
                           list that should substitute the place holder.
           :param mapset: The mapset of the abstract dataset or temporal
                          database location, if None the current mapset
                          will be used
        """
        if mapset is None:
            mapset = self.current_mapset

        if mapset not in self.tgis_mapsets.keys():
            self.msgr.fatal(_("Unable to mogrify sql statement. " +
                              self._create_mapset_error_message(mapset)))

        return self.connections[mapset].mogrify_sql_statement(content)

    def check_table(self, table_name, mapset=None):
        """Check if a table exists in the temporal database

           :param table_name: The name of the table to be checked for existence
           :param mapset: The mapset of the abstract dataset or temporal
                          database location, if None the current mapset
                          will be used
           :returns: True if the table exists, False otherwise

           TODO:
           There may be several temporal databases in a location, hence
           the mapset is used to query the correct temporal database.
        """
        if mapset is None:
            mapset = self.current_mapset

        if mapset not in self.tgis_mapsets.keys():
            self.msgr.fatal(_("Unable to check table. " +
                              self._create_mapset_error_message(mapset)))

        return self.connections[mapset].check_table(table_name)

    def execute(self,  statement,  args=None,  mapset=None):
        """

        :param mapset: The mapset of the abstract dataset or temporal
                       database location, if None the current mapset
                       will be used
        """
        if mapset is None:
            mapset = self.current_mapset

        if mapset not in self.tgis_mapsets.keys():
            self.msgr.fatal(_("Unable to execute sql statement. " +
                              self._create_mapset_error_message(mapset)))

        return self.connections[mapset].execute(statement,  args)

    def fetchone(self,  mapset=None):
        if mapset is None:
            mapset = self.current_mapset

        if mapset not in self.tgis_mapsets.keys():
            self.msgr.fatal(_("Unable to fetch one. " +
                              self._create_mapset_error_message(mapset)))

        return self.connections[mapset].fetchone()

    def fetchall(self,  mapset=None):
        if mapset is None:
            mapset = self.current_mapset

        if mapset not in self.tgis_mapsets.keys():
            self.msgr.fatal(_("Unable to fetch all. " +
                              self._create_mapset_error_message(mapset)))

        return self.connections[mapset].fetchall()

    def execute_transaction(self, statement, mapset=None):
        """Execute a transactional SQL statement

           The BEGIN and END TRANSACTION statements will be added automatically
           to the sql statement

           :param statement: The executable SQL statement or SQL script
        """
        if mapset is None:
            mapset = self.current_mapset

        if mapset not in self.tgis_mapsets.keys():
            self.msgr.fatal(_("Unable to execute transaction. " +
                              self._create_mapset_error_message(mapset)))

        return self.connections[mapset].execute_transaction(statement)

    def _create_mapset_error_message(self, mapset):

          return("You have no permission to "
                 "access mapset <%(mapset)s>, or "
                 "mapset <%(mapset)s> has no temporal database. "
                 "Accessible mapsets are: <%(mapsets)s>" % \
                 {"mapset": mapset,
                  "mapsets":','.join(self.tgis_mapsets.keys())})

###############################################################################


class DBConnection(object):
    """This class represents the database interface connection
       and provides access to the chosen backend modules.

       The following DBMS are supported:

         - sqlite via the sqlite3 standard library
         - postgresql via psycopg2
    """

    def __init__(self, backend=None, dbstring=None):
        """ Constructor of a database connection

            param backend:The database backend sqlite or pg
            param dbstring: The database connection string
        """
        self.connected = False
        if backend is None:
            global tgis_backend
            if tgis_backend == "sqlite":
                self.dbmi = sqlite3
            else:
                self.dbmi = psycopg2
        else:
            if backend == "sqlite":
                self.dbmi = sqlite3
            else:
                self.dbmi = psycopg2

        if dbstring is None:
            global tgis_database_string
            self.dbstring = tgis_database_string
        
        self.dbstring = dbstring

        self.msgr = get_tgis_message_interface()
        self.msgr.debug(1, "DBConnection constructor:"\
                           "\n  backend: %s"\
                           "\n  dbstring: %s"%(backend, self.dbstring))
                           #"\n  traceback:%s"%(backend, self.dbstring, 
                           #str("  \n".join(traceback.format_stack()))))

    def __del__(self):
        if self.connected is True:
            self.close()

    def is_connected(self):
        return self.connected

    def rollback(self):
        """
            Roll back the last transaction. This must be called
            in case a new query should be performed after a db error.

            This is only relevant for postgresql database.
        """
        if self.dbmi.__name__ == "psycopg2":
            if self.connected:
                self.connection.rollback()

    def connect(self,  dbstring=None):
        """Connect to the DBMI to execute SQL statements

            Supported backends are sqlite3 and postgresql

            param dbstring: The database connection string
        """
        # Connection in the current mapset
        if dbstring is None:
            dbstring = self.dbstring
        try:
            if self.dbmi.__name__ == "sqlite3":
                self.connection = self.dbmi.connect(dbstring,
                        detect_types=self.dbmi.PARSE_DECLTYPES | self.dbmi.PARSE_COLNAMES)
                self.connection.row_factory = self.dbmi.Row
                self.connection.isolation_level = None
                self.cursor = self.connection.cursor()
                self.cursor.execute("PRAGMA synchronous = OFF")
                self.cursor.execute("PRAGMA journal_mode = MEMORY")
            elif self.dbmi.__name__ == "psycopg2":
                self.connection = self.dbmi.connect(dbstring)
                #self.connection.set_isolation_level(dbmi.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
                self.cursor = self.connection.cursor(
                    cursor_factory=self.dbmi.extras.DictCursor)
            self.connected = True
        except Exception as e:
            self.msgr.fatal(_("Unable to connect to %(db)s database: "
                              "%(string)s\nException: \"%(ex)s\"\nPlease use"
                              " t.connect to set a read- and writable "
                              "temporal database backend") % (
                            {"db": self.dbmi.__name__,
                             "string": tgis_database_string, "ex": e, }))

    def close(self):
        """Close the DBMI connection
           TODO:
           There may be several temporal databases in a location, hence
           close all temporal databases that have been opened. Use a dictionary
           to manage different connections.
        """
        self.connection.commit()
        self.cursor.close()
        self.connected = False

    def mogrify_sql_statement(self, content):
        """Return the SQL statement and arguments as executable SQL string

           TODO:
           Use the mapset argument to identify the correct database driver

           :param content: The content as tuple with two entries, the first
                           entry is the SQL statement with DBMI specific
                           place holder (?), the second entry is the argument
                           list that should substitute the place holder.
           :param mapset: The mapset of the abstract dataset or temporal
                          database location, if None the current mapset
                          will be used

           Usage:

           .. code-block:: python

               >>> init()
               >>> dbif = SQLDatabaseInterfaceConnection()
               >>> dbif.mogrify_sql_statement(["SELECT ctime FROM raster_base WHERE id = ?",
               ... ["soil@PERMANENT",]])
               "SELECT ctime FROM raster_base WHERE id = 'soil@PERMANENT'"

        """
        sql = content[0]
        args = content[1]

        if self.dbmi.__name__ == "psycopg2":
            if len(args) == 0:
                return sql
            else:
                if self.connected:
                    try:
                        return self.cursor.mogrify(sql, args)
                    except Exception as exc:
                        print(sql, args)
                        raise exc
                else:
                    self.connect()
                    statement = self.cursor.mogrify(sql, args)
                    self.close()
                    return statement

        elif self.dbmi.__name__ == "sqlite3":
            if len(args) == 0:
                return sql
            else:
                # Unfortunately as sqlite does not support
                # the transformation of sql strings and qmarked or
                # named arguments we must make our hands dirty
                # and do it by ourself. :(
                # Doors are open for SQL injection because of the
                # limited python sqlite3 implementation!!!
                pos = 0
                count = 0
                maxcount = 100
                statement = sql

                while count < maxcount:
                    pos = statement.find("?", pos + 1)
                    if pos == -1:
                        break

                    if args[count] is None:
                        statement = "%sNULL%s" % (statement[0:pos],
                                                  statement[pos + 1:])
                    elif isinstance(args[count], (int, long)):
                        statement = "%s%d%s" % (statement[0:pos], args[count],
                                                statement[pos + 1:])
                    elif isinstance(args[count], float):
                        statement = "%s%f%s" % (statement[0:pos], args[count],
                                                statement[pos + 1:])
                    else:
                        # Default is a string, this works for datetime
                        # objects too
                        statement = "%s\'%s\'%s" % (statement[0:pos],
                                                    str(args[count]),
                                                    statement[pos + 1:])
                    count += 1

                return statement

    def check_table(self, table_name):
        """Check if a table exists in the temporal database

           :param table_name: The name of the table to be checked for existence
           :param mapset: The mapset of the abstract dataset or temporal
                          database location, if None the current mapset
                          will be used
           :returns: True if the table exists, False otherwise

           TODO:
           There may be several temporal databases in a location, hence
           the mapset is used to query the correct temporal database.
        """
        table_exists = False
        connected = False
        if not self.connected:
            self.connect()
            connected = True

        # Check if the database already exists
        if self.dbmi.__name__ == "sqlite3":

            self.cursor.execute("SELECT name FROM sqlite_master WHERE "
                                "type='table' AND name='%s';" % table_name)
            name = self.cursor.fetchone()
            if name and name[0] == table_name:
                table_exists = True
        else:
            # Check for raster_base table
            self.cursor.execute("SELECT EXISTS(SELECT * FROM information_schema.tables "
                                "WHERE table_name=%s)", ('%s' % table_name,))
            if self.cursor.fetchone()[0]:
                table_exists = True

        if connected:
            self.close()

        return table_exists

    def execute(self, statement,  args=None):
        """Execute a SQL statement

           :param statement: The executable SQL statement or SQL script
        """
        connected = False
        if not self.connected:
            self.connect()
            connected = True
        try:
            if args:
                self.cursor.execute(statement,  args)
            else:
                self.cursor.execute(statement)
        except:
            if connected:
                self.close()
            self.msgr.error(_("Unable to execute :\n %(sql)s" %
                            {"sql": statement}))
            raise

        if connected:
            self.close()

    def fetchone(self):
        if self.connected:
            return self.cursor.fetchone()
        return None

    def fetchall(self):
        if self.connected:
            return self.cursor.fetchall()
        return None

    def execute_transaction(self, statement, mapset=None):
        """Execute a transactional SQL statement

           The BEGIN and END TRANSACTION statements will be added automatically
           to the sql statement

           :param statement: The executable SQL statement or SQL script
        """
        connected = False
        if not self.connected:
            self.connect()
            connected = True

        sql_script = ""
        sql_script += "BEGIN TRANSACTION;\n"
        sql_script += statement
        sql_script += "END TRANSACTION;"

        try:
            if self.dbmi.__name__ == "sqlite3":
                self.cursor.executescript(statement)
            else:
                self.cursor.execute(statement)
            self.connection.commit()
        except:
            if connected:
                self.close()
            self.msgr.error(_("Unable to execute transaction:\n %(sql)s" %
                            {"sql": statement}))
            raise

        if connected:
            self.close()

###############################################################################


def init_dbif(dbif):
    """This method checks if the database interface connection exists,
        if not a new one will be created, connected and True will be returned.
        If the database interface exists but is connected, the connection will
        be established.

        :returns: the tuple (dbif, True|False)

        Usage code sample:

        .. code-block:: python

            dbif, connect = tgis.init_dbif(None)

            sql = dbif.mogrify_sql_statement(["SELECT * FROM raster_base WHERE ? = ?"],
                                                   ["id", "soil@PERMANENT"])
            dbif.execute_transaction(sql)

            if connect:
                dbif.close()

    """
    if dbif is None:
        dbif = SQLDatabaseInterfaceConnection()
        dbif.connect()
        return dbif, True
    elif dbif.is_connected() is False:
        dbif.connect()
        return dbif, True

    return dbif, False

###############################################################################

if __name__ == "__main__":
    import doctest
    doctest.testmod()