I have a PostgreSQL table
CREATE TABLE reservation_table (
idreservation SERIAL NOT NULL,
entry_datetime TIMESTAMPTZ NOT NULL DEFAULT 'NOW',
start_end_dates DATERANGE NOT NULL ,
property_id INT NOT NULL REFERENCES property_table,
...
)
and a constraint to prevent 2 reservations of the same property on same date
ALTER TABLE ONLY reservation_table
ADD CONSTRAINT reservation_double_booking_constraint
EXCLUDE USING gist
(property_id WITH =, start_end_dates WITH &&)
;
Can I enforce my SQL constraint within my Grails Reservation domain ?
I am considering accessing reservation using a view, to avoid problems with postgresql range in groovy
create view resView as
select idReservation,
lower(start_end_dates) AS startDate,
upper(start_end_dates) AS endDate,
property_id
from reservation_table
Ok , but you specified very minimum information to solve this kind of problem , since i have not understood it fully , i have the following suggestion.
How about using before and after interceptor on grails.
class Reservation {
Date startDate ...
def beforeInterceptor = {
//do some date validation here start data or end date
//for exmaple you might check that we have
//any start date currently existing on db
//by findbyStartDate or endDate
//then reject the reservation or saving of this model
println "validation error here , cancel save"
}
static constraints = {
//do some validation here related to ur constraint
startDate max: new Date()
}
}
let me know anything if u need more help . . .
Related
I have a PostgresPagingQueryProvider that has a simple query
Select id from action
This is expected to return 1 column. When I run the batch I have an exception saying
PreparedStatementCallback; SQL [SELECT id FROM action WHERE 1=1 ORDER BY id ASC LIMIT 1000];
The column index is out of range: 1, number of columns: 0.; nested exception is org.postgresql.util.PSQLException:
The column index is out of range: 1, number of columns: 0.
This is the query provider:
#Bean
public PostgresPagingQueryProvider queryProvider() {
PostgresPagingQueryProvider provider = new PostgresPagingQueryProvider();
HashMap<String, Order> sorting = new HashMap<>();
sorting.put("id", Order.ASCENDING);
provider.setSelectClause("Select id");
provider.setFromClause("from action");
provider.setWhereClause("where 1=1");
provider.setSortKeys(sorting);
return provider;
}
And this is the creation of the table
CREATE TABLE action (
id int4 NOT NULL,
"timestamp" timestamp NULL,
CONSTRAINT action_pkey PRIMARY KEY (id)
);
When using the same query with ItemReader this works just fine.
Ok, I have figured it out.
The problem was that due to a copy paste of mine I setting the first variable of the query to STOPPED .
As someone might notice the query does not accept any parameters. So deleting that fixed the issue.
In addition to that I thought that the part where I pass in the HashMap of the variables was unrelated, thus it is not included in the question so I guess no one could have answered that.
I am going to leave this here as a tribute to the monumental errors and time wasting a copy paste might lead.
I am using sqlx to create a go api.
I want to insert a record in a table named day.
The corresponding go struct is the following
type Day struct {
ID string `db:"id" json:"id"`
Dateday string `db:"dateday" json:"dateday"`
Nameday string `db:"nameday" json:"nameday"`
Holyday bool `db:"holyday" json:"holyday"`
}
In an endpoint for Day creation, will be receiving all fields but the ID via a post request
What method should I use to interact with my db so as to:
a) create the record
b) not need to pass the ID myself and instruct postgres to auto-generate the field.
The table creation statement is the following:
CREATE TABLE IF NOT EXISTS "day" (
"id" SERIAL PRIMARY KEY,
"dateday" date NOT NULL,
"nameday" varchar(10) NOT NULL,
"holyday" boolean NOT NULL
);
I would suggest to override the MarshalJSON method as mentioned below:
func (r Day) MarshalJSON() ([]byte, error) {
root := make(map[string]interface{})
root["dateday"] = r.Dateday
root["nameday"] = r.Nameday
root["holyday"] = r.Holyday
return json.Marshal(root)
}
Ref: https://golang.org/pkg/encoding/json/#example__customMarshalJSON
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;
Actually i have manually entered records in mysql database-using grails but i want to show the date in a coloumn in same table.
Is there any solution for this
here is my controller class
class test {
String company_name
String contact_person
Integer phone_no
String status
String place
String address
static constraints = {
company_name(nullable:false)
contact_person(nullable:false)
phone_no(uinque:true,nullable:false)
status(nullable:false)
place(nullable:false)
address( nullable:false )
}
}
Grails provides automatic timestamps via the "dateCreated" property:
Automatic timestamping
If you define a dateCreated property it will be set to the current
date for you when you create new instances. Likewise, if you define a
lastUpdated property it will be automatically be updated for you
when you change persistent instances.
(From the Grails user guide: Events and auto timestamping)
Have a look at dateCreated and lastUpdated in autoTimestamp property in GORM.
I have two tables:
create table dbo.Dates (
Id int not null
constraint Dates_Id_PK primary key clustered (Id),
[DateValue] date not null
}
create table dbo.Posts (
Id int identity not null
constraint Posts_Id_PK primary key clustered (Id),
Created datetime not null,
Title nvarchar (200) not null
)
For these tables I have Date and Post entities.
How can I get a table that has the column DateValue from Dates and the number of Posts with that date.
I need to match the datetime Created value to the date DateValue.
Thank you,
Miguel
I assume your Posts have dates with times, so you'll have to truncate them to the date part (as in the Date property of a DateTime):
from d in context.Dates
select new {
Date = d.DateValue,
NrOfPosts = (from p in context.Posts
where EntityFunctions.TruncateTime(t.Created) == d.DateValue
select p).Count()
}
you can use anonymous types. try the following snippet.
DateTime dateToMatch = GetDateToMatch();
using(YourEntities context = new YourEntities())
{
var result = context.Dates.Where(d => d.DateValue == dateToMatch)
.Select(d => new { Date = d.DateValue, PostCount = d.Posts.Count() });
}