Как pg_dump только операторы INSERT без SET / SELECTS / - Комментарии в POSTGRESQL? - PullRequest
0 голосов
/ 24 февраля 2020

Мой bash код для вывода только указанных c строк таблицы:

acc_db mydb -c "create table export_table as $1"
mypg_dump -d mydb -a -t export_table --data-only --column-inserts >> /tmp/export_data.sql
acc_db mydb -c "drop table export_table"
sed -i -e 's/export_table/'$table'/g' /tmp/export_data.sql

# where : 
# $1 contains my SELECT statement 
# $table is the actual name of the table I'm interest in
# acc_db is a wrapper to override the pwd insert 
# mydb is ... some db 

Во-первых, я использовал grep в строке mypg_dump, чтобы получать только операторы INSERT, но когда я обнаружил, что многострочные поля были выделены, что привело к нарушению оператора sql, мне пришлось его изменить. Однако теперь у меня есть такой вывод:

-- some comment 
-- comment 
*blank lines* 

*various SET statements* 
*SELECT statements* 

INSERT [...]

-- some comments 
*more blank lines* 

Все, что мне действительно нужно, это оператор INSERT, но я не могу найти какой-либо способ получить только вставку.

1 Ответ

0 голосов
/ 24 февраля 2020

Если вы получаете многострочные вставки, вам нужно использовать что-то более гибкое, чем grep. Пример использования perl однострочной:

perl -wlne 'if (!$current_statement){if (/^\s*INSERT/){if (/;\s*$/) {push @inserts, $_} else {s/\r//g;$current_statement = $_}}} else {$current_statement .= $_;if (/;\s*$/){push @inserts, $current_statement;$current_statement = "";}}}{print for (@inserts)' /tmp/export_data.sql > /tmp/insert_data.sql

Разбивка того, что происходит:

# - w: use warnings
# - l: loop through input storing each line's contents in $_
# - n: don't print the line after processing
# - e: execute one liner

if (!$current_statement) { # if not in multi-line insert
  if (/^\s*INSERT/) {      # skip if it's not an INSERT statement
    if (/;\s*$/){          # single line insert, push to list
      push @inserts, $_
    } else {               # multi-line insert strip off CR, save line and continue
      s/\r//g;
      $current_statement = $_
    }
  }
} else {                     # continue an multi-line existing multi-line insert
  $current_statement .= $_;  # always append the statement
  if (/;\s*$/){              # if finished, push to @inserts, reset variable
    push @inserts, $current_statement;
    $current_statement = "";
  }
}
}{  # "eskimo kiss": finishes the loop from -n, runs code after processing the files
  print for (@inserts) # print each entry of the inserts array
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...