File: base.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 (1066 lines) | stat: -rw-r--r-- 39,756 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
"""
This packages includes all base classes to store basic information
like id, name, mapset creation and modification time as well as sql
serialization and de-serialization and the sql database interface.

Usage:

.. code-block:: python

    >>> import grass.temporal as tgis
    >>> tgis.init()
    >>> rbase = tgis.RasterBase(ident="soil@PERMANENT")
    >>> vbase = tgis.VectorBase(ident="soil:1@PERMANENT")
    >>> r3base = tgis.Raster3DBase(ident="soil@PERMANENT")
    >>> strdsbase = tgis.STRDSBase(ident="soil@PERMANENT")
    >>> stvdsbase = tgis.STVDSBase(ident="soil@PERMANENT")
    >>> str3dsbase = tgis.STR3DSBase(ident="soil@PERMANENT")


(C) 2011-2013 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
"""
from __future__ import print_function
from datetime import datetime
from .core import *

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


class DictSQLSerializer(object):
    def __init__(self):
        self.D = {}
        self.dbmi_paramstyle = get_tgis_dbmi_paramstyle()

    def serialize(self, type, table, where=None):
        """Convert the internal dictionary into a string of semicolon
            separated SQL statements The keys are the column names and
            the values are the row entries

            Usage:

            .. code-block:: python

                >>> init()
                >>> t = DictSQLSerializer()
                >>> t.D["id"] = "soil@PERMANENT"
                >>> t.D["name"] = "soil"
                >>> t.D["mapset"] = "PERMANENT"
                >>> t.D["creator"] = "soeren"
                >>> t.D["creation_time"] = datetime(2001,1,1)
                >>> t.D["modification_time"] = datetime(2001,1,1)
                >>> t.serialize(type="SELECT", table="raster_base")
                ('SELECT  name  , creator  , creation_time  , modification_time  , mapset  , id  FROM raster_base ;\\n', ())
                >>> t.serialize(type="INSERT", table="raster_base")
                ('INSERT INTO raster_base ( name  ,creator  ,creation_time  ,modification_time  ,mapset  ,id ) VALUES (? ,? ,? ,? ,? ,?) ;\\n', ('soil', 'soeren', datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2001, 1, 1, 0, 0), 'PERMANENT', 'soil@PERMANENT'))
                >>> t.serialize(type="UPDATE", table="raster_base")
                ('UPDATE raster_base SET  name = ?  ,creator = ?  ,creation_time = ?  ,modification_time = ?  ,mapset = ?  ,id = ? ;\\n', ('soil', 'soeren', datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2001, 1, 1, 0, 0), 'PERMANENT', 'soil@PERMANENT'))
                >>> t.serialize(type="UPDATE ALL", table="raster_base")
                ('UPDATE raster_base SET  name = ?  ,creator = ?  ,creation_time = ?  ,modification_time = ?  ,mapset = ?  ,id = ? ;\\n', ('soil', 'soeren', datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2001, 1, 1, 0, 0), 'PERMANENT', 'soil@PERMANENT'))

                :param type: must be SELECT. INSERT, UPDATE
                :param table: The name of the table to select, insert or update
                :param where: The optional where statement
                :return: a tuple containing the SQL string and the arguments

        """

        sql = ""
        args = []

        # Create ordered select statement
        if type == "SELECT":
            sql += 'SELECT '
            count = 0
            for key in self.D.keys():
                if count == 0:
                    sql += ' %s ' % key
                else:
                    sql += ' , %s ' % key
                count += 1
            sql += ' FROM ' + table + ' '
            if where:
                sql += where
            sql += ";\n"

        # Create insert statement
        if type == "INSERT":
            count = 0
            sql += 'INSERT INTO ' + table + ' ('
            for key in self.D.keys():
                if count == 0:
                    sql += ' %s ' % key
                else:
                    sql += ' ,%s ' % key
                count += 1

            count = 0
            sql += ') VALUES ('
            for key in self.D.keys():
                if count == 0:
                    if self.dbmi_paramstyle == "qmark":
                        sql += '?'
                    else:
                        sql += '%s'
                else:
                    if self.dbmi_paramstyle == "qmark":
                        sql += ' ,?'
                    else:
                        sql += ' ,%s'
                count += 1
                args.append(self.D[key])
            sql += ') '

            if where:
                sql += where
            sql += ";\n"

        # Create update statement for existing entries
        if type == "UPDATE":
            count = 0
            sql += 'UPDATE ' + table + ' SET '
            for key in self.D.keys():
                # Update only entries which are not None
                if self.D[key] is not None:
                    if count == 0:
                        if self.dbmi_paramstyle == "qmark":
                            sql += ' %s = ? ' % key
                        else:
                            sql += ' %s ' % key
                            sql += '= %s '
                    else:
                        if self.dbmi_paramstyle == "qmark":
                            sql += ' ,%s = ? ' % key
                        else:
                            sql += ' ,%s ' % key
                            sql += '= %s '
                    count += 1
                    args.append(self.D[key])
            if where:
                sql += where
            sql += ";\n"

        # Create update statement for all entries
        if type == "UPDATE ALL":
            count = 0
            sql += 'UPDATE ' + table + ' SET '
            for key in self.D.keys():
                if count == 0:
                    if self.dbmi_paramstyle == "qmark":
                        sql += ' %s = ? ' % key
                    else:
                        sql += ' %s ' % key
                        sql += '= %s '
                else:
                    if self.dbmi_paramstyle == "qmark":
                        sql += ' ,%s = ? ' % key
                    else:
                        sql += ' ,%s ' % key
                        sql += '= %s '
                count += 1
                args.append(self.D[key])
            if where:
                sql += where
            sql += ";\n"

        return sql, tuple(args)

    def deserialize(self, row):
        """Convert the content of the dbmi dictionary like row into the
           internal dictionary

           :param row: The dictionary like row to store in the internal dict
        """
        self.D = {}
        for key in row.keys():
            self.D[key] = row[key]

    def clear(self):
        """Initialize the internal storage"""
        self.D = {}

    def print_self(self):
        """Print the content of the internal dictionary to stdout
        """
        print(self.D)

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


