Examples:
Sample 1: This is an example of the go code used on the backend for the Nation Water Prediction Service (NWPS) application. It uses the Go version 1.26.0 on the backend and is primarily a database-driven application.
// From cmd/hefsingester/main_test.go
...
func TestFlags(t *testing.T) {
oldArgs := os.Args
defer func() {
os.Args = oldArgs
}()
cases := []struct {
Name string
Args []string
ExpectedExit int
ExpectedOutput string
}{
// We cannot test "-version", "-help" and "-config" because of errors.
{"flag set db_host", []string{"-db_host", "localhost"}, 0, "localhost"},
{"flag set db_name", []string{"-db_name", "owp_water_website"}, 0, "owp_water_website"},
{"flag set db_user", []string{"-db_user", "wps_website"}, 0, "wps_website"},
{"flag set db_port", []string{"-db_port", "55432"}, 0, "55432"},
{"flag set db_password", []string{"-db_password", "password"}, 0, "password"},
{"flag set max_workers", []string{"-max_workers", "2"}, 0, ""},
}
// Important! This has to be set otherwise we see an error.
os.Args = []string{"-config", "../../config/ons-dev.conf.yaml.example"}
for _, tc := range cases {
// this call is required because otherwise flags panics,
// if args are set between flag.Parse call
flag.CommandLine = flag.NewFlagSet(tc.Name, flag.ExitOnError)
os.Args = append([]string{tc.Name}, tc.Args...)
var buf bytes.Buffer
actualExit := runMain(&buf)
if tc.ExpectedExit != actualExit {
t.Errorf("Wrong exit code for args: %v, expected: %v, got: %v", tc.Args, tc.ExpectedExit, actualExit)
}
actualOutput := buf.String()
if tc.ExpectedOutput != actualOutput {
t.Errorf("Wrong output for args :%v:, expected %v, got :%v:", tc.Args, tc.ExpectedOutput, actualOutput)
}
}
}
...
// From cmd/hefsingester/main.go
...
func runMain(out io.Writer) int {
var fpath = flag.String("config", "dist/hefsingester/hefsingester.conf.yaml", "Path to configuration file")
var dbHost = flag.String("db_host", "", "The database host")
var dbName = flag.String("db_name", "", "The database name")
var dbPort = flag.Int("db_port", 0, "The database port")
var dbUser = flag.String("db_user", "", "The database user")
var dbPassword = flag.String("db_password", "", "The database user's password")
var maxWorkers = flag.Int("max_workers", 0, "Max number of concurrent worker processes [10]")
flag.Parse()
if *versionFlag {
fmt.Println(version.GetInfo(os.Args[0]))
os.Exit(0)
}
if *helpFlag {
fmt.Printf("Usage of %s:\n", os.Args[0])
flag.PrintDefaults()
os.Exit(0)
}
configs = config.GetConfigs(*fpath)
// Let and params passed in via CLI override the config file
// this is necessary to run hefsIngester from local docker containers
if *dbName != "" {
configs.Database.DBName = *dbName
}
if *dbHost != "" {
configs.Database.DBHost = *dbHost
}
if *dbPort != 0 {
configs.Database.DBPort = *dbPort
}
if *dbUser != "" {
configs.Database.DBUser = *dbUser
}
if *dbPassword != "" {
configs.Database.DBPassword = *dbPassword
}
if *maxWorkers != 0 {
configs.HEFSIngester.MaxWorkers = *maxWorkers
} else if configs.HEFSIngester.MaxWorkers == 0 {
configs.HEFSIngester.MaxWorkers = 10
}
// For http timeout value
if *timeout != 10 {
configs.HEFSIngester.Timeout = *timeout
}
n := hefs.RunApp(*lid, configs, runNowFlag)
return n
}
...
// From storage/postgres/gauge.go
...
// CheckFloodCatStages returns the flood category stage for a given value or "unknown" if not defined.
// Checks if flood categories exist; input is water level in stage, output is flood category as string.
func (db *DB) CheckFloodCatStages(val float64, fc ahps.FloodCategories) string {
if fc.ActionStage <= -999 && fc.MinorStage <= -999 && fc.ModerateStage <= -999 && fc.MajorStage <= -999 {
return "not_defined"
// If any Flood Categories exist return the category if the data value is above the flood category value
} else if val >= fc.MajorStage && fc.MajorStage > -999 {
return "major"
} else if val >= fc.ModerateStage && fc.ModerateStage > -999 {
return "moderate"
} else if val >= fc.MinorStage && fc.MinorStage > -999 {
return "minor"
} else if val >= fc.ActionStage && fc.ActionStage > -999 {
return "action"
}
return "no_flooding"
}
// CheckFloodCatFlows returns the flood category flow for a given value or "unknown" if not defined.
// Input is water level in flow (must be in cfs); output is flood category as string.
func (db *DB) CheckFloodCatFlows(val float64, fc ahps.FloodCategories) string {
if fc.ActionFlow <= -999 && fc.MinorFlow <= -999 && fc.ModerateFlow <= -999 && fc.MajorFlow <= -999 {
return "not_defined"
// If any Flood Categories exist return the category if the data value is above the flood category value
} else if val >= fc.MajorFlow && fc.MajorFlow > -999 {
return "major"
} else if val >= fc.ModerateFlow && fc.ModerateFlow > -999 {
return "moderate"
} else if val >= fc.MinorFlow && fc.MinorFlow > -999 {
return "minor"
} else if val >= fc.ActionFlow && fc.ActionFlow > -999 {
return "action"
}
return "no_flooding"
}
...
Sample 2: This is an example of the Go code used on the backend for the Nation Water Prediction Service (NWPS) application. It uses the Go version 1.26.0 on the backend and is primarily a database-driven application.
// From storage/postgres/hefs.go
...
// GetHEFS gets hydrologic ensemble forecast system data output for a specific gauge with all forecast lengths.
func (db *DB) GetHEFS(lid string) (ahps.HEFS, error) {
var hefs ahps.HEFS
q := db.sb.Select("lid", "units", "start_time", "end_time", "forecast_time", "last_updated", "enabled", "hefs_5_1", "hefs_5_25", "hefs_5_3", "hefs_5_5", "hefs_5_7", "hefs_5_75", "hefs_5_9", "hefs_10_1", "hefs_10_25", "hefs_10_3", "hefs_10_5", "hefs_10_7", "hefs_10_75", "hefs_10_9", "hefs_15_1", "hefs_15_25", "hefs_15_3", "hefs_15_5", "hefs_15_7", "hefs_15_75", "hefs_15_9", "hefs_20_1", "hefs_20_25", "hefs_20_3", "hefs_20_5", "hefs_20_7", "hefs_20_75", "hefs_20_9", "hefs_30_1", "hefs_30_25", "hefs_30_3", "hefs_30_5", "hefs_30_7", "hefs_30_75", "hefs_30_9").
From("map_hefs").
Where("lid = ?", lid).
OrderBy("start_time DESC").
Limit(1)
err := q.QueryRow().Scan(
&hefs.Lid,
&hefs.Units,
&hefs.StartTime,
&hefs.EndTime,
&hefs.ForecastTime,
&hefs.LastUpdated,
&hefs.Enabled,
&hefs.Hefs_5_1,
&hefs.Hefs_5_25,
&hefs.Hefs_5_3,
&hefs.Hefs_5_5,
&hefs.Hefs_5_7,
&hefs.Hefs_5_75,
&hefs.Hefs_5_9,
&hefs.Hefs_10_1,
&hefs.Hefs_10_25,
&hefs.Hefs_10_3,
&hefs.Hefs_10_5,
&hefs.Hefs_10_7,
&hefs.Hefs_10_75,
&hefs.Hefs_10_9,
&hefs.Hefs_15_1,
&hefs.Hefs_15_25,
&hefs.Hefs_15_3,
&hefs.Hefs_15_5,
&hefs.Hefs_15_7,
&hefs.Hefs_15_75,
&hefs.Hefs_15_9,
&hefs.Hefs_20_1,
&hefs.Hefs_20_25,
&hefs.Hefs_20_3,
&hefs.Hefs_20_5,
&hefs.Hefs_20_7,
&hefs.Hefs_20_75,
&hefs.Hefs_20_9,
&hefs.Hefs_30_1,
&hefs.Hefs_30_25,
&hefs.Hefs_30_3,
&hefs.Hefs_30_5,
&hefs.Hefs_30_7,
&hefs.Hefs_30_75,
&hefs.Hefs_30_9,
)
if err != nil {
if err == sql.ErrNoRows {
db.Logger.Tracef("[%s] no hefs rows found with gauge: %v", lid, err)
} else {
return hefs, fmt.Errorf("[%s] error scanning GetHEFS: %v", lid, err)
}
}
return hefs, nil
}
// ListHEFSGauges will show the hefs gauges.
func (db *DB) ListHEFSGauges(gauge string) ([]string, error) {
q := db.sb.Select("lid").
From("map_hefs")
if gauge != "" {
q = q.Where("lid = ?", strings.ToUpper(gauge))
} else {
q = q.OrderBy("lid")
}
rows, err := q.Query()
if err != nil {
return nil, fmt.Errorf("error querying for list of configured hefs gauges: %v", err)
}
defer rows.Close()
var gauges []string
for rows.Next() {
var gauge string
if err := rows.Scan(
&gauge,
); err != nil {
return nil, fmt.Errorf("error scanning list of configured hefs gauges: %v", err)
}
gauges = append(gauges, gauge)
}
if err = rows.Err(); err != nil {
return nil, fmt.Errorf("error on rows while listing configured hefs gauges: %v", err)
}
return gauges, err
}
// GetHefsLidsFromGaugeConfig will return all gauges found in the map_hefs table.
func (db *DB) GetHefsLidsFromGaugeConfig() ([]string, error) {
var gauges []string
q := db.sb.Select("id").
From("cms_regional_config").
Where("type = 'gauge'")
rows, err := q.Query()
if err != nil {
if err == sql.ErrNoRows {
return gauges, fmt.Errorf("no hefs gauges found")
}
return gauges, err
}
defer rows.Close()
for rows.Next() {
var gauge string
if err := rows.Scan(
&gauge,
); err != nil {
return gauges, fmt.Errorf("error scanning list of configured hefs gauges: %v", err)
}
gauges = append(gauges, gauge)
}
if err = rows.Err(); err != nil {
return nil, fmt.Errorf("error on rows of hefs gauges: %v", err)
}
return gauges, err
}
// InsertUpdateHEFSTable will do an `INSERT...ON CONFLICT` for the table `map_hefs`.
func (db *DB) InsertUpdateHEFSTable(data MapHEFS, datums map[string]string, hash string) error {
// Timeout the context after 60 seconds
q := db.sb.Insert("map_hefs").
Columns("lid", "parameter_id", "units", "start_time", "end_time", "forecast_time", "last_updated", "hefs_5_1", "hefs_5_25", "hefs_5_3", "hefs_5_5", "hefs_5_7", "hefs_5_75", "hefs_5_9", "hefs_10_1", "hefs_10_25", "hefs_10_3", "hefs_10_5", "hefs_10_7", "hefs_10_75", "hefs_10_9", "hefs_15_1", "hefs_15_25", "hefs_15_3", "hefs_15_5", "hefs_15_7", "hefs_15_75", "hefs_15_9", "hefs_20_1", "hefs_20_25", "hefs_20_3", "hefs_20_5", "hefs_20_7", "hefs_20_75", "hefs_20_9", "hefs_30_1", "hefs_30_25", "hefs_30_3", "hefs_30_5", "hefs_30_7", "hefs_30_75", "hefs_30_9", "hash").
Values(
data.Lid,
data.ParameterID,
data.Units,
data.StartTime,
data.EndTime,
data.ForecastTime,
data.LastUpdated,
datums["hefs_5_1"],
datums["hefs_5_25"],
datums["hefs_5_3"],
datums["hefs_5_5"],
datums["hefs_5_7"],
datums["hefs_5_75"],
datums["hefs_5_9"],
datums["hefs_10_1"],
datums["hefs_10_25"],
datums["hefs_10_3"],
datums["hefs_10_5"],
datums["hefs_10_7"],
datums["hefs_10_75"],
datums["hefs_10_9"],
datums["hefs_15_1"],
datums["hefs_15_25"],
datums["hefs_15_3"],
datums["hefs_15_5"],
datums["hefs_15_7"],
datums["hefs_15_75"],
datums["hefs_15_9"],
datums["hefs_20_1"],
datums["hefs_20_25"],
datums["hefs_20_3"],
datums["hefs_20_5"],
datums["hefs_20_7"],
datums["hefs_20_75"],
datums["hefs_20_9"],
datums["hefs_30_1"],
datums["hefs_30_25"],
datums["hefs_30_3"],
datums["hefs_30_5"],
datums["hefs_30_7"],
datums["hefs_30_75"],
datums["hefs_30_9"],
hash,
).
Suffix(`ON CONFLICT (lid, parameter_id) DO UPDATE
SET
lid = EXCLUDED.lid,
parameter_id = EXCLUDED.parameter_id,
units = EXCLUDED.units,
start_time = EXCLUDED.start_time,
end_time = EXCLUDED.end_time,
forecast_time = EXCLUDED.forecast_time,
last_updated = now(),
hefs_5_1 = EXCLUDED.hefs_5_1,
hefs_5_25 = EXCLUDED.hefs_5_25,
hefs_5_3 = EXCLUDED.hefs_5_3,
hefs_5_5 = EXCLUDED.hefs_5_5,
hefs_5_7 = EXCLUDED.hefs_5_7,
hefs_5_75 = EXCLUDED.hefs_5_75,
hefs_5_9 = EXCLUDED.hefs_5_9,
hefs_10_1 = EXCLUDED.hefs_10_1,
hefs_10_25 = EXCLUDED.hefs_10_25,
hefs_10_3 = EXCLUDED.hefs_10_3,
hefs_10_5 = EXCLUDED.hefs_10_5,
hefs_10_7 = EXCLUDED.hefs_10_7,
hefs_10_75 = EXCLUDED.hefs_10_75,
hefs_10_9 = EXCLUDED.hefs_10_9,
hefs_15_1 = EXCLUDED.hefs_15_1,
hefs_15_25 = EXCLUDED.hefs_15_25,
hefs_15_3 = EXCLUDED.hefs_15_3,
hefs_15_5 = EXCLUDED.hefs_15_5,
hefs_15_7 = EXCLUDED.hefs_15_7,
hefs_15_75 = EXCLUDED.hefs_15_75,
hefs_15_9 = EXCLUDED.hefs_15_9,
hefs_20_1 = EXCLUDED.hefs_20_1,
hefs_20_25 = EXCLUDED.hefs_20_25,
hefs_20_3 = EXCLUDED.hefs_20_3,
hefs_20_5 = EXCLUDED.hefs_20_5,
hefs_20_7 = EXCLUDED.hefs_20_7,
hefs_20_75 = EXCLUDED.hefs_20_75,
hefs_20_9 = EXCLUDED.hefs_20_9,
hefs_30_1 = EXCLUDED.hefs_30_1,
hefs_30_25 = EXCLUDED.hefs_30_25,
hefs_30_3 = EXCLUDED.hefs_30_3,
hefs_30_5 = EXCLUDED.hefs_30_5,
hefs_30_7 = EXCLUDED.hefs_30_7,
hefs_30_75 = EXCLUDED.hefs_30_75,
hefs_30_9 = EXCLUDED.hefs_30_9,
hash = EXCLUDED.hash;
`)
_, err := q.Exec()
if err != nil {
// Check for "could not serialize" PSQL error code: 40001
if err, ok := err.(*pq.Error); ok {
// Check for "could not serialize" PSQL error code: 40001
if err.Code == pgerrcode.SerializationFailure {
db.Logger.Tracef("retrying insert for %v: %v", data.Lid, err)
return retry.RetryableError(fmt.Errorf("could not insert %v due to concurrency lock", data.Lid))
}
}
return fmt.Errorf("error executing insert-update query for gauge %v: %v", data.Lid, err)
}
db.Logger.Debugf("[%s] new data inserted ", data.Lid)
return nil
}
// GetEarliestHEFSUpdatedDateTime will return the earliest updated time for a HEFS gauge from the map_hefs table or coalesce the date 14 days ago.
func (db *DB) GetEarliestHEFSUpdatedDateTime(gauge string) (time.Time, error) {
now := time.Now()
lastUpdated := now.AddDate(0, 0, -14)
q := db.sb.Select(fmt.Sprintf("COALESCE(MIN(last_updated), CURRENT_TIMESTAMP - INTERVAL '14 days')")).
From("map_hefs")
if gauge != "" {
q = q.Where("lid = ?", strings.ToUpper(gauge))
}
err := q.QueryRow().Scan(&lastUpdated)
if err != nil {
if err == sql.ErrNoRows {
return lastUpdated, nil
}
return lastUpdated, fmt.Errorf("[%v] could not get last updated time from map_hefs: %v", gauge, err)
}
return lastUpdated, nil
}
...
Sample 3: This is an example of the go code used on the backend for the Nation Water Prediction Service (NWPS) application. It uses the Go on the backend and is primarily a database-driven application.
// From cmd/qpeingester/main.go
...
// TransfersRastersProcessed is used to transfer the files from owp_water_website to qpe raster tables and then clean up.
func TransfersRastersProcessed() error {
// Move all ready files from owp_water_website.*_qperasters to partitioned qpe.*_qperasters tables.
// move the dated data into the partitions tables
err := db.TransferQpeRasterDateToPartitions()
if err != nil {
log.Errorf("error with transferring qpe date partitions: %v", err)
return err
}
// move the current hourly data into partitions tables
err = db.TransferQpeRasterCurrentToPartitions()
if err != nil {
log.Errorf("error with transferring qpe current hours partitions: %v", err)
return err
}
// Cleanup the original owp_water_website tables
err = db.TruncatePrecipSetupTables()
if err != nil {
return fmt.Errorf("error with deleting and truncating owp_water_website tables: %v", err)
}
return nil
}
...
// From storage/postgres/qpe.go
...
// TransferQpeRasterDateToPartitions moves the date data in the owp_water_website.o_2_qperasters,
// owp_water_website.o_3_qperasters, owp_water_website.qperasters tables to their respective counterpart
// partititioned tables in the qpe schema. EXAMPLE: nws_precip_1day_20241026_ak.tif -> 202410
func (db *DB) TransferQpeRasterDateToPartitions() error {
db.Logger.Debug(`Begin transfer from NWPS schema to Daily QPE partition schema`)
tables := [3]string{"o_2_qperasters", "o_3_qperasters", "qperasters"}
// The original database schema name
dbName := db.Config.Database.DBName
// QPE database name schema
qpeDBName := db.Config.Database.QpeDBName
for _, table := range tables {
var qString string
if table == "qperasters" {
qString = fmt.Sprintf(`SELECT DISTINCT UNNEST(REGEXP_MATCHES(native_path, '[0-9]{6}')) AS fkey FROM %v.%v;`, dbName, table)
} else {
qString = fmt.Sprintf(`SELECT DISTINCT UNNEST(REGEXP_MATCHES(filename, '[0-9]{6}')) AS fkey FROM %v.%v;`, dbName, table)
}
// db.Logger.Trace(qString)
rows, err := db.Query(qString)
if err != nil {
// If no rows, continue. Could mean qperasters table is fresh-ish and we need to add what we need to add.
if err == sql.ErrNoRows {
return fmt.Errorf("error no fkey values rows found with %v.%v_processed: %v", qpeDBName, table, err)
}
return err
}
defer rows.Close()
// id is a switch
for rows.Next() {
var fkey string
if err := rows.Scan(
&fkey); err != nil {
db.Logger.Error("Error: ", err)
return fmt.Errorf("error scanning fkey value in table %v for fkeys: %v", table, err)
}
_, err = db.CreateQpePartition("date", table, fkey)
if err != nil {
return fmt.Errorf("could not create hourly partition for owp.%v and fkey %v", table, fkey)
}
}
// Transfer the rows
if table == "qperasters" {
qString = fmt.Sprintf(`INSERT INTO %v.%v_processed (SELECT rid, rast, filename, md5, native_path, UNNEST(REGEXP_MATCHES(filename, '_([0-9]{6})')) FROM %v.%v WHERE fkey IS NOT NULL);`, qpeDBName, table, dbName, table)
} else {
qString = fmt.Sprintf(`INSERT INTO %v.%v_processed (SELECT rid, rast, filename, md5, UNNEST(REGEXP_MATCHES(filename, '_([0-9]{6})')) FROM %v.%v WHERE fkey IS NOT NULL);`, qpeDBName, table, dbName, table)
}
//db.Logger.Debugf(`========= qString: %v`, qString)
// db.Logger.Trace(qString)
_, err = db.Exec(qString)
if err != nil {
return err
}
}
db.Logger.Debug(`Completed transfer from NWPS schema to Daily QPE partition schema`)
return nil
}
// TransferQpeRasterCurrentToPartitions moves the current data in the owp_water_website.o_2_qperasters,
// owp_water_website.o_3_qperasters, owp_water_website.qperasters tables to their respective counterpart
// partititioned tables in the qpe schema. EXAMPLE: nws_precip_last6hours_conus.tif -> last6hours
func (db *DB) TransferQpeRasterCurrentToPartitions() error {
db.Logger.Debug(`Begin transfer from NWPS schema to Hourly QPE partition schema`)
// The original database schema name
dbName := db.Config.Database.DBName
// QPE database name schema
qpeDBName := db.Config.Database.QpeDBName
tables := [3]string{"o_2_qperasters", "o_3_qperasters", "qperasters"}
// id is a switch
for _, table := range tables {
qString := fmt.Sprintf(`SELECT DISTINCT UNNEST(REGEXP_MATCHES(filename, '1hour|last12hours|last6hours|last2hours|last3hours|last24hours|since12z')) as fkey FROM %v.%v;`, dbName, table)
// db.Logger.Trace(qString)
rows, err := db.Query(qString)
if err != nil {
// If no rows, continue. Could mean qperasters table is fresh-ish and we need to add what we need to add.
if err == sql.ErrNoRows {
return fmt.Errorf("error no fkey values rows found with %v.%v: %v", dbName, table, err)
}
return err
}
defer rows.Close()
for rows.Next() {
var fkey string
if err := rows.Scan(
&fkey); err != nil {
db.Logger.Error("Error: ", err)
return fmt.Errorf("error scanning fkey value in table %v for fkeys: %v", table, err)
}
_, err = db.CreateQpePartition("hour", table, fkey)
if err != nil {
return fmt.Errorf("could not create hourly partition for %v.%v and fkey %v", qpeDBName, table, fkey)
}
}
// Transfer the rows
if table == "qperasters" {
qString = fmt.Sprintf(`INSERT INTO %v.%v_processed (SELECT rid, rast, filename, md5, native_path, unnest(regexp_matches(filename, '1hour|last12hours|last6hours|last2hours|last3hours|last24hours|since12z')) FROM %v.%v WHERE fkey IS NOT NULL);`, qpeDBName, table, dbName, table)
} else {
qString = fmt.Sprintf(`INSERT INTO %v.%v_processed (SELECT rid, rast, filename, md5, unnest(regexp_matches(filename, '1hour|last12hours|last6hours|last2hours|last3hours|last24hours|since12z')) FROM %v.%v WHERE fkey IS NOT NULL);`, qpeDBName, table, dbName, table)
}
// db.Logger.Trace(qString)
_, err = db.Exec(qString)
if err != nil {
return fmt.Errorf(`error inserting current hours data into %v.%v: %v`, qpeDBName, table, err)
}
}
db.Logger.Debug(`Completed transfer from NWPS schema to Hourly QPE partition schema`)
return nil
}
...