ipld-eth-server/pkg/datastore/postgres/repositories/address_repository.go

63 lines
2.2 KiB
Go
Raw Normal View History

2019-08-05 18:28:06 +00:00
// VulcanizeDB
// Copyright © 2019 Vulcanize
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
2019-08-01 20:24:02 +00:00
package repositories
import (
"database/sql"
2019-08-19 21:51:17 +00:00
2019-08-01 20:24:02 +00:00
"github.com/ethereum/go-ethereum/common"
"github.com/jmoiron/sqlx"
2019-08-19 21:51:17 +00:00
2019-08-01 20:24:02 +00:00
"github.com/vulcanize/vulcanizedb/pkg/datastore/postgres"
)
type AddressRepository struct{}
2019-08-01 20:24:02 +00:00
2019-08-19 21:55:38 +00:00
func (AddressRepository) GetOrCreateAddress(db *postgres.DB, address string) (int64, error) {
2019-08-01 20:24:02 +00:00
stringAddressToCommonAddress := common.HexToAddress(address)
hexAddress := stringAddressToCommonAddress.Hex()
2019-08-19 21:55:38 +00:00
var addressId int64
2019-08-01 20:44:13 +00:00
getErr := db.Get(&addressId, `SELECT id FROM public.addresses WHERE address = $1`, hexAddress)
2019-08-01 20:24:02 +00:00
if getErr == sql.ErrNoRows {
2019-08-01 20:44:13 +00:00
insertErr := db.QueryRow(`INSERT INTO public.addresses (address) VALUES($1) RETURNING id`, hexAddress).Scan(&addressId)
2019-08-01 20:24:02 +00:00
return addressId, insertErr
}
return addressId, getErr
}
2019-08-19 21:55:38 +00:00
func (AddressRepository) GetOrCreateAddressInTransaction(tx *sqlx.Tx, address string) (int64, error) {
stringAddressToCommonAddress := common.HexToAddress(address)
hexAddress := stringAddressToCommonAddress.Hex()
2019-08-19 21:55:38 +00:00
var addressId int64
getErr := tx.Get(&addressId, `SELECT id FROM public.addresses WHERE address = $1`, hexAddress)
if getErr == sql.ErrNoRows {
insertErr := tx.QueryRow(`INSERT INTO public.addresses (address) VALUES($1) RETURNING id`, hexAddress).Scan(&addressId)
return addressId, insertErr
}
return addressId, getErr
}
2019-08-02 14:58:30 +00:00
2019-08-19 21:55:38 +00:00
func (AddressRepository) GetAddressById(db *postgres.DB, id int64) (string, error) {
2019-08-02 14:58:30 +00:00
var address string
getErr := db.Get(&address, `SELECT address FROM public.addresses WHERE id = $1`, id)
2019-08-19 21:51:17 +00:00
return address, getErr
2019-08-02 14:58:30 +00:00
}