Table not being created in Grails 3 - grails

I am using Grails 3.0.9
application.yml:
hibernate:
cache:
queries: false
use_second_level_cache: true
use_query_cache: false
region.factory_class: 'org.hibernate.cache.ehcache.EhCacheRegionFactory'
endpoints:
jmx:
unique-names: true
dataSource:
pooled: true
jmxExport: true
driverClassName: com.mysql.jdbc.Driver
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
username: root
password: 123
environments:
development:
dataSource:
dbCreate: update
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/blereview?useUnicode=true&characterEncoding=UTF-8
on grails run-app no errors on console but no table is created in the database.
Domain class I am using
DataRequest {
String token;
static constraints = { }
}

On windows,one of my friend is also facing same issue.He fixed it by setting GRAILS-HOME using cygwin(grails run-app from cygwin) and it works for him.
Hope it helps you.

Related

How to add environment variables in config.json?

I am working on a database migration project and it requires me to use sequelize. I initialized sequelize's CLI (using npx sequelize-cli init) that added the config.json file:
config, contains config file, which tells CLI how to connect with database
The config.json file has this object:
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
But I don't want to save my password in a config.json file. I want to use an environmental variable instead. What can I do?
Rename the config.json to config.js, install dotenv and use the below code
require('dotenv').config();
module.exports = {
development: {
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
dialect: process.env.DB_DRIVER
},
test: {
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
dialect: process.env.DB_DRIVER
},
production: {
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
dialect: process.env.DB_DRIVER
}
};
First you have to create a .sequelizerc file in root. Then add the following code there.
var path = require('path')
module.exports = {
'config': path.resolve('config', 'config.js'),
}
Note: Change the path as per your project.
Then you can rename the config.json file to config.js and add the below code there. (As in Tunde's answer.)
require('dotenv').config();
module.exports = {
development: {
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
dialect: process.env.DB_DRIVER
},
test: {
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
dialect: process.env.DB_DRIVER
},
production: {
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
dialect: process.env.DB_DRIVER
}
};

how to save data permanently in grails?

everytime i press debug project, the data in my database is gone. but if i only press run project its still fine. can someone tell me whats wrong in my code? no error appeared when im debugging or running the project.
package test
class Test1 {
String name
int age
String email
String gender
static constraints = {
email email: true,blank: false
gender inList:["Male","Female"]
}
static mapping = {
table 'test1'
version false
id generator: 'increment'
name column: 'name'
age column: 'age'
email column: 'email'
gender column: 'gender'
}
}
this is the controller
package test
class Test1Controller {
static scaffold = Test1
}
this is inside application.yml, i used port 8090
---
grails:
profile: web
codegen:
defaultPackage: test
gorm:
reactor:
# Whether to translate GORM events into Reactor events
# Disabled by default for performance reasons
events: false
info:
app:
name: '#info.app.name#'
version: '#info.app.version#'
grailsVersion: '#info.app.grailsVersion#'
spring:
main:
banner-mode: "off"
groovy:
template:
check-template-location: false
# Spring Actuator Endpoints are Disabled by Default
endpoints:
enabled: false
jmx:
enabled: true
---
grails:
mime:
disable:
accept:
header:
userAgents:
- Gecko
- WebKit
- Presto
- Trident
types:
all: '*/*'
atom: application/atom+xml
css: text/css
csv: text/csv
form: application/x-www-form-urlencoded
html:
- text/html
- application/xhtml+xml
js: text/javascript
json:
- application/json
- text/json
multipartForm: multipart/form-data
pdf: application/pdf
rss: application/rss+xml
text: text/plain
hal:
- application/hal+json
- application/hal+xml
xml:
- text/xml
- application/xml
urlmapping:
cache:
maxsize: 1000
controllers:
defaultScope: singleton
converters:
encoding: UTF-8
views:
default:
codec: html
gsp:
encoding: UTF-8
htmlcodec: xml
codecs:
expression: html
scriptlets: html
taglib: none
staticparts: none
endpoints:
jmx:
unique-names: true
---
hibernate:
cache:
queries: false
use_second_level_cache: true
use_query_cache: false
dataSource:
pooled: true
jmxExport: true
driverClassName: org.postgresql.Driver
dialect: org.hibernate.dialect.PostgreSQLDialect
username: postgres
password: 'admin'
environments:
development:
dataSource:
dbCreate: create-drop
url: jdbc:postgresql://localhost:5432/test
test:
dataSource:
dbCreate: update
url: jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
production:
dataSource:
dbCreate: none
url: jdbc:h2:./prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
properties:
jmxEnabled: true
initialSize: 5
maxActive: 50
minIdle: 5
maxIdle: 25
maxWait: 10000
maxAge: 600000
timeBetweenEvictionRunsMillis: 5000
minEvictableIdleTimeMillis: 60000
validationQuery: SELECT 1
validationQueryTimeout: 3
validationInterval: 15000
testOnBorrow: true
testWhileIdle: true
testOnReturn: false
jdbcInterceptors: ConnectionState
defaultTransactionIsolation: 2 # TRANSACTION_READ_COMMITTED
server:
port: 8090
this is inside build.gradle, i already put the jdbc for postgresql
buildscript {
repositories {
mavenLocal()
maven { url "https://repo.grails.org/grails/core" }
}
dependencies {
classpath "org.grails:grails-gradle-plugin:$grailsVersion"
classpath "org.grails.plugins:hibernate5:${gormVersion-".RELEASE"}"
classpath "com.bertramlabs.plugins:asset-pipeline-gradle:2.14.8"
} }
version "0.1" group "test"
apply plugin:"eclipse" apply plugin:"idea" apply plugin:"war" apply plugin:"org.grails.grails-web" apply plugin:"asset-pipeline" apply plugin:"org.grails.grails-gsp"
repositories {
mavenLocal()
maven { url "https://repo.grails.org/grails/core" } }
dependencies {
compile "org.springframework.boot:spring-boot-starter-logging"
compile "org.springframework.boot:spring-boot-autoconfigure"
compile "org.grails:grails-core"
compile "org.springframework.boot:spring-boot-starter-actuator"
compile "org.springframework.boot:spring-boot-starter-tomcat"
compile "org.grails:grails-web-boot"
compile "org.grails:grails-logging"
compile "org.grails:grails-plugin-rest"
compile "org.grails:grails-plugin-databinding"
compile "org.grails:grails-plugin-i18n"
compile "org.grails:grails-plugin-services"
compile "org.grails:grails-plugin-url-mappings"
compile "org.grails:grails-plugin-interceptors"
compile "org.grails.plugins:cache"
compile "org.grails.plugins:async"
compile "org.grails.plugins:scaffolding"
compile "org.grails.plugins:events"
compile "org.grails.plugins:hibernate5"
compile "org.hibernate:hibernate-core:5.1.5.Final"
compile "org.grails.plugins:gsp"
console "org.grails:grails-console"
profile "org.grails.profiles:web"
runtime "org.glassfish.web:el-impl:2.1.2-b03"
runtime "com.h2database:h2"
runtime "org.apache.tomcat:tomcat-jdbc"
runtime "com.bertramlabs.plugins:asset-pipeline-grails:2.14.8"
testCompile "org.grails:grails-gorm-testing-support"
testCompile "org.grails:grails-web-testing-support"
testCompile "org.grails.plugins:geb:1.1.2"
testRuntime "org.seleniumhq.selenium:selenium-chrome-driver:2.47.1"
testRuntime "org.seleniumhq.selenium:selenium-htmlunit-driver:2.47.1"
testRuntime "net.sourceforge.htmlunit:htmlunit:2.18"
runtime "org.postgresql:postgresql:9.3-1103-jdbc3" }
bootRun {
jvmArgs('-Dspring.output.ansi.enabled=always')
addResources = true
String springProfilesActive = 'spring.profiles.active'
systemProperty springProfilesActive, System.getProperty(springProfilesActive) }
tasks.withType(Test) {
systemProperty "geb.env", System.getProperty('geb.env')
systemProperty "geb.build.reportsDir", reporting.file("geb/integrationTest")
systemProperty "webdriver.chrome.driver", System.getProperty('webdriver.chrome.driver')
systemProperty "webdriver.gecko.driver", System.getProperty('webdriver.gecko.driver') }
assets {
minifyJs = true
minifyCss = true }
I would look into your application.yml or application.groovy for your db settings, and check what your dbcreate is set to. Here's the docs for the data source settings:
https://docs.grails.org/latest/guide/conf.html#dataSource

TypeORM connection provider as Connection class

Is it possible to use connection class as provide like here?
import { Connection, createConnection } from 'typeorm';
export const databaseProviders = [{
provide: Connection,
useFactory: async () => await createConnection({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'postgres',
password: 'postgres',
database: 'testo',
entities: [
__dirname + '/../**/*.entity{.ts,.js}',
],
logging: true,
synchronize: true,
}),
}];
To make imports work like:
constructor(
private connection: Connection,
) {
this.repository = connection.getRepository(Project);
}
In that case nestjs can't find dependency. I guess the problem is in typeorm, it is compiled to plain es5 function. But maybe there a solution for this?
repository to reproduce
UPDATE:
I found acceptable solution nestjs typeorm module, but don't understand why my Connection class is not worked, but it works well with strings. Hope #kamil-myśliwiec will help to understand.
modules: [
TypeOrmModule.forRoot(
[
Build,
Project,
],
{
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'postgres',
password: 'postgres',
database: 'testo',
entities: [
Build,
],
logging: true,
synchronize: true,
}),
],
// And the n inject like this by entity name
#InjectRepository(Build) private repository: Repository<Build>,

schema.yml using sfDoctrineGuardPlugin

I'm building a schema.yml and I'm trying to add foreign key constraints to the table sf_guard_user.
But, when I do doctrine:insert-sql (edit: doctrine:build --all), the links between my tables and sf_guard_user are not there ! Am I missing something ?
I'm using mysql (InnoDB) and Symfony 1.4
Here's a sample of my schema.yml :
Author:
connection: doctrine
tableName: ec_author
actAs:
Sluggable:
fields: [name]
unique: true
canUpdate: false
columns:
sf_guard_user_id:
type: integer
fixed: false
unsigned: false
primary: true
autoincrement: false
name:
type: string(30)
fixed: false
unsigned: false
primary: false
notnull: true
autoincrement: false
contents:
type: string()
fixed: false
unsigned: false
primary: false
notnull: false
autoincrement: false
relations:
User:
class: sfGuardUser
foreignType: one
local: sf_guard_user_id
foreign: id
There are no links to sfGuardUser, even though they are described in schema.yml :
This one works:
Author:
connection: doctrine
tableName: ec_author
actAs:
Sluggable:
fields: [name]
unique: true
canUpdate: false
columns:
sf_guard_user_id:
type: integer
fixed: false
unsigned: false
primary: false
autoincrement: false
name:
type: string(30)
fixed: false
unsigned: false
primary: false
notnull: true
autoincrement: false
contents:
type: string()
fixed: false
unsigned: false
primary: false
notnull: false
autoincrement: false
relations:
User:
class: sfGuardUser
foreignType: one
local: sf_guard_user_id
foreign: id
foreignAlias: author
sf_guard_user_id is a foreign key, then it can't be a primary key. so I changed
primary: true to primary: false.
You should be rebuilding the models and sql as well. Try running:
symfony doctrine:build --all
This will clobber all existing data. If you don't want that, you'll have to write a migration.
The Class name needs to be the same name as you specified when opening the corresponding table in your schema file.
So, for example, you are using:
relations:
User:
class: sfGuardUser
foreignType: one
The class name here must match the declaration of the sfGuardUser table. Just make sure they are the same. Sometimes, it can be declared as sf_guard_user.
If that is fine, you can try adding a few more definitions to your Relations entry:
relations:
User:
class: sfGuardUser
foreignType: one
local: sf_guard_user_id
foreign: sf_guard_user_id

Cannot Configure Grails 3 Multiple Data Sources

I have recently attempted to create an application that allows me to compare 3 separate databases for their values. The databases are 3 Oracle instances which house (essentially) the same database, but in a DEV/TEST/PROD setting.
What I want to do is create one Domain class in GRAILS 3. I then want to be able to fetch the records which that domain class maps to, but do it for all 3 environments.
From reading the Grails 3 docs, it looks like this should be possible by defining 3 datasources in application.yml (in my example here I define 4):
dataSources:
dataSource:
pooled: true
jmxExport: true
logSql: true
driverClassName: oracle.jdbc.OracleDriver
username: MYUSER
password: Password1
dbCreate: validate
url: jdbc:oracle:thin:#someserver:1521:DEV1
dataSource1:
pooled: true
jmxExport: true
logSql: true
driverClassName: oracle.jdbc.OracleDriver
username: MYUSER
password: Password1
dbCreate: validate
url: jdbc:oracle:thin:#someserver:1521:DEV1
dataSource2:
pooled: true
jmxExport: true
logSql: true
driverClassName: oracle.jdbc.OracleDriver
username: MYUSER
password: Password1
dbCreate: validate
url: jdbc:oracle:thin:#someserver:1521:TEST1
dataSource3:
pooled: true
jmxExport: true
logSql: true
driverClassName: oracle.jdbc.OracleDriver
username: MYUSER
password: Password1
dbCreate: validate
url: jdbc:oracle:thin:#someserver:1521:PROD1
and then within the domain class' mapping specifying datasources in the mapping:
package plsutils
class DmjTypes {
String code
String description
Date insertDate
String insertUser
Date modifyDate
String modifyUser
String dbEnv
static mapping = {
datasources(['dataSource1', 'dataSource2', 'dataSource3'])
version false
table name: "CDE_DMJ_TYPES", schema: "MYSCHEMA"
id generator: 'sequence' ,params:[sequence: 'DMJTY_SEQ']
columns {
id column: "DMJTY_ID"
code column: "DMJTY_CDE"
description column: "DMJTY_DESCR"
insertDate column: "INSERT_DTT"
insertUser column: "INSERT_USER"
modifyDate column: "MODIFY_DTT"
modifyUser column: "MODIFY_USER"
dbEnv formula:'( select inst.instance_name || \'-\' || inst.host_name from v$instance inst ) '
}
}
}
and then, within my controller, I should be able to do something like this:
params.max = Math.min(max ?: 10, 100)
dmjTypesListDev = DmjTypes.dataSource1.list(params)
dmjTypesListTest = DmjTypes.dataSource2.list(params)
dmjTypesListProd = DmjTypes.dataSource3.list(params)
I am getting an error upon the first call:
URI /dmjTypes/index
Class groovy.lang.MissingPropertyException
Message null
Caused by No such property: dataSource1 for class: plsutils.DmjTypes
I'm using ojdbc7.jar, connection to Oracle 11g and I'm using Grails 3.0.9.
I can't help but think I'm doing something subtly stupid somewhere. Can anyone please help me with this?
Cheers,
Allen
Basing on official documantation try dataSources keyword:
dataSources:
dataSource:
pooled: true
jmxExport: true
driverClassName: org.h2.Driver
username: sa
password:
lookup:
dialect: org.hibernate.dialect.MySQLInnoDBDialect
driverClassName: com.mysql.jdbc.Driver
username: lookup
password: secret
url: jdbc:mysql://localhost/lookup
dbCreate: update
environments:
development:
dataSources:
dataSource:
dbCreate: create-drop
url: jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
test:
dataSources:
dataSource:
dbCreate: update
url: jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
production:
dataSources:
dataSource:
dbCreate: update
url: jdbc:h2:prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
properties:
jmxEnabled: true
initialSize: 5
…
lookup:
dialect: org.hibernate.dialect.Oracle10gDialect
driverClassName: oracle.jdbc.driver.OracleDriver
username: lookup
password: secret
url: jdbc:oracle:thin:#localhost:1521:lookup
dbCreate: update
Once I corrected the version of grails referred to in the gradle.properties and performed a complete clean and rebuild, I was able to get it working. I believe all my issues were because of a version mismatch of the grails I was using to build it.
So, this is the appropriate datasource entry:
dataSources:
dataSource:
pooled: true
jmxExport: true
driverClassName: oracle.jdbc.OracleDriver
username: MYUSER
password: Password1
dbCreate: validate
url: jdbc:oracle:thin:#somelocalserver:1521:LOCAL
one:
pooled: true
jmxExport: true
driverClassName: oracle.jdbc.OracleDriver
username: MYUSER
password: Password1
dbCreate: validate
url: jdbc:oracle:thin:#somedevserver:1521:DEV1
two:
pooled: true
jmxExport: true
driverClassName: oracle.jdbc.OracleDriver
username: MYUSER
password: Password1
dbCreate: validate
url: jdbc:oracle:thin:#sometestserver:1521:TEST1
three:
pooled: true
jmxExport: true
driverClassName: oracle.jdbc.OracleDriver
username: MYUSER
password: Password1
dbCreate: validate
url: jdbc:oracle:thin:#someproductionserver:1523:PROD1
This is the working domain class:
class DmjTypes {
String code
String description
Date insertDate
String insertUser
Date modifyDate
String modifyUser
String dbEnv
static mapping = {
datasources(['one', 'two', 'three'])
version false
table name: "CDE_DMJ_TYPES", schema: "MYSCHEMA"
id generator: 'sequence' ,params:[sequence: 'DMJTY_SEQ']
columns {
id column: "DMJTY_ID"
code column: "DMJTY_CDE"
description column: "DMJTY_DESCR"
insertDate column: "INSERT_DTT"
insertUser column: "INSERT_USER"
modifyDate column: "MODIFY_DTT"
modifyUser column: "MODIFY_USER"
dbEnv formula:'( select inst.instance_name || \'-\' || inst.host_name from v$instance inst ) '
}
}
}
Try this:
dataSources:
dataSource:
pooled: true
jmxExport: true
logSql: true
driverClassName: oracle.jdbc.driver.OracleDriver
username: MYUSER
password: Password1
dbCreate: validate
autoReconnect: true
#url: jdbc:oracle:thin:#someserver:1521:DEV1(I remember in 3.0.9 this is under environments:development:dataSources:dataSource)
dataSource2:
pooled: true
jmxExport: true
logSql: true
driverClassName: oracle.jdbc.driver.OracleDriver
dialect: org.hibernate.dialect.OracleDialect
username: MYUSER
password: Password1
dbCreate: validate
url: jdbc:oracle:thin:#someserver:1521:TEST1
autoReconnect: true
dataSource3:
pooled: true
jmxExport: true
logSql: true
driverClassName: oracle.jdbc.driver.OracleDriver
dialect: org.hibernate.dialect.OracleDialect
username: MYUSER
password: Password1
dbCreate: validate
url: jdbc:oracle:thin:#someserver:1521:PROD1
autoReconnect: true
In controller:
static mapping = {
datasources(['dataSource', 'dataSource2', 'dataSource3'])
.....
}

Resources