Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 30th, 2012  |  syntax: None  |  size: 1.07 KB  |  hits: 9  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. What's a good way to provide versioned rows in PostgreSQL? How to query them?
  2. id BigSerial, PRIMARY KEY  
  3. version Integer  
  4. text Text  
  5. origin BigInt
  6.        
  7. 1,0,"My Text, first Version",null  
  8. 2,1,"My Text, second Version",1  
  9. 3,0,"My 2nd Text v1",null  
  10. 4,1,"My 2nd Text v2",3
  11.        
  12. create temp table my_table (
  13.   id integer not null,
  14.   version integer not null check(version > 0),
  15.   -- Give a lot of thought to whether text should also be unique. *I* think
  16.   -- it probably should, but it's really application-dependent.
  17.   text Text not null unique,
  18.   primary key (id, version)
  19. );
  20.  
  21. insert into my_table values
  22. (1, 1, 'My Text, first Version'),
  23. (1, 2, 'My Text, second Version'),
  24. (2, 1, 'My 2nd text v1'),
  25. (2, 2, 'My 2nd text v2')
  26.        
  27. select id, count(*)
  28. from my_table
  29. group by id;
  30.        
  31. with current_ver as (
  32.   select id, max(version) as version
  33.   from my_table
  34.   group by id
  35. )
  36. select m.* from my_table m
  37. inner join current_ver c on c.id = m.id and c.version = m.version
  38.        
  39. select t.id
  40. from table parent
  41. left join table descendants on parent.id = descendants.origin
  42. where descendants.id is null;