stored procedure combining firstname with lastname - stored-procedures

I have a stored procedure and i wanted to combine both the firstname and lastname together as fullname and not sure how to do that.
U.FirstName,
U.LastName
I want to have FullName as FirstName and LastName.
Thanks for the help ahead.

Amina, you're going to have to be very specific about which database this is for. Stored procedures are implemented differently depending on the engine. If you're just doing this in a select you could do the following:
For Oracle you could do
select
U.FirstName || ' ' || U.LastName AS FullName
from
USERS AS U
For MS-SQL Server (not sure on this)
select
[U].[FirstName] + ' ' + [U].[LastName] AS FullName
from
USERS AS U
Again this is database dependent.

If you want to concatenate the two fields, use ("foo" || "bar") in an SQL statement to join the two strings. An example: SELECT U.FirstName, U.LastName, (U.FirstName || " " || U.LastName) AS FullName FROM users as U.

Not sure of the database you are using but something like:
SELECT firstname, lastname, firstname + ' ' + lastname as fullname FROM User
should work

Related

Prisma with psql db - incompatible types: text and uuid

I am trying to learn how to use prisma with a psql database.
I'm running into an issue using references where the id is a uuid string.
I have a user model with:
model User {
id String #id #default(dbgenerated("gen_random_uuid()")) #db.Uuid
request Request?
createdAt DateTime #default(now()) #db.Timestamptz(6)
updatedAt DateTime #default(now()) #updatedAt #db.Timestamptz(6)
}
model Request {
id Int #id #default(autoincrement())
user User #relation(fields: [id], references: [id])
// I also tried making the relation field userId
createdAt DateTime #default(now()) #db.Timestamptz(6)
updatedAt DateTime #default(now()) #updatedAt #db.Timestamptz(6)
}
When I try to migrate this, I get an error that says:
failed to apply cleanly to the shadow database. Error: db error:
ERROR: foreign key constraint "Request_userId_fkey" cannot be
implemented DETAIL: Key columns "userId" and "id" are of incompatible
types: text and uuid.
The prisma documents dont show an example using uuid.
The example they do give has a second parameter in the Profile model which has a userId as an Int. I tried adding this to my Request model (as an int, as a string and as a uuid). None of these worked.
model User {
id Int #id #default(autoincrement())
email String #unique
name String?
role Role #default(USER)
posts Post[]
profile Profile?
}
model Profile {
id Int #id #default(autoincrement())
bio String
user User #relation(fields: [userId], references: [id])
userId Int
}
How can I reference a userId when it is generated using uuid?
This segment of the prisma documentation suggests (if I have understood it correctly), that any of String or Int or enum should work to recognise a uuid:
Relational databases Corresponding database type: PRIMARY KEY
Can be annotated with a #default() value that uses functions to
auto-generate an ID:
autoincrement() cuid() uuid() Can be defined on any scalar field
(String, Int, enum)
When I try adding the pgcrypto extension to psql, I try to run the migration again and get an error that has less verbose messaging, but still similar issue:
Error parsing attribute "#relation": The type of the field id in the
model Request is not matching the type of the referenced field id
in model User.
I have seen this discussion which suggests somehow lying to prisma. I am not clever enough to understand the gist of what the lie is supposed to be or how to do it.
Someone on github suggested using this referencing syntax in the request model:
user User #relation(fields: [userId], references: [id])
userId String #unique #db.Uuid
I tried it as above, and without the #unique flag, but I still get a migration error that says that uuid and text are incompatible references. I can't find a section of the prisma documentation that addresses how to make uuid references compatible with relation models.
fyi: the migration file for the attempt above shows the following:
CREATE TABLE "Request" (
"id" SERIAL NOT NULL,
"userId" UUID NOT NULL,
CONSTRAINT "Request_pkey" PRIMARY KEY ("id")
);
You will have to use the annotation #db.Uuid on the reference column userId, read more about it here.
Example:
model Request {
id Int #id #default(autoincrement())
user User #relation(fields: [userId], references: [id])
userId String #db.Uuid
...your other stuff
}
In your Request model is missing the foreign key userId with #db.Uuid this will make postgreSql use the uuid type on a column and #relation the field name must be the same as the foreign key like this #relation(fields: [userId]). The complete code should look like this:
model User {
id String #id #default(dbgenerated("gen_random_uuid()")) #db.Uuid
request Request?
createdAt DateTime #default(now()) #db.Timestamptz(6)
updatedAt DateTime #default(now()) #updatedAt #db.Timestamptz(6)
}
model Request {
id Int #id #default(autoincrement())
user User #relation(fields: [userId], references: [id]) <-ADD userId here
userId String #db.Uuid <-ADD THIS
createdAt DateTime #default(now()) #db.Timestamptz(6)
updatedAt DateTime #default(now()) #updatedAt #db.Timestamptz(6)
}
You can do this with other types, here are some examples: https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#string
I had a similar error and it was because I did not change the type of the relation's ID from Int to String from the example.
If you update the Request model to look like this, does it work?
model Request {
id Int #id #default(autoincrement())
user User #relation(fields: [id], references: [id])
userId String // <- this was missing
createdAt DateTime #default(now()) #db.Timestamptz(6)
updatedAt DateTime #default(now()) #updatedAt #db.Timestamptz(6)
}
I think that the Felix Hagspiel answer is the solution. I could add you should remove the failed generated migration sql (by removing the folder) and retry it again after fixing the problem.

