how to create column dynamically in grails 2.4.4 using GORM - grails

I want to create a table in my database based on file upload. Means once upload the csv file then only that should create tables in my database and for each csv file a new table should be created dynamically.
now am trying to upload file from controller. from controller i should pass fields values to domain class and tables name same as the csv file name how can i solve this?

A relational database really isn't a good fit for a dynmaic persistence model, something like MongoDB would be better. The best you can do with a GORM domain model is something like
class CsvFile {
String fileName
static hasMany = [rows: Row]
}
class Row {
static belongsTo = [csvFile: CsvFile]
Map<String, Object> fields
}
I realise this doesn't exactly match your requirement insofar as each CSV file being stored in a separate table, but that's just not really practical with a GORM domain model being stored in a relational database.

Related

How can I update my existing database table using domain class in grails 3.3.0?

I would like to add new column in my existed table using domain class but it is not happening. if I use create-drop in application.yml file then it works but at the same time I lost my data. I needed to keep the data as well as I needed to add new column by updating domain class property in grails 3.3.0 and SQL Server 2012
package com.alumni
class Student
{
String studentId
String studentName
String age
static constraints = {
}
}
Database is not updating with column address
It's unclear from your code snippet, but it sounds like you're trying to add
String address
Note that columns are made NOT NULL by default, so if data exists in the table, it's attempting to add a non-nullable column, with null data on every row, so the column will fail to create. You need to allow this column to be nullable in the constraints block as well
static constraints = {
address(nullable: true)
}
If you add that, the column should create successfully.

How to model stored procedure records in Grails?

I need to call some stored procedures that return their own kinds of records, that are not directly mapped to tables or views.
I have used stored procedures in the past with groovy.sql.Sql and plain (unmodelled) Maps, but for this application I would like to model those records with something akin to domain classes, in order to define data types, data binding, validation, associations to other entities, and so on.
What is the best way to do so?
Should I model the stored procedure records as proper domain classes (entities) and then try to disable (or redefine) their database persistence? How?
Should I use non-domain POJOs where I selectively enable the features I need? (such as validation with #Validatable) How can I handle associations then? (Associations arise when the record returned from the SP contains a foreign key to some other persisted entity.)
If you want data binding, validation and associations to be maintained in an easy way then you should go with the Domain approach.
To disable database persistence for a domain class you can add static mapWith = "none" to a domain class and a table won't be created for that domain class.
Sample Entity class:
#ToString
public class SPTest {
Long idField
User user
GroupIntegrationKey integrationKey
static constraints = {
}
static mapWith = "none"
}
Stored Procedure statement:
SELECT id AS idField, user_id AS user, key AS integrationKey FROM
my_domain;
In order to map the result of the SP to the entity you can use result transformers.
Query query = session.createSQLQuery("CALL getSPData()");
List<Map> results = query.with {
resultTransformer = AliasToEntityMapResultTransformer.INSTANCE
list()
}
Now iterate over list and create a new entity object
List<MyDomain> list = results.collect {
new MyDomain(it)
}
System.err.println(list)
Drawbacks:
You can not map identifier field
You would have to iterate over result again to create entity objects
You can not map hasMany relationships
If you want to go with pojo, then in that case you would have to create your own version of getters to get associated objects.

How can I JOIN tables in different databases (on the same server) using Slick?

I'd like to do a join on two tables residing in different databases on the same MySQL server, using Slick 2.0. Usually this would just be a matter of referring to the tables via a qualified name, e.g. DB1.TABLE1.
Can someone show me how to do this in Slick?
If I don't specify a database in the JDBC connection string, I get an exception. If I do specify one of the databases there, say DB1, and specify the table name in the Table constructors as DB1.TABLE1 and DB2.TABLE2, then I get an exception about the missing table DB1.DB2.TABLE2.
Specify any database in the connection string and pass the database as the schema argument to Table for each table class.
class SomeTable(tag: Tag) extends Table[(Int,String)](
tag, Some("SOME_DB"), "SOME_TABLE"
) {
def id = column[Int]("id")
def title = column[String]("title")
def * = (id, title)
}
This should really be documented somewhere: https://github.com/slick/slick/issues/659

Change model after database is created on EF4 code only

Hey, sorry for my bad english...
Using EF4 code-only, I have created some POCO classes and my database was generated from that. All worked fine, I inserted some data on the tables but now I need to create a new property on one of my classes. If i just create it, the application give me the exception:
{"The model backing the 'TestContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the RecreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data."}
I tried to create manually the field on the table, but it is still complaining... does someone know if there is a way and if so how can I manually update the database schema (i don't want to recreate it because i already have data) to match the model?
It should work if you make sure that your new column match exactly your new property.
For example, if you add a property NewProp
public class MyEntity
{
[Key]
public int Id;
public string PropA;
public int PropB;
public int NewProp;
}
then in your database table MyEntities, you would add a column NewProp of type int not null.
What you can do to check if the column you add is correct, is to rename your database, then let Code-First recreate the database and see what's different between the original and new databases.
EF generates partial classes. So you can add new properties(fields) in another partial class.

LINQ Modelling Automagically Retrieving Data Via EntityRef

I'm using LINQ to model my database, but I'm writing it by hand (Steve Sanderson recommends this in his ASP.NET MVC book). What I need to know is what's happening when you create an EntityRef, and how it's referenced. If I create my queries manually (without using LINQ), but use LINQ to model it, and I bring back just the ID of something, then reference the actual table column using EntityRef in the view, does it do the join, or does it re-query the database for that bit of information?
To clear things up, if I have this in my repository:
public IEnumerable<MyTable> ListMyTable(int? myColumnVar)
{
string query = "SELECT * FROM MyTable WHERE MyColumn = {0}";
return this.ExecuteQuery<MyTable>(query, myColumnVar);
}
and then in my controller I do this:
IEnumerable<MyTable> mytables = _contractsControlService.ListMyTable(1);
return View(mytables);
then in my view I do things like
<%=tbl.Ref.MyColumn %>
I'm referencing something set out by the LINQ model, but isn't actually in the table output. How does it get that data?
To clear things up further, we're using systems which require ultimate speed, so the LINQ-to-SQL is too slow for us, hence why we're using direct queries in our repository. I wouldn't mind using this EntityRef business if only I knew what was happening underneath.
You have most likely used the Object Relational designer to create an entity class for the Ref entity and an association between the MyTable and the Ref entity. You can also do that manually by creating the appropriate entity classes and using attributes to map the classes to the database schema. You can read the details in How to: Customize Entity Classes by Using the Code Editor (LINQ to SQL) on MSDN.
In your generated (or handwritten) code you will find some attributes:
[Table(Name="dbo.Ref")]
public partial class Ref : INotifyPropertyChanging, INotifyPropertyChanged
and
public partial class MyTable: INotifyPropertyChanging, INotifyPropertyChanged
{
[Association(Name="Ref_MyTable", Storage="_Ref", ThisKey="RefId",
OtherKey="Id", IsForeignKey=true)]
public Ref Ref
{
get
...
The entity classes combined with the attributes enables the Linq-to-Sql framework to retrieve entity classes directly from the database.
If you want to monitor the SQL genereated by Linq-to-Sql you can assign the DataContext.Log property:
context.Log = Console.Out;
In your example, navigating from MyTable to Ref, probably generates SQL along these lines:
SELECT Id, Field1, Field2, Field3
FROM Ref
WHERE Id = #RefId

Resources