|
| 1 | +// Copyright 2020 The SQLFlow Authors. All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +// you may not use this file except in compliance with the License. |
| 4 | +// You may obtain a copy of the License at |
| 5 | +// |
| 6 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +// |
| 8 | +// Unless required by applicable law or agreed to in writing, software |
| 9 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +// See the License for the specific language governing permissions and |
| 12 | +// limitations under the License. |
| 13 | + |
| 14 | +package experimental |
| 15 | + |
| 16 | +import ( |
| 17 | + "bytes" |
| 18 | + "text/template" |
| 19 | + |
| 20 | + pb "sqlflow.org/sqlflow/go/proto" |
| 21 | +) |
| 22 | + |
| 23 | +var normalStmtStepTmpl = ` |
| 24 | +def step_entry_{{.StepIndex}}(): |
| 25 | + import runtime |
| 26 | + import runtime.dbapi |
| 27 | + conn = runtime.dbapi.connect("{{.DataSource}}") |
| 28 | + stmt = """{{.Stmt}}""" |
| 29 | + if conn.is_query(stmt): |
| 30 | + rs = conn.query(stmt) |
| 31 | + # write rs to stdout using protobuf table writer |
| 32 | + else: |
| 33 | + success = conn.execute(stmt) |
| 34 | + if not success: |
| 35 | + raise Exception("execute statment error: " % stmt) |
| 36 | +` |
| 37 | + |
| 38 | +var normalStmtStepTemplate = template.Must(template.New("NormalStmtStep").Parse(normalStmtStepTmpl)) |
| 39 | + |
| 40 | +type normalStmtFiller struct { |
| 41 | + StepIndex int |
| 42 | + DataSource string |
| 43 | + Stmt string |
| 44 | +} |
| 45 | + |
| 46 | +// GenerateNormalStmtStep generate step Python code to run a normal SQL statement. |
| 47 | +func GenerateNormalStmtStep(stmt string, session *pb.Session, stepIndex int) (string, error) { |
| 48 | + filler := &normalStmtFiller{ |
| 49 | + StepIndex: stepIndex, |
| 50 | + DataSource: session.DbConnStr, |
| 51 | + Stmt: stmt, |
| 52 | + } |
| 53 | + var program bytes.Buffer |
| 54 | + if err := normalStmtStepTemplate.Execute(&program, filler); err != nil { |
| 55 | + return "", err |
| 56 | + } |
| 57 | + return program.String(), nil |
| 58 | +} |
0 commit comments