Note that there are some explanatory texts on larger screens.

plurals
  1. POEnforce/check uniqueness of primary key across multiple tables
    primarykey
    data
    text
    <p>I'm doing a data format conversion from Program A's CSV format to Program B's CSV format.</p> <p>Program A's format looks like:</p> <pre><code>Fruit, Orange, $1.99 Fruit, Apple, $2.99 Fruit, Pear, $5.99 Colour, Red, #FF0000 Colour, Green, #00FF00 Colour, Blue, #0000FF Colour, Orange, #FF8800 </code></pre> <p>I've converted Program A's CSV file into an SQLite database containing multiple tables, one for each type of record in the original CSV file. Here that would be <code>Fruit</code> and <code>Colour</code>. This maps well onto Program B's file format, which uses similar tables (with a few funky conversions required.)</p> <p>Each table in Program A's CSV file has an ID primary key which is not required to be unique. That is, there can be a "<code>Fruit</code>" row with ID "<code>Orange</code>" and also a "<code>Colour</code>" row with ID "<code>Orange</code>".</p> <p><em>However Program B would consider this an error</em> - it requires the ID primary key to be unique across ALL tables.</p> <p>What is an efficient way to detect non-unique ID keys, either in the original file (formatted like above) or in the SQL database? There are dozens of tables and thousands of records.</p> <p>My current approach is similar to (Python code):</p> <pre><code>import sqlite3, collections db_conn = sqlite3.connect('db.sqlite3') db_conn.row_factory = sqlite3.Row IDs = [] # build a list of (ID, table_name) pairs tables = ['Fruit','Colour']; for table in tables: rows = db_conn.execute("SELECT ID FROM %s" % table) for row in rows: IDs.append( (row['ID'],table) ) id_counts = collections.Counter([x(0) for x in IDs]) duplicated_ids = [x for x in id_counts if id_counts[x] &gt; 1] for duplicated_id in duplicated_ids: duplicated_types = [x(1) for x in IDs if x(0) == duplicated_id ] print ("Duplicate ID %(duplicated_id)s used for %(duplicated_types)s" % locals()) </code></pre> <p>This seems hilariously inefficient. There must exist a more elegant/more Pythonic way of doing this, possibly using some kind of set notation.</p> <p>Alternately, could I define my SQL schema (SQLite flavoured) so that SQLite enforces uniqueness of the ID across all tables?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload