Error when i want insert a date in DB with laravel - postgresql

I'm using laravel 5.1 with eloquent, i have a postgre database and i would like to insert an object with some date in. My start format date is like '15/10/2015', and i need to convert into 'Y-m-d'.
For that i use date mutators in my model, i add this line :
protected $dates = ['created_at', 'updated_at', 'prj_start_date', 'prj_end_date_init'];
I use an architecture with services and repositories so in my repository for create my object in DB i have this :
$this->model->create($data);
When i try to insert i have this error
InvalidArgumentException in Carbon.php line 425:
Unexpected data found.
Unexpected data found.
Data missing
in Carbon.php line 425
at Carbon::createFromFormat('Y-m-d H:i:s', '15/10/2015') in Model.php line 2959
at Model->asDateTime('15/10/2015') in Model.php line 2915
at Model->fromDateTime('15/10/2015') in Model.php line 2870
at Model->setAttribute('prj_start_date', '15/10/2015') in Model.php line 422
Why isn't work, i've miss something ?
Can someone help me please ?

In at Carbon::createFromFormat('Y-m-d H:i:s', '15/10/2015') in Model.php line 2959 it is pretty clear that somehow laravel hardcoded it's dates mutator. I suggest using a manual approach, converting your string into Carbon instance via:
Carbon::createFromFormat($format, $time, $tz);
for example assuming have a date field instead of timestamp:
Carbon::createFromFormat('d/m/Y', '15/10/2015');
ps. i did not have the time to test this yet. Nevertheless, learning from the source is much interesting right?
ps. you might interested in changing laravel's format just like the docs however, i suspect this will affect created_at and updated_at (also deleted_at) fields that by default is a timestamp instead of dates.
ps. right, i do forget to mention you had to include Carbon to your controller, just add use Carbon/Carbon

Related

Using the toInteger function with locale and format parameters

I've got a dataflow with a csv file as source. The column NewPositive is a string and it contains numbers formatted in European style with a dot as thousand seperator e.g 1.019 meaning 1019
If I use the function toInteger to convert my NewPositive column to an int via toInteger(NewPositive,'#.###','de'), I only get the thousand cipher e.g 1 for 1.019 and not the rest. Why? For testing I tried creating a constant column: toInteger('1.019','#.###','de') and it gives 1019 as expected. So why does the function not work for my column? The column is trimmed and if I compare the first value with equality function: equals('1.019',NewPositive) returns true.
Please note: I know it's very easy to create a workaround by toInteger(replace(NewPositive,'.','')), but I want to learn how to use the toInteger function with the locale and format parameters.
Here is sample data:
Dato;NewPositive
2021-08-20;1.234
2021-08-21;1.789
I was able to repro this and probably looks to be a bug to me . I have reported this to the ADF team , will let you know once I hear back from them . You already have a work around please go ahead that to unblock yourself .

How to insert similar value into multiple locations of a psycopg2 query statement using dict? [duplicate]

I have a Python script that runs a pgSQL file through SQLAlchemy's connection.execute function. Here's the block of code in Python:
results = pg_conn.execute(sql_cmd, beg_date = datetime.date(2015,4,1), end_date = datetime.date(2015,4,30))
And here's one of the areas where the variable gets inputted in my SQL:
WHERE
( dv.date >= %(beg_date)s AND
dv.date <= %(end_date)s)
When I run this, I get a cryptic python error:
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) argument formats can't be mixed
…followed by a huge dump of the offending SQL query. I've run this exact code with the same variable convention before. Why isn't it working this time?
I encountered a similar issue as Nikhil. I have a query with LIKE clauses which worked until I modified it to include a bind variable, at which point I received the following error:
DatabaseError: Execution failed on sql '...': argument formats can't be mixed
The solution is not to give up on the LIKE clause. That would be pretty crazy if psycopg2 simply didn't permit LIKE clauses. Rather, we can escape the literal % with %%. For example, the following query:
SELECT *
FROM people
WHERE start_date > %(beg_date)s
AND name LIKE 'John%';
would need to be modified to:
SELECT *
FROM people
WHERE start_date > %(beg_date)s
AND name LIKE 'John%%';
More details in the pscopg2 docs: http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries
As it turned out, I had used a SQL LIKE operator in the new SQL query, and the % operand was messing with Python's escaping capability. For instance:
dv.device LIKE 'iPhone%' or
dv.device LIKE '%Phone'
Another answer offered a way to un-escape and re-escape, which I felt would add unnecessary complexity to otherwise simple code. Instead, I used pgSQL's ability to handle regex to modify the SQL query itself. This changed the above portion of the query to:
dv.device ~ E'iPhone.*' or
dv.device ~ E'.*Phone$'
So for others: you may need to change your LIKE operators to regex '~' to get it to work. Just remember that it'll be WAY slower for large queries. (More info here.)
For me it's turn out I have % in sql comment
/* Any future change in the testing size will not require
a change here... even if we do a 100% test
*/
This works fine:
/* Any future change in the testing size will not require
a change here... even if we do a 100pct test
*/

