Created
April 19, 2018 12:09
-
-
Save samonzeweb/4d9fe0d50f2b4099c1531d401f7f2ff5 to your computer and use it in GitHub Desktop.
Use of github.com/shopspring/decimal with SQL Server (through godb)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"github.com/samonzeweb/godb" | |
"github.com/samonzeweb/godb/adapters/mssql" | |
"github.com/samonzeweb/godb/dbreflect" | |
"github.com/shopspring/decimal" | |
) | |
// CREATE TABLE [dbo].[Montants]( | |
// [Id] [int] IDENTITY(1,1) NOT NULL, | |
// [Version] [timestamp] NOT NULL, | |
// [Montant] [decimal](12, 2) NOT NULL, | |
// [Libelle] [nvarchar](64) NOT NULL, | |
// CONSTRAINT [PK_Montants] PRIMARY KEY CLUSTERED | |
// ( | |
// [Id] ASC | |
// )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] | |
// ) ON [PRIMARY] | |
const connString string = "XXXXX" // replace with a valid one | |
type Montant struct { | |
Id int `db:"Id,key,auto"` | |
Libelle string `db:"Libelle"` | |
Montant decimal.Decimal `db:"Montant"` | |
} | |
func (Montant) TableName() string { | |
return "Montants" | |
} | |
func main() { | |
dbreflect.RegisterScannableStruct(decimal.Decimal{}) | |
db, err := godb.Open(mssql.Adapter, connString) | |
panicIfErr(err) | |
defer db.Close() | |
_, err = db.CurrentDB().Exec("truncate table Montants") | |
panicIfErr(err) | |
// Insert | |
err = db.Begin() | |
panicIfErr(err) | |
n := 0 | |
montantsToInsert := make([]*Montant, 0, 1000) | |
for i := 0; i < 10000000; i += 97 { | |
decVal := decimal.NewFromFloat(float64(i) / 100.0) | |
decVal = decVal.Round(2) | |
montant := Montant{ | |
Libelle: decVal.String(), | |
Montant: decVal, | |
} | |
montantsToInsert = append(montantsToInsert, &montant) | |
n++ | |
if n >= 1000 { | |
err := db.BulkInsert(&montantsToInsert).Do() | |
panicIfErr(err) | |
montantsToInsert = montantsToInsert[:0] | |
n = 0 | |
} | |
} | |
err = db.BulkInsert(&montantsToInsert).Do() | |
panicIfErr(err) | |
err = db.Commit() | |
panicIfErr(err) | |
// Select | |
montants := make([]Montant, 0, 11000) | |
err = db.Select(&montants).OrderBy("Id").Do() | |
panicIfErr(err) | |
for _, montant := range montants { | |
fmt.Printf("%d %s %v\n", montant.Id, montant.Libelle, montant.Montant) | |
} | |
fmt.Println("That's all folks !") | |
} | |
func panicIfErr(err error) { | |
if err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment