Getting DatabaseError: multiple default values specified for column - sql

I can't figure out what to do to avoid this error whenever I try to make a migration using South in one of my Django projects:
ERROR:
Running migrations for askbot:
Migrating forwards to 0006_auto__del_field_tagplus_tag_ptr__add_field_tagplus_id__add_field_tagpl.
askbot:0006_auto__del_field_tagplus_tag_ptr__add_field_tagplus_id__add_field_tagpl
FATAL ERROR - The following SQL query failed: ALTER TABLE "tagplus" ADD COLUMN "id" serial NOT >NULL PRIMARY KEY DEFAULT -1;
The error was: multiple default values specified for column "id" of table "tagplus"
Error in migration: >askbot:0006_auto__del_field_tagplus_tag_ptr__add_field_tagplus_id__add_field_tagpl
DatabaseError: multiple default values specified for column "id" of table "tagplus"
MIGRATION FILE 0006 CODE (Partial):
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'TagPlus.tag_ptr'
db.delete_column(u'tagplus', u'tag_ptr_id')
# Adding field 'TagPlus.id'
db.add_column(u'tagplus', u'id',
self.gf('django.db.models.fields.AutoField')(default=0, primary_key=True),
keep_default=False)
# Adding field 'TagPlus.name'
db.add_column(u'tagplus', 'name',
self.gf('django.db.models.fields.CharField')(default=0, unique=True, max_length=255),
keep_default=False)
Thanks!
EDIT:
I Guess the error has something to do with this choice I was prompted while creating the migration file.
? The field 'TagPlus.tag_ptr' does not have a default specified, yet is NOT NULL.
? Since you are removing this field, you MUST specify a default
? value to use for existing rows. Would you like to:
? 1. Quit now.
? 2. Specify a one-off value to use for existing columns now
? 3. Disable the backwards migration by raising an exception; you can edit the migration to fix it later
? Please select a choice:
I selected 'specify one-off value' and I set this value to 0

You are anyways saying keep_default=False. So remove that default=0 from your code
db.add_column(u'tagplus', u'id',
self.gf('django.db.models.fields.AutoField')(primary_key=True),
keep_default=False)
Per SQL it should be (remove the NOT NULL)
ALTER TABLE tagplus ADD COLUMN id serial PRIMARY KEY
See this document which explains the reason behind this error http://www.postgresql.org/docs/8.3/interactive/datatype-numeric.html#DATATYPE-SERIAL

There are two things to note:
Django will use 'id' as the default primary key if you haven't manually set one before, see here.
Postgres does not really have a 'serial' type. To resolve this issue, try to replace:
# Adding field 'TagPlus.id'
db.add_column(u'tagplus', u'id', self.gf('django.db.models.fields.AutoField')(default=0, primary_key=True), keep_default=False)
with:
# Adding field 'TagPlus.id'
if 'postgres' in db.backend_name.lower():
db.execute("CREATE SEQUENCE tagplus_id_seq")
db.execute("SELECT setval('tagplus_id_seq', (SELECT MAX(id) FROM tagplus))")
db.execute("ALTER TABLE tagplus ADD COLUMN id SET DEFAULT nextval('tagplus_id_seq'::regclass)")
db.execute("ALTER SEQUENCE tagplus_id_seq OWNED BY tagplus.id")
else:
db.add_column(u'tagplus', u'id', self.gf('django.db.models.fields.AutoField')(default=0, primary_key=True), keep_default=False)

Related

How can I get Rails 5 to play nicely with a primary key that has a period in it?