class SQLDatabaseInterface(DictSQLSerializer):
    """This class represents the SQL database interface

       Functions to insert, select and update the internal
       structure of this class in the temporal database are implemented.
       This is the base class for raster, raster3d, vector and
       space time datasets data management classes:

       - Identification information (base)
       - Spatial extent
       - Temporal extent
       - Metadata

       Usage:

       .. code-block:: python

            >>> init()
            >>> t = SQLDatabaseInterface("raster", "soil@PERMANENT")
            >>> t.mapset = get_current_mapset()
            >>> t.D["name"] = "soil"
            >>> t.D["mapset"] = "PERMANENT"
            >>> t.D["creator"] = "soeren"
            >>> t.D["creation_time"] = datetime(2001,1,1)
            >>> t.get_delete_statement()
            "DELETE FROM raster WHERE id = 'soil@PERMANENT';\\n"
            >>> t.get_is_in_db_statement()
            "SELECT id FROM raster WHERE id = 'soil@PERMANENT';\\n"
            >>> t.get_select_statement()
            ("SELECT  creation_time  , mapset  , name  , creator  FROM raster WHERE id = 'soil@PERMANENT';\\n", ())
            >>> t.get_select_statement_mogrified()
            "SELECT  creation_time  , mapset  , name  , creator  FROM raster WHERE id = 'soil@PERMANENT';\\n"
            >>> t.get_insert_statement()
            ('INSERT INTO raster ( creation_time  ,mapset  ,name  ,creator ) VALUES (? ,? ,? ,?) ;\\n', (datetime.datetime(2001, 1, 1, 0, 0), 'PERMANENT', 'soil', 'soeren'))
            >>> t.get_insert_statement_mogrified()
            "INSERT INTO raster ( creation_time  ,mapset  ,name  ,creator ) VALUES ('2001-01-01 00:00:00' ,'PERMANENT' ,'soil' ,'soeren') ;\\n"
            >>> t.get_update_statement()
            ("UPDATE raster SET  creation_time = ?  ,mapset = ?  ,name = ?  ,creator = ? WHERE id = 'soil@PERMANENT';\\n", (datetime.datetime(2001, 1, 1, 0, 0), 'PERMANENT', 'soil', 'soeren'))
            >>> t.get_update_statement_mogrified()
            "UPDATE raster SET  creation_time = '2001-01-01 00:00:00'  ,mapset = 'PERMANENT'  ,name = 'soil'  ,creator = 'soeren' WHERE id = 'soil@PERMANENT';\\n"
            >>> t.get_update_all_statement()
            ("UPDATE raster SET  creation_time = ?  ,mapset = ?  ,name = ?  ,creator = ? WHERE id = 'soil@PERMANENT';\\n", (datetime.datetime(2001, 1, 1, 0, 0), 'PERMANENT', 'soil', 'soeren'))
            >>> t.get_update_all_statement_mogrified()
            "UPDATE raster SET  creation_time = '2001-01-01 00:00:00'  ,mapset = 'PERMANENT'  ,name = 'soil'  ,creator = 'soeren' WHERE id = 'soil@PERMANENT';\\n"

    """
    def __init__(self, table=None, ident=None):
        """Constructor of this class

           :param table: The name of the table
           :param ident: The identifier (primary key) of this
                         object in the database table
        """
        DictSQLSerializer.__init__(self)

        self.table = table  # Name of the table, set in the subclass
        self.ident = ident
        self.msgr = get_tgis_message_interface()

        if self.ident and self.ident.find("@") >= 0:
            self.mapset = self.ident.split("@""")[1]
        else:
            self.mapset = None

    def get_table_name(self):
        """Return the name of the table in which the internal
           data are inserted, updated or selected
           :return: The name of the table
           """
        return self.table

    def get_delete_statement(self):
        """Return the delete string
           :return: The DELETE string
        """
        return "DELETE FROM " + self.get_table_name() + \
               " WHERE id = \'" + str(self.ident) + "\';\n"

    def delete(self, dbif=None):
        """Delete the entry of this object from the temporal database

           :param dbif: The database interface to be used,
                        if None a temporary connection will be established
        """
        sql = self.get_delete_statement()
        #print(sql)

        if dbif:
            dbif.execute(sql,   mapset=self.mapset)
        else:
            dbif = SQLDatabaseInterfaceConnection()
            dbif.connect()
            dbif.execute(sql,   mapset=self.mapset)
            dbif.close()

    def get_is_in_db_statement(self):
        """Return the selection string that checks if this object is registered in the
           temporal database
           :return: The SELECT string
        """
        return "SELECT id FROM " + self.get_table_name() + \
               " WHERE id = \'" + str(self.ident) + "\';\n"

    def is_in_db(self, dbif=None):
        """Check if this object is present in the temporal database

           :param dbif: The database interface to be used,
                        if None a temporary connection will be established
           :return: True if this object is present in the temporal database,
                    False otherwise
        """

        sql = self.get_is_in_db_statement()

        if dbif:
            dbif.execute(sql, mapset=self.mapset)
            row = dbif.fetchone(mapset=self.mapset)
        else:
            dbif = SQLDatabaseInterfaceConnection()
            dbif.connect()
            dbif.execute(sql, mapset=self.mapset)
            row = dbif.fetchone(mapset=self.mapset)
            dbif.close()

        # Nothing found
        if row is None:
            return False

        return True

    def get_select_statement(self):
        """Return the sql statement and the argument list in
           database specific style
           :return: The SELECT string
        """
        return self.serialize("SELECT", self.get_table_name(),
                              "WHERE id = \'" + str(self.ident) + "\'")

    def get_select_statement_mogrified(self, dbif=None):
        """Return the select statement as mogrified string

           :param dbif: The database interface to be used,
                        if None a temporary connection will be established
           :return: The SELECT string
        """
        if not dbif:
            dbif = SQLDatabaseInterfaceConnection()

        return dbif.mogrify_sql_statement(self.get_select_statement(),
                                          mapset=self.mapset)

    def select(self, dbif=None):
        """Select the content from the temporal database and store it
           in the internal dictionary structure

           :param dbif: The database interface to be used,
                        if None a temporary connection will be established
        """
        sql, args = self.get_select_statement()
        #print(sql)
        #print(args)

        if dbif:
            if len(args) == 0:
                dbif.execute(sql,  mapset=self.mapset)
            else:
                dbif.execute(sql, args,  mapset=self.mapset)
            row = dbif.fetchone(mapset=self.mapset)
        else:
            dbif = SQLDatabaseInterfaceConnection()
            dbif.connect()
            if len(args) == 0:
                dbif.execute(sql, mapset=self.mapset)
            else:
                dbif.execute(sql, args, mapset=self.mapset)
            row = dbif.fetchone(mapset=self.mapset)
            dbif.close()

        # Nothing found
        if row is None:
            return False

        if len(row) > 0:
            self.deserialize(row)
        else:
            self.msgr.fatal(_("Object <%s> not found in the temporal database")
                            % self.get_id())

        return True

    def get_insert_statement(self):
        """Return the sql statement and the argument
           list in database specific style
           :return: The INSERT string"""
        return self.serialize("INSERT", self.get_table_name())

    def get_insert_statement_mogrified(self, dbif=None):
        """Return the insert statement as mogrified string

           :param dbif: The database interface to be used,
                        if None a temporary connection will be established
           :return: The INSERT string
        """
        if not dbif:
            dbif = SQLDatabaseInterfaceConnection()

        return dbif.mogrify_sql_statement(self.get_insert_statement(),
                                          mapset=self.mapset)

    def insert(self, dbif=None):
        """Serialize the content of this object and store it in the temporal
           database using the internal identifier

           :param dbif: The database interface to be used,
                        if None a temporary connection will be established
        """
        sql, args = self.get_insert_statement()
        #print(sql)
        #print(args)

        if dbif:
            dbif.execute(sql, args, mapset=self.mapset)
        else:
            dbif = SQLDatabaseInterfaceConnection()
            dbif.connect()
            dbif.execute(sql, args, mapset=self.mapset)
            dbif.close()

    def get_update_statement(self, ident=None):
        """Return the sql statement and the argument list
           in database specific style

           :param ident: The identifier to be updated, useful for renaming
           :return: The UPDATE string

           """
        if ident:
            return self.serialize("UPDATE", self.get_table_name(),
                                  "WHERE id = \'" + str(ident) + "\'")
        else:
            return self.serialize("UPDATE", self.get_table_name(),
                                  "WHERE id = \'" + str(self.ident) + "\'")

    def get_update_statement_mogrified(self, dbif=None, ident=None):
        """Return the update statement as mogrified string

           :param dbif: The database interface to be used,
                        if None a temporary connection will be established
           :param ident: The identifier to be updated, useful for renaming
           :return: The UPDATE string
        """
        if not dbif:
            dbif = SQLDatabaseInterfaceConnection()

        return dbif.mogrify_sql_statement(self.get_update_statement(ident),
                                          mapset=self.mapset)

    def update(self, dbif=None, ident=None):
        """Serialize the content of this object and update it in the temporal
           database using the internal identifier

           Only object entries which are exists (not None) are updated

           :param dbif: The database interface to be used,
                        if None a temporary connection will be established
           :param ident: The identifier to be updated, useful for renaming
        """
        if self.ident is None:
            self.msgr.fatal(_("Missing identifier"))

        sql, args = self.get_update_statement(ident)
        #print(sql)
        #print(args)

        if dbif:
            dbif.execute(sql, args, mapset=self.mapset)
        else:
            dbif = SQLDatabaseInterfaceConnection()
            dbif.connect()
            dbif.execute(sql, args, mapset=self.mapset)
            dbif.close()

    def get_update_all_statement(self, ident=None):
        """Return the sql statement and the argument
           list in database specific style

           :param ident: The identifier to be updated, useful for renaming
           :return: The UPDATE string
           """
        if ident:
            return self.serialize("UPDATE ALL", self.get_table_name(),
                                  "WHERE id = \'" + str(ident) + "\'")
        else:
            return self.serialize("UPDATE ALL", self.get_table_name(),
                                  "WHERE id = \'" + str(self.ident) + "\'")

    def get_update_all_statement_mogrified(self, dbif=None, ident=None):
        """Return the update all statement as mogrified string

           :param dbif: The database interface to be used,
                        if None a temporary connection will be established
           :param ident: The identifier to be updated, useful for renaming
           :return: The UPDATE string
        """
        if not dbif:
            dbif = SQLDatabaseInterfaceConnection()

        return dbif.mogrify_sql_statement(self.get_update_all_statement(ident),
                                          mapset=self.mapset)

    def update_all(self, dbif=None, ident=None):
        """Serialize the content of this object, including None objects,
        and update it in the temporal database using the internal identifier

           :param dbif: The database interface to be used,
                        if None a temporary connection will be established
           :param ident: The identifier to be updated, useful for renaming
        """
        if self.ident is None:
            self.msgr.fatal(_("Missing identifier"))

        sql, args = self.get_update_all_statement(ident)
        #print(sql)
        #print(args)

        if dbif:
            dbif.execute(sql, args, mapset=self.mapset)
        else:
            dbif = SQLDatabaseInterfaceConnection()
            dbif.connect()
            dbif.execute(sql, args, mapset=self.mapset)
            dbif.close()

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


