Guest User

Untitled

a guest
Jan 22nd, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. #!/usr/bin/perl
  2. #
  3. # This program manages the star database used by glyphinator
  4. # It performs the following functions:
  5. #
  6. # * Fill star db from probe data
  7. # * Merge a second db into the main one
  8.  
  9. use strict;
  10. use warnings;
  11.  
  12. use DBI;
  13. use FindBin;
  14. use Getopt::Long;
  15. use POSIX qw(strftime);
  16.  
  17. use lib "$FindBin::Bin/../lib";
  18. use Text::CSV_XS;
  19.  
  20. my %opts;
  21. GetOptions( \%opts, 'h|help', 'v|verbose', 'q|quiet', 'db=s', 'csv=s' );
  22.  
  23. usage() if $opts{h};
  24.  
  25. my $star_db = DBI->connect("dbi:SQLite:$opts{db}")
  26. or die "Can't open star database $opts{db}: $DBI::errstr\n";
  27. $star_db->{RaiseError} = 1;
  28. $star_db->{PrintError} = 0;
  29. $star_db->{AutoCommit} = 0;
  30.  
  31. my $clear_stars_table
  32. = $star_db->prepare_cached(
  33. 'delete from stars'
  34. );
  35. my $clear_orbitals_table
  36. = $star_db->prepare_cached(
  37. 'delete from orbitals'
  38. );
  39.  
  40. my $insert_star
  41. = $star_db->prepare_cached(
  42. 'insert into stars (id, name, x, y, color, zone, last_checked) values (?,?,?,?,?,?,?)'
  43. );
  44.  
  45. my $insert_orbital = $star_db->prepare_cached(
  46. 'insert into orbitals (star_id, orbit, x, y) values (?,?,?,?)' );
  47.  
  48. my $when = strftime "%Y-%m-%d %T", gmtime;
  49.  
  50. my $planets = [
  51. sub { ( 1, $_[0] + 1, $_[1] + 2 ) }, # Orbit 1: X+1, Y+2
  52. sub { ( 2, $_[0] + 2, $_[1] + 1 ) }, # Orbit 2: X+2, Y+1
  53. sub { ( 3, $_[0] + 2, $_[1] - 1 ) }, # Orbit 3: X+2, Y-1
  54. sub { ( 4, $_[0] + 1, $_[1] - 2 ) }, # Orbit 4: X+1, Y-2
  55. sub { ( 5, $_[0] - 1, $_[1] - 2 ) }, # Orbit 5: X-1, Y-2
  56. sub { ( 6, $_[0] - 2, $_[1] - 1 ) }, # Orbit 6: X-2, Y-1
  57. sub { ( 7, $_[0] - 2, $_[1] + 1 ) }, # Orbit 7: X-2, Y+1
  58. sub { ( 8, $_[0] - 1, $_[1] + 2 ) }, # Orbit 8: X-1, Y+2
  59. ];
  60.  
  61. my $csv = Text::CSV_XS->new( { binary => 1 } )
  62. or die "Cannot use CSV: " . Text::CSV_XS->error_diag();
  63. open my $fh, "<:encoding(utf8)", $opts{csv} or die "$opts{csv}: $!";
  64. $clear_stars_table->execute();
  65. $clear_orbitals_table->execute();
  66. while ( my $row = $csv->getline($fh) ) {
  67.  
  68. my ( $id, $name, $x, $y, $color, $zone ) = @$row;
  69. warn "Inserting star $name at $x, $y\n";
  70. $insert_star->execute( $id, $name, $x, $y, $color, $zone, $when )
  71. or die "Can't insert star: " . $insert_star->errstr;
  72.  
  73. for my $extrapolate (@$planets) {
  74. my ( $orbit, $x, $y ) = $extrapolate->( $x, $y );
  75. $insert_orbital->execute( $id, $orbit, $x, $y );
  76. }
  77. }
  78. $csv->eof or $csv->error_diag();
  79. close $fh;
  80.  
  81. $star_db->commit;
  82.  
  83. sub usage { }
Add Comment
Please, Sign In to add comment