(connection, tables, apply_changes=True)
| 100 | |
| 101 | |
| 102 | def verify_database(connection, tables, apply_changes=True): |
| 103 | # type: (sqlite3.Connection, Sequence[TableSchema], bool) -> List[str] |
| 104 | result = [] |
| 105 | existing_tables = set((x[0].lower() for x in |
| 106 | connection.execute('SELECT name FROM sqlite_master where type=?', ('table',)))) |
| 107 | for table in tables: |
| 108 | queries = [] |
| 109 | if table.table_name.lower() in existing_tables: |
| 110 | column_info = connection.execute(f'PRAGMA table_info(\'{table.table_name}\')').fetchall() |
| 111 | column_info.sort(key=lambda x: x[0]) |
| 112 | columns = set((x[1].lower() for x in column_info)) |
| 113 | |
| 114 | pk_cols = [] |
| 115 | if table.owner_column: |
| 116 | pk_cols.append(table.owner_column) |
| 117 | pk_cols.extend(table.primary_key) |
| 118 | for col in pk_cols: |
| 119 | if col.lower() not in columns: |
| 120 | raise ValueError(f'Table \"{table.table_name}\" misses primary key \"{col}\".') |
| 121 | missing_columns = [x for x in table.columns if x.lower() not in columns] |
| 122 | for col in missing_columns: |
| 123 | field_schema = table.class_fields.get(col.lower()) |
| 124 | column_type = _to_sqlite_type(field_schema.type if field_schema else str) |
| 125 | queries.append(f'ALTER TABLE {table.table_name} ADD COLUMN {col} {column_type}') |
| 126 | |
| 127 | if table.indexes: |
| 128 | index_names = [x[1] for x in connection.execute(f'PRAGMA index_list(\'{table.table_name}\')')] |
| 129 | indexes = {} |
| 130 | for index_name in index_names: |
| 131 | index_info = connection.execute(f'PRAGMA index_info(\'{index_name}\')').fetchall() |
| 132 | index_info.sort(key=lambda x: x[0]) |
| 133 | indexes[index_name.lower()] = [x[2] for x in index_info] |
| 134 | for index_name, index_columns in table.indexes.items(): |
| 135 | cols = [] |
| 136 | if table.owner_column: |
| 137 | cols.append(table.owner_column) |
| 138 | cols.extend(index_columns) |
| 139 | index_found = None |
| 140 | for existing_index_name, existing_index_columns in indexes.items(): |
| 141 | if len(existing_index_columns) != len(cols): |
| 142 | continue |
| 143 | if any(True for x in zip(existing_index_columns, cols) if x[0].lower() != x[1].lower()): |
| 144 | continue |
| 145 | index_found = existing_index_name |
| 146 | break |
| 147 | if index_found: |
| 148 | continue |
| 149 | index_name = f'{table.table_name}_{index_name}_IDX' |
| 150 | if index_name.lower() in indexes: |
| 151 | queries.append(f'DROP INDEX "{index_name}"') |
| 152 | queries.append(f'CREATE INDEX "{index_name}" ON {table.table_name} (' + ', '.join(cols) + ')') |
| 153 | else: |
| 154 | added_columns = set() |
| 155 | table_columns = [] |
| 156 | pks = [] |
| 157 | if table.owner_column: |
| 158 | pks.append(table.owner_column) |
| 159 | column_type = _to_sqlite_type(table.owner_column_type or str) |
nothing calls this directly
no test coverage detected