16 | | raise NotImplementedError |
| 35 | """ |
| 36 | Returns a dictionary of {field_index: (field_index_other_table, other_table)} |
| 37 | representing all relationships to the given table. Indexes are 0-based. |
| 38 | """ |
| 39 | my_field_dict = _name_to_index(cursor, table_name) |
| 40 | constraints = [ ] |
| 41 | relations = {} |
| 42 | |
| 43 | try: |
| 44 | # This should work for MySQL 5.0 |
| 45 | # Shouldn't we limit the select to table_schema? |
| 46 | cursor.execute( |
| 47 | """select column_name, referenced_table_name, referenced_column_name |
| 48 | from information_schema.key_column_usage |
| 49 | where table_name = %s |
| 50 | and referenced_table_name is not null |
| 51 | and referenced_column_name is not null""", |
| 52 | [table_name]) |
| 53 | constraints.extend(cursor.fetchall()) |
| 54 | except OperationalError: |
| 55 | # Fall back to `show create table` |
| 56 | # go through all constraints (== matches) and save these |
| 57 | cursor.execute("SHOW CREATE TABLE "+ table_name) |
| 58 | for row in cursor.fetchall(): |
| 59 | pos = 0 |
| 60 | while True: |
| 61 | match = FKEY_PARSER.search(row[1], pos) |
| 62 | if match == None: |
| 63 | break |
| 64 | pos = match.end() |
| 65 | constraints.append(match.groups()) |
| 66 | |
| 67 | # handle constraints. (can't do this in the loop above since we need the cursor in both places) |
| 68 | for (my_fieldname, other_table, other_field) in constraints: |
| 69 | other_field_index = _name_to_index(cursor, other_table)[other_field] |
| 70 | my_field_index = my_field_dict[my_fieldname] |
| 71 | relations[my_field_index] = (other_field_index, other_table) |
| 72 | return relations |