4 HOME PGHOST PGPORT PGUSER PGDATABASE MIGSCHEMA
5 MIGBASEWORKDIR MIGBASEGITDIR MIGGITDIR MIGWORKDIR
7 use Net::Google::Spreadsheets;
8 use Net::Google::DataAPI::Auth::OAuth2;
9 use Net::OAuth2::AccessToken;
13 use lib "$FindBin::Bin/";
14 my $mig_bin = "$FindBin::Bin/";
18 HOME PGHOST PGPORT PGUSER PGDATABASE MIGSCHEMA
19 MIGBASEWORKDIR MIGBASEGITDIR MIGGITDIR MIGWORKDIR
27 pod2usage(-verbose => 2) if defined $ARGV[0] && $ARGV[0] eq '--help';
29 Mig::die_if_no_env_migschema();
30 die_if_gsheet_tracked_table_does_not_exist();
31 die_if_gsheet_tracked_column_does_not_exist();
45 foreach my $arg (@ARGV) {
46 if ($arg eq '--push') {
47 $next_arg_is_push = 1;
50 if ($next_arg_is_push) {
52 $next_arg_is_push = 0;
55 if ($arg eq '--pull') {
56 $next_arg_is_pull = 1;
59 if ($next_arg_is_pull) {
61 $next_arg_is_pull = 0;
64 if ($arg eq '--export') {
70 abort('must specify --push (db->worksheets) or --pull (worksheets->db)') unless (defined $cmd_push or defined $cmd_pull);
71 if (defined $cmd_push and defined $cmd_pull) { abort('you can not specify both a --push and --pull on the same command'); }
73 my $dbh = Mig::db_connect();
74 my $spreadsheet = connect_gsheet();
75 abort('could not connect to google sheet') unless (defined $spreadsheet);
77 $sql = 'SELECT tab_name FROM gsheet_tracked_table;';
78 $sth = $dbh->prepare($sql);
79 my $ra = $sth->execute();
80 while (my @row = $sth->fetchrow_array) {
81 push @tracked_ws_names, $row[0];
84 if (defined $cmd_pull) {
86 if ($cmd_pull eq 'all') {
87 print "all worksheets.\n";
88 @ws = $spreadsheet->worksheets;
89 foreach my $wsn (@ws) { push @worksheet_names, $wsn->title; }
91 print "only worksheet $cmd_pull.\n";
92 if (!defined $cmd_pull) { abort('command incomplete'); }
93 push @worksheet_names, $cmd_pull;
95 my @m = array_match(\@worksheet_names,\@tracked_ws_names);
97 my $pull_ws = $spreadsheet->worksheet( {title => $w} );
98 my $push_tb = get_table_name($MIGSCHEMA,$w,$dbh);
99 my @rows = $pull_ws->rows;
101 map { $content[$_->row - 1][$_->col - 1] = $_->content } $pull_ws->cells;
102 my @tab_headers = shift @content;
103 my $tab_headers_length = $#{ $tab_headers[0] };
105 for my $i ( 0 .. $tab_headers_length ) {
106 push @pg_headers, $tab_headers[0][$i];
109 #todo: check for clean headers at some point ...
110 truncate_table($MIGSCHEMA,$push_tb,$dbh);
111 print "Inserting from $w to $push_tb.\n";
112 for my $j (@content) {
113 insert_row($MIGSCHEMA,$push_tb,$dbh,\@pg_headers,$j);
115 timestamp($MIGSCHEMA,$push_tb,$dbh,'pull');
116 if ($cmd_export == 1) { export_table($dbh,$push_tb); }
120 if (defined $cmd_push) {
122 if ($cmd_push eq 'all') {
123 print "all tables.\n";
124 $sql = 'SELECT table_name FROM ' . $MIGSCHEMA . '.gsheet_tracked_table';
125 $sth = $dbh->prepare($sql);
126 $ra = $sth->execute();
127 while (my @row = $sth->fetchrow_array) {
128 push @table_names, $row[0];
131 print "only table $cmd_push.\n";
132 if (!defined $cmd_push) { abort('command incomplete'); }
133 push @table_names, $cmd_push;
135 foreach my $t (@table_names) {
136 my $pull_tb = $MIGSCHEMA . "." . $t;;
137 my @table_headers = get_pg_column_headers($t,$MIGSCHEMA);
138 my $push_ws_name = get_worksheet_name($MIGSCHEMA,$t,$dbh);
139 my $push_ws = $spreadsheet->worksheet( {title => $push_ws_name} );
140 if (!defined $push_ws) { next; }
143 foreach my $rth (@table_headers) { $rows[0][$i] = $rth; $i++; }
144 $sql = "SELECT * FROM $pull_tb;";
145 $sth = $dbh->prepare($sql);
147 my $grabhash = $sth->fetchall_arrayref({});
148 erase_sheet($push_ws,$push_ws_name);
150 #get from postgres the headers to use in the sheet from tracked columns
151 $sql = 'SELECT column_name FROM ' . $MIGSCHEMA . '.gsheet_tracked_column WHERE table_id = (SELECT id FROM ' . $MIGSCHEMA . '.gsheet_tracked_table WHERE table_name = \'' . $t . '\')';
152 $sth = $dbh->prepare($sql);
154 my $sheet_headers = $sth->fetchall_arrayref();
155 my $sheet_headers_length = @$sheet_headers;
156 #now I need to do new rows using those headers
158 foreach my $row ( @{$grabhash} ) {
160 for my $column ( sort keys %{ $row } ) {
161 #print Dumper(@$sheet_headers);
162 #print "column: $column\n";
163 my $clean_column = $column;
164 $clean_column =~ s/_//g;
165 if ( $column ~~ @$sheet_headers ) {
166 $record->{$clean_column} = $row->{$column};
169 push @content, $record;
172 foreach my $fillsheet (@content) {
173 my $new_row = $push_ws->add_row (
177 timestamp($MIGSCHEMA,$pull_tb,$dbh,'push');
178 if ($cmd_export == 1) { export_table($dbh,$pull_tb); }
186 my $dt = DateTime->now;
189 my $efile = $MIGGITDIR . $table . '_' . $date . '_' . $hms . '.tsv';
191 my $record_count = 0;
192 $dbh->do("COPY $table TO STDOUT CSV HEADER;");
193 1 while $dbh->pg_getcopydata(\$data[$record_count++]) >= 0;
194 open (my $eout, '>', $efile) or abort("Could NOT open $efile.");
195 foreach my $d (@data) {
198 print "$efile written.\n";
204 sub die_if_gsheet_tracked_table_does_not_exist {
205 if (!check_for_gsheet_tracked_table()) {
206 die "Table $MIGSCHEMA.gsheet_tracked_table does not exist. Bailing...\n";
216 foreach my $av (@a) {
217 foreach my $bv (@b) {
218 if ($av eq $bv) { push @r, $bv; }
224 sub get_pg_column_headers {
225 my $table_name = shift;
226 my $schema_name = shift;
228 my $dbh = Mig::db_connect();
229 $sql = 'SELECT column_name FROM information_schema.columns WHERE table_schema = ' . $dbh->quote( $schema_name ) . ' AND table_name = ' . $dbh->quote( $table_name ) . ';';
230 $sth = $dbh->prepare($sql);
231 $ra = $sth->execute();
232 while (my @row = $sth->fetchrow_array) {
233 push @headers, $row[0];
242 print "Erasing $ws_name.\n";
243 my @rows = $ws->rows;
246 $j = int(($j / 2))-1;
247 if ($j < 2) { $j = 2; }
249 #bodge until I figure out why google sheets is only deleting even numbered rows
251 foreach my $row (@rows) {
252 if ($i != 1) { $row->delete; }
260 sub check_for_gsheet_tracked_table {
261 my $dbh = Mig::db_connect();
262 my $sth = $dbh->prepare("
265 FROM information_schema.tables
266 WHERE table_schema = " . $dbh->quote( $MIGSCHEMA ) . "
267 AND table_name = 'gsheet_tracked_table'
270 my $rv = $sth->execute()
271 || die "Error checking for table (tracked_gsheet_table): $!";
272 my @cols = $sth->fetchrow_array;
274 Mig::db_disconnect($dbh);
278 sub die_if_gsheet_tracked_column_does_not_exist {
279 if (!check_for_gsheet_tracked_column()) {
280 die "Table $MIGSCHEMA.gsheet_tracked_column does not exist. Bailing...\n";
286 my $worksheet = shift;
289 my $sql = 'SELECT table_name FROM ' . $migs . '.gsheet_tracked_table WHERE tab_name = \'' . $worksheet . '\';';
290 my $sth = $dbh->prepare($sql);
291 my $xs = $sth->execute();
293 while (my @row = $sth->fetchrow_array) {
294 $table_name = $row[0];
300 sub get_worksheet_name {
305 my $sql = 'SELECT tab_name FROM ' . $migs . '.gsheet_tracked_table WHERE table_name = \'' . $table . '\';';
306 my $sth = $dbh->prepare($sql);
307 my $xs = $sth->execute();
309 while (my @row = $sth->fetchrow_array) {
310 $worksheet_name = $row[0];
313 return $worksheet_name;
317 sub check_for_gsheet_tracked_column {
318 my $dbh = Mig::db_connect();
319 my $sth = $dbh->prepare("
322 FROM information_schema.tables
323 WHERE table_schema = " . $dbh->quote( $MIGSCHEMA ) . "
324 AND table_name = 'gsheet_tracked_column'
327 my $rv = $sth->execute()
328 || die "Error checking for table (gsheet_tracked_column): $!";
329 my @cols = $sth->fetchrow_array;
331 Mig::db_disconnect($dbh);
336 my ($schema, $table, $dbh, $headers_ref, $row_ref) = @_;
337 my @headers = @{ $headers_ref };
338 my @row_data = @{ $row_ref };
340 my $header_string = '(' . join(",", @headers) . ')';
341 map {s/\'/\'\'/g; } @row_data;
342 my $row_string = '(' . join(",", map {qq/'$_'/} @row_data) . ')';
343 #print "INSERT INTO $schema.$table $header_string VALUES $row_string\n";
345 INSERT INTO $schema.$table $header_string VALUES $row_string ;
350 my ($schema, $table, $dbh, $action) = @_;
353 if ($action eq 'pull') { $column = 'last_pulled' }
354 else { $column = 'last_pushed' };
357 UPDATE $schema.gsheet_tracked_table SET $column = NOW() WHERE table_name = '$table';
369 TRUNCATE TABLE $schema.$table;;
371 print "Table $schema.$table truncated.\n";
376 print STDERR "$0: $msg", "\n";
381 if (!defined $ENV{'CLIENTID'}) {
382 exec '/bin/bash', '--init-file', '~/.mig/oauth.env';
383 print "Open Authentication settings were not loaded, please re-run.\n";
385 my $session_filename = $ENV{SESSIONFILE};
386 my $oauth2 = Net::Google::DataAPI::Auth::OAuth2->new(
387 client_id => $ENV{CLIENTID},
388 client_secret => $ENV{CLIENTSECRET},
389 scope => ['http://spreadsheets.google.com/feeds/'],
390 redirect_uri => 'https://developers.google.com/oauthplayground',
392 my $session = retrieve($session_filename);
393 my $restored_token = Net::OAuth2::AccessToken->session_thaw(
396 profile => $oauth2->oauth2_webserver,
398 $oauth2->access_token($restored_token);
399 my $service = Net::Google::Spreadsheets->new(auth => $oauth2);
401 my $spreadsheet = $service->spreadsheet(