58 | | raise NotImplementedError |
| 58 | """ |
| 59 | Returns a dictionary of {field_index: (field_index_other_table, other_table)} |
| 60 | representing all relationships to the given table. Indexes are 0-based. |
| 61 | """ |
| 62 | |
| 63 | import re |
| 64 | |
| 65 | # Dictionary of relations to return |
| 66 | relations = {} |
| 67 | |
| 68 | # Schema for this table |
| 69 | cursor.execute("select sql from sqlite_master where tbl_name='%s'" % table_name) |
| 70 | results = cursor.fetchone()[0].strip() |
| 71 | results = results.split('(', 1)[1] |
| 72 | results = results.rsplit(')', 1)[0] |
| 73 | |
| 74 | # walk through and look for references to other tables. |
| 75 | for index, i in enumerate(results.split(',')): |
| 76 | i = i.strip() |
| 77 | if i.startswith("UNIQUE"): |
| 78 | continue |
| 79 | |
| 80 | m = re.search('references (.*) \(["|](.*)["|]\)', i, re.I) |
| 81 | |
| 82 | if not m: |
| 83 | continue |
| 84 | |
| 85 | table, column = m.groups() |
| 86 | |
| 87 | table = table.strip('"') |
| 88 | column = column.strip('"') |
| 89 | |
| 90 | cursor.execute("select sql from sqlite_master where tbl_name='%s'" % table) |
| 91 | |
| 92 | other_table_results = cursor.fetchone()[0].strip() |
| 93 | other_table_results = other_table_results.split('(', 1)[1] |
| 94 | other_table_results = other_table_results.rsplit(')', 1)[0] |
| 95 | |
| 96 | second_index = None |
| 97 | for _index, j in enumerate(other_table_results.split(',')): |
| 98 | j = j.strip() |
| 99 | if j.startswith('UNIQUE'): |
| 100 | continue |
| 101 | |
| 102 | name = j.split(' ', 1)[0].strip('"') |
| 103 | if name == column: |
| 104 | second_index = _index |
| 105 | |
| 106 | if second_index != None: |
| 107 | relations[index] = (second_index, table) |
| 108 | |
| 109 | return relations |