Search code examples
postgresqlgrailsgrails-orm

Grails doesn't create foreign key column in PostgreSQL


I am having trouble generating my tables in PostgreSQL from Grails. I have simple Email and EmailAttachment domain classes with a hasMany and belongsTo relationship. This setup worked well on our production server (AS400 DB2), but when I try to run my program on PostgreSQL (the new dev environment), the Email class does not have the attachment_id column.

Email.groovy:

class Email {

   static hasMany = [attachments:EmailAttachment]
   Integer id
   Integer version = 0
   String subject
   String recipients
   String sender
   Date sentDate
   String plainTextMessage
   Set attachments

static mapping = {
    datasources(['DEFAULT'])
    table name:'error_email', schema: Appointment.schema
    sort sentDate:'desc'
}

static constraints = {
    subject nullable:true
    version nullable:true
    recipients nullable:true
    sender nullable:true
    sentDate nullable:true
    plainTextMessage nullable:true
    attachments nullable:true
}

def String toString(){
    return subject
}
}

EmailAttachment.groovy:

class EmailAttachment {
static belongsTo = [email:ErrorEmail]

ErrorEmail email
String filename
byte[] content

static mapping = {
    datasources(['DEFAULT'])
    table name:'error_email_attachment', schema: Appointment.schema
}
static constraints = {
    filename nullable:true
    content nullable:true
}
}

Also, here are the relevant lines from schema-export:

alter table program.email_attachment drop constraint FK2E592AFD1D80E229;
drop table program.email cascade;
drop table program.email_attachment cascade;
drop sequence hibernate_sequence;
create table program.email (id int4 not null, version int4, plain_text_message varchar(255), recipients varchar(255), sender varchar(255), sent_date timestamp, subject varchar(255), primary key (id));
create table program.email_attachment (id int8 not null, version int8 not null, content bytea, email_id int4 not null, filename varchar(255), primary key (id));
alter table program.email_attachment add constraint FK2E592AFD1D80E229 foreign key  (email_id) references program.error_email;
create sequence hibernate_sequence;

I've tried specifying joinTable: attachments joinTable:[name: 'email_table', column: 'attachment_id', key: 'id'] to no avail, as well as leaving it out, and trying other collection types for attachment. Thanks in advance for your time and brain cells.


Solution

  • The email doesn't have an attachment_id column because it's the one side of the one-to-many. The many side, attachment in this case, has a reference to its owning email in the email_id int4 not null column. Given an email with id 42 you (and Grails/GORM/Hibernate) can find all of the attachments by querying for all rows in that table with email_id=42.