Multiple roles using #PreAuthorize

To check multiple roles has the method level access
I have used #PreAuthorize annotation to check the role
#PreAuthorize("hasRole(\"" + AuthoritiesConstants.USER + "\",)" )
How to check multiple roles using #PreAuthorize annotaion?
You can create a custom annotation to validate many roles and conditions. P.e.:
#Retention(RetentionPolicy.RUNTIME)
#PreAuthorize("hasRole(T(com.bs.dmsbox.api.constants.RoleConstants).ROLE_AGENT) " +
"|| hasRole(T(com.bs.dmsbox.api.constants.RoleConstants).ROLE_ADMIN)" +
"|| (hasRole(T(com.bs.dmsbox.api.constants.RoleConstants).ROLE_CUSTOMER) && #userId == principal.username)")
public #interface IsAuthenticatedAsAgentOrCustomerIsUserId {
}
Then, you can use this annotation as below:
#IsAuthenticatedAsAgentOrCustomerIsUserId
Folder findByUserIdAndType(#Param("userId") String userId, #Param("typeId") FolderType id);
This annotation validate that user logged as role AGENT or ADMIN. If user has role CUSTOMER validate if userId parameter is equals to user logged
#PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_USER')")
hasAnyRole()
When you need to support multiple roles, you can use the hasAnyRole() expression.
#PreAuthorize("hasAnyRole('ADMIN','DB-ADMIN')")
https://docs.spring.io/spring-security/site/docs/3.0.x/reference/el-access.html
https://www.appsdeveloperblog.com/spring-security-preauthorize-annotation-example/
Simply combine roles by using && or || in SpEL expressions
#PreAuthorize("hasRole('" + AuthoritiesConstants.USER + "')" +
" && hasRole('" + AuthoritiesConstants.ADMIN + "')" )
SecurityExpressionOperations interface in package org.springframework.security.access.expression; contains all the authorization-related methods.
Below are the most useful methods for authentication.
boolean hasRole(String role);
boolean hasAnyRole(String... roles)
boolean isAuthenticated();
boolean hasPermission(Object target, Object permission);
boolean hasPermission(Object targetId, String targetType, Object permission);
I believe the best option is to use #PreAuthorize("hasAnyRole()")
In this case I suppose #PreAuthorize("hasAnyRole(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN)")

SubmitChanges doesn't always update database

I am using ASP.NET MVC 4 (.NET framework 4.5) with LINQ-to-SQL and SQL Server 2008 R2
This function returns always true if I run it through debug mode, but when I run it without debug, it returns false. I once got this error: http://i.imgur.com/HydhT.png
I tried googling this, some similiar problems came up but I checked them all:
UserProfiles table has a primary key
The datacontext is in sync with the database
I've tried putting ConflictMode.ContinueOnConflict as an argument in SubmitChanges()
I've tried to put above the facebookID in LINQ designer: UpdateCheck=UpdateCheck.Never
Nothing works. I have never experienced anything like this before. Does anyone have any idea?
Code:
facebookID field in SQL Server is varchar(50) NULL with default value NULL
public static bool changeFacebookIDByEmail(string email, string facebookID)
{
UserProfile profile = (from s in _dc.Users
join u in _dc.Memberships on s.UserId equals u.UserId
join i in _dc.UserProfiles on u.UserId equals i.userID
where u.Email == email
select i).SingleOrDefault();
profile.facebookID = facebookID;
ChangeSet cs = _dc.GetChangeSet();
_dc.SubmitChanges();
if (cs.Updates.Count <= 0)
return false;
else
return true;
}
It seems like you are executing a manual SQL statement:
UPDATE UserProfiles SET facebookID = NULL WHERE userID = '85A6D951-15C8-4892-B17D-BD93F3D0ACBB'
This will set the facebookID to null. Entity framework does not know this, though. It cannot interpret raw SQL. So it still thinks the facebookID is set to some value. When you later set it to that value in changeFacebookIDByEmail EF thinks nothing changed.
Sou you probably should not execute raw SQL strings. Use EF to change the value to null.
Change .singleordefault to .single I think your problem will be revealed pretty soon after that.
Basically anything found by your query with be in the datacontext. Anything new eg default will not.
You need to rewrite your routine to insert the new user in the case where it's not found.
EDIT
This is some code from a project I have been working on. I've cut out a bunch of stuff to demonstrate how it should work.
// add the identity as necessary
var found = dB.Identities.SingleOrDefault(q => q.UserName == userName);
if (found == null)
{
found = new Identity
{
Domain = domain,
Password = User.Identity.AuthenticationType,
Salt = "",
UserName = userName,
LastUpdatedDateTime = DateTime.Now
};
dB.Identities.InsertOnSubmit(found);
}
dB.SubmitChanges(null);

How do I code this SQL query in Linq-To-SQL?

I'm new to MVC and its going well but struggling a bit with the back to front SQL etc
select * from aspnet_Users
where Active = 1 and UserId in (select UserId from aspnet_UsersInRoles,aspnet_Roles where aspnet_Roles.RoleId = aspnet_UsersInRoles.RoleId and aspnet_Roles.RoleName = 'Auth Level 1')
Tables and fields are:
aspnet_Users (UserId int, Active bit, eMail varchar)
aspnet_UsersInRoles (UserId, RoleId)
aspnet_Roles (RoleId int, RoleName varchar)
My attempt - but incomplete looks like this so far:
LmsDataContext db = new LmsDataContext();
var AuthUsers = from aspnet_User in db.aspnet_Users
join userinroles in db.aspnet_UsersInRoles on aspnet_User.UserId equals userinroles.UserId
where aspnet_User.Active
select aspnet_User;
Many thanks in advance
Assuming that you have the associations defined in the database (or the designer), you should be able to access via properties the related entities without resorting to explicit joins. The following example is untested, but should put you on the right track. The basic idea is to find if there are any associations where the associated role has the correct name and choose the user if any are found.
var users = db.aspnet_Users
.Where( u => u.Active )
.Any( u => u.aspnet_UsersInRoles
.Any( r => r.aspnet_Roles.RoleName == "Auth Level 1" ) );
Thanks tvanfossen for the prompt reply, I tried to implement your way but could not get it right. I think your approach is neater bu tI got the following to work :
// Loop through all the Users on the System who are in Auth Level 1 Role and Email them
LmsDataContext db = new LmsDataContext();
var AuthUsers = from aspnet_User in db.aspnet_Users
join userinroles in db.aspnet_UsersInRoles on aspnet_User.UserId equals userinroles.UserId
where aspnet_User.Active
&& userinroles.aspnet_Role.RoleName == "Auth Level 1"
select aspnet_User;
Cheers
J

Rhino UnitOfWorkApplication + Castle Automatic Transaction Management application does not flush automatically on request end

I'm building ASP.Net MVC aplication based on UnitOfWorkApplication and I'd like to use Castle ATM facility. At the moment I've problem with flushing the session on request end. My service class (which is called in my controller action method) looks like this:
[Transactional]
public class UserAdminService : IUserAdminService
{
[Transaction(TransactionMode.Requires)]
public User CreateNewUser(string username, string password, string firstName, string lastName)
{
var u = new User(username)
{
PasswordHash = GetPasswordHash(password),
FirstName = firstName,
LastName = lastName
};
userRepo.Save(u);
//UnitOfWork.CurrentSession.Flush();
return u;
}
When I uncomment the "UnitOfWork.CurrentSession.Flush();" row everything works fine - new user is persisted in DB. But nothing is persisted if I don't flush the session explicitely.
The UnitOfWorkApplication + ATM should flush changes on request end AFAIK - is that right? Does anybody have an advice what should I try to make it work without the explicit session.Flush() call?
I just registered RhinoTransactionFacility instead of original Castle ATM facility + DefaultTransactionManager and everything started to work.

Resources