class DatasetBase(SQLDatabaseInterface):
    """This is the base class for all maps and spacetime datasets storing
        basic identification information

        Usage:

        .. code-block:: python

            >>> init()
            >>> t = DatasetBase("raster", "soil@PERMANENT", creator="soeren", ctime=datetime(2001,1,1), ttype="absolute")
            >>> t.id
            'soil@PERMANENT'
            >>> t.name
            'soil'
            >>> t.mapset
            'PERMANENT'
            >>> t.creator
            'soeren'
            >>> t.ctime
            datetime.datetime(2001, 1, 1, 0, 0)
            >>> t.ttype
            'absolute'
            >>> t.print_info()
             +-------------------- Basic information -------------------------------------+
             | Id: ........................ soil@PERMANENT
             | Name: ...................... soil
             | Mapset: .................... PERMANENT
             | Creator: ................... soeren
             | Temporal type: ............. absolute
             | Creation time: ............. 2001-01-01 00:00:00
            >>> t.print_shell_info()
            id=soil@PERMANENT
            name=soil
            mapset=PERMANENT
            creator=soeren
            temporal_type=absolute
            creation_time=2001-01-01 00:00:00

    """

    def __init__(self, table=None, ident=None, name=None, mapset=None,
                 creator=None, ctime=None, ttype=None):
        """Constructor

            :param table: The name of the temporal database table
                          that should be used to store the values
            :param ident: The unique identifier must be a combination of
                          the dataset name, layer name and the mapset
                          "name@mapset" or "name:layer@mapset"
                          used as as primary key in the temporal database
            :param name: The name of the map or dataset
            :param mapset: The name of the mapset
            :param creator: The name of the creator
            :param ctime: The creation datetime object
            :param ttype: The temporal type

                              - "absolute" Identifier for absolute time
                              - "relative" Identifier for relative time
        """

        SQLDatabaseInterface.__init__(self, table, ident)

        self.set_id(ident)
        if ident is not None and name is None and mapset is None:
            if ident.find("@") >= 0:
                name, mapset = ident.split("@")
            if name.find(":") >= 0:
                name, layer = ident.split(":")
        self.set_name(name)
        self.set_mapset(mapset)
        self.set_creator(creator)
        self.set_ctime(ctime)
        self.set_ttype(ttype)

    def set_id(self, ident):
        """Convenient method to set the unique identifier (primary key)

           :param ident: The unique identifier must be a combination
                         of the dataset name, layer name and the mapset
                         "name@mapset" or "name:layer@mapset"
        """
        self.ident = ident
        self.D["id"] = ident

        if ident is not None:
            if ident.find("@") >= 0:
                name, mapset = ident.split("@")
                self.set_mapset(mapset)
                self.set_name(name)
            else:
                self.msgr.fatal(_("Wrong identifier, the mapset is missing"))
            if name.find(":") >= 0:
                name, layer = ident.split(":")
                self.set_layer(layer)
            self.set_name(name)

    def set_name(self, name):
        """Set the name of the dataset

           :param name: The name of the dataset
        """
        self.D["name"] = name

    def set_mapset(self, mapset):
        """Set the mapset of the dataset

           :param mapset: The name of the mapset in which this dataset is stored
        """
        self.D["mapset"] = mapset

    def set_layer(self, layer):
        """Convenient method to set the layer of the map (part of primary key)

           Layer are supported for vector maps

           :param layer: The layer of the map
        """
        self.D["layer"] = layer

    def set_creator(self, creator):
        """Set the creator of the dataset

           :param creator: The name of the creator
        """
        self.D["creator"] = creator

    def set_ctime(self, ctime=None):
        """Set the creation time of the dataset,
           if nothing set the current time is used

           :param ctime: The current time of type datetime
        """
        if ctime is None:
            self.D["creation_time"] = datetime.today()
        else:
            self.D["creation_time"] = ctime

    def set_ttype(self, ttype):
        """Set the temporal type of the dataset: absolute or relative,
           if nothing set absolute time will assumed

           :param ttype: The temporal type of the dataset "absolute or relative"
        """
        if ttype is None or (ttype != "absolute" and ttype != "relative"):
            self.D["temporal_type"] = "absolute"
        else:
            self.D["temporal_type"] = ttype

    def get_id(self):
        """Convenient method to get the unique identifier (primary key)

           :return: None if not found
        """
        if "id" in self.D:
            return self.D["id"]
        else:
            return None

    def get_map_id(self):
        """Convenient method to get the unique map identifier
           without layer information

           :return: the name of the vector map as "name@mapset"
                  or None in case the id was not set
        """
        if self.id:
            if self.id.find(":") >= 0:
                # Remove the layer identifier from the id
                return self.id.split("@")[0].split(":")[0] + "@" + \
                       self.id.split("@")[1]
            else:
                return self.id
        else:
            return None

    def get_layer(self):
        """Convenient method to get the layer of the map (part of primary key)

           Layer are currently supported for vector maps

           :return: None if not found
        """
        if "layer" in self.D:
            return self.D["layer"]
        else:
            return None

    def get_name(self):
        """Get the name of the dataset
           :return: None if not found"""
        if "name" in self.D:
            return self.D["name"]
        else:
            return None

    def get_mapset(self):
        """Get the name of mapset of this dataset
           :return: None if not found"""
        if "mapset" in self.D:
            return self.D["mapset"]
        else:
            return None

    def get_creator(self):
        """Get the creator of the dataset
           :return: None if not found"""
        if "creator" in self.D:
            return self.D["creator"]
        else:
            return None

    def get_ctime(self):
        """Get the creation time of the dataset, datatype is datetime
           :return: None if not found"""
        if "creation_time" in self.D:
            return self.D["creation_time"]
        else:
            return None

    def get_ttype(self):
        """Get the temporal type of the map
           :return: None if not found"""
        if "temporal_type" in self.D:
            return self.D["temporal_type"]
        else:
            return None

    # Properties of this class
    id = property(fget=get_id, fset=set_id)
    map_id = property(fget=get_map_id, fset=None)
    name = property(fget=get_name, fset=set_name)
    mapset = property(fget=get_mapset, fset=set_mapset)
    ctime = property(fget=get_ctime, fset=set_ctime)
    ttype = property(fget=get_ttype, fset=set_ttype)
    creator = property(fget=get_creator, fset=set_creator)

    def print_info(self):
        """Print information about this class in human readable style"""
        #      0123456789012345678901234567890
        print( " +-------------------- Basic information -------------------------------------+")
        print( " | Id: ........................ " + str(self.get_id()))
        print(" | Name: ...................... " + str(self.get_name()))
        print(" | Mapset: .................... " + str(self.get_mapset()))
        if self.get_layer():
            print(" | Layer:...................... " + str(self.get_layer()))
        print(" | Creator: ................... " + str(self.get_creator()))
        print(" | Temporal type: ............. " + str(self.get_ttype()))
        print(" | Creation time: ............. " + str(self.get_ctime()))

    def print_shell_info(self):
        """Print information about this class in shell style"""
        print("id=" + str(self.get_id()))
        print("name=" + str(self.get_name()))
        print("mapset=" + str(self.get_mapset()))
        if self.get_layer():
            print("layer=" + str(self.get_layer()))
        print("creator=" + str(self.get_creator()))
        print("temporal_type=" + str(self.get_ttype()))
        print("creation_time=" + str(self.get_ctime()))

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


