示例#1
0
func (ss SqlStore) RemoveColumnIfExists(tableName string, columnName string) bool {
	count, err := ss.GetMaster().SelectInt(
		`SELECT 
		    COUNT(0) AS column_exists
		FROM
		    information_schema.COLUMNS
		WHERE
		    TABLE_SCHEMA = DATABASE()
		        AND TABLE_NAME = ?
		        AND COLUMN_NAME = ?`,
		tableName,
		columnName,
	)
	if err != nil {
		l4g.Critical("Failed to check if column exists %v", err)
		time.Sleep(time.Second)
		panic("Failed to check if column exists " + err.Error())
	}

	if count == 0 {
		return false
	}

	_, err = ss.GetMaster().Exec("ALTER TABLE " + tableName + " DROP COLUMN " + columnName)
	if err != nil {
		l4g.Critical("Failed to drop column %v", err)
		time.Sleep(time.Second)
		panic("Failed to drop column " + err.Error())
	}

	return true
}
示例#2
0
func RedisClient() *redis.Client {

	if client == nil {

		addr := utils.Cfg.RedisSettings.DataSource

		client = redis.NewTCPClient(&redis.Options{
			Addr:     addr,
			Password: "",
			DB:       0,
			PoolSize: utils.Cfg.RedisSettings.MaxOpenConns,
		})

		l4g.Info("Pinging redis at '%v'", addr)
		pong, err := client.Ping().Result()

		if err != nil {
			l4g.Critical("Failed to open redis connection to '%v' err:%v", addr, err)
			time.Sleep(time.Second)
			panic("Failed to open redis connection " + err.Error())
		}

		if pong != "PONG" {
			l4g.Critical("Failed to ping redis connection to '%v' err:%v", addr, err)
			time.Sleep(time.Second)
			panic("Failed to open ping connection " + err.Error())
		}
	}

	return client
}
示例#3
0
func (ss SqlStore) CreateColumnIfNotExists(tableName string, columnName string, mySqlColType string, postgresColType string, defaultValue string) bool {

	if ss.DoesColumnExist(tableName, columnName) {
		return false
	}

	if utils.Cfg.SqlSettings.DriverName == "postgres" {
		_, err := ss.GetMaster().Exec("ALTER TABLE " + tableName + " ADD " + columnName + " " + postgresColType + " DEFAULT '" + defaultValue + "'")
		if err != nil {
			l4g.Critical("Failed to create column %v", err)
			time.Sleep(time.Second)
			panic("Failed to create column " + err.Error())
		}

		return true

	} else if utils.Cfg.SqlSettings.DriverName == "mysql" {
		_, err := ss.GetMaster().Exec("ALTER TABLE " + tableName + " ADD " + columnName + " " + mySqlColType + " DEFAULT '" + defaultValue + "'")
		if err != nil {
			l4g.Critical("Failed to create column %v", err)
			time.Sleep(time.Second)
			panic("Failed to create column " + err.Error())
		}

		return true

	} else {
		l4g.Critical("Failed to create column because of missing driver")
		time.Sleep(time.Second)
		panic("Failed to create column because of missing driver")
	}
}
示例#4
0
func (ss SqlStore) CreateColumnIfNotExists(tableName string, columnName string, afterName string, colType string, defaultValue string) bool {
	count, err := ss.GetMaster().SelectInt(
		`SELECT 
		    COUNT(0) AS column_exists
		FROM
		    information_schema.COLUMNS
		WHERE
		    TABLE_SCHEMA = DATABASE()
		        AND TABLE_NAME = ?
		        AND COLUMN_NAME = ?`,
		tableName,
		columnName,
	)
	if err != nil {
		l4g.Critical("Failed to check if column exists %v", err)
		time.Sleep(time.Second)
		panic("Failed to check if column exists " + err.Error())
	}

	if count > 0 {
		return false
	}

	_, err = ss.GetMaster().Exec("ALTER TABLE " + tableName + " ADD " + columnName + " " + colType + " DEFAULT '" + defaultValue + "'" + " AFTER " + afterName)
	if err != nil {
		l4g.Critical("Failed to create column %v", err)
		time.Sleep(time.Second)
		panic("Failed to create column " + err.Error())
	}

	return true
}
示例#5
0
func (ss SqlStore) DoesColumnExist(tableName string, columnName string) bool {
	if utils.Cfg.SqlSettings.DriverName == model.DATABASE_DRIVER_POSTGRES {
		count, err := ss.GetMaster().SelectInt(
			`SELECT COUNT(0)
			FROM   pg_attribute
			WHERE  attrelid = $1::regclass
			AND    attname = $2
			AND    NOT attisdropped`,
			strings.ToLower(tableName),
			strings.ToLower(columnName),
		)

		if err != nil {
			if err.Error() == "pq: relation \""+strings.ToLower(tableName)+"\" does not exist" {
				return false
			}

			l4g.Critical("Failed to check if column exists %v", err)
			time.Sleep(time.Second)
			panic("Failed to check if column exists " + err.Error())
		}

		return count > 0

	} else if utils.Cfg.SqlSettings.DriverName == model.DATABASE_DRIVER_MYSQL {

		count, err := ss.GetMaster().SelectInt(
			`SELECT
		    COUNT(0) AS column_exists
		FROM
		    information_schema.COLUMNS
		WHERE
		    TABLE_SCHEMA = DATABASE()
		        AND TABLE_NAME = ?
		        AND COLUMN_NAME = ?`,
			tableName,
			columnName,
		)

		if err != nil {
			l4g.Critical("Failed to check if column exists %v", err)
			time.Sleep(time.Second)
			panic("Failed to check if column exists " + err.Error())
		}

		return count > 0

	} else {
		l4g.Critical("Failed to check if column exists because of missing driver")
		time.Sleep(time.Second)
		panic("Failed to check if column exists because of missing driver")
	}

}
示例#6
0
func (ss SqlStore) createIndexIfNotExists(indexName string, tableName string, columnName string, fullText bool) {

	if utils.Cfg.SqlSettings.DriverName == "postgres" {
		_, err := ss.GetMaster().SelectStr("SELECT to_regclass($1)", indexName)
		// It should fail if the index does not exist
		if err == nil {
			return
		}

		query := ""
		if fullText {
			query = "CREATE INDEX " + indexName + " ON " + tableName + " USING gin(to_tsvector('english', " + columnName + "))"
		} else {
			query = "CREATE INDEX " + indexName + " ON " + tableName + " (" + columnName + ")"
		}

		_, err = ss.GetMaster().Exec(query)
		if err != nil {
			l4g.Critical("Failed to create index %v", err)
			time.Sleep(time.Second)
			panic("Failed to create index " + err.Error())
		}
	} else if utils.Cfg.SqlSettings.DriverName == "mysql" {

		count, err := ss.GetMaster().SelectInt("SELECT COUNT(0) AS index_exists FROM information_schema.statistics WHERE TABLE_SCHEMA = DATABASE() and table_name = ? AND index_name = ?", tableName, indexName)
		if err != nil {
			l4g.Critical("Failed to check index %v", err)
			time.Sleep(time.Second)
			panic("Failed to check index " + err.Error())
		}

		if count > 0 {
			return
		}

		fullTextIndex := ""
		if fullText {
			fullTextIndex = " FULLTEXT "
		}

		_, err = ss.GetMaster().Exec("CREATE " + fullTextIndex + " INDEX " + indexName + " ON " + tableName + " (" + columnName + ")")
		if err != nil {
			l4g.Critical("Failed to create index %v", err)
			time.Sleep(time.Second)
			panic("Failed to create index " + err.Error())
		}
	} else {
		l4g.Critical("Failed to create index because of missing driver")
		time.Sleep(time.Second)
		panic("Failed to create index because of missing driver")
	}
}
示例#7
0
// Finalizes Application configuration and starts the application webserver
func (a *Application) Start() error {
	http.HandleFunc("/", a.outerHandler)

	err := a.Server.ListenAndServe()
	log.Critical(err)
	return err
}
示例#8
0
func (ss SqlStore) DoesColumnExist(tableName string, columnName string) bool {
	// XXX TODO FIXME this should be removed after 0.6.0
	if utils.Cfg.SqlSettings.DriverName == "postgres" {
		return false
	}

	count, err := ss.GetMaster().SelectInt(
		`SELECT
		    COUNT(0) AS column_exists
		FROM
		    information_schema.COLUMNS
		WHERE
		    TABLE_SCHEMA = DATABASE()
		        AND TABLE_NAME = ?
		        AND COLUMN_NAME = ?`,
		tableName,
		columnName,
	)
	if err != nil {
		l4g.Critical("Failed to check if column exists %v", err)
		time.Sleep(time.Second)
		panic("Failed to check if column exists " + err.Error())
	}

	return count > 0
}
示例#9
0
func (ctx *AntUsbContext) ListAntUsbDevices() ([]*AntUsbDevice, error) {
	devs, err := ctx.usb.ListDevices(func(desc *usb.Descriptor) bool {
		log4go.Debug("Found %03d.%03d %s:%s %s\n", desc.Bus, desc.Address, desc.Vendor, desc.Product, usbid.Describe(desc))

		// The usbid package can be used to print out human readable information.
		log4go.Debug("  Protocol: %s\n", usbid.Classify(desc))

		// We are looking for the specific vendor and device
		if desc.Vendor == ANT_VENDOR_ID && desc.Product == ANT_PRODUCT_ID {
			log4go.Debug("This is an ANT device")

			// The configurations can be examined from the Descriptor, though they can only
			// be set once the device is opened.  All configuration references must be closed,
			// to free up the memory in libusb.
			for _, cfg := range desc.Configs {
				// This loop just uses more of the built-in and usbid pretty printing to list
				// the USB devices.
				log4go.Debug("  %s:\n", cfg)
				for _, alt := range cfg.Interfaces {
					log4go.Debug("    --------------\n")
					for _, iface := range alt.Setups {
						log4go.Debug("(iface)    %s\n", iface)
						log4go.Debug("(classify)      %s\n", usbid.Classify(iface))
						for _, end := range iface.Endpoints {
							log4go.Debug("(end)      %s\n", end)
							log4go.Debug("	number: %s\n", end.Number())
							log4go.Debug("	address: %s\n", end.Address)
							log4go.Debug("	sync: %s\n", end.SynchAddress)
						}
					}
				}
				log4go.Debug("    --------------\n")
			}

			return true
		}

		return false
	})

	// ListDevices can occaionally fail, so be sure to check its return value.
	if err != nil {
		log4go.Critical("list: %s", err)
		return nil, err
	}

	nDevices := len(devs)
	channels := make([]*AntUsbDevice, nDevices)
	for i := 0; i < len(devs); i++ {
		usbDevice := devs[i]
		channels[i], err = newAntUsbDevice(usbDevice)

		if err != nil {
			panic(err)
		}
	}
	return channels, nil
}
示例#10
0
func setupConnection(con_type string, driver string, dataSource string, maxIdle int, maxOpen int, trace bool) *gorp.DbMap {

	charset := ""
	if strings.Index(dataSource, "?") > -1 {
		charset = "&charset=utf8mb4,utf8"
	} else {
		charset = "?charset=utf8mb4,utf8"
	}

	db, err := dbsql.Open(driver, dataSource+charset)
	if err != nil {
		l4g.Critical("Failed to open sql connection to '%v' err:%v", dataSource, err)
		time.Sleep(time.Second)
		panic("Failed to open sql connection" + err.Error())
	}

	l4g.Info("Pinging sql %v database at '%v'", con_type, dataSource)
	err = db.Ping()
	if err != nil {
		l4g.Critical("Failed to ping db err:%v", err)
		time.Sleep(time.Second)
		panic("Failed to open sql connection " + err.Error())
	}

	db.SetMaxIdleConns(maxIdle)
	db.SetMaxOpenConns(maxOpen)

	var dbmap *gorp.DbMap

	if driver == "sqlite3" {
		dbmap = &gorp.DbMap{Db: db, TypeConverter: mattermConverter{}, Dialect: gorp.SqliteDialect{}}
	} else if driver == "mysql" {
		dbmap = &gorp.DbMap{Db: db, TypeConverter: mattermConverter{}, Dialect: gorp.MySQLDialect{Engine: "InnoDB", Encoding: "UTF8MB4"}}
	} else {
		l4g.Critical("Failed to create dialect specific driver")
		time.Sleep(time.Second)
		panic("Failed to create dialect specific driver " + err.Error())
	}

	if trace {
		dbmap.TraceOn("", sqltrace.New(os.Stdout, "sql-trace:", sqltrace.Lmicroseconds))
	}

	return dbmap
}
示例#11
0
func (ss SqlStore) DoesTableExist(tableName string) bool {
	if utils.Cfg.SqlSettings.DriverName == model.DATABASE_DRIVER_POSTGRES {
		count, err := ss.GetMaster().SelectInt(
			`SELECT count(relname) FROM pg_class WHERE relname=$1`,
			strings.ToLower(tableName),
		)

		if err != nil {
			l4g.Critical("Failed to check if table exists %v", err)
			time.Sleep(time.Second)
			panic("Failed to check if table exists " + err.Error())
		}

		return count > 0

	} else if utils.Cfg.SqlSettings.DriverName == model.DATABASE_DRIVER_MYSQL {

		count, err := ss.GetMaster().SelectInt(
			`SELECT
		    COUNT(0) AS table_exists
			FROM
			    information_schema.TABLES
			WHERE
			    TABLE_SCHEMA = DATABASE()
			        AND TABLE_NAME = ?
		    `,
			tableName,
		)

		if err != nil {
			l4g.Critical("Failed to check if table exists %v", err)
			time.Sleep(time.Second)
			panic("Failed to check if table exists " + err.Error())
		}

		return count > 0

	} else {
		l4g.Critical("Failed to check if column exists because of missing driver")
		time.Sleep(time.Second)
		panic("Failed to check if column exists because of missing driver")
	}

}
示例#12
0
文件: main.go 项目: pjvds/promise
func Serve(info *ServeInfo) {
	ctrl := info.promiseTicketController

	http.Handle("/", http.FileServer(http.Dir("static")))
	http.HandleFunc("/api/v1/promise", func(w http.ResponseWriter, r *http.Request) {
		ctrl.Handle(w, r)
	})

	log.Info("Serving at " + info.uri)
	log.Critical(http.ListenAndServe(info.uri, Log(http.DefaultServeMux)))
}
示例#13
0
func setupConnection(con_type string, driver string, dataSource string, maxIdle int, maxOpen int, trace bool) *gorp.DbMap {

	db, err := dbsql.Open(driver, dataSource)
	if err != nil {
		l4g.Critical("Failed to open sql connection to err:%v", err)
		time.Sleep(time.Second)
		panic("Failed to open sql connection" + err.Error())
	}

	l4g.Info("Pinging sql %v database", con_type)
	err = db.Ping()
	if err != nil {
		l4g.Critical("Failed to ping db err:%v", err)
		time.Sleep(time.Second)
		panic("Failed to open sql connection " + err.Error())
	}

	db.SetMaxIdleConns(maxIdle)
	db.SetMaxOpenConns(maxOpen)

	var dbmap *gorp.DbMap

	if driver == "sqlite3" {
		dbmap = &gorp.DbMap{Db: db, TypeConverter: mattermConverter{}, Dialect: gorp.SqliteDialect{}}
	} else if driver == model.DATABASE_DRIVER_MYSQL {
		//dbmap = &gorp.DbMap{Db: db, TypeConverter: mattermConverter{}, Dialect: gorp.MySQLDialect{Engine: "InnoDB", Encoding: "UTF8MB4"}}
		dbmap = &gorp.DbMap{Db: db, TypeConverter: mattermConverter{}, Dialect: gorp.MySQLDialect{Engine: "MyISAM", Encoding: "UTF8"}}
	} else if driver == model.DATABASE_DRIVER_POSTGRES {
		dbmap = &gorp.DbMap{Db: db, TypeConverter: mattermConverter{}, Dialect: gorp.PostgresDialect{}}
	} else {
		l4g.Critical("Failed to create dialect specific driver")
		time.Sleep(time.Second)
		panic("Failed to create dialect specific driver " + err.Error())
	}

	if trace {
		dbmap.TraceOn("", sqltrace.New(os.Stdout, "sql-trace:", sqltrace.Lmicroseconds))
	}

	return dbmap
}
示例#14
0
文件: main.go 项目: nhelke/dht
func main() {
	flag.Parse()
	// Change to l4g.DEBUG to see *lots* of debugging information.
	l4g.AddFilter("stdout", l4g.WARNING, l4g.NewConsoleLogWriter())
	if len(flag.Args()) != 1 {
		fmt.Fprintf(os.Stderr, "Usage: %v <infohash>\n\n", os.Args[0])
		fmt.Fprintf(os.Stderr, "Example infohash: d1c5676ae7ac98e8b19f63565905105e3c4c37a2\n")
		flag.PrintDefaults()
		os.Exit(1)
	}
	ih, err := dht.DecodeInfoHash(flag.Args()[0])
	if err != nil {
		l4g.Critical("DecodeInfoHash error: %v\n", err)
		os.Exit(1)
	}

	// This is a hint to the DHT of the minimum number of peers it will try to
	// find for the given node. This is not a reliable limit. In the future this
	// might be moved to "PeersRequest()", so the controlling client can have
	// different targets at different moments or for different infohashes.
	targetNumPeers := 5
	d, err := dht.NewDHTNode(dhtPortUDP, targetNumPeers, false)
	if err != nil {
		l4g.Critical("NewDHTNode error: %v", err)
		os.Exit(1)

	}
	// For debugging.
	go http.ListenAndServe(fmt.Sprintf(":%d", httpPortTCP), nil)

	go d.DoDHT()
	go drainresults(d)

	for {
		// Give the DHT some time to "warm-up" its routing table.
		time.Sleep(5 * time.Second)

		d.PeersRequest(string(ih), false)
	}
}
示例#15
0
func (ss SqlStore) GetColumnDataType(tableName, columnName string) string {
	dataType, err := ss.GetMaster().SelectStr("SELECT data_type FROM INFORMATION_SCHEMA.COLUMNS where table_name = :Tablename AND column_name = :Columnname", map[string]interface{}{
		"Tablename":  tableName,
		"Columnname": columnName,
	})
	if err != nil {
		l4g.Critical("Failed to get data type for column %s from table %s: %v", columnName, tableName, err.Error())
		time.Sleep(time.Second)
		panic("Failed to get get data type for column " + columnName + " from table " + tableName + ": " + err.Error())
	}

	return dataType
}
示例#16
0
func StartServer() {
	l4g.Info("Starting Server...")

	l4g.Info("Server is listening on " + utils.Cfg.ServiceSettings.Port)
	go func() {
		err := Srv.Server.ListenAndServe(":"+utils.Cfg.ServiceSettings.Port, Srv.Router)
		if err != nil {
			l4g.Critical("Error starting server, err:%v", err)
			time.Sleep(time.Second)
			panic("Error starting server " + err.Error())
		}
	}()
}
示例#17
0
func (ss SqlStore) RemoveColumnIfExists(tableName string, columnName string) bool {
	if !ss.DoesColumnExist(tableName, columnName) {
		return false
	}

	_, err := ss.GetMaster().Exec("ALTER TABLE " + tableName + " DROP COLUMN " + columnName)
	if err != nil {
		l4g.Critical("Failed to drop column %v", err)
		time.Sleep(time.Second)
		panic("Failed to drop column " + err.Error())
	}

	return true
}
示例#18
0
func (ss SqlStore) CreateColumnIfNotExists(tableName string, columnName string, afterName string, colType string, defaultValue string) bool {
	if ss.DoesColumnExist(tableName, columnName) {
		return false
	}

	_, err := ss.GetMaster().Exec("ALTER TABLE " + tableName + " ADD " + columnName + " " + colType + " DEFAULT '" + defaultValue + "'" + " AFTER " + afterName)
	if err != nil {
		l4g.Critical("Failed to create column %v", err)
		time.Sleep(time.Second)
		panic("Failed to create column " + err.Error())
	}

	return true
}
示例#19
0
func (ss SqlStore) createIndexIfNotExists(indexName string, tableName string, columnName string, fullText bool) {
	count, err := ss.GetMaster().SelectInt("SELECT COUNT(0) AS index_exists FROM information_schema.statistics WHERE TABLE_SCHEMA = DATABASE() and table_name = ? AND index_name = ?", tableName, indexName)
	if err != nil {
		l4g.Critical("Failed to check index", err)
		time.Sleep(time.Second)
		panic("Failed to check index" + err.Error())
	}

	if count > 0 {
		return
	}

	fullTextIndex := ""
	if fullText {
		fullTextIndex = " FULLTEXT "
	}

	_, err = ss.GetMaster().Exec("CREATE " + fullTextIndex + " INDEX " + indexName + " ON " + tableName + " (" + columnName + ")")
	if err != nil {
		l4g.Critical("Failed to create index", err)
		time.Sleep(time.Second)
		panic("Failed to create index " + err.Error())
	}
}
示例#20
0
func (s SqlPostStore) UpgradeSchemaIfNeeded() {
	colType := s.GetColumnDataType("Posts", "Props")
	if colType != "text" {

		query := "ALTER TABLE Posts MODIFY COLUMN Props TEXT"
		if utils.Cfg.SqlSettings.DriverName == model.DATABASE_DRIVER_POSTGRES {
			query = "ALTER TABLE Posts ALTER COLUMN Props TYPE text"
		}

		_, err := s.GetMaster().Exec(query)
		if err != nil {
			l4g.Critical("Failed to alter column Posts.Props to TEXT: " + err.Error())
			time.Sleep(time.Second)
			panic("Failed to alter column Posts.Props to TEXT: " + err.Error())
		}
	}
}
示例#21
0
func (ss SqlStore) RenameColumnIfExists(tableName string, oldColumnName string, newColumnName string, colType string) bool {
	if !ss.DoesColumnExist(tableName, oldColumnName) {
		return false
	}

	_, err := ss.GetMaster().Exec("ALTER TABLE " + tableName + " CHANGE " + oldColumnName + " " + newColumnName + " " + colType)

	// when we eventually support PostgreSQL, we can use the following instead
	//_, err := ss.GetMaster().Exec("ALTER TABLE " + tableName + " RENAME COLUMN " + oldColumnName + " TO " + newColumnName)

	if err != nil {
		l4g.Critical("Failed to rename column %v", err)
		time.Sleep(time.Second)
		panic("Failed to drop column " + err.Error())
	}

	return true
}
示例#22
0
文件: server.go 项目: no2key/platform
func StartServer() {
	l4g.Info("Starting Server...")
	l4g.Info("Server is listening on " + utils.Cfg.ServiceSettings.ListenAddress)

	var handler http.Handler = Srv.Router

	if utils.Cfg.RateLimitSettings.EnableRateLimiter {
		l4g.Info("RateLimiter is enabled")

		vary := throttled.VaryBy{}

		if utils.Cfg.RateLimitSettings.VaryByRemoteAddr {
			vary.RemoteAddr = true
		}

		if len(utils.Cfg.RateLimitSettings.VaryByHeader) > 0 {
			vary.Headers = strings.Fields(utils.Cfg.RateLimitSettings.VaryByHeader)

			if utils.Cfg.RateLimitSettings.VaryByRemoteAddr {
				l4g.Warn("RateLimitSettings not configured properly using VaryByHeader and disabling VaryByRemoteAddr")
				vary.RemoteAddr = false
			}
		}

		th := throttled.RateLimit(throttled.PerSec(utils.Cfg.RateLimitSettings.PerSec), &vary, throttledStore.NewMemStore(utils.Cfg.RateLimitSettings.MemoryStoreSize))

		th.DeniedHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			l4g.Error("%v: code=429 ip=%v", r.URL.Path, GetIpAddress(r))
			throttled.DefaultDeniedHandler.ServeHTTP(w, r)
		})

		handler = th.Throttle(Srv.Router)
	}

	go func() {
		err := Srv.Server.ListenAndServe(utils.Cfg.ServiceSettings.ListenAddress, handler)
		if err != nil {
			l4g.Critical("Error starting server, err:%v", err)
			time.Sleep(time.Second)
			panic("Error starting server " + err.Error())
		}
	}()
}
示例#23
0
func (ss SqlStore) RenameColumnIfExists(tableName string, oldColumnName string, newColumnName string, colType string) bool {
	if !ss.DoesColumnExist(tableName, oldColumnName) {
		return false
	}

	var err error
	if utils.Cfg.SqlSettings.DriverName == model.DATABASE_DRIVER_MYSQL {
		_, err = ss.GetMaster().Exec("ALTER TABLE " + tableName + " CHANGE " + oldColumnName + " " + newColumnName + " " + colType)
	} else if utils.Cfg.SqlSettings.DriverName == model.DATABASE_DRIVER_POSTGRES {
		_, err = ss.GetMaster().Exec("ALTER TABLE " + tableName + " RENAME COLUMN " + oldColumnName + " TO " + newColumnName)
	}

	if err != nil {
		l4g.Critical("Failed to rename column %v", err)
		time.Sleep(time.Second)
		panic("Failed to drop column " + err.Error())
	}

	return true
}
示例#24
0
func (ss SqlStore) RemoveColumnIfExists(tableName string, columnName string) bool {

	// XXX TODO FIXME this should be removed after 0.6.0
	if utils.Cfg.SqlSettings.DriverName == "postgres" {
		return false
	}

	if !ss.DoesColumnExist(tableName, columnName) {
		return false
	}

	_, err := ss.GetMaster().Exec("ALTER TABLE " + tableName + " DROP COLUMN " + columnName)
	if err != nil {
		l4g.Critical("Failed to drop column %v", err)
		time.Sleep(time.Second)
		panic("Failed to drop column " + err.Error())
	}

	return true
}
示例#25
0
func (ss SqlStore) CreateColumnIfNotExists(tableName string, columnName string, afterName string, colType string, defaultValue string) bool {

	// XXX TODO FIXME this should be removed after 0.6.0
	if utils.Cfg.SqlSettings.DriverName == "postgres" {
		return false
	}

	if ss.DoesColumnExist(tableName, columnName) {
		return false
	}

	_, err := ss.GetMaster().Exec("ALTER TABLE " + tableName + " ADD " + columnName + " " + colType + " DEFAULT '" + defaultValue + "'" + " AFTER " + afterName)
	if err != nil {
		l4g.Critical("Failed to create column %v", err)
		time.Sleep(time.Second)
		panic("Failed to create column " + err.Error())
	}

	return true
}
示例#26
0
func (ss SqlStore) DoesColumnExist(tableName string, columnName string) bool {
	count, err := ss.GetMaster().SelectInt(
		`SELECT
		    COUNT(0) AS column_exists
		FROM
		    information_schema.COLUMNS
		WHERE
		    TABLE_SCHEMA = DATABASE()
		        AND TABLE_NAME = ?
		        AND COLUMN_NAME = ?`,
		tableName,
		columnName,
	)
	if err != nil {
		l4g.Critical("Failed to check if column exists %v", err)
		time.Sleep(time.Second)
		panic("Failed to check if column exists " + err.Error())
	}

	return count > 0
}
示例#27
0
func NewSqlStore() Store {

	sqlStore := &SqlStore{}

	sqlStore.master = setupConnection("master", utils.Cfg.SqlSettings.DriverName,
		utils.Cfg.SqlSettings.DataSource, utils.Cfg.SqlSettings.MaxIdleConns,
		utils.Cfg.SqlSettings.MaxOpenConns, utils.Cfg.SqlSettings.Trace)

	if len(utils.Cfg.SqlSettings.DataSourceReplicas) == 0 {
		sqlStore.replicas = make([]*gorp.DbMap, 1)
		sqlStore.replicas[0] = setupConnection(fmt.Sprintf("replica-%v", 0), utils.Cfg.SqlSettings.DriverName, utils.Cfg.SqlSettings.DataSource,
			utils.Cfg.SqlSettings.MaxIdleConns, utils.Cfg.SqlSettings.MaxOpenConns,
			utils.Cfg.SqlSettings.Trace)
	} else {
		sqlStore.replicas = make([]*gorp.DbMap, len(utils.Cfg.SqlSettings.DataSourceReplicas))
		for i, replica := range utils.Cfg.SqlSettings.DataSourceReplicas {
			sqlStore.replicas[i] = setupConnection(fmt.Sprintf("replica-%v", i), utils.Cfg.SqlSettings.DriverName, replica,
				utils.Cfg.SqlSettings.MaxIdleConns, utils.Cfg.SqlSettings.MaxOpenConns,
				utils.Cfg.SqlSettings.Trace)
		}
	}

	schemaVersion := sqlStore.GetCurrentSchemaVersion()
	isSchemaVersion07 := false // REMOVE AFTER 1.2 SHIP see PLT-828
	isSchemaVersion10 := false // REMOVE AFTER 1.2 SHIP see PLT-828

	// If the version is already set then we are potentially in an 'upgrade needed' state
	if schemaVersion != "" {
		// Check to see if it's the most current database schema version
		if !model.IsCurrentVersion(schemaVersion) {
			// If we are upgrading from the previous version then print a warning and continue

			// Special case
			if schemaVersion == "0.7.1" || schemaVersion == "0.7.0" {
				isSchemaVersion07 = true
			}

			if schemaVersion == "1.0.0" {
				isSchemaVersion10 = true
			}

			if model.IsPreviousVersion(schemaVersion) || isSchemaVersion07 || isSchemaVersion10 {
				l4g.Warn("The database schema version of " + schemaVersion + " appears to be out of date")
				l4g.Warn("Attempting to upgrade the database schema version to " + model.CurrentVersion)
			} else {
				// If this is an 'upgrade needed' state but the user is attempting to skip a version then halt the world
				l4g.Critical("The database schema version of " + schemaVersion + " cannot be upgraded.  You must not skip a version.")
				time.Sleep(time.Second)
				panic("The database schema version of " + schemaVersion + " cannot be upgraded.  You must not skip a version.")
			}
		}
	}

	// REMOVE AFTER 1.2 SHIP see PLT-828
	if sqlStore.DoesTableExist("Sessions") {
		if sqlStore.DoesColumnExist("Sessions", "AltId") {
			sqlStore.GetMaster().Exec("DROP TABLE IF EXISTS Sessions")
		}
	}

	sqlStore.team = NewSqlTeamStore(sqlStore)
	sqlStore.channel = NewSqlChannelStore(sqlStore)
	sqlStore.post = NewSqlPostStore(sqlStore)
	sqlStore.user = NewSqlUserStore(sqlStore)
	sqlStore.audit = NewSqlAuditStore(sqlStore)
	sqlStore.session = NewSqlSessionStore(sqlStore)
	sqlStore.oauth = NewSqlOAuthStore(sqlStore)
	sqlStore.system = NewSqlSystemStore(sqlStore)
	sqlStore.webhook = NewSqlWebhookStore(sqlStore)
	sqlStore.preference = NewSqlPreferenceStore(sqlStore)

	sqlStore.master.CreateTablesIfNotExists()

	sqlStore.team.(*SqlTeamStore).UpgradeSchemaIfNeeded()
	sqlStore.channel.(*SqlChannelStore).UpgradeSchemaIfNeeded()
	sqlStore.post.(*SqlPostStore).UpgradeSchemaIfNeeded()
	sqlStore.user.(*SqlUserStore).UpgradeSchemaIfNeeded()
	sqlStore.audit.(*SqlAuditStore).UpgradeSchemaIfNeeded()
	sqlStore.session.(*SqlSessionStore).UpgradeSchemaIfNeeded()
	sqlStore.oauth.(*SqlOAuthStore).UpgradeSchemaIfNeeded()
	sqlStore.system.(*SqlSystemStore).UpgradeSchemaIfNeeded()
	sqlStore.webhook.(*SqlWebhookStore).UpgradeSchemaIfNeeded()
	sqlStore.preference.(*SqlPreferenceStore).UpgradeSchemaIfNeeded()

	sqlStore.team.(*SqlTeamStore).CreateIndexesIfNotExists()
	sqlStore.channel.(*SqlChannelStore).CreateIndexesIfNotExists()
	sqlStore.post.(*SqlPostStore).CreateIndexesIfNotExists()
	sqlStore.user.(*SqlUserStore).CreateIndexesIfNotExists()
	sqlStore.audit.(*SqlAuditStore).CreateIndexesIfNotExists()
	sqlStore.session.(*SqlSessionStore).CreateIndexesIfNotExists()
	sqlStore.oauth.(*SqlOAuthStore).CreateIndexesIfNotExists()
	sqlStore.system.(*SqlSystemStore).CreateIndexesIfNotExists()
	sqlStore.webhook.(*SqlWebhookStore).CreateIndexesIfNotExists()
	sqlStore.preference.(*SqlPreferenceStore).CreateIndexesIfNotExists()

	if model.IsPreviousVersion(schemaVersion) || isSchemaVersion07 || isSchemaVersion10 {
		sqlStore.system.Update(&model.System{Name: "Version", Value: model.CurrentVersion})
		l4g.Warn("The database schema has been upgraded to version " + model.CurrentVersion)
	}

	if schemaVersion == "" {
		sqlStore.system.Save(&model.System{Name: "Version", Value: model.CurrentVersion})
		l4g.Info("The database schema has been set to version " + model.CurrentVersion)
	}

	return sqlStore
}