I'm working with a database I have no control over, and cannot make alterations to. This database has a table called warehouse_items. Each warehouse item is uniquely identified by a primary key indicating the item id.
Unfortunately, that primary key attribute is named WAREHOUSE_ITEM.ID
(Note the obnoxious period between "item" and "id")
When I try to run a basic query, such as:
WarehouseItem.find('wh3453')
I get an Undefined Table error.
Fortunately, when looking at what Rails is attempting to do, the problem becomes obvious:
: SELECT "warehouse_items".* FROM "warehouse_items" WHERE "WAREHOUSE_ITEM"."ID" = $1 LIMIT $2
Because of the period in the attribute name, Rails is treating "WAREHOUSE_ITEM.ID" as a table/attribute combination, rather than an attribute name with a period in it.
When I run the following PSQL query by hand, I get exactly what I need:
SELECT "warehouse_items".* FROM "warehouse_items" WHERE "warehouse_items"."WAREHOUSE_ITEM.ID" = 'wh3453'
Why is Rails screwing this up, and how can I fix it?
EDIT:
Also worth noting: I've tried using self.primary_key to override the primary key to no avail.
I've tried both a string and a symbol, as in:
self.primary_key="WAREHOUSE_ITEM.ID"
and
self.primary_key=:"WAREHOUSE_ITEM.ID"
Neither one has worked...
Thanks for all the help, everyone!
A suggestion in the comments to use find_by_sql does work! However, I stumbled onto a different solution that works even better.
First, I aliased the annoying attribute name to something simple: id
alias_attribute :id, :"WAREHOUSE_ITEM.ID"
Notice that it's still a symbol, which is important for the next step.
I then overwrite the primary_key method with a custom function:
def self.primary_key
return "id"
end
Now, when I do WarehouseItem.find('wh3453'), Rails defaults to checking id, which is aliased to the correct symbol and it works as intended!!!

SQL Constraint Validation without incrementing the Sequence - Odoo 10

I made a SQL Constraint in a form but we when enter something wrong it give us the constraint error but the Form is still not saved, but the problem is behind, the system make the incrementation of the sequence of this form. knowing that i make the sequence to get created only once the from get saved by super the create function.
How can make a validation of Constraint without incrementing the Sequence ?
This My Sequence Code
#api.model
def create(self, vals):
if vals.get('name','/')=='/':
sequence = self.env['ir.sequence'].next_by_code('archive.dossier')
vals['name'] = sequence
return super(oeArchiveDossier, self).create(vals)
There are two types (Implementation) of sequence used in odoo.
Standard
No Gap
Standard
If you selected this implementation type in sequence (it's default) then sequence will be created in postgresql and managed by postgresql. There is no such control over it. So in case any transactions gets failed then sequence (next number) won't rollbacked.
No Gap
If you select this implementation type then it will be managed by odoo, so in case any issue is there then no sequence number will be skipped.
To better control the validations there is an option in odoo to set method for constrains.
#api.constrains('field1', 'field2')
def check_validations(self):
## Perform Validation
## If condition not satisfied then raise an error.
if validation_conditions:
## Raise an error

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints. error in VB.Net

There were three similar questions in StackOverFlow but none gave an answer..
If have found why this error in occurring but don't know the fix.
I am using Strongly Typed Dataset for my project which is created as a dll for DAL.
I have added the Sql Server Table into this dataset using the designer and has created a DataAdapter
It works fine when i insert using DataTableAdapter
daLabTest.Insert(txtLabTestId.Text, cmbLabTestType.Text, cmbTestName.Text, txtLabFees.Text, dtpLabEffDate.Value)
but when i want to show the data from the table in a combobox or gridview i get this error.
i told that i found out what the problem is, I just previewed the data using DataSet designer and found out that the Function returns data like this...
The query i wrote to view this in dataset is
Select distinct(TestType) from LabTestTypes
so this should return only one column but the dataset is returning 5 columns but others as null, and the TestName column is a primary which should not be null when returned, so the problem exists..
To resolve this i tried to change the NullValue & AllowDBNull property to [Empty] and true respectively but that didn't worked for me.
Please help me in this...
That overly general constraint exception is nasty, where's the InnerException after so many complaints?!
This template may help identify the problem row and column but a "Fill" version of the query function is needed. E.g. GetDistinct*() --> Fill*(). Then a table can be created and interrogated for the row's error text.
SomeTable tTable = new SomeTable()
try {
// sorry, if you have a GetData, change to the fill version
someTable.FillByActiveLogin(tTable, loginName);
} catch (System.Data.ConstraintException constrExc) {
System.Data.DataRow[] rowsErr = tTable.GetErrors();
for (int i = 0; i < rowsErr.Count(); i++)
if (rowsErr[i].HasErrors)
Dbg.WriteLine(rowsErr[i].RowError);
}
(Thanks Michael S for this hint whoever/wherever you are!)
I got this error in a function from a DLL that uses a stored procedure. The procedure did not return all the fields in the table. One of the fields excluded was one that cannot be null. That apparently caused the constraint exception. When I changed the procedure and the DLL to include that field, the exception went away.
After spending ages on this problem myself, I have resolved it modifying the query in the dataset to return a dummy value (that can be ignored) for each key field that is not required in the output.
So your query would become...
Select distinct TestType, 1 as ID, "Dummy" as TestName, "Dummy" as TestFees, "Dummy" as TestDate
from LabTestTypes

Why can't my As400 select from a newly created member alias?

I have set up the code as described in this question.
Creating an alias works, as well as dropping it.
For members that I have created myself, this is working correctly, but for existing members I get the following error when selecting from the alias:
SQL State: 42704
Vendor Code: -204
Message: [SQL0204] MyMemberName in MyLib type *FILE not found.
Cause . . . . . : MyMemberName in
TPLWHS type *FILE was not found. If the member name is *ALL, the table
is not partitioned. If this is an ALTER TABLE statement and the type
is *N, a constraint or partition was not found. If this is not an
ALTER TABLE statement and the type is *N, a function, procedure,
trigger or sequence object was not found. If a function was not found,
MyMemberName is the service program that contains the function. The
function will not be found unless the external name and usage name
match exactly. Examine the job log for a message that gives more
details on which function name is being searched for and the name that
did not match.
Recovery . . . : Change the name and try the request
again. If the object is a node group, ensure that the DB2 Multisystem
product is installed on your system and create a nodegroup with the
CRTNODGRP CL command. If an external function was not found, be sure
that the case of the EXTERNAL NAME on the CREATE FUNCTION statement
exactly matches the case of the name exported by the service program.
Any help you can offer is much appreciated. Thanks!
EDIT: Here is my code:
create alias MyLib.MyAlias for MyLib.MyLogicalFile(MyMember);
select * from MyLib.MyAlias;
drop alias MyLib.MyAlias;
The format of Lib.Alias has worked for me when I directly created the phyiscal and logical members. Perhaps the logical file is missing? I'll double check...
This error message can indicate that the file/logical file/member does not exist.

Yii framework - picking up field value from other model

I have been struggling with this, i have two models and showing data in Cgridview with one model, this model contains some id's whose values are in different table
So, i have added
'value'=> 'TblAreaoflaw::model()->FindByPk($data->typeoflaw)->areaoflaw'
which is giving this error
"Trying to get property of non-object"
Might be due to this reason that the some records doesn't exist in the TblAreaoflaw. Can't we check in this line through isset?
When i put static value, it work well, like
'value'=> 'TblAreaoflaw::model()->FindByPk(5)->areaoflaw',
Could anyone please help
thanks a lot
The error you get is because this expression TblAreaoflaw::model()->FindByPk($data->typeoflaw) is returning null. This means that you are effectively trying to get null->areaoflaw which won't work (this is what the error message "Trying to get property of non-object" clarifies).
My best guess is that $data->typeoflaw returns a non-existing primary key for the TblAreaoflaw model.
Make sure :
TblAreaoflaw is actually a model, I doubt its Areaoflaw
You have database specified primary key which is the id (5) you are passing
Try:
'value'=> '(TblAreaoflaw::model()->FindByPk($data->typeoflaw)->areaoflaw) ?
: "default or null value"'
Obviously substitute the null string to whatever you want. You may need to adjust the condition to use !empty() or similar, but see how it goes. (And if you do that or aren't using PHP 5.3, use the full ternary expression.)