class RasterBase(DatasetBase):
    """Time stamped raster map base information class"""
    def __init__(self, ident=None, name=None, mapset=None, creator=None,
                 creation_time=None, temporal_type=None):
        DatasetBase.__init__(self, "raster_base", ident, name, mapset,
                             creator, creation_time, temporal_type)


class Raster3DBase(DatasetBase):
    """Time stamped 3D raster map base information class"""
    def __init__(self, ident=None, name=None, mapset=None, creator=None,
                 creation_time=None, temporal_type=None,):
        DatasetBase.__init__(self, "raster3d_base", ident, name,
                             mapset, creator, creation_time,
                             temporal_type)


class VectorBase(DatasetBase):
    """Time stamped vector map base information class"""
    def __init__(self, ident=None, name=None, mapset=None, layer=None,
                 creator=None, creation_time=None, temporal_type=None):
        DatasetBase.__init__(self, "vector_base", ident, name, mapset,
                             creator, creation_time, temporal_type)

        self.set_id(ident)
        if ident is not None and name is None and mapset is None:
            if ident.find("@") >= 0:
                name, mapset = ident.split("@")
            if layer is None:
                if name.find(":") >= 0:
                    name, layer = name.split(":")
        self.set_name(name)
        self.set_mapset(mapset)
        # Layer currently only in use by vector maps
        self.set_layer(layer)

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


class STDSBase(DatasetBase):
    """Base class for space time datasets

       This class adds the semantic type member variable to the dataset
       base class.

    Usage:

    .. code-block:: python

        >>> init()
        >>> t = STDSBase("stds", "soil@PERMANENT", semantic_type="average", creator="soeren", ctime=datetime(2001,1,1), ttype="absolute", mtime=datetime(2001,1,1))
        >>> t.semantic_type
        'average'
        >>> t.print_info()
         +-------------------- Basic information -------------------------------------+
         | Id: ........................ soil@PERMANENT
         | Name: ...................... soil
         | Mapset: .................... PERMANENT
         | Creator: ................... soeren
         | Temporal type: ............. absolute
         | Creation time: ............. 2001-01-01 00:00:00
         | Modification time:.......... 2001-01-01 00:00:00
         | Semantic type:.............. average
        >>> t.print_shell_info()
        id=soil@PERMANENT
        name=soil
        mapset=PERMANENT
        creator=soeren
        temporal_type=absolute
        creation_time=2001-01-01 00:00:00
        modification_time=2001-01-01 00:00:00
        semantic_type=average

    """
    def __init__(self, table=None, ident=None, name=None, mapset=None,
                 semantic_type=None, creator=None, ctime=None,
                 ttype=None, mtime=None):
        DatasetBase.__init__(self, table, ident, name, mapset, creator,
                             ctime, ttype)

        self.set_semantic_type(semantic_type)
        self.set_mtime(mtime)

    def set_semantic_type(self, semantic_type):
        """Set the semantic type of the space time dataset"""
        self.D["semantic_type"] = semantic_type

    def set_mtime(self, mtime=None):
        """Set the modification time of the space time dataset, if nothing set
           the current time is used
        """
        if mtime is None:
            self.D["modification_time"] = datetime.now()
        else:
            self.D["modification_time"] = mtime

    def get_semantic_type(self):
        """Get the semantic type of the space time dataset
           :return: None if not found
        """
        if "semantic_type" in self.D:
            return self.D["semantic_type"]
        else:
            return None

    def get_mtime(self):
        """Get the modification time of the space time dataset, datatype is
           datetime

           :return: None if not found
        """
        if "modification_time" in self.D:
            return self.D["modification_time"]
        else:
            return None

    semantic_type = property(fget=get_semantic_type, fset=set_semantic_type)

    def print_info(self):
        """Print information about this class in human readable style"""
        DatasetBase.print_info(self)
        #      0123456789012345678901234567890
        print(" | Modification time:.......... " + str(self.get_mtime()))
        print(" | Semantic type:.............. " + str(
            self.get_semantic_type()))

    def print_shell_info(self):
        """Print information about this class in shell style"""
        DatasetBase.print_shell_info(self)
        print("modification_time=" + str(self.get_mtime()))
        print("semantic_type=" + str(self.get_semantic_type()))

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


class STRDSBase(STDSBase):
    """Space time raster dataset base information class"""
    def __init__(self, ident=None, name=None, mapset=None,
                 semantic_type=None, creator=None, ctime=None,
                 ttype=None):
        STDSBase.__init__(self, "strds_base", ident, name, mapset,
                          semantic_type, creator, ctime,
                          ttype)


class STR3DSBase(STDSBase):
    """Space time 3D raster dataset base information class"""
    def __init__(self, ident=None, name=None, mapset=None,
                 semantic_type=None, creator=None, ctime=None,
                 ttype=None):
        STDSBase.__init__(self, "str3ds_base", ident, name, mapset,
                          semantic_type, creator, ctime,
                          ttype)


class STVDSBase(STDSBase):
    """Space time vector dataset base information class"""
    def __init__(self, ident=None, name=None, mapset=None,
                 semantic_type=None, creator=None, ctime=None,
                 ttype=None):
        STDSBase.__init__(self, "stvds_base", ident, name, mapset,
                          semantic_type, creator, ctime,
                          ttype)

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


class AbstractSTDSRegister(SQLDatabaseInterface):
    """This is the base class for all maps to store the space time datasets
       as comma separated string in which they are registered

        Usage:

        .. code-block:: python

            >>> init()
            >>> t = AbstractSTDSRegister("raster", "soil@PERMANENT", "A@P,B@P,C@P")
            >>> t.id
            'soil@PERMANENT'
            >>> t.registered_stds
            'A@P,B@P,C@P'

    """

    def __init__(self, table=None, ident=None, registered_stds=None):
        """Constructor

            :param table: The name of the temporal database table
                          that should be used to store the values
            :param ident: The unique identifier must be a combination of
                          the dataset name, layer name and the mapset
                          "name@mapset" or "name:layer@mapset"
                          used as as primary key in the temporal database
            :param stds: A comma separated list of space time dataset ids
        """

        SQLDatabaseInterface.__init__(self, table, ident)

        self.set_id(ident)
        self.set_registered_stds(registered_stds)

    def set_id(self, ident):
        """Convenient method to set the unique identifier (primary key)

           :param ident: The unique identifier must be a combination
                         of the dataset name, layer name and the mapset
                         "name@mapset" or "name:layer@mapset"
        """
        self.ident = ident
        self.D["id"] = ident

    def set_registered_stds(self, registered_stds):
        """Get the comma separated list of space time datasets ids
           in which this map is registered

           :param registered_stds: A comma separated list of space time
                                   dataset ids in which this map is registered
        """
        self.D["registered_stds"] = registered_stds

    def get_id(self):
        """Convenient method to get the unique identifier (primary key)

           :return: None if not found
        """
        if "id" in self.D:
            return self.D["id"]
        else:
            return None

    def get_registered_stds(self):
        """Get the comma separated list of space time datasets ids
           in which this map is registered

           :return: None if not found
        """
        if "registered_stds" in self.D:
            return self.D["registered_stds"]
        else:
            return None

    # Properties of this class
    id = property(fget=get_id, fset=set_id)
    registered_stds = property(fget=get_registered_stds,
                               fset=set_registered_stds)

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


class RasterSTDSRegister(AbstractSTDSRegister):
    """Time stamped raster map base information class"""
    def __init__(self, ident=None, registered_stds=None):
        AbstractSTDSRegister.__init__(self, "raster_stds_register", ident,
                                      registered_stds)


class Raster3DSTDSRegister(AbstractSTDSRegister):
    """Time stamped 3D raster map base information class"""
    def __init__(self, ident=None, registered_stds=None):
        AbstractSTDSRegister.__init__(self, "raster3d_stds_register", ident,
                                      registered_stds)


class VectorSTDSRegister(AbstractSTDSRegister):
    """Time stamped vector map base information class"""
    def __init__(self, ident=None, registered_stds=None):
        AbstractSTDSRegister.__init__(self, "vector_stds_register", ident,
                                      registered_stds)

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

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