示例#1
0
def _get_sqlite_col_length(layer, fieldname):
    """
    Get the length of a sqlite based column using the metadata

    NOTE: SQLITE doesn't support this. And this is a bit of a hack.

    NOTE NOTE: Looks for VARCHAR(...) as the datatype which isn't really a
    sqlite data type.

    :returns: True, length if column is found in table metadata
    """
    source = layer.source()
    if ".sqlite" not in source:
        return False, 0

    database = Database.fromLayer(layer)
    uri = QgsDataSourceUri(layer.dataProvider().dataSourceUri())
    layer = uri.quotedTablename()

    try:
        tabledata = list(database.query("pragma table_info({})".format(layer)))
        for row in tabledata:
            if not row['name'] == fieldname:
                continue

            import re
            # Look for varchar(...) so we can grab the length.
            match = re.search("VARCHAR\((\d.*)\)", row['type'], re.IGNORECASE)
            if match:
                length = match.group(1)
                return True, int(length)
    except DatabaseException:
        pass
    finally:
        database.close()

    return False, 0