@@ -18,12 +18,19 @@ function containStr(name, val) {
1818 return false ;
1919}
2020
21+ function isTimeType ( type ) {
22+ if ( containStr ( type , 'date' ) || containStr ( type , 'datetime' ) || containStr ( type , 'timestamp' ) ) {
23+ return true ;
24+ }
25+ return false ;
26+ }
27+
2128function sqlTypeToGoType ( type ) {
2229 let isContainUsign = false ;
2330 if ( containStr ( type , 'unsigned' ) ) {
2431 isContainUsign = true ;
2532 }
26- if ( containStr ( type , 'varchar' ) ) {
33+ if ( containStr ( type , 'varchar' ) || containStr ( type , 'text' ) ) {
2734 return 'string' ;
2835 }
2936 if ( containStr ( type , 'int' ) ) {
@@ -32,33 +39,52 @@ function sqlTypeToGoType(type) {
3239 }
3340 return 'uint64' ;
3441 }
42+ if ( containStr ( type , 'float' ) ) {
43+ return 'float64' ;
44+ }
45+ if ( containStr ( type , 'decimal' ) ) {
46+ return 'float64' ;
47+ }
48+ if ( isTimeType ( type ) ) {
49+ return 'time.Time' ;
50+ }
3551 return 'unknown' ;
3652}
3753
3854function sqlToModel ( data ) {
3955 const dbName = data . tableName ;
4056 const dbNameStr = dbNameToCamelCase ( dbName ) ;
4157 const packageName = 'db' ;
42- const importPackages = [ 'context' ,
43- 'github.com/jinzhu/gorm' ,
44- 'pkg.poizon.com/golang/go-common/mysql' ] ;
58+ const importPackages = [ ] ;
4559 let importPackageStr = '' ;
46- importPackages . map ( ( val ) => {
47- importPackageStr += `"${ val } "\n` ;
48- } ) ;
4960 let columsStr = '' ;
61+ let isTime = false ;
5062 data . columns . map ( ( val ) => {
5163 let defaultStr = '' ;
52- if ( val . default !== undefined && val . default !== 'NULL' ) {
64+ if ( val . default !== undefined && val . default !== 'NULL' && val . default !== '' ) {
5365 defaultStr = `;default:${ val . default } ` ;
5466 }
55- columsStr += ` ${ dbNameToCamelCase ( val . name ) } ${ sqlTypeToGoType ( val . type ) } \`gorm:"column:${ val . name } ${ defaultStr } " json:"${ val . name } "\`\n` ;
67+ const goType = sqlTypeToGoType ( val . type ) ;
68+ if ( ! isTime && isTimeType ( val . type ) ) {
69+ isTime = true ;
70+ }
71+ columsStr += ` ${ dbNameToCamelCase ( val . name ) } ${ goType } \`gorm:"column:${ val . name } ${ defaultStr } " json:"${ val . name } "\`\n` ;
5672 } ) ;
73+ if ( isTime ) {
74+ importPackages . push ( 'time' ) ;
75+ }
76+ let importStr = '' ;
77+ if ( importPackages . length > 0 ) {
78+ importPackages . map ( ( val ) => {
79+ importPackageStr += `"${ val } "\n` ;
80+ } ) ;
81+ importStr = `import (
82+ ${ importPackageStr }
83+ )` ;
84+ }
5785 const resultStr = `
5886package ${ packageName }
59- import (
60- ${ importPackageStr }
61- )
87+ ${ importStr }
6288var New${ dbNameStr } ${ dbNameStr } Model
6389type ${ dbNameStr } Model struct {
6490${ columsStr }
0 commit comments