How to set relation column type in TypeORM when using separated schema definition? - typeorm

how can I set the type of column for relation when using a separated schema definition?
I'm trying to join on uuid (Postgres) column, but the migration generator generates character varying. Here's how relation is defined in schema:
...
relations: {
tenant: {
type: "many-to-one",
target: Tenant.name,
onDelete: "CASCADE",
onUpdate: "CASCADE",
joinColumn: {
foreignKeyConstraintName: "user_tenant_fk",
},
},
},
...
Here's how schema:log looks:
CREATE TABLE "tenant" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "name" character varying NOT NULL, CONSTRAINT "tenant_pk" PRIMARY KEY ("id"));
CREATE TABLE "user" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "email" character varying NOT NULL, "passwordHash" character varying NOT NULL, "tenantId" character varying, CONSTRAINT "user_email_key" UNIQUE ("email", "tenantId"), CONSTRAINT "user_pk" PRIMARY KEY ("id"));
...
But this will fail, as user.tenantId and tenant.id have different types. So how can I set manually the type of user.tenantId? Can't find relevant property in EntitySchemaRelationOptions. Adding tenantId as column with uuid type also not helped.

Related

PG:Undefined object error when using activeimport with constraint

I am trying to do an upsert with ActiveImport. When running the import I am trying to pass it a named constraint in order to tell it when to update certain columns.
User.import(
#import_values,
on_duplicate_key_update: {
constraint_name: :index_users_on_uid_and_tenant_id,
columns: %i[title location_id email active]
}
)
The code above is my import statement which is correct according to activeimport documentation. However, when I run this, I get PG:UndefinedObject error which shows the following:
Caused by PG::UndefinedObject: ERROR: constraint "index_users_on_uid_and_tenant_id" for table "users" does not exist
However, in my schema.rb, on my users table schema, the constraint clearly exists:
t.index ["uid", "tenant_id"], name: "index_users_on_uid_and_tenant_id", unique: true
and also, this returns true:
ActiveRecord::Base.connection.index_exists?(:users, [:uid, :tenant_id]) => true
Any help as to why this is happening would be very helpful!
A unique constraint implies the creation of a unique index, but not vice versa.
In your case, you created a unique index but not a unique constraint, so there's no constraint "index_users_on_uid_and_tenant_id", you can add a constraint, or use conflict_target to declare explicitly which columns the conflict would occur
User.import(
#import_values,
on_duplicate_key_update: {
conflict_target: [:uid, :tenant_id],
columns: %i[title location_id email active]
}
)

Issue trying to drop a table / migration in Rails 4