Not able to pass complete datetime(Y-m-d H:i:s) in DB::raw in eloquent

$shop=DB::table('shops')
->leftJoin('orderbookings',function($join)
{
$join->on('shops.id','=','orderbookings.shop_id');
$join->on('orderbookings.created_at','>=',DB::raw(date("Y-m-d",strtotime("now"))));
})
->select('shops.*')
->selectRaw('COUNT(orderbookings.id) as totalorder, SUM(orderbookings.grand_total) as gtotal')
->orderBy('shops.shop_name', 'asc')
->groupby('shops.id')
->paginate(10);
Above code working fine(But not giving total order and amount correct) and also gives result almost close to what I want,
But I am not able to give date format (Y-m-d H:i:s), it shows syntax error. I am using Laravel 5.2 version
Note: I want to give time as well with date to rectify result,
On giving [example: 2017-03-08 11:15:00] shows syntax error
working query in mysql
SELECT COUNT(orderbookings.id), SUM(orderbookings.grand_total), shops.shop_name FROMshopsLEFT JOIN orderbookings on orderbookings.shop_id = shops.id and orderbookings.created_at BETWEEN "2015-10-22 17:02:02" AND "2017-03-07 17:02:02" GROUP BY shops.id
But not able to to convert in eloquent
You should be able to do the following:
$join->on('orderbookings.created_at', '>=', date("Y-m-d"));
You don't need to use DB::raw, and leaving the second parameter null for date, assumes "now".
If this doesn't solve your issue, please post the exact error you're seeing.

Running a query using date from a form MS Access

How do I run a query using a value from a textbox from a form I have? I know that there is another post here at Stackoverflow dealing with this issue but I found it to be insufficient for my needs.
I formated my textbox into Medium Date format with its default value being =Date(). However, when I pick up a date and open my report I get this error:
Runtime error 3071: Expression Too Complex
My where clause is this
WHERE
(
(AllInfo.DateOpened >= CDate([Forms]![Main Form]![WindowPrintOptions]![CustomizedReport]!txtDateOpenedFrom.Value))
)
and I am sure it is this code piece that is throwing the problem since when I take it out of the query the error message simply disappears.
Any ideas?
Try with:
(AllInfo.DateOpened >= DateValue([Forms]![Main Form]![WindowPrintOptions].[Form]!txtDateOpenedFrom))
)
Folks,
I got the problem. It was the "AllInfo" alias. It wasn't applicable at that escope inside the query. By changing the proper things, it was enough to write:
[Forms]![Main Form]![WindowPrintOptions]![CustomizedReport]!txtDateOpenedFrom.Value
Issue solved. Thank you all!

Add shp. name as attribute, looping through dates

I have been stuck on this for a few days. I have a folder with hundreds of shapefiles. I want to add an attribute field to the shapefiles giving the shapefile's name as a date. The shapefile name includes Landsat path/row, year, and Julien date ('1800742003032.shp). I want just the date '2003032' to be added under a "Date" field.
Here's what I have so far:
arcpy.env.workspace = r"C:\Users\mkelly\Documents\Namibia\Raster_Water\1993\Polygons"
for fc in arcpy.ListFeatureClasses("*", "ALL"):
print str("processing" + fc)
field = "DATE"
expression = str(fc)[6:13]
arcpy.AddField_management(fc, field, "TEXT")
arcpy.CalculateField_management(fc, field, "expression", "PYTHON")
Results:
processing1800742003032.shp
processing1800742009136.shp
processing1820732010289.shp
end Processing...
It runs perfectly (on a sample 3 shapefiles) but the problem is that when I open the shapefiles in Arcmap, they all have the same date. The results show that it processed each of the 3 shapefiles, and the add field management must have worked because all of the fields are populated. So there is an issue with either the expression, or the Calculate field command.
How can I get it to populate the specific date for each shapefile, and not just have all of them be '2003032'?? There are no error messages.
Thanks in advance!
I figured it out! For calculate field management, expression should not be in quotes. It should be: arcpy.CalculateField_management(fc, field, expression, "PYTHON")
This post may have been a waste of time, but at least maybe it will help someone with a similar problem in the future.