I am writing a simple database wrapper for sqlite as a learning experience. In doing so, I have been reading code for other, more complicated programs like Django. In the django.db.backends.sqlite3.introspection module, there is a method called get_primary_key_column in the DatabaseIntrospection class which is using re.search to find the primary key:
def get_primary_key_column(self, cursor, table_name):
"""
Get the column name of the primary key for the given table.
"""
# Don't use PRAGMA because that causes issues with some transactions
cursor.execute("SELECT sql FROM sqlite_master WHERE tbl_name = %s AND type = %s", [table_name, "table"])
row = cursor.fetchone()
if row is None:
raise ValueError("Table %s does not exist" % table_name)
results = row[0].strip()
results = results[results.index('(') + 1:results.rindex(')')]
for field_desc in results.split(','):
field_desc = field_desc.strip()
m = re.search('"(.*)".*PRIMARY KEY( AUTOINCREMENT)?$', field_desc)
if m:
return m.groups()[0]
return None
When I first saw this, I thought, "Now why don't they just use pragma table_info(foo) and pick out the pk from the last items of the returned tuple set?" Then I saw the comment # Don't use PRAGMA because that causes issues with some transactions which threw me for a loop. So my question is why not use the pragma statement? what issues could that possibly cause?
Aucun commentaire:
Enregistrer un commentaire