FOS User bundle : Column 'salt' cannot be null during change password - fosuserbundle

Previously, the app was in PHP7.0, SF 3.1, and FOS/UserBundle 2.0.
After the migration to PHP7.2 with SF 3.4 and FOS/UserBundle 2.1, during a change password, I encounter that:
$ bin/console fos:user:change-password toto pass1234
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'salt' cannot be null" ["exception" => Doctrine\DBAL\Exception\NotNullConstraintViolationException { …},"command" => "fos:user:change-password toto pass1234","message" => """ An exception occurred while executing 'UPDATE fos_user SET salt = ?, password = ? WHERE id = ?' with params [null, "$2y$13$LOb\/************************************wof0QpTGGpzGi", 2]:\n \n SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'salt' cannot be null """] []
In AbstractMySQLDriver.php line 123:
An exception occurred while executing 'UPDATE fos_user SET salt = ?, password = ? WHERE id = ?' with params [null, "$2y$13$LOb\/************************************wof0QpTGGpzGi", 2]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'salt' cannot be null
In PDOStatement.php line 144:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'salt' cannot be null
In PDOStatement.php line 142:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'salt' cannot be null
fos:user:change-password [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-e|--env ENV] [--no-debug] [--] <command> <username> <password>

Solved!
I edited file app/config/security.yml and replace the value of security.encoders.FOS\UserBundle\Model\UserInterface (which was bcrypt) with argon2i.
Then I cleared the cache, retried, and that worked!
https://symfony.com/doc/current/reference/configuration/security.html#reference-security-argon2i

Related

Django migrate column is not the same data type as referencing column

I have the below model which is an existing DB model and through Django's inspectdb management command the below model is created.
class ExistingLegacyModel(models.Model):
period = models.TextField(db_column="Period", blank=True, null=True)
key = models.AutoField(db_column="OutlookKey", primary_key=True)
class Meta:
managed = False
db_table = "table_name"
and currently, I'm trying to create a model with a field foreign key reference to the existing legacy DB model
class TestModel(models.Model):
period = models.ForeignKey(
ExistingLegacyModel,
on_delete=models.CASCADE,
db_column="OutlookKey",
)
so when I run the makemigrations command the migration file is successfully getting created with no issue. below is the migration file content.
class Migration(migrations.Migration):
initial = True
dependencies = [
('historical', '0011_phoenixcontractprice'),
]
operations = [
migrations.CreateModel(
name='TestModel',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('period', models.ForeignKey(db_column='OutlookKey', on_delete=django.db.models.deletion.CASCADE, to='app.ExistingLegacyModel')),
],
),
]
so now when i run the migrate command now, it is failing and giving the below error.
django.db.utils.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Column 'table_name.OutlookKey' is not the same data type as referencing column 'version_testmodel.OutlookKey' in foreign key 'version_testmodel_OutlookKey_eb16c31c_fk_table_name_OutlookKey'. (1778) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Could not create constraint or index. See previous errors. (1750)")
I'm stuck with this issue for the past couple of days and I searched all over the internet but didn't get any resolution. I found a couple of StackOverflow questions that are very similar to my issue, but those questions are also unanswered.
Django - Migration foreign key field type not matching current type
Django 3.2 update AutoField to BigAutoField backward compatibility with foreign key relations
I'm currently using Django 3.2.13 and mssql-django to connect to the MSSQL database.
Any help on this will be highly appreciated! Thank you in advance.
UPDATE 1
I ran the sqlmigrate command for the initial migration. So for the period column, it is creating the table with a foreign key field with big int [OutlookKey] bigint NOT NULL whereas the existing legacy model has a normal integer field.
ALTER TABLE [<app>_<model>] ADD CONSTRAINT [<app>_<model>_OutlookKey_3505d410_fk_<existing_legacy_table>_OutlookKey] FOREIGN KEY ([OutlookKey]) REFERENCES [<existing_legacy_table>] ([OutlookKey]);

SQLAlchemy There are no primary or candidate keys that match the referencing column list in the foreign key

I have a model that was updated
Before Users
class Users(db.Model):
username = db.Column(db.String(64), index=True, unique=True)
user_created_timestamp = db.Column(db.DateTime)
email = db.Column(db.String(120), index=True, unique=True)
password_hash = db.Column(db.String(128))
user_uuid = db.Column(UNIQUEIDENTIFIER, primary_key=True)
scores = db.relationship("Scores", backref="owner", lazy="dynamic")
After Users
class Users(db.Model):
uuid = db.Column(UNIQUEIDENTIFIER, primary_key=True)
email = db.Column(db.String(120), index=True, unique=True)
user_created_timestamp = db.Column(db.DateTime)
password_hash = db.Column(db.String(128))
scores = db.relationship("Scores", backref="owner", lazy="dynamic")
So I wanted to remove username and rename user_uuid to uuid.
I generated a migration file and fixed a couple of errors for dropping the username, but I cannot get the user_uuid to rename to uuid.
Here is the migration script
op.add_column('users', sa.Column('uuid', mssql.UNIQUEIDENTIFIER(), nullable=False))
sa.PrimaryKeyConstraint("uuid")
op.create_foreign_key(None, 'scores', 'users', ['user_uuid'], ['uuid'])
op.drop_constraint('FK__scores__user_uui__17F790F9', 'scores', type_='foreignkey')
op.drop_index(op.f("ix_users_username"), table_name="users")
op.drop_column('users', 'username')
op.drop_constraint('pk_users', 'users', type_='primary')
op.drop_column('users', 'user_uuid')
And here is the error
sqlalchemy.exc.ProgrammingError: (pyodbc.ProgrammingError) ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]There are no primary or candidate keys in the referenced table 'users' that match the referencing column list in the foreign key 'FK__scores__user_uui__2BFE89A6'. (1776) (SQLExecDirectW)
I understand what the error means, but for the life of me, I can't get this to update even after making a number of changes to the original migration. Is there something obvious I'm doing wrong?
Okay, I figured it out. The line
sa.PrimaryKeyConstraint("uuid")
Creates a constraint, but it does not actually create a primary key. I also needed to add
op.create_primary_key("pk_users", "users", ["uuid"])
And the final order of commands looks like
op.add_column('users', sa.Column('uuid', mssql.UNIQUEIDENTIFIER(), nullable=False))
op.drop_constraint('FK__scores__user_uui__17F790F9', 'scores', type_='foreignkey')
op.drop_index(op.f("ix_users_username"), table_name="users")
op.drop_column('users', 'username')
op.drop_constraint('pk_users', 'users', type_='primary')
op.drop_column('users', 'user_uuid')
sa.PrimaryKeyConstraint("uuid")
op.create_primary_key("pk_users", "users", ["uuid"])
op.create_foreign_key(None, 'scores', 'users', ['user_uuid'], ['uuid'])

Spring boot JPA ddl-auto update

When i try to set ddl auto to update, every time I run the application, it shows that hibernate tries to create the tables again. I am trying to add another column in the database using the entity
#Column(name = "xref_reason", length = 20)
private String xRefReason;
Shouldn't it creates this column only that I added?
Here is the error.
Hibernate: create table tbcodetable (id bigint identity not null, codename varchar(255), codevalue varchar(255), desc1 varchar(255), desc2 varchar(255), primary key (id))2018-06-26 16:23:09.342 WARN 4284 --- [ost-startStop-1] o.h.t.s.i.ExceptionHandlerLoggedImpl : GenerationTarget encountered exception accepting command : Error executing DDL via JDBC Statement
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: There is already an object named 'tbcodetable' in the database.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:258) ~[mssql-jdbc-6.2.2.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1535) ~[mssql-jdbc-6.2.2.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerStatement.doExecuteStatement(SQLServerStatement.java:845) ~[mssql-jdbc-6.2.2.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerStatement$StmtExecCmd.doExecute(SQLServerStatement.java:752) ~[mssql-jdbc-6.2.2.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7151) ~[mssql-jdbc-6.2.2.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2478) ~[mssql-jdbc-6.2.2.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:219) ~[mssql-jdbc-6.2.2.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:199) ~[mssql-jdbc-6.2.2.jre8.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerStatement.execute(SQLServerStatement.java:729) ~[mssql-jdbc-6.2.2.jre8.jar:na]
at com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:95) ~[HikariCP-2.7.8.jar:na]
at com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java) ~[HikariCP-2.7.8.jar:na]
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
... 119 common frames omitted
even the foreign keys has the same error.
application.yml
spring:
profiles:
active: dev
datasource:
url: jdbc:sqlserver://localhost;database=dbname
username: user
password: password
driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
hikari:
minimum-idle: 1
maximum-pool-size: 10
pool-name: collectionPool
auto-commit: false
jpa:
show-sql: true
hibernate:
default_schema: dbo
ddl-auto: update
naming:
physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
implicit-strategy: org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy

Exception Handling in T-SQL - Multiple messages vs. multiple states?

I've got a stored procedure that can fail for a number of reasons:
A parameter has the value of zero.
Foreign key violation in Table A.
Foreign key violation in Table B.
Unique constraint violation in Table C.
In terms of 'best practice', should I be using error states or error messages to notify the end user of the problem?
I know states are used to indicate where an error occurred in the actual code, but to an end user it's useless without some kind of documentation.
Having an entry in sys.messages seems overkill for every possible failure case for every stored procedure/trigger in the database.
So should I do this:
THROW 50001, 'Parameter value cannot be 0', 1
THROW 50002, 'Matching value not found in table A', 1
THROW 50003, 'Matching value not found in table B', 1
THROW 50004, 'Combination of values already exists in table C.', 1
Or this:
THROW 50001, 'An error occurred in the procedure.', 1
THROW 50001, 'An error occurred in the procedure.', 2
THROW 50001, 'An error occurred in the procedure.', 3
THROW 50001, 'An error occurred in the procedure.', 4

How to map two tables and not make any changes when mapping legacy database tables in Grails?

I'm new to Grails and mapping and I have something that looks like this.
I have two domain classes and I need to make a relationship between them, and when the relationship is done that no changes would be made to existing tables from my PostgreSQL database.
class Insurance{
Integer id
String osg_name
String osg_logo
String osg_email
String osg_link
static hasMany = [ insurancePackage: InsurancePackage]
static constraints = {
id(blank: false)
osg_name (blank: false, size: 0..155)
osg_logo (size: 0..155)
osg_email (blank: false, size: 0..100)
osg_link (size: 0..155)
}
static mapping = {
table name: "insurance", schema: "common"
version false
id generator :'identity', column :'osg_id', type:'integer'
}
}
class InsurancePackage{
Integer id
Integer osg_id
String osgp_comment
Integer tpo_id
String osgp_link
String osgp_label
//static belongsTo = Insurance
static belongsTo = [insurance: Insurance]
static constraints = {
id(blank: false)
osg_id (blank: false)
osgp_comment (blank: false, size: 0..500)
tpo_id (blank: false,)
osgp_link (blank: false, size: 0..155)
osgp_label (blank: false, size: 0..10)
}
static mapping = {
table name: "insurance_package", schema: 'common'
version false
id generator :'identity', column :'osgp_id', type:'integer'
}
}
This is the error that I'm getting
Error 2015-07-16 13:38:49,845 [localhost-startStop-1] ERROR hbm2ddl.SchemaUpdate - Unsuccessful: alter table revoco.insurance_package add column insurance_id int4 not null
| Error 2015-07-16 13:38:49,845 [localhost-startStop-1] ERROR hbm2ddl.SchemaUpdate - ERROR: column "insurance_id " contains null values
| Error 2015-07-16 13:38:49,845 [localhost-startStop-1] ERROR hbm2ddl.SchemaUpdate - Unsuccessful: alter table revoco.insurance_package add constraint FK684953517A89512C foreign key (insurance_id ) references revoco.insurance
| Error 2015-07-16 13:38:49,845 [localhost-startStop-1] ERROR hbm2ddl.SchemaUpdate - ERROR: column "insurance_id " referenced in foreign key constraint does not exist
So I cant connect the two tables and I'm getting the same error, for some reason Grails are trying to find insurance_id but that is not defined in classes and they are trying to alter my tables and I don't want that to happen.
You are created a new column in the insurance_package table that holds a foreign key to the insurance table. (hasMany and belongsTo --> one-to-many)
The problem here is that the column has a NOT NULL contraint by default but the table appears to have already data in it.
The question is now: What to do with the data already contained in the table. Grails wants to set the NOT NULL constraint but can't because there are already in there and because you have just created the column and the values are NULL
You have 3 options depending on your use case:
delete the values already contained in the table (maybe not wanted)
Go in your db management tool and set a foreign key for those rows and then restart the server. The error should disappear
set the constraint for your insurance reference (belongsTo) in your "InsurancePackage" object to be nullable:true

Resources