| SHA512 | `, pb);
100 |
101 | if (web_crypto && file.size < max_crypto_file_size) {
102 | crypto_algos.push({id: id, name: 'SHA-512'});
103 | } else {
104 | let worker = new Worker('/static/js/file_hash.worker.js');
105 | worker.addEventListener('message', onWorkerEvent(id));
106 | worker.postMessage({type: 'algo', name: 'SHA-512'});
107 | workers.push(worker)
108 | }
109 | }
110 |
111 | if (crypto_algos.length > 0) {
112 | calcByWebCrypto(file, crypto_algos)
113 | }
114 | if (workers.length > 0) {
115 | calcByCryptoJS(file, workers)
116 | }
117 | }
118 |
119 | document.getElementById('tbody_hash').innerHTML = table.join('')
120 | }
121 |
122 | function updateProgress(eid, progress) {
123 | let pb = document.querySelector('#' + eid + ' .progress');
124 | pb.setAttribute('value', progress);
125 | }
126 |
127 | function calcByWebCrypto(file, algos) {
128 | let reader = new FileReader();
129 | reader.onprogress = function (e) {
130 | for (let i = 0; i < algos.length; i++) {
131 | updateProgress(algos[i].id, e.loaded * 100 / e.total);
132 | }
133 | };
134 | reader.onload = function (e) {
135 | for (let i = 0; i < algos.length; i++) {
136 | let algo = algos[i];
137 | window.crypto.subtle.digest({name: algo.name}, e.target.result)
138 | .then(function (hash) {
139 | let hexString = '', hashResult = new Uint8Array(hash);
140 | for (let i = 0; i < hashResult.length; i++) {
141 | hexString += ("00" + hashResult[i].toString(16)).slice(-2);
142 | }
143 | document.getElementById(algo.id).innerText = hexString
144 | }).catch(e => console.error(e));
145 | }
146 | };
147 | reader.readAsArrayBuffer(file);
148 | }
149 |
150 | function readChunked(file, chunkCallback, endCallback) {
151 | let fileSize = file.size;
152 | let chunkSize = 4 * 1024 * 1024;
153 | let offset = 0;
154 |
155 | let reader = new FileReader();
156 | reader.onload = function () {
157 | if (reader.error) {
158 | endCallback(reader.error || {});
159 | return;
160 | }
161 | offset += reader.result.length;
162 | chunkCallback(reader.result, offset, fileSize);
163 | if (offset >= fileSize) {
164 | endCallback(null);
165 | return;
166 | }
167 | readNext();
168 | };
169 |
170 | reader.onerror = function (err) {
171 | endCallback(err || {});
172 | };
173 |
174 | function readNext() {
175 | let slice = file.slice(offset, offset + chunkSize);
176 | reader.readAsBinaryString(slice);
177 | }
178 |
179 | readNext();
180 | }
181 |
182 | function onWorkerEvent(id) {
183 | return function (e) {
184 | if (e.data.type === 'progress') {
185 | updateProgress(id, e.data.value);
186 | } else if (e.data.type === 'result') {
187 | document.getElementById(id).innerText = e.data.value;
188 | }
189 | }
190 | }
191 |
192 | function calcByCryptoJS(file, workers) {
193 | readChunked(file, (chunk, offs, total) => {
194 | for (let i = 0; i < workers.length; i++) {
195 | workers[i].postMessage({type: 'chunk', chunk: chunk, offs: offs, total: total});
196 | }
197 | }, err => {
198 | if (err) {
199 | alert(err)
200 | } else {
201 | for (let i = 0; i < workers.length; i++) {
202 | workers[i].postMessage({type: 'done'});
203 | }
204 | }
205 | });
206 | }
207 |
208 | document.getElementById('input_file').addEventListener('change', onFileSelected, false);
209 | document.getElementById('drop_zone').addEventListener('drop', onFileSelected, false);
210 | document.getElementById('drop_zone').addEventListener('dragover', function (e) {
211 | e.stopPropagation();
212 | e.preventDefault();
213 | }, false);
214 |
--------------------------------------------------------------------------------
/static/js/sql2struct.js:
--------------------------------------------------------------------------------
1 | new Vue({
2 | el: '#app',
3 | data() {
4 | return {
5 | cache: null,
6 | sqlContent: '',
7 | structContent: '',
8 | activeIndex: '1',
9 | typeMap: getTypeMap(),
10 | typeMapStr: '',
11 | useGorm: true,
12 | useSqlx: true,
13 | useJson: true,
14 | useForm: true,
15 | dialogFormVisible: false
16 | }
17 | },
18 | created() {
19 | var message = {
20 | act: 'getOptions'
21 | }
22 | var that = this
23 | // 获取缓存数据
24 | chrome.runtime.sendMessage(message, function(res) {
25 | if (!res) { // 不存在缓存数据
26 | // 初始配置数据
27 | var data = {
28 | useGorm: that.useGorm,
29 | useSqlx: that.useSqlx,
30 | useJson: that.useJson,
31 | useForm: that.useForm,
32 | typeMap: that.typeMap
33 | }
34 | that.setCache(data)
35 | for (var k in that.typeMap) {
36 | that.typeMapStr += k + ': ' + that.typeMap[k] + '\n'
37 | }
38 | return
39 | }
40 | var obj = JSON.parse(res)
41 | if (obj.useGorm != undefined) {
42 | that.useGorm = obj.useGorm
43 | }
44 | if (obj.useSqlx != undefined) {
45 | that.useSqlx = obj.useSqlx
46 | }
47 | if (obj.useJson != undefined) {
48 | that.useJson = obj.useJson
49 | }
50 | if (obj.useForm != undefined) {
51 | that.useForm = obj.useForm
52 | }
53 | if (obj.typeMap != undefined) {
54 | that.typeMap = obj.typeMap
55 | for (var k in obj.typeMap) {
56 | that.typeMapStr += k + ': ' + obj.typeMap[k] + '\n'
57 | }
58 | }
59 | })
60 | },
61 | watch: {
62 | sqlContent(val) {
63 | if (!val) {
64 | this.structContent = ''
65 | return
66 | }
67 | var res = val.match(/\`[\w_]+\`\s+[\w_\(\)]+(\s+|\,)/g)
68 | if (!res) {
69 | this.structContent = 'invalid sql'
70 | return
71 | }
72 | var types = this.typeMap
73 | var structResult = 'type '
74 | for (var i = 0, len = res.length; i < len; i++) {
75 | var field = res[i].match(/\`(.+)\`\s+(tinyint|smallint|int|mediumint|bigint|float|double|decimal|varchar|char|text|mediumtext|longtext|datetime|time|date|enum|set|blob)?/)
76 | if (i == 0) { // 第一个字段为数据表名称
77 | if (field && field[1] != undefined && field[2] == undefined) {
78 | var tbName = titleCase(field[1])
79 | structResult += tbName + ' struct {'
80 | continue
81 | } else {
82 | return
83 | }
84 | } else { // 数据表字段
85 | if (field && field[1] != undefined && field[2] != undefined) {
86 | if (types[field[2]] != undefined) {
87 | var fieldName = titleCase(field[1])
88 | var fieldType = types[field[2]]
89 | var fieldJsonName = field[1].toLowerCase()
90 | if (fieldName.toLowerCase() == 'id') {
91 | fieldName = 'ID'
92 | }
93 | structResult += '\n\t' + fieldName + ' ' + fieldType + ' '
94 | structArr = []
95 | if (this.useGorm) {
96 | structArr.push('gorm:"column:'+ fieldJsonName +'"')
97 | }
98 | if (this.useSqlx) {
99 | structArr.push('db:"column:'+ fieldJsonName +'"')
100 | }
101 | if (this.useJson) {
102 | structArr.push('json:"' + fieldJsonName + '"')
103 | }
104 | if (this.useForm) {
105 | structArr.push('form:"' + fieldJsonName + '"')
106 | }
107 | if (structArr.length > 0) {
108 | structResult += '`'+structArr.join(' ')+'`'
109 | }
110 | } else {
111 | continue
112 | }
113 | } else {
114 | continue
115 | }
116 | }
117 | }
118 | structResult += '\n}'
119 | this.structContent = structResult
120 | },
121 | typeMapStr(val) {
122 | var typeArr = val.split('\n')
123 | var typeMap = {}
124 | for (var i = 0, len = typeArr.length; i < len; i++) {
125 | var itemArr = typeArr[i].split(/\:\s+/)
126 | if (itemArr[0] != undefined && itemArr[1] != undefined) {
127 | typeMap[itemArr[0]] = itemArr[1]
128 | }
129 | }
130 | this.typeMap = typeMap
131 | var data = {
132 | useGorm: this.useGorm,
133 | useSqlx: this.useSqlx,
134 | useJson: this.useJson,
135 | useForm: this.useForm,
136 | typeMap: this.typeMap
137 | }
138 | this.setCache(data)
139 | },
140 | useGorm(val) {
141 | this.useGorm = val
142 | var data = {
143 | useGorm: this.useGorm,
144 | useSqlx: this.useSqlx,
145 | useJson: this.useJson,
146 | useForm: this.useForm,
147 | typeMap: this.typeMap
148 | }
149 | this.setCache(data)
150 | },
151 | useSqlx(val) {
152 | this.useSqlx = val
153 | var data = {
154 | useGorm: this.useGorm,
155 | useSqlx: this.useSqlx,
156 | useJson: this.useJson,
157 | useForm: this.useForm,
158 | typeMap: this.typeMap
159 | }
160 | this.setCache(data)
161 | },
162 | useJson(val) {
163 | this.useJson = val
164 | var data = {
165 | useGorm: this.useGorm,
166 | useSqlx: this.useSqlx,
167 | useJson: this.useJson,
168 | useForm: this.useForm,
169 | typeMap: this.typeMap
170 | }
171 | this.setCache(data)
172 | },
173 | useForm(val) {
174 | this.useForm = val
175 | var data = {
176 | useGorm: this.useGorm,
177 | useSqlx: this.useSqlx,
178 | useJson: this.useJson,
179 | useForm: this.useForm,
180 | typeMap: this.typeMap
181 | }
182 | this.setCache(data)
183 | }
184 | },
185 | methods: {
186 | handleSelect(key, keyPath) {
187 |
188 | },
189 | setCache(data) {
190 | var message = {
191 | act: 'setOptions',
192 | data: JSON.stringify(data)
193 | }
194 | chrome.runtime.sendMessage(message, function(res) {
195 | //console.log(res)
196 | })
197 | }
198 | }
199 | })
200 |
201 | // 首字母大写
202 | function titleCase(str) {
203 |
204 | var array = str.toLowerCase().split("_");
205 | for (var i = 0; i < array.length; i++){
206 | array[i] = array[i][0].toUpperCase() + array[i].substring(1, array[i].length);
207 | }
208 | var string = array.join("");
209 |
210 | return string;
211 | }
212 |
213 | // 类型映射
214 | function getTypeMap() {
215 | return {
216 | 'tinyint': 'int64',
217 | 'smallint': 'int64',
218 | 'int': 'int64',
219 | 'mediumint': 'int64',
220 | 'bigint': 'int64',
221 | 'float': 'float64',
222 | 'double': 'float64',
223 | 'decimal': 'float64',
224 | 'char': 'string',
225 | 'varchar': 'string',
226 | 'text': 'string',
227 | 'mediumtext': 'string',
228 | 'longtext': 'string',
229 | 'time': 'time.Time',
230 | 'date': 'time.Time',
231 | 'datetime': 'time.Time',
232 | 'timestramp': 'int64',
233 | 'enum': 'string',
234 | 'set': 'string',
235 | 'blob': 'string'
236 | }
237 | }
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/PuerkitoBio/goquery v1.5.1/go.mod h1:GsLWisAFVj4WgDibEWF4pvYnkVQBpKBKeU+7zCJoLcc=
2 | github.com/andybalholm/cascadia v1.1.0/go.mod h1:GsXiBklL0woXo1j/WYWtSYYC4ouU9PqHO0sqidkEA4Y=
3 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
4 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
5 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
6 | github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd h1:83Wprp6ROGeiHFAP8WJdI2RoxALQYgdllERc3N5N2DM=
7 | github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU=
8 | github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5 h1:Yzb9+7DPaBjB8zlTR87/ElzFsnQfuHnVUVqpZZIcV5Y=
9 | github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0=
10 | github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
11 | github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
12 | github.com/gin-gonic/gin v1.7.0 h1:jGB9xAJQ12AIGNB4HguylppmDK1Am9ppF7XnGXXJuoU=
13 | github.com/gin-gonic/gin v1.7.0/go.mod h1:jD2toBW3GZUr5UMcdrwQA10I7RuaFOl/SGeDjXkfUtY=
14 | github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A=
15 | github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
16 | github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q=
17 | github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=
18 | github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no=
19 | github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
20 | github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE=
21 | github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4=
22 | github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs=
23 | github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
24 | github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY=
25 | github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
26 | github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I=
27 | github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
28 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
29 | github.com/jinzhu/gorm v1.9.16 h1:+IyIjPEABKRpsu/F8OvDPy9fyQlgsg2luMV2ZIH5i5o=
30 | github.com/jinzhu/gorm v1.9.16/go.mod h1:G3LB3wezTOWM2ITLzPxEXgSkOXAntiLHS7UdBefADcs=
31 | github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
32 | github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
33 | github.com/jinzhu/now v1.0.1 h1:HjfetcXq097iXP0uoPCdnM4Efp5/9MsM0/M+XOTeR3M=
34 | github.com/jinzhu/now v1.0.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
35 | github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns=
36 | github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
37 | github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y=
38 | github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
39 | github.com/lib/pq v1.1.1 h1:sJZmqHoEaY7f+NPP8pgLB/WxulyR3fewgCM2qaSlBb4=
40 | github.com/lib/pq v1.1.1/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
41 | github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
42 | github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
43 | github.com/mattn/go-sqlite3 v1.14.0 h1:mLyGNKR8+Vv9CAU7PphKa2hkEqxxhn8i32J6FPj1/QA=
44 | github.com/mattn/go-sqlite3 v1.14.0/go.mod h1:JIl7NbARA7phWnGvh0LKTyg7S9BA+6gx71ShQilpsus=
45 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
46 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
47 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
48 | github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
49 | github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI=
50 | github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
51 | github.com/onrik/logrus v0.8.0 h1:lM37gnPr1doWCR1lgeV01Ti8zlDdsPWhEP2OEE1phZk=
52 | github.com/onrik/logrus v0.8.0/go.mod h1:qfe9NeZVAJfIxviw3cYkZo3kvBtLoPRJriAO8zl7qTk=
53 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
54 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
55 | github.com/sirupsen/logrus v1.7.0 h1:ShrD1U9pZB12TX0cVy0DtePoCH97K8EtX+mg7ZARUtM=
56 | github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
57 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
58 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
59 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
60 | github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
61 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
62 | github.com/tdewolff/minify v2.3.6+incompatible h1:2hw5/9ZvxhWLvBUnHE06gElGYz+Jv9R4Eys0XUzItYo=
63 | github.com/tdewolff/minify v2.3.6+incompatible/go.mod h1:9Ov578KJUmAWpS6NeZwRZyT56Uf6o3Mcz9CEsg8USYs=
64 | github.com/tdewolff/parse v2.3.4+incompatible h1:x05/cnGwIMf4ceLuDMBOdQ1qGniMoxpP46ghf0Qzh38=
65 | github.com/tdewolff/parse v2.3.4+incompatible/go.mod h1:8oBwCsVmUkgHO8M5iCzSIDtpzXOT0WXX9cWhz+bIzJQ=
66 | github.com/tdewolff/test v1.0.0 h1:jOwzqCXr5ePXEPGJaq2ivoR6HOCi+D5TPfpoyg8yvmU=
67 | github.com/tdewolff/test v1.0.0/go.mod h1:DiQUlutnqlEvdvhSn2LPGy4TFwRauAaYDsL+683RNX4=
68 | github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
69 | github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs=
70 | github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
71 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
72 | golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
73 | golang.org/x/crypto v0.0.0-20191205180655-e7c4368fe9dd/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
74 | golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI=
75 | golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
76 | golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
77 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
78 | golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
79 | golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
80 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
81 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
82 | golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
83 | golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
84 | golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20uW+C3Rm0FD/WLDX8884=
85 | golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
86 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
87 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
88 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
89 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
90 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
91 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
92 | gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
93 | gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
94 |
--------------------------------------------------------------------------------
/src/model/fund.go:
--------------------------------------------------------------------------------
1 | package model
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "github.com/jinzhu/gorm"
7 | . "oktools/src/global"
8 | "time"
9 | )
10 |
11 | type FundDataGenerated struct {
12 | Data FundData `json:"data"`
13 | ResultCode int `json:"result_code"`
14 | }
15 | type StockList struct {
16 | Name string `json:"name"`
17 | Code string `json:"code"`
18 | Percent float64 `json:"percent"`
19 | CurrentPrice float64 `json:"current_price"`
20 | ChangePercentage float64 `json:"change_percentage"`
21 | XqSymbol string `json:"xq_symbol"`
22 | XqURL string `json:"xq_url"`
23 | Amarket bool `json:"amarket"`
24 | }
25 | type FundPosition struct {
26 | StockPercent float64 `json:"stock_percent"`
27 | CashPercent float64 `json:"cash_percent"`
28 | OtherPercent float64 `json:"other_percent"`
29 | AssetTot float64 `json:"asset_tot"`
30 | AssetVal float64 `json:"asset_val"`
31 | SourceMark string `json:"source_mark"`
32 | Source string `json:"source"`
33 | Enddate string `json:"enddate"`
34 | StockList []StockList `json:"stock_list"`
35 | BondList []interface{} `json:"bond_list"`
36 | }
37 | type DeclareRateTable struct {
38 | Name string `json:"name"`
39 | Value string `json:"value"`
40 | }
41 | type WithdrawRateTable struct {
42 | Name string `json:"name"`
43 | Value string `json:"value"`
44 | }
45 | type OtherRateTable struct {
46 | Name string `json:"name"`
47 | Value string `json:"value"`
48 | }
49 | type FundRates struct {
50 | FdCode string `json:"fd_code"`
51 | SubscribeRate string `json:"subscribe_rate"`
52 | DeclareRate string `json:"declare_rate"`
53 | WithdrawRate string `json:"withdraw_rate"`
54 | Discount string `json:"discount"`
55 | SubscribeDiscount string `json:"subscribe_discount"`
56 | DeclareDiscount string `json:"declare_discount"`
57 | DeclareRateTable []DeclareRateTable `json:"declare_rate_table"`
58 | WithdrawRateTable []WithdrawRateTable `json:"withdraw_rate_table"`
59 | OtherRateTable []OtherRateTable `json:"other_rate_table"`
60 | }
61 | type AchievementList struct {
62 | FundCode string `json:"fund_code"`
63 | Fundsname string `json:"fundsname"`
64 | PostDate string `json:"post_date"`
65 | CpRate float64 `json:"cp_rate"`
66 | ResiDate string `json:"resi_date,omitempty"`
67 | }
68 | type ManagerList struct {
69 | Name string `json:"name"`
70 | Resume string `json:"resume"`
71 | College string `json:"college"`
72 | AchievementList []AchievementList `json:"achievement_list"`
73 | }
74 | type FundDateConf struct {
75 | FdCode string `json:"fd_code"`
76 | BuyConfirmDate int `json:"buy_confirm_date"`
77 | BuyQueryDate int `json:"buy_query_date"`
78 | SaleConfirmDate int `json:"sale_confirm_date"`
79 | SaleQueryDate int `json:"sale_query_date"`
80 | AllBuyDays int `json:"all_buy_days"`
81 | AllSaleDays int `json:"all_sale_days"`
82 | }
83 | type FundData struct {
84 | FundCompany string `json:"fund_company"`
85 | FundPosition FundPosition `json:"fund_position"`
86 | FundRates FundRates `json:"fund_rates"`
87 | ManagerList []ManagerList `json:"manager_list"`
88 | FundDateConf FundDateConf `json:"fund_date_conf"`
89 | }
90 | type Fund struct {
91 | /*
92 | `id` int(11) NOT NULL AUTO_INCREMENT,
93 | `fund_name` varchar(64) DEFAULT '' COMMENT '基金名称',
94 | `fund_code` varchar(16) NOT NULL DEFAULT '' COMMENT '基金代码',
95 | `managers` varchar(32) NOT NULL DEFAULT '' COMMENT '管理人',
96 | `enddate` varchar(32) NOT NULL DEFAULT '' COMMENT '季报日期',
97 | `type` varchar(32) NOT NULL DEFAULT '' COMMENT '基金类型',
98 | `detail_json` text NOT NULL COMMENT '蛋卷基金详细信息 json',
99 | `created_at` timestamp NULL DEFAULT NULL COMMENT '创建时间',
100 | `updated_at` timestamp NULL DEFAULT NULL COMMENT '更新时间',
101 | `deleted_at` timestamp NULL DEFAULT NULL COMMENT '删除时间',
102 | */
103 |
104 | FundName string `json:"fund_name"`
105 | FundCode string `json:"fund_code"`
106 | Managers string `json:"managers"`
107 | Enddate string `json:"enddate"`
108 | Type string `json:"type"`
109 | DetailJson string `json:"detail_json"`
110 |
111 | ID int64 `json:"id" gorm:"primary_key"`
112 | CreatedAt JSONTime `json:"created_at" gorm:"column:created_at"` //创建日期
113 | UpdatedAt time.Time `json:"-" gorm:"column:updated_at"`
114 | DeletedAt *time.Time `json:"-" gorm:"column:deleted_at" sql:"index"`
115 |
116 | DB *gorm.DB `json:"-" gorm:"-"` // 数据库操作DB
117 |
118 | FundDataShow FundDataGenerated `json:"fund_data_show" gorm:"-"`
119 | }
120 |
121 | /**
122 | * 数据打码
123 | */
124 | func (obj *Fund) Init() {
125 | if obj == nil {
126 | return
127 | }
128 | err := json.Unmarshal([]byte(obj.DetailJson), &obj.FundDataShow)
129 | if err != nil {
130 | fmt.Println(err.Error())
131 | }
132 |
133 | return
134 | }
135 |
136 | /**
137 | * 获取结构体,方便对结构体的数据进行初始化
138 | */
139 | func GetFund() Fund {
140 | var obj Fund
141 | obj.DB = SqlDB.Conn
142 | fmt.Println(SqlDB.Database)
143 | return obj
144 | }
145 |
146 | // 设置User的表名为`profiles`
147 | func (obj Fund) TableName() string {
148 | return "danjuan_fund"
149 | }
150 |
151 | // 获取数据库链接
152 | func (obj Fund) getDB() (db *gorm.DB) {
153 | db = obj.DB
154 | if db == nil {
155 | db = SqlDB.GetConn()
156 | }
157 | db = db.Table(obj.TableName())
158 | db = db.Select(obj.FieldList())
159 | return db
160 | }
161 |
162 | func (obj Fund) FieldList() (fieldList []string) {
163 | fieldList = SqlDB.GetFieldName(obj)
164 | return
165 | }
166 |
167 | //传递过来的json数据初始化
168 | func (obj *Fund) Insert() (id int64, err error) {
169 | err = obj.getDB().Create(&obj).Error
170 | if err == nil {
171 | id = obj.ID
172 | }
173 | return
174 | }
175 |
176 | // 更新部分, 可以清空
177 | func (obj *Fund) Update(id int64, updateData map[string]interface{}) (err error) {
178 | err = obj.Get(id)
179 | if err != nil {
180 | return
181 | }
182 | updateData = SqlDB.CleanChangeMap(updateData, obj)
183 | err = obj.getDB().Model(&obj).Updates(updateData).Error
184 | return
185 | }
186 |
187 | //删除数据
188 | func (obj *Fund) Delete(id int64) (err error) {
189 | err = obj.Get(id)
190 | if err != nil {
191 | return
192 | }
193 | err = obj.getDB().Delete(&obj).Error
194 | return
195 | }
196 |
197 | func (obj *Fund) GetCompanyByBankCardNum(company_id int64, bankNum string) (err error) {
198 | searchMap := make(map[string]string)
199 | searchMap["bd_num"] = bankNum
200 |
201 | err = obj.QueryOneByCondition(searchMap)
202 | return
203 | }
204 |
205 | //获取一个
206 | func (obj *Fund) Get(id int64) (err error) {
207 | err = obj.getDB().First(&obj, id).Error
208 | if err == nil {
209 | obj.Init()
210 | }
211 | return
212 | }
213 |
214 | //获取查询db
215 | func (obj *Fund) QueryDB(db *gorm.DB, searchKey map[string]string) (returnDB *gorm.DB) {
216 |
217 | // 查询扩展
218 | // 字段中如果字段 为 realname
219 | // 则默认支持以下查询
220 | // searchKey["realname"] 精确查询 "realname = ?", "%" + searchKey["realname_min"] + "%"
221 | // searchKey["realname_not"] 精确查询 "realname <> ?", "%" + searchKey["realname_min"] + "%"
222 | // searchKey["realname_like"] 模糊查询 "realname like ?", "%" + searchKey["realname_min"] + "%"
223 | // searchKey["realname_left_like"] 模糊左匹配查询 "realname like ?", searchKey["realname_min"] + "%"
224 | // searchKey["realname_min"] 查询 "realname >= ?" , searchKey["realname_min"]
225 | // searchKey["realname_max"] 查询 "realname <= ?" , searchKey["realname_min"]
226 | db = SqlDB.QueryDbInit(db, obj.FieldList(), searchKey)
227 |
228 | returnDB = db
229 | return
230 | }
231 |
232 | func (obj *Fund) QueryOneByCondition(searchKey map[string]string) (err error) {
233 | db := obj.getDB()
234 | db = obj.QueryDB(db, searchKey)
235 | err = db.First(&obj).Error
236 |
237 | if err == nil {
238 | obj.Init()
239 | }
240 |
241 | return
242 | }
243 |
244 | //列表
245 | func (obj *Fund) List(searchKey map[string]string, page int64, pageSize int64) (results []Fund, err error) {
246 | db := obj.getDB()
247 |
248 | db = obj.QueryDB(db, searchKey)
249 |
250 | // 待调整成
251 | // select a.* from 表1 a, (select id from 表1 where 条件 limit 100000,20) b where a.id=b.id
252 | //
253 |
254 | // 分页
255 | if page > 0 && pageSize > 0 {
256 | if page <= 30 {
257 | //30页前直接获取
258 | db = db.Limit(pageSize).Offset((page - 1) * pageSize)
259 | } else {
260 |
261 | db = db.Select("id as b__id")
262 | db = db.Limit(pageSize).Offset((page - 1) * pageSize)
263 |
264 | db = obj.getDB().
265 | Table(obj.TableName()).
266 | Joins("join (?) b on id = b__id", db.QueryExpr())
267 | }
268 | } else {
269 | if pageSize > 0 {
270 | db = db.Limit(pageSize)
271 | }
272 | }
273 |
274 | // 查询数据
275 | err = db.Find(&results).Error
276 |
277 | if err == nil {
278 | for k, _ := range results {
279 | (&results[k]).Init()
280 | }
281 | }
282 | return
283 | }
284 |
285 | //获取数量
286 | func (obj *Fund) Count(searchKey map[string]string) (totalSize int64, err error) {
287 | db := obj.getDB().Where("deleted_at is null")
288 | err = obj.QueryDB(db, searchKey).Count(&totalSize).Error
289 |
290 | return
291 | }
292 |
--------------------------------------------------------------------------------
|