Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- System.debug(System.now());
- System.debug(System.now().format());
- Integer x = 1;
- Integer y = 2;
- System.assert(y<x, 'A condição esperada não foi atingida');
- List<Account> contas = [SELECT Name, phone FROM Account WHERE Name LIKE 'U%'];
- //System.assertEquals(5, contas.size());
- //System.assert(contas.size()==5, 'Não são iguais');
- //System.assertNotEquals(5, contas.size(), 'Mensagem');
- //System.debug(contas.size());
- List<Account> contas1 = [SELECT Name, phone FROM Account WHERE Name LIKE 'U%'];
- List<Account> contas2 = [SELECT Name, phone FROM Account WHERE Name LIKE 'E%'];
- System.debug(System.equals(contas1, contas2));
- Account a = new Account(Name='Burlington', billingstate='NY');
- Account b = new Account(Name='Burlington', billingstate='NA');
- String msg = System.equals(a, b)?'São iguais':'Não são iguais';
- System.debug(msg);
- List<User> userDetails = [SELECT Id, Name, ProfileId, isActive FROM User];
- for(User u:userDetails){
- System.debug(u);
- }
- //COMO BUSCAR DADOS DE UM USUÁRIO, RESETAR A SENHA, GERAR NOVA E OBTER E ATRIBUIR SENHA MANUALMENTE
- List<User> userDetails = [SELECT Id, Name, ProfileId, isActive FROM User
- WHERE Name = 'Getulio Vargas'];
- Id idUser;
- for(User u:userDetails){
- System.debug(u);
- idUser = u.Id;
- }
- String novaSenha = System.resetPassword(idUser, true).getPassword();
- //o valor boolean de dentro de resetPassword, é para enviar (true) ou não (false) um email para o usuário redefinir a senha.
- System.debug(novaSenha);
- System.setPassword(idUser, 'a1aaaaaa');
- //DATABASE INSERT COM UM ÚNICO OBJETO
- try{
- Account a = new Account(Name='Tesla Motors', billingstate='NY', accountNumber = '12345678');
- Account b = new Account(Name='Chevrolet', billingstate='CA');
- Database.SaveResult resultado = Database.insert(b, false);
- System.debug('Resultado: '+resultado.isSuccess());
- }catch(Exception e){
- System.debug('Gerou uma exceção dentro no nosso catch pq o argumento booleano de Database.insert é true. '+e.getMessage());
- }
- //DATABASE INSERT COM LISTA
- try{
- Account a = new Account(Name='Tesla Motors', billingstate='NY', accountNumber = '12345678');
- Account b = new Account(Name='Chevrolet', billingstate='CA');
- Account c = new Account(Name='Fiat', billingstate='NE', accountNumber = '12345678');
- Account d = new Account(Name='Peugeot', billingstate='AZ');
- List<Account> contas = new List<Account>{a, b, c, d};
- Database.SaveResult[] resultados = Database.insert(contas, false);
- //System.debug('Resultado: '+resultado.isSuccess());
- for(Database.SaveResult dsr:resultados){
- System.debug(dsr);
- }
- }catch(Exception e){
- System.debug('Gerou uma exceção dentro no nosso catch pq o argumento booleano de Database.insert é true. '+e.getMessage());
- }
- try{
- Account a = new Account(Name='Tesla Motors', billingstate='NY', accountNumber = '12345678');
- Account b = new Account(Name='Chevrolet', billingstate='CA');
- Account c = new Account(Name='Fiat', billingstate='NE', accountNumber = '12345678');
- Account d = new Account(Name='Peugeot', billingstate='AZ');
- List<Account> contas = new List<Account>{a, b, c, d};
- Database.SaveResult[] resultados = Database.insert(contas, false);
- //System.debug('Resultado: '+resultado.isSuccess());
- for(Database.SaveResult dsr:resultados){
- if(dsr.isSuccess()){
- System.debug('Conta inserida com sucesso: '+dsr.getId());
- }else{
- List<Database.Error> dbeList = dsr.getErrors();
- for(Database.Error dbe:dbeList){
- System.debug('Erro: ');
- System.debug(dbe.getStatusCode()+' - '+dbe.getMessage());
- System.debug('Campos do erro: ');
- System.debug(dbe.getFields());
- }
- }
- }
- }catch(Exception e){
- System.debug('Gerou uma exceção dentro no nosso catch pq o argumento booleano de Database.insert é true. '+e.getMessage());
- }
- //DATABASE UPDATE COM UM ÚNICO OBJETO
- String geraResposta(Boolean b){
- return b?'Registro atualizado com sucesso':'Erro na atualização';
- }
- try{
- Account pop = [SELECT Name, billingState, accountNumber FROM Account LIMIT 1];
- System.debug(pop.Name+' - '+pop.accountNumber);
- pop.AccountNumber = 'ABCDEFGH';
- pop.Name = pop.Name+' Ltda';
- Database.SaveResult resultado = Database.update(pop, true);
- System.debug('Resultado: '+geraResposta(resultado.isSuccess()));
- pop = [SELECT Name, billingState, accountNumber FROM Account WHERE Id = :resultado.getId()];
- System.debug(pop.Name+' - '+pop.AccountNumber);
- }catch(Exception e){
- System.debug('Gerou uma exceção dentro no nosso catch pq o argumento booleano de Database.update é true. '+e.getMessage());
- }
- //DATABASE UPDATE COM LISTA
- List<Account> contasAtualizadas = new List<Account>();
- try{
- List<Account> contas = [SELECT Name, AccountNumber FROM Account LIMIT 4];
- for(Account a:contas){
- System.debug(a.Name+' - '+a.AccountNumber);
- if(a.AccountNumber.startsWith('CC')){
- a.AccountNumber = a.AccountNumber.replace('CC', 'CD');
- System.debug('Objeto a'+a);
- }else if(a.AccountNumber.startsWith('AB')){
- System.debug('Conta que começa com AB '+a.AccountNumber);
- a.AccountNumber = null;
- }
- contasAtualizadas.add(a);
- }
- Database.SaveResult[] resultados = Database.update(contasAtualizadas, false);
- //System.debug('Resultado: '+resultado.isSuccess());
- for(Database.SaveResult dsr:resultados){
- if(dsr.isSuccess()){
- System.debug('Conta atualizada com sucesso: '+dsr.getId());
- }else{
- List<Database.Error> dbeList = dsr.getErrors();
- for(Database.Error dbe:dbeList){
- System.debug('Erro: ');
- System.debug(dbe.getStatusCode()+' - '+dbe.getMessage());
- System.debug('Campos do erro: ');
- System.debug(dbe.getFields());
- }
- }
- }
- }catch(Exception e){
- System.debug('Gerou uma exceção dentro no nosso catch pq o argumento booleano de Database.update é true. '+e.getMessage());
- }finally{
- for(Account a:contasAtualizadas){
- System.debug('Conta após a atualização: '+a);
- }
- }
- //DATABASE SAVEPOINT COM DATABASE UPDATE COM LISTA
- List<Account> contasAtualizadas = new List<Account>();
- try{
- List<Account> contas = [SELECT Name, AccountNumber FROM Account LIMIT 4];
- for(Account a:contas){
- System.debug(a.Name+' - '+a.AccountNumber);
- if(a.AccountNumber.startsWith('CD')){
- a.AccountNumber = a.AccountNumber.replace('CD', 'CF');
- }else if(a.AccountNumber.startsWith('AB')){
- a.AccountNumber = 'ZZ';
- }
- contasAtualizadas.add(a);
- }
- Savepoint sp = Database.setSavePoint();
- Database.SaveResult[] resultados = Database.update(contasAtualizadas, false);
- //System.debug('Resultado: '+resultado.isSuccess());
- for(Database.SaveResult dsr:resultados){
- if(dsr.isSuccess()){
- System.debug('Conta atualizada com sucesso: '+dsr.getId());
- Account ac = [SELECT Name, accountNumber FROM Account WHERE Id = :dsr.getId()];
- System.debug(ac.Name+' - '+ac.accountNumber);
- }else{
- List<Database.Error> dbeList = dsr.getErrors();
- for(Database.Error dbe:dbeList){
- System.debug('Erro: ');
- System.debug(dbe.getStatusCode()+' - '+dbe.getMessage());
- System.debug('Campos do erro: ');
- System.debug(dbe.getFields());
- }
- }
- }
- Database.rollback(sp);
- }catch(Exception e){
- System.debug('Gerou uma exceção dentro no nosso catch pq o argumento booleano de Database.update é true. '+e.getMessage());
- }finally{
- List<Account> contas = [SELECT Name, AccountNumber FROM Account LIMIT 4];
- for(Account c:contas){
- System.debug(c.Name+' - '+c.AccountNumber);
- }
- }
- //Delete Individual sem Classe
- Account a = [SELECT Name FROM Account WHERE Name LIKE 'Conta%' LIMIT 1];
- delete a;
- System.debug(a.Id);
- System.debug(a.Name);
- Account a = [SELECT Name FROM Account WHERE id='0018Y00002w78LHQAY'];
- System.debug(a.Name);
- //Undelete de um único objeto
- List<Account> listaParaUndelete = [SELECT Id, Name FROM Account WHERE isDeleted = true AND Id = '0018Y00002w78LHQAY' ALL ROWS];
- for(Account a:listaParaUndelete){
- System.debug(a);
- undelete a;
- }
- //EXIBINDO REGISTROS QUE FORAM EXCLUÍDOS DA LIXEIRA MAS NÃO É POSSÍVEL DE SE FAZER O UNDELETE
- //Enquanto está na lixeira, é possível utilizar o undelete. Porém, mesmo excluído da lixeira, é possível lê-lo.
- List<Account> listaParaUndelete = [SELECT Id, Name FROM Account WHERE isDeleted = true AND Name LIKE 'Conta%' ALL ROWS];
- for(Account a:listaParaUndelete){
- System.debug(a);
- }
- undelete listaParaUndelete;
- //recuperando 2 registros da lixeira à partir de uma lista
- List<Contact> listaParaUndelete = [SELECT Id, Name FROM Contact WHERE isDeleted = true AND Name LIKE 'Antônio%' ALL ROWS];
- for(Contact a:listaParaUndelete){
- System.debug(a);
- }
- undelete listaParaUndelete;
- //DATABASE SAVEPOINT COM DATABASE DELETE COM ÚNICO OBJETO
- Account contaParaExclusao = [SELECT Name, AccountNumber FROM Account WHERE Name LIKE 'Conta%' LIMIT 1];
- try{
- System.debug('Conta antes de excluir: '+contaParaExclusao.Name);
- Savepoint sp = Database.setSavePoint();
- Database.DeleteResult resultado = Database.delete(contaParaExclusao, false);
- if(resultado.isSuccess()){
- System.debug('Conta excluída com sucesso: '+resultado.getId());
- Account ac = [SELECT Name FROM Account WHERE Id = :resultado.getId() ALL ROWS];
- System.debug(ac.Name+' - Esta conta foi excluída e está na lixeira');
- }else{
- // List<Database.Error> dbeList = dsr.getErrors();
- // for(Database.Error dbe:dbeList){
- // System.debug('Erro: ');
- // System.debug(dbe.getStatusCode()+' - '+dbe.getMessage());
- // System.debug('Campos do erro: ');
- // System.debug(dbe.getFields());
- // }
- }
- Database.rollback(sp);
- }catch(Exception e){
- System.debug('Gerou uma exceção dentro no nosso catch pq o argumento booleano de Database.update é true. '+e.getMessage());
- }finally{
- List<Account> contas = [SELECT Name FROM Account WHERE Id = :contaParaExclusao.Id];
- for(Account c:contas){
- System.debug(c.Name+' - Visualização após rollback');
- }
- }
- //DATABASE SAVEPOINT COM DATABASE DELETE COM ÚNICO OBJETO COM Database.Error
- Account contaParaExclusao = [SELECT Name, AccountNumber FROM Account WHERE Name LIKE 'Edge%' LIMIT 1];
- try{
- System.debug('Conta antes de excluir: '+contaParaExclusao.Name);
- Savepoint sp = Database.setSavePoint();
- Database.DeleteResult resultado = Database.delete(contaParaExclusao, false);
- if(resultado.isSuccess()){
- System.debug('Conta excluída com sucesso: '+resultado.getId());
- Account ac = [SELECT Name FROM Account WHERE Id = :resultado.getId() ALL ROWS];
- System.debug(ac.Name+' - Esta conta foi excluída e está na lixeira');
- }else{
- List<Database.Error> erros = resultado.getErrors();
- for(Database.Error dbe:erros){
- System.debug('Erro: ');
- System.debug(dbe.getStatusCode()+' - '+dbe.getMessage());
- System.debug('Campos do erro: ');
- System.debug(dbe.getFields());
- }
- }
- Database.rollback(sp);
- }catch(Exception e){
- System.debug('Gerou uma exceção dentro no nosso catch pq o argumento booleano de Database.update é true. '+e.getMessage());
- }finally{
- List<Account> contas = [SELECT Name FROM Account WHERE Id = :contaParaExclusao.Id];
- for(Account c:contas){
- System.debug(c.Name+' - Visualização após rollback');
- }
- }
- //DATABASE SAVEPOINT COM DATABASE MERGE COM LISTA
- List<Account> contaParaMergeMaster = [SELECT Name, website FROM Account WHERE Name LIKE 'Fiat%' ORDER BY ID];
- System.debug('Primeira query');
- System.debug(contaParaMergeMaster);
- List<Account> contasParaMerge2 = [SELECT Name, website FROM Account WHERE Name LIKE 'Fiat%' ORDER BY ID OFFSET 1];
- System.debug('Segunda query');
- System.debug(contasParaMerge2);
- try{
- System.debug('Conta master: '+contaParaMergeMaster[0]);
- System.debug('Contato conta master: '+contaParaMergeMaster[0].Contacts);
- //Savepoint sp = Database.setSavePoint();
- Database.MergeResult[] resultado = Database.merge(contaParaMergeMaster[0], contasParaMerge2, false);
- for(Database.MergeResult registro:resultado){
- if(registro.isSuccess()){
- System.debug('Registro sucesso: '+registro);
- }else{
- List<Database.Error> erros = registro.getErrors();
- for(Database.Error dbe:erros){
- System.debug('Erro sObject: ');
- System.debug(dbe.getStatusCode()+' - '+dbe.getMessage());
- System.debug('Campos do erro: ');
- System.debug(dbe.getFields());
- }
- }
- }
- System.debug('Após o merge, antes do rollback');
- for(Account a:[SELECT Name, website, (SELECT Name, email, phone, accountid FROM Contacts) FROM Account WHERE Name LIKE 'Fiat%' ORDER BY ID]){
- for(Contact c:a.Contacts){
- System.debug('Contato da conta: '+ a+' - '+c);
- }
- }
- //Database.rollback(sp);
- }catch(Exception e){
- System.debug('Gerou uma exceção dentro no nosso catch: '+e.getMessage());
- }finally{
- System.debug('Feito rollback, tudo volta a ser como antes:');
- for(Account a:[SELECT Name, website, (SELECT Name, email, phone, accountid FROM Contacts) FROM Account WHERE Name LIKE 'Fiat%' ORDER BY ID]){
- for(Contact c:a.Contacts){
- System.debug('Contato da conta: '+ a+' - '+c);
- }
- }
- }
- EXERCÍCIO:
- Criar uma classe com 2 métodos estáticos com polimorfismo. Ambos devem ter o mesmo nome, porém com assinaturas diferentes. 1 deles deve poder fazer a inclusão de uma lista de Contatos utilizando a Classe Database.SaveResult. O outro também deverá utilizar a Classe Database.SaveResult, porém, deverá poder gravar um único objeto. Utilizar a classe Database.Error e try{}catch{} para ambos os métodos.
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement