ExportDB exports the db, with optional output to a file, default gzip targetDB is the db name if not default "db"
(dumpFile string, compressionType string, targetDB string)
| 1114 | // ExportDB exports the db, with optional output to a file, default gzip |
| 1115 | // targetDB is the db name if not default "db" |
| 1116 | func (app *DdevApp) ExportDB(dumpFile string, compressionType string, targetDB string) error { |
| 1117 | _ = app.DockerEnv() |
| 1118 | if targetDB == "" { |
| 1119 | targetDB = "db" |
| 1120 | } |
| 1121 | |
| 1122 | exportCmd := app.GetDBDumpCommand() + " " + targetDB |
| 1123 | if app.Database.Type == "postgres" { |
| 1124 | exportCmd = "pg_dump -U db " + targetDB |
| 1125 | } |
| 1126 | |
| 1127 | if app.Database.Type == nodeps.MariaDB { |
| 1128 | // The `tail --lines=+2` is a workaround that removes the new mariadb directive added |
| 1129 | // 2024-05 in mariadb-dump. It removes the first line of the dump, which has |
| 1130 | // the offending /*!999999\- enable the sandbox mode */. See |
| 1131 | // https://mariadb.org/mariadb-dump-file-compatibility-change/ |
| 1132 | // If not on a newer MariaDB version, this will remove the identification |
| 1133 | // line from the top of the dump. |
| 1134 | exportCmd = exportCmd + " | tail --lines=+2 " |
| 1135 | } |
| 1136 | |
| 1137 | if compressionType == "" { |
| 1138 | compressionType = "cat" |
| 1139 | } |
| 1140 | exportCmd = exportCmd + " | " + compressionType |
| 1141 | |
| 1142 | opts := &ExecOpts{ |
| 1143 | Service: "db", |
| 1144 | RawCmd: []string{"bash", "-c", `set -eu -o pipefail; ` + exportCmd}, |
| 1145 | NoCapture: true, |
| 1146 | } |
| 1147 | if dumpFile != "" { |
| 1148 | f, err := os.OpenFile(dumpFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) |
| 1149 | if err != nil { |
| 1150 | return fmt.Errorf("failed to open %s: %v", dumpFile, err) |
| 1151 | } |
| 1152 | opts.Stdout = f |
| 1153 | defer func() { |
| 1154 | _ = f.Close() |
| 1155 | }() |
| 1156 | } |
| 1157 | stdout, stderr, err := app.Exec(opts) |
| 1158 | |
| 1159 | if err != nil { |
| 1160 | return fmt.Errorf("unable to export db: %v\nstdout: %s\nstderr: %s", err, stdout, stderr) |
| 1161 | } |
| 1162 | |
| 1163 | confMsg := "Wrote database dump from project '" + app.Name + "' database '" + targetDB + "'" |
| 1164 | if dumpFile != "" { |
| 1165 | confMsg = confMsg + " to file " + dumpFile |
| 1166 | } else { |
| 1167 | confMsg = confMsg + " to stdout" |
| 1168 | } |
| 1169 | if compressionType == "cat" { |
| 1170 | confMsg = confMsg + " in plain text format" |
| 1171 | } else { |
| 1172 | confMsg = fmt.Sprintf("%s in %s format", confMsg, compressionType) |
| 1173 | } |