code_junkie

How do I cleanly extract MySQL enum values in Perl?

Nov 11th, 2011
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. sub enum_values {
  2. my ( $self, $schema, $table, $column ) = @_;
  3.  
  4. # don't eval to let the error bubble up
  5. my $columns = $schema->storage->dbh->selectrow_hashref(
  6. "SHOW COLUMNS FROM `$table` like ?",
  7. {},
  8. $column
  9. );
  10.  
  11. unless ($columns) {
  12. X::Internal::Database::UnknownColumn->throw(
  13. column => $column,
  14. table => $table,
  15. );
  16. }
  17.  
  18. my $type = $columns->{Type} or X::Panic->throw(
  19. details => "Could not determine type for $table.$column",
  20. );
  21.  
  22. unless ( $type =~ /Aenum((.*))z/ ) {
  23. X::Internal::Database::IncorrectTypeForColumn->throw(
  24. type_wanted => 'enum',
  25. type_found => $type,
  26. );
  27. }
  28. $type = $1;
  29.  
  30. require Text::CSV_XS;
  31. my $csv = Text::CSV_XS->new;
  32. $csv->parse($type) or X::Panic->throw(
  33. details => "Could not parse enum CSV data: ".$csv->error_input,
  34. );
  35. return map { /A'(.*)'z/; $1 }$csv->fields;
  36. }
  37.  
  38. my $sth = $dbh->column_info(undef, undef, 'mytable', '%');
  39.  
  40. foreach my $col_info ($sth->fetchrow_hashref)
  41. {
  42. if($col_info->{'TYPE_NAME'} eq 'ENUM')
  43. {
  44. # The mysql_values key contains a reference to an array of valid enum values
  45. print "Valid enum values for $col_info->{'COLUMN_NAME'}: ",
  46. join(', ', @{$col_info->{'mysql_values'}}), "n";
  47. }
  48. ...
  49. }
  50.  
  51. my @fields = $type =~ / ' ([^']+) ' (?:,|z) /msgx;
Add Comment
Please, Sign In to add comment