Golang: gorm use Find(&model) for non gorm migrate table - postgresql

There is table customer_account (postgres) which one was migrate from YII2.
DDL:
CREATE TABLE public.test_table (
id INTEGER PRIMARY KEY NOT NULL DEFAULT nextval('test_table_id_seq'::regclass),
data JSONB
);
In go project i try to get value from this table.
type TableGo struct {
Id int
Data string `gorm:"type:jsonb"`
}
table := TableGo{}
db.Where("id = ?", 75).Find(&table)
println(table.Data)
But there is (pq: relation "table_gos" does not exist)
How i can link structure which table without db.AutoMigrate(&TableGo{})?

I think table name in your migration script is wrong. Because it is not in GORM convention. If you want to use that name,you can use following method in your model for custom table name.
func (m *Model) TableName() string {
return "custom_table_name"
}

Found the solution:
func(TableGo) TableName() string {
return "account_status"
}

Related

Golang Gorm Automigrate not create filed type "time"

My struct looks like:
type AdvertContent struct {
Id string `gorm:"column:id;primaryKey;type:uuid;default:uuid_generate_v4()" json:"id" example:"4ff8eb91-640b-4e26-a50f-3bcd1f933d0c"`
FromTime *time.Time `gorm:"column:from_time;type:time;" json:"fromTime,omitempty" example:"HH:MM"`
ToTime *time.Time `gorm:"column:to_time;type:time;" json:"toTime,omitempty" example:"HH:MM"`
} //#name AdvertContent
func (this AdvertContent) TableName() string {
return "advert_content"
}
When I use gorm.AutoMigrate, table fields from_time and to_time created with type timestampz, not time.
Gorm debug mode:
CREATE TABLE "advert_content" ("id" uuid DEFAULT uuid_generate_v4(),"from_time" timestamptz,"to_time" timestamptz)
How can I create table with time type fields?
when using specified database data type, it needs to be a full
database data type, for example: MEDIUMINT UNSIGNED NOT NULL
AUTO_INCREMENT
You should use the database data type like this

EF Core - Change column type from varchar to uuid in PostgreSQL 13: column cannot be cast automatically to type uuid

Before:
public class MyEntity
{
public string Id { get; set; }
//...
}
Config:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//...
modelBuilder.Entity<MyEntity>()
.Property(e => e.Id)
.ValueGeneratedOnAdd();
}
This was the previous developer's code which resulted in GUID values for the column. But in C# I had to deal with strings, so I decided to change the model.
After:
public class MyEntity
{
public Guid Id { get; set; }
//...
}
And I removed the ValueGeneratedOnAdd() code from Fluent API config.
I get the column "Id" cannot be cast automatically to type uuid error.
I think the key in this message is the automatically word.
Now my question is that since the values on that column are already GUID/UUID, is there any way to tell Postgres to change the varchar type to uuid and cast the current string value to UUID and put it in the column? I'm guessing there should be a SQL script that can do this without any data loss.
Use USING _columnname::uuid. Here is an illustration.
-- Prepare a test case:
create table delme (x varchar);
insert into delme (x) values
('b575ec3a-2776-11eb-adc1-0242ac120002'),
('4d5c5440-2776-11eb-adc1-0242ac120002'),
('b575f25c-2776-11eb-adc1-0242ac120002');
-- Here is the conversion that you need:
ALTER TABLE delme ALTER COLUMN x TYPE uuid USING x::uuid;
In your particular case:
ALTER TABLE "MyEntity" ALTER COLUMN "Id" TYPE uuid USING "Id"::uuid;
Btw, is your application the sole owner of the database model? If not then changing an existing table is a bad idea.

Cannot read "one to many" Relation with go-pg

I am trying to implement a little state machine with go and store my states in a postgres db.
i created my database like this:
CREATE TABLE state_machines
(
id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
initial_state TEXT NOT NULL,
"name" TEXT NOT NULL
);
CREATE TABLE state_machine_states
(
state_machine_id uuid NOT NULL REFERENCES state_machines(id) ON DELETE CASCADE,
"name" TEXT NOT NULL,
PRIMARY KEY(state_machine_id, "name")
);
// StateMachine is the DB schema
type StateMachine struct {
ID *uuid.UUID `pg:"id,pk,type:uuid,default:uuid_generate_v4()"`
Name string `pg:"name"`
InitialState string `pg:"initial_state"`
States []*StateMachineState `pg:"fk:state_machine_id"`
}
// StateMachineState is the DB schema
type StateMachineState struct {
StateMachineID uuid.UUID `pg:"state_machine_id,fk"`
Name string `pg:"name"`
}
I am using go-pg 9.2 and i am trying to load a state machine and a list of its states from the "States" relation.
My function to load the state machines looks like this:
func (cep *repository) GetStateMachines() ([]*StateMachine, error) {
stateMachines := []*StateMachine{}
err := cep.db.Model(&stateMachines).
Relation("States").
Relation("Transitions").
Select()
return stateMachines, err
}
If I execute it, I always get the error message Error reading state machine: model=StateMachine does not have relation="States"
I have done similar relations before and they worked and now, I cannot get it to work again :(
Try upgrading to v10 which fully supports relations: https://pg.uptrace.dev/orm/has-many-relation/
See if there is .Debug() function in go-pg for a query.
I use https://gorm.io/ , and there is a Debug funcion, that returns all of the SQL queries.
When i see what queries are send, i log in postgresql and try them manually to see a more detailed error.

golang ORM name of table

I have some code to create the table in Postgres DB
import (
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
)
type Table struct {
Id int `gorm:"primary_key"`
Name string `gorm:"type:varchar(100)"`
Addr string `gorm:"type:varchar(100)"`
}
func main() {
db, _ := gorm.Open("postgres", "user=postgres password=poilo777 dbname=mydb sslmode=disable")
defer db.Close()
db.CreateTable(&Table{})
user := &Table{Name: "ololo", Addr: "pololo"}
there are 2 problems, i faced:
1) in database created a table "tables" instead of "Table"
2) how can I insert data in existing another tables? (for example "users")
1) You can set Table's table name to be table
func (Table) TableName() string {
return "table"
}
Another way is to set singularTable true, then Table's default table name will be table instead of tables. But it will affect all tables the same.
set db.SingularTable(true)
2) In ORM you should define your table object. Here is a struct called Table. Gorm will create a new table called tables in database unless you want to overwrite table's name you can follow step 1.
By default, the golang Postgres Client will implicitly use the pluralized version of your struct name[1]. For example
type Student struct {
FirstName string
LastName string
}
// will create a table name `students`
You can override it like the following, depending on what you are using
GORM
// Set User's table name to be `profiles`
func (Student) TableName() string {
return "college_students"
}
GO-PQ
type Student struct {
tableName struct{} `pg:"college_students,alias:g"``
}
https://gorm.io/docs/conventions.html#Pluralized-Table-Name
My solving of this problem:
db.Table("my_table").CreateTable(&Table{})
user := &Table{Name: "ololo", Addr: "pololo"}
db.Table("my_table").Create(user)
This code creates table my_table as I wanted

Selecting Postgres UUID's on Laravel

I have a table on Postgres that auto generates UUIDs, when I dd Customer::all(); on Laravel I get an array with "cs_id" => "d0402be5-e1ba-4cb2-a80c-5340b406e2c3" which is fine. When I loop or select one record with the only the cs_id the data it retuns 0,2,5 for the three records currently on the table which is incorrect data.
EDIT:
CREATE TABLE customers
(
cs_id character varying(255) NOT NULL DEFAULT gen_random_uuid(),
CONSTRAINT cs_customers_pkey PRIMARY KEY (cs_id),
}
On laravel
$customerData = Customer::where('cs_id','d0402be5-e1ba-4cb2-a80c-5340b406e2c3')->first();
dd($customerData['cs_id']);
For some reason Eloquent messes up there.
just add a getter and use it whenever you need the cs_id
public function getGuid()
{
return $this->attributes['cs_id'];
}
To use uuids auto-generated by the database, define your model as follows:
class Customer extends Model
{
// rename the id column (optional)
protected $primaryKey = 'cs_id';
// tell Eloquent that your id is not an integer
protected $keyType = 'string';
// do NOT set $incrementing to false
}
Then you can use all Eloquent's methods as you would with classic ids:
$customerData = Customer::findOrFail('d0402be5-e1ba-4cb2-a80c-5340b406e2c3');
Use Customer::findOrFail('d0402be5-e1ba-4cb2-a80c-5340b406e2c3');
to get the record matching that pk.
I'm assuming on top you have use App\Customer;