MCPcopy Index your code
hub / github.com/bytebase/bytebase / generateSQLForTable

Function generateSQLForTable

backend/plugin/parser/pg/backup.go:129–180  ·  view source on GitHub ↗
(statementInfoList []statementInfo, targetSchema string, tablePrefix string)

Source from the content-addressed store, hash-verified

127}
128
129func generateSQLForTable(statementInfoList []statementInfo, targetSchema string, tablePrefix string) (*base.BackupStatement, error) {
130 table := statementInfoList[0].table
131
132 targetTable := fmt.Sprintf("%s_%s_%s", tablePrefix, table.Table, table.Schema)
133 targetTable, _ = common.TruncateString(targetTable, maxTableNameLength)
134 var buf strings.Builder
135 if _, err := fmt.Fprintf(&buf, `CREATE TABLE "%s"."%s" AS`+"\n", targetSchema, targetTable); err != nil {
136 return nil, errors.Wrap(err, "failed to write to buffer")
137 }
138
139 // In PostgreSQL, WITH clause must appear once before the first SELECT.
140 cteClause := extractCTE(statementInfoList[0].node, statementInfoList[0].fullSQL)
141 if cteClause != "" {
142 if _, err := fmt.Fprintf(&buf, "%s\n", cteClause); err != nil {
143 return nil, errors.Wrap(err, "failed to write to buffer")
144 }
145 }
146
147 for i, item := range statementInfoList {
148 if i != 0 {
149 if _, err := buf.WriteString("\n UNION\n"); err != nil {
150 return nil, errors.Wrap(err, "failed to write to buffer")
151 }
152 }
153 if table.Alias != "" {
154 if _, err := fmt.Fprintf(&buf, ` SELECT "%s".* `, table.Alias); err != nil {
155 return nil, errors.Wrap(err, "failed to write to buffer")
156 }
157 } else {
158 if _, err := fmt.Fprintf(&buf, ` SELECT %s.* `, table.String()); err != nil {
159 return nil, errors.Wrap(err, "failed to write to buffer")
160 }
161 }
162
163 if err := writeSuffixSelectClause(&buf, item.node, item.fullSQL); err != nil {
164 return nil, errors.Wrap(err, "failed to write string with new line")
165 }
166 }
167
168 if _, err := buf.WriteString(";"); err != nil {
169 return nil, errors.Wrap(err, "failed to write to buffer")
170 }
171
172 return &base.BackupStatement{
173 Statement: buf.String(),
174 SourceSchema: table.Schema,
175 SourceTableName: table.Table,
176 TargetTableName: targetTable,
177 StartPosition: statementInfoList[0].startPos,
178 EndPosition: statementInfoList[len(statementInfoList)-1].endPos,
179 }, nil
180}
181
182func extractCTE(node ast.Node, fullSQL string) string {
183 var wc *ast.WithClause

Callers 1

generateSQLFunction · 0.70

Calls 4

TruncateStringFunction · 0.92
extractCTEFunction · 0.70
writeSuffixSelectClauseFunction · 0.70
StringMethod · 0.65

Tested by

no test coverage detected