Skip to content

Commit

Permalink
v1.0.1
Browse files Browse the repository at this point in the history
  • Loading branch information
yugj committed Dec 4, 2023
1 parent 43405ff commit 58f3783
Show file tree
Hide file tree
Showing 9 changed files with 216 additions and 38 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
# sql to java change log

## 2023-12-02
* fix windows os .Author null
* support organizing directories by package path
* support some built-in functions

## 2023-11-25
* support generate java file from templates
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,35 @@ or
./sql2java table.sql config.json
```

output
```shell
└── com
└── yunx
└── ldct
├── controller
│   ├── ProductController.java
│   └── UserController.java
├── dao
│   ├── ProductDao.java
│   └── UserDao.java
├── entity
│   ├── ProductEntity.java
│   └── UserEntity.java
├── mapper
│   ├── ProductMapper.java
│   └── UserMapper.java
├── model
│   └── request
│   ├── ProductRequest.java
│   └── UserRequest.java
└── service
├── ProductService.java
├── UserService.java
└── impl
├── ProductServiceImpl.java
└── UserServiceImpl.java
```

## 4. Templates Specification
### 4.1 naming
* lower case
Expand All @@ -63,4 +92,10 @@ or
}
```

### 4.3 supported functions
| function | description | example |
|:---------|--------------------------------------------------------------:|:--------------------------------:|
| toLower | returns with all Unicode letters mapped to their lower case | {{.EntityName | toLower}} |
| toUpper | returns with all Unicode letters mapped to their upper case | {{.EntityName | toUpper}} |

