Skip to content

Instantly share code, notes, and snippets.

@garex
Created October 31, 2012 15:56
Show Gist options
  • Save garex/3987864 to your computer and use it in GitHub Desktop.
Save garex/3987864 to your computer and use it in GitHub Desktop.
Mysql dump sort keys contraints
#!/usr/bin/gawk -f
#FUNCTIONS
function printRecords(array) {
if( array[0] != "" ) {
asort(array);
for( j = length(array); j >= 1 ; j-- ) {
lastChar = "";
if (j > 1) {
lastChar = ",";
}
sub(/,$/, "", array[j]);
print array[j], lastChar;
}
delete array;
}
}
#MAIN
BEGIN {
keyRegex = " KEY.*";
constraintRegex = " CONSTRAINT.*";
aSortedIndex = 0;
aSorted[0] = "";
}
{
if( match($0, keyRegex) ) {
aSorted[aSortedIndex++] = $0;
} else if( match($0, constraintRegex) ) {
aSorted[aSortedIndex++] = $0;
} else {
printRecords(aSorted);
aSortedIndex = 0;
print $0;
}
}
END {
}
@derylspielman
Copy link

Your code still gives me an extra comma.. notice the extra comma on KEY FK_report_package_report_acct_run_type_report_acct_run_type_id

CREATE TABLE report_package_report_accounting_run_type (
report_package_id int(11) NOT NULL,
report_accounting_run_type_id int(11) NOT NULL,
UNIQUE KEY report_package_id (report_package_id,report_accounting_run_type_id),
KEY FK_report_package_report_accounting_run_type_rpt_pkg_id (report_package_id),
KEY FK_report_package_report_acct_run_type_report_acct_run_type_id (report_accounting_run_type_id),
CONSTRAINT FK_report_package_report_acct_run_type_report_acct_run_type_id FOREIGN KEY (report_accounting_run_type_id) REFERENCES report_accounting_run_type (id),
CONSTRAINT FK_report_package_report_accounting_run_type_rpt_pkg_id FOREIGN KEY (report_package_id) REFERENCES report_package (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

results in

CREATE TABLE report_package_report_accounting_run_type (
report_package_id int(11) NOT NULL,
report_accounting_run_type_id int(11) NOT NULL,
UNIQUE KEY report_package_id (report_package_id,report_accounting_run_type_id),
KEY FK_report_package_report_acct_run_type_report_acct_run_type_id (report_accounting_run_type_id),
,
KEY FK_report_package_report_accounting_run_type_rpt_pkg_id (report_package_id),
,
CONSTRAINT FK_report_package_report_acct_run_type_report_acct_run_type_id FOREIGN KEY (report_accounting_run_type_id) REFERENCES report_accounting_run_type (id)
,
CONSTRAINT FK_report_package_report_accounting_run_type_rpt_pkg_id FOREIGN KEY (report_package_id) REFERENCES report_package (id),

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

@derylspielman
Copy link

Also it would be great if the comma was not on an entirely new line

@nestoru
Copy link

nestoru commented Jan 28, 2013

Thanks for the heads up I have pushed a new version to github https://raw.github.com/nestoru/pob-recipes/master/common/mysql/mysqldump_sort.gawk which correctly keeps the commas and just removes it from the very last line.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment