- Notifications
You must be signed in to change notification settings - Fork975
Postgres Store Procedure#3160
-
Does sqlc have support to generate code for migrations that contain stored procedures? |
BetaWas this translation helpful?Give feedback.
All reactions
Replies: 3 comments
-
@skedee Did you find the answer? |
BetaWas this translation helpful?Give feedback.
All reactions
-
@skedee I don't think I can answer your question without more information. Can you provide a full example? |
BetaWas this translation helpful?Give feedback.
All reactions
-
@kyleconroy Hi, let me give an example. migration.sql -- Table: accountCREATETABLEaccount ( account_idSERIALPRIMARY KEY, usernameVARCHAR(50)NOT NULL UNIQUE, password_hashTEXTNOT NULL, emailVARCHAR(100), created_atTIMESTAMP DEFAULTCURRENT_TIMESTAMP, account_typeVARCHAR(20),-- can be 'user', 'admin', or 'superadmin' is_activeBOOLEANNOT NULL DEFAULT TRUE, admin_idINT,FOREIGN KEY (admin_id)REFERENCES account (account_id)ON DELETESETNULL);-- For bulk updateCREATETYPEaccount_updateAS ( account_idINT, usernameVARCHAR(50), password_hashTEXT, emailVARCHAR(100), account_typeVARCHAR(20), is_activeBOOLEAN, admin_idINT);-- For bulk updateCREATE OR REPLACEFUNCTIONbulk_update_accounts(admin_idINT, accounts account_update[])RETURNS VOIDAS $$BEGINUPDATE accountAS aSET username= COALESCE(u.username,a.username), password_hash= COALESCE(u.password_hash,a.password_hash), email= COALESCE(u.email,a.email), account_type= COALESCE(u.account_type,a.account_type), is_active= COALESCE(u.is_active,a.is_active)FROM UNNEST(accounts)AS uWHEREa.account_id=u.account_idANDa.admin_id= admin_id;END;$$ LANGUAGE plpgsql; Now in account.sql repo for sqlc: -- name: BulkUpdateAccounts :execSELECT bulk_update_accounts($1, $2); This generates this code- constbulkUpdateAccounts=`-- name: BulkUpdateAccounts :execSELECT bulk_update_accounts($1, $2)`typeBulkUpdateAccountsParamsstruct {AdminIDint32`json:"adminId"`Accountsstring`json:"accounts"`// Account is of string type instead of a slice of struct}func (q*Queries)BulkUpdateAccounts(ctx context.Context,argBulkUpdateAccountsParams)error {_,err:=q.db.Exec(ctx,bulkUpdateAccounts,arg.AdminID,arg.Accounts)returnerr} See, the Accounts is of string type instead of a slice of struct. Before using SP, I have tried this in the account.sql as well but it also has the same issue with generated type. -- name: BulkUpdateAccounts :execUPDATE accountAS aSETusername= COALESCE(u.username,a.username),password_hash= COALESCE(u.password_hash,a.password_hash),email= COALESCE(u.email,a.email),account_type= COALESCE(u.account_type,a.account_type),is_active= COALESCE(u.is_active,a.is_active),admin_id= COALESCE(u.admin_id,a.admin_id)FROMUNNEST(sqlc.arg('accounts')::account_update[])AS uWHEREa.account_id=u.account_idANDa.admin_id=sqlc.arg('admin_id'); |
BetaWas this translation helpful?Give feedback.