Skip to content

Instantly share code, notes, and snippets.

@t33chong
Created July 15, 2014 01:48
Show Gist options
  • Select an option

  • Save t33chong/4baa0171fb4bce6e9955 to your computer and use it in GitHub Desktop.

Select an option

Save t33chong/4baa0171fb4bce6e9955 to your computer and use it in GitHub Desktop.
Is there a way to avoid having to select in order to get the UID after inserting a new row?
def get_location_uid(name, country_code):
# TODO: DRY, figure out a better way to do this
cursor.execute("SELECT uid FROM location WHERE name = '%s' AND country_code = '%s'" % (name, country_code))
result = cursor.fetchone()
if result is not None:
return result[0]
cursor.execute("INSERT INTO location (name, country_code) VALUES ('%s', '%s')" % (name, country_code))
db.commit()
cursor.execute("SELECT uid FROM location WHERE name = '%s' AND country_code = '%s'" % (name, country_code))
result = cursor.fetchone()
return result[0]
@t33chong
Copy link
Author

Here's the schema for the location table:

CREATE TABLE location (
  uid bytea PRIMARY KEY NOT NULL DEFAULT generate_uid() CHECK (octet_length(uid)=12),
  name text NOT NULL,
  country_code text NOT NULL,
  CONSTRAINT loc_constraint UNIQUE (name, country_code)
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment