(ctx context.Context, tCtx base.TransformContext, statementInfoList []StatementInfo, databaseName string, tablePrefix string)
| 526 | } |
| 527 | |
| 528 | func generateSQLForTable(ctx context.Context, tCtx base.TransformContext, statementInfoList []StatementInfo, databaseName string, tablePrefix string) (*base.BackupStatement, error) { |
| 529 | table := statementInfoList[0].Table |
| 530 | |
| 531 | generatedColumns, normalColumns, err := classifyColumns(ctx, tCtx.GetDatabaseMetadataFunc, tCtx.ListDatabaseNamesFunc, tCtx.IsCaseSensitive, tCtx.InstanceID, table) |
| 532 | if err != nil { |
| 533 | return nil, errors.Wrap(err, "failed to classify columns") |
| 534 | } |
| 535 | |
| 536 | targetTable := fmt.Sprintf("%s_%s_%s", tablePrefix, table.Table, table.Database) |
| 537 | targetTable, _ = common.TruncateString(targetTable, maxTableNameLength) |
| 538 | var buf strings.Builder |
| 539 | if _, err := fmt.Fprintf(&buf, "CREATE TABLE `%s`.`%s` LIKE `%s`.`%s`;\n", databaseName, targetTable, table.Database, table.Table); err != nil { |
| 540 | return nil, errors.Wrap(err, "failed to write create table statement") |
| 541 | } |
| 542 | |
| 543 | if _, err := fmt.Fprintf(&buf, "INSERT INTO `%s`.`%s`", databaseName, targetTable); err != nil { |
| 544 | return nil, errors.Wrap(err, "failed to write insert into statement") |
| 545 | } |
| 546 | if len(generatedColumns) > 0 { |
| 547 | if _, err := buf.WriteString(" ("); err != nil { |
| 548 | return nil, errors.Wrap(err, "failed to write insert into statement") |
| 549 | } |
| 550 | for i, column := range normalColumns { |
| 551 | if i > 0 { |
| 552 | if err := buf.WriteByte(','); err != nil { |
| 553 | return nil, errors.Wrap(err, "failed to write comma") |
| 554 | } |
| 555 | } |
| 556 | if _, err := fmt.Fprintf(&buf, "`%s`", column); err != nil { |
| 557 | return nil, errors.Wrap(err, "failed to write column") |
| 558 | } |
| 559 | } |
| 560 | if _, err := buf.WriteString(")"); err != nil { |
| 561 | return nil, errors.Wrap(err, "failed to write insert into statement") |
| 562 | } |
| 563 | } |
| 564 | for i, item := range statementInfoList { |
| 565 | if i != 0 { |
| 566 | if _, err := buf.WriteString("\n UNION DISTINCT\n"); err != nil { |
| 567 | return nil, errors.Wrap(err, "failed to write union all statement") |
| 568 | } |
| 569 | } |
| 570 | tableNameOrAlias := item.Table.Table |
| 571 | if len(item.Table.Alias) > 0 { |
| 572 | tableNameOrAlias = item.Table.Alias |
| 573 | } |
| 574 | if _, err := buf.WriteString(" "); err != nil { |
| 575 | return nil, errors.Wrap(err, "failed to write space") |
| 576 | } |
| 577 | |
| 578 | stmtLoc := nodeStmtLoc(item.Node) |
| 579 | cteString := extractCTE(item.FullSQL, stmtLoc) |
| 580 | if len(cteString) > 0 { |
| 581 | if _, err := fmt.Fprintf(&buf, "%s ", cteString); err != nil { |
| 582 | return nil, errors.Wrap(err, "failed to write cte") |
| 583 | } |
| 584 | } |
| 585 |
no test coverage detected