Example #1
0
    def whichdb(filename):
        """Guess which db package to use to open a db file.
        
        Return values:
        
        - None if the database file can't be read;
        - empty string if the file can be read but can't be recognized
        - the name of the dbm submodule (e.g. 'ndbm' or 'gnu') if recognized.
        
        Importing the given module may still fail, and opening the
        database using that module may still fail.
        
        - Actually it is a bit extended  form of `whichdb.whichdb`
        that accounts for `sqlite3`
        """

        tst = _whichdb(filename)
        if tst or tst is None: return tst

        if issqlite3(filename): return "sqlite3"

        return tst
Example #2
0
        def whichdb(filename):
            """Guess which db package to use to open a db file.

            Return values:
            
            - None if the database file can't be read;
            - empty string if the file can be read but can't be recognized
            - the name of the dbm submodule (e.g. 'ndbm' or 'gnu') if recognized.
            
            Importing the given module may still fail, and opening the
            database using that module may still fail.
            
            - Actually it is a bit extended  form of `dbm.whichdb`
            that accounts for `bsddb3` and `sqlite3`
            """

            ## use the standard function
            tst = dbm.whichdb(filename)

            ## identified or non-existing DB  ?
            if tst or tst is None: return tst

            ## non-identified DB

            ## check for bsddb magic numbers (from python2)
            try:
                with io.open(filename, 'rb') as f:
                    # Read the start of the file -- the magic number
                    s16 = f.read(16)
            except OSError:
                return None

            s = s16[0:4]

            # Return "" if not at least 4 bytes
            if len(s) != 4:
                return ""

            # Convert to 4-byte int in native byte order -- return "" if impossible
            try:
                (magic, ) = struct.unpack("=l", s)
            except struct.error:
                return ""

            # Check for GNU dbm
            if magic in (0x13579ace, 0x13579acd, 0x13579acf):
                return "dbm.gnu"

            # Check for old Berkeley db hash file format v2
            if magic in (0x00061561, 0x61150600):
                return "bsddb185"

            # Later versions of Berkeley db hash file have a 12-byte pad in
            # front of the file type
            try:
                (magic, ) = struct.unpack("=l", s16[-4:])
            except struct.error:
                return ""

            # Check for BSD hash
            if magic in (0x00061561, 0x61150600):
                return "bsddb3"

            if issqlite3(filename): return 'sqlite3'

            # Unknown
            return ""