the next stage will distinguish between built-in configurations and support for user-defined configurations
1 change: 1 addition & 0 deletions cmd/Generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ func Execute() {
genConfig.Author = localConfig.Author
genConfig.TablePrefix = localConfig.TablePrefix
genConfig.DateType = localConfig.DateType
genConfig.OutputFormat = localConfig.OutputFormat

if len(localConfig.BasePath) > 0 {
genConfig.BasePath = localConfig.BasePath
Expand Down
3 changes: 2 additions & 1 deletion config.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@
"Author": "yugj",
"ParentEntityName": "AbstractEntity",
"ParentEntityFields": "id,createTime,modifyTime,createBy,modifyBy",
"TablePrefix": "t_"
"TablePrefix": "t_",
"OutputFormat": true
}
2 changes: 1 addition & 1 deletion internal/convert/EntityConvert.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func TableToEntity(table model.Table, config model.GenConfig) model.Entity {
var domainName = strings.ToUpper(camelName[:1]) + camelName[1:]

entity.EntityName = domainName
entity.Author = config.SystemUser
entity.Author = config.Author
entity.Description = table.Description
entity.ParentEntityName = config.ParentEntityName

Expand Down
51 changes: 20 additions & 31 deletions internal/gen/EntityGen.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,13 @@ func Generate(entity model.Entity, config model.GenConfig) {
// tpl abst path
var tplBase = config.BasePath + "/templates/"

tpl, err := template.ParseGlob(tplBase + "/*")
// register custom functions
funcMap := template.FuncMap{
"toLower": toLower,
"toUpper": toUpper,
}

tpl, err := template.New("sql2java").Funcs(funcMap).ParseGlob(tplBase + "/*")
if err != nil {
log.Println("create templates failed, err:", err)
return
Expand All @@ -27,6 +33,11 @@ func Generate(entity model.Entity, config model.GenConfig) {
tplGenerate(convert.ToTplData(entity, config), tpl, f.Name())
}

// format output file in need
if config.OutputFormat {
outputFormat(config.BasePath)
}

log.Println("end of generate")
}

Expand Down Expand Up @@ -58,39 +69,17 @@ func tplGenerate(tplData model.TplData, tpl *template.Template, filename string)
}
}

func createDirIfNeed(basePath string, name string) {

var path = basePath + "/" + name

if !existsPath(path) {
_ = os.MkdirAll(path, os.ModePerm)
}
}

func existsPath(path string) bool {
_, err := os.Stat(path)
if err != nil {
if os.IsExist(err) {
return true
}
return false
}
return true
}

func openFile(destFile string) *os.File {
file, err := os.OpenFile(destFile, os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
log.Println("Open file err =", err)
panic(err)
}
//defer file.Close()
return file
}

func firstUpper(s string) string {
if s == "" {
return ""
}
return strings.ToUpper(s[:1]) + s[1:]
}

func toLower(s string) string {
return strings.ToLower(s)
}

func toUpper(s string) string {
return strings.ToUpper(s)
}
40 changes: 40 additions & 0 deletions internal/gen/FileUtil.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package gen

import (
"log"
"os"
)

func createDirIfNeed(basePath string, name string) {

var path = basePath + "/" + name
autoCreateDir(path)
}

func autoCreateDir(path string) {

if !existsPath(path) {
_ = os.MkdirAll(path, os.ModePerm)
}
}

func existsPath(path string) bool {
_, err := os.Stat(path)
if err != nil {
if os.IsExist(err) {
return true
}
return false
}
return true
}

func openFile(destFile string) *os.File {
file, err := os.OpenFile(destFile, os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
log.Println("Open file err =", err)
panic(err)
}
//defer file.Close()
return file
}
110 changes: 110 additions & 0 deletions internal/gen/OutputFormat.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package gen

import (
"bufio"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
)

func outputFormat(baseDir string) {

var outputDir = baseDir + "/output"
var outputFormatDir = baseDir + "/output_format"

filePackageMap, err := getJavaPackagePath(outputDir)
if err != nil {
return
}

for javaFile, packagePath := range filePackageMap {
println(javaFile + "->" + packagePath)
dest := outputFormatDir + "/" + packagePath
fileCopy(javaFile, dest)
}
}

// java file path -> packagePath
func getJavaPackagePath(outputDir string) (map[string]string, error) {

var result = make(map[string]string)
outputDirFiles, _ := ioutil.ReadDir(outputDir)

for _, subDir := range outputDirFiles {
abstSubDir := outputDir + "/" + subDir.Name()

if !subDir.IsDir() {
continue
}

subDirFiles, _ := ioutil.ReadDir(abstSubDir)
for _, file := range subDirFiles {
if strings.HasSuffix(file.Name(), ".java") {
javaPath := abstSubDir + "/" + file.Name()

packageName := getPackageName(javaPath)

if len(packageName) == 0 {
continue
}

result[javaPath] = packageName2Path(packageName)
}
}
}

return result, nil
}

func packageName2Path(packageName string) string {
return strings.ReplaceAll(packageName, ".", "/")
}

func getPackageName(javaFile string) string {

packageLine := readFirstLine(javaFile)
if len(packageLine) == 0 {
return ""
}

packageLine = strings.TrimPrefix(packageLine, "package")
packageLine = strings.TrimSuffix(packageLine, ";")
packageLine = strings.TrimSpace(packageLine)

return packageLine
}

func readFirstLine(javaFile string) string {

file, err := os.Open(javaFile)
if err != nil {
fmt.Println("Failed to open file:", err)
return ""
}

defer file.Close()
scanner := bufio.NewScanner(file)
if scanner.Scan() {
firstLine := scanner.Text()
return firstLine
} else {
return ""
}
}

func fileCopy(sourceFile string, dir string) {

if !existsPath(dir) {
autoCreateDir(dir)
}

_, fileName := filepath.Split(sourceFile)

input, _ := ioutil.ReadFile(sourceFile)

destFile := dir + "/" + fileName
_ = ioutil.WriteFile(destFile, input, 0644)

}
7 changes: 2 additions & 5 deletions internal/model/Models.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,7 @@ type GenConfig struct {
TablePrefix string // table prefix like t_
DateType string // support Data&LocalDateTime, not support yet
ParentEntityFields string
}

type CommonDomain struct {
Entity Entity
Config GenConfig
OutputFormat bool
}

// TplData built-in Params
Expand All @@ -58,4 +54,5 @@ type TplData struct {
SystemUser string
DateTime string
BasePath string
OutputFormat bool
}

0 comments on commit 58f3783

Please sign in to comment.