I have tried to implement a gem that uses the same model (comment.rb) as one of the gem I was trying to install before. I have tried rake db:rollback and rake db:rollback VERSION= to come back to the point where I'm supposed not to have any migrations or any tables named 'comment', but sqlite3 keeps telling me that there is a table with that name and it can not move forward.
rake db:migrate:status
Status Migration ID Migration Name
--------------------------------------------------
up 20140616150625 Devise create users
up 20140616151746 Create hacks
up 20140616155718 Acts as taggable on migration.acts as taggable on engine
up 20140616155719 Add missing unique indices.acts as taggable on engine
up 20140616155720 Add taggings counter cache to tags.acts as taggable on engine
up 20140617185601 Add picture to hacks
up 20140617190705 Add attachment image to hacks
up 20140617194434 Add name to users
up 20140617194509 Create identities
up 20140618125514 Add confirmable to devise
up 20140619150148 Create comments
up 20140619162204 The comments change user.the comments engine
down 20140619162205 The comments create comments.the comments engine
down 20140619162206 The comments change commentable.the comments engine
down 20140619163035 Drop comments
And the issue - I'm not sure if this called rack trace?
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: table "comments" already exists: CREATE TABLE "comments" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "user_id" integer, "holder_id" integer, "commentable_id" integer, "commentable_type" varchar(255), "commentable_url" varchar(255), "commentable_title" varchar(255), "commentable_state" varchar(255), "anchor" varchar(255), "title" varchar(255), "contacts" varchar(255), "raw_content" text, "content" text, "view_token" varchar(255), "state" varchar(255) DEFAULT 'draft', "ip" varchar(255) DEFAULT 'undefined', "referer" varchar(255) DEFAULT 'undefined', "user_agent" varchar(255) DEFAULT 'undefined', "tolerance_time" integer, "spam" boolean DEFAULT 'f', "parent_id" integer, "lft" integer, "rgt" integer, "depth" integer DEFAULT 0, "created_at" datetime, "updated_at" datetime) /Users/javier/.rvm/gems/ruby-2.1.2/gems/sqlite3-1.3.9/lib/sqlite3/database.rb:91:in `initialize'
I have tried to drop the same table by accessing sqlite3, but I'm not able to access the tables. Any advice?
You have two migrations with table comments creating (one, second). The DB can't create second table with the same name.
About migrations. Main details can be found in the guides.
rollback does not delete migration - it is just revert it (run method down). If you would like to use second table comments you have at least two ways:
rollback creating the first table. Delete migration (delete physically file). run rake db:migrate
You can create a new migration which drop_table comments then generate a new migration with new version of table comments (it is important that timestamp for migration with dropping table was less than timestamp for migration with creating table). After this run rake db:migrate

How to change primary key in rails migration file?

I need to migrate an old mysql table like this:
Products
name (string, primary_key)
to this schema:
Products
id (integer, primary_key, auto_generated)
name (unique)
I need the Products.id values populated in the new table.
How can i write the rails migration file? I am using Rails 3.2.7
I have 2 problems now:
1. I can't find a method to remove primary key in ActiveRecord::Migration
2. I don't know how to generate values for newly added primary key.
You could execute arbitrary SQL in your migration:
execute "ALTER TABLE `products` DROP PRIMARY KEY"
and then add the new column:
add_column :products, :id, :primary_key
See:
Remove Primary Key in MySQL
how to add a primary key to a table in rails
http://thinkwhere.wordpress.com/2009/05/09/adding-a-primary-key-id-to-table-in-rails/
http://api.rubyonrails.org/classes/ActiveRecord/Migration.html
If you're on Postgresql, the syntax is slightly different.
ALTER TABLE <table_name> DROP CONSTRAINT <table_name>_pkey;

Rails 3 ActiveRecord Insert Cannot Insert Value Null

I am using:
Rails 3.0.9
MSSQL 2005
I have the table:
CREATE TABLE [dbo].[edocs](
[id] [int] IDENTITY(1,1) NOT NULL,
[id_claim] [int] NOT NULL,
[id_material] [smallint] NOT NULL,
[is_secondary] [bit] NOT NULL CONSTRAINT [DF_edocs_is_secondary] DEFAULT ((0)),
[title] [varchar](100) COLLATE Ukrainian_CI_AS NOT NULL,
[ext] [varchar](4) COLLATE Ukrainian_CI_AS NOT NULL,
[size] [int] NOT NULL,
[code] [varchar](10) COLLATE Ukrainian_CI_AS NULL,
[receive_date] [datetime] NOT NULL CONSTRAINT [DF_edocs_receive_date] DEFAULT (getdate()),
[reg_date] [datetime] NULL,
[reg_numb] [varchar](10) COLLATE Ukrainian_CI_AS NULL,
[idcead] [int] NULL,
[efile] [int] NULL
)
Some of fields has default value (for exapmle receive_date).
In Rails controller I try to create new record:
Edoc.create(
:id_claim => #claim_index,
:id_material => #doc_code,
:title => #file_list.first[:name],
:ext => #file_list.first[:ext],
:size => #file_list.first[:size],
:code => #materials[#doc_code]["code"]
)
But I get error message:
ActiveRecord::StatementInvalid (TinyTds::Error: Cannot insert the value NULL int
o column 'receive_date', table 'eFilling.dbo.edocs'; column does not allow nulls
. INSERT fails.: INSERT INTO [edocs] ([id_claim], [id_material], [is_secondary],
[title], [ext], [size], [code], [receive_date], [reg_date], [reg_numb], [idCEAD
], [eFile]) VALUES (100000, 3, 0, N'text', N'rtf', 80
472, N'al', NULL, NULL, NULL, NULL, NULL)):
But In MSSQL 2005 console I can do that:
insert into edocs ([id_claim], [id_material],[title], [ext], [size]) values(1, 1, 'rrr', 'rtf', 123)
I don't want ActiveRecord auto completes the query by adding fields are not pointed in my create method.
How Can I do that?
I believe that even if you wrote straight SQL queries to insert, and didn't specify values for the "not null" fields, and they didn't have a default value, you would still throw a SQL error. I would suggest either allowing NULL on those fields or giving them a default value (maybe '' or 0?).
This isn't just a Rails thing, this comes down to the SQL queries themselves.
Example, for table with 'id', 'email' and 'name', where 'name' is not null and has no default value, this would fail:
INSERT INTO table (id, email) VALUES ('3', 'test#example.com')
As SQL passes NULL or emptiness as the value to 'name'
Think of it kind of like a 'required field' when it is not null without default value

Activerecord, 'foregin_key' has to be a combination of 2 fields

I want a has_many relationship described below
class User < ActiveRecord::Base
has_many :mcollections, :foreign_key=>'obj_id'
end
Below is definition of table mcollections
create table mcollections (
id int not null auto_increment,
obj_id varchar(255) not null,
category varchar(255) not null,
);
The :foreign_key is NOT A SINGLE FIELD on table mcollections. Foreign key has to be a combination of 2 fields (obj_id + category). How can I specify this in User class?
I don't see the sense of using foreign keys here.
A foreign key should be the primary key of another table. Neither obj_id nor category could be used as foreign key because they are not part of the primary key.
Cant you do it another way?
Its not the best practice to use multi-column foreign keys in rails...

Resources