One place for hosting & domains

      Como Gerenciar um Banco de Dados SQL


      Um Guia de Consulta Rápida SQL

      Introdução

      Os bancos de dados SQL vêm instalados com todos os comandos necessários para adicionar, modificar, excluir e consultar seus dados. Este guia de consulta rápida fornece uma referência para alguns dos comandos SQL mais usados.

      Como Utilizar Este Guia:

      • Este guia está no formato de consulta rápida com trechos de linha de comando independentes

      • Salte para qualquer seção que seja relevante para a tarefa que você está tentando concluir

      • Quando você vir texto destacado nos comandos deste guia, tenha em mente que este texto deve se referir às colunas, tabelas e dados em seu próprio banco de dados.

      • Em todo este guia, os valores de dados de exemplo fornecidos são todos agrupados em apóstrofos ('). No SQL, é necessário envolver quaisquer valores de dados que consistam em strings em apóstrofos. Isso não é necessário para dados numéricos, mas também não causará problemas se você incluir apóstrofos.

      Por favor, observe que, embora o SQL seja reconhecido como padrão, a maioria dos programas de banco de dados SQL possui suas próprias extensões proprietárias. Este guia utiliza o MySQL como exemplo de sistema gerenciador de banco de dados relacional (SGBD), mas os comandos executados irão funcionar com outros programs de banco de dados relacionais, incluindo PostgreSQL, MariaDB, and SQLite. Onde existem diferenças significativas entre os SGDBs, incluímos os comandos alternativos.

      Abrindo o Prompt do Banco de Dados (usando Autenticação Socket/Trust)

      Por padrão no Ubuntu 18.04, o usuário root do MySQL pode se autenticar sem uma senha utilizando o seguinte comando:

      Para abrir um prompt no PostgreSQL, use o seguinte comando. Este exemplo irá logar você como o usuário postgres, que é a função de superusuário incluída, mas você pode substituir isso por qualquer função já criada:

      Abrindo o Prompt do Banco de Dados (usando Autenticação por Senha)

      Se seu usuário root do MySQL está configurado para se autenticar com uma senha, você pode fazer isso com o seguinte comando:

      Se você já tiver configurado uma conta de usuário não-root para seu banco de dados, você também poderá usar esse método para efetuar login como esse usuário:

      O comando acima irá solicitar a sua senha após executá-lo. Se voce gostaria de fornecer sua senha como parte do comando, siga imediatamente a opção -p com a sua senha, sem espaço entre elas:

      Criando um Banco de Dados

      O seguinte comando cria um banco de dados com configurações padrão.

      • CREATE DATABASE nome_do_banco_de_dados;

      Se você quer que seu banco de dados utilize um conjunto de caracteres e collation diferentes do padrão, você pode especificá-los usando esta sintaxe:

      • CREATE DATABASE nome_do_banco_de_dados CHARACTER SET character_set COLLATE collation;

      Listando Bancos de Dados

      Para ver quais bancos de dados existem em sua instalação de MySQL ou MariaDB, execute o seguinte comando:

      No PostgreSQL, você pode ver quais bancos de dados foram criados com o seguinte comando:

      Excluindo um Banco de Dados

      Para excluir um banco de dados, incluindo quaisquer tabelas e dados contidos nele, execute um comando que segue esta estrutura:

      • DROP DATABASE IF EXISTS banco_de_dados;

      Criando um Usuário

      Para criar um perfil de usuário para o seu banco de dados sem especificar nenhum privilégio para ele, execute o seguinte comando:

      • CREATE USER nome_do_usuário IDENTIFIED BY 'senha';

      O PostgreSQL usa uma sintaxe similar, mas ligeiramente diferente:

      • CREATE USER nome_do_usuário WITH PASSWORD 'senha';

      Se você quiser criar um novo usuário e conceder-lhe privilégios em um comando, você pode fazer isso usando um comando GRANT. O seguinte comando cria um novo usuário e concede a ele privilégios totais em todos os bancos de dados e tabelas do SGBD:

      • GRANT ALL PRIVILEGES ON *.* TO 'nome_do_usuário'@'localhost' IDENTIFIED BY 'senha';

      Observe a palavra-chave PRIVILEGES no comando GRANT anterior. na maioria dos SGBDs, esta palavra-chave é opcional, e esse comando pode ser escrito equivalentemente como:

      • GRANT ALL ON *.* TO 'nome_do_usuário'@'localhost' IDENTIFIED BY 'senha';

      Esteja ciente, porém, que a palavra-chave PRIVILEGES é necessária para a concessão de privilégios como este, quando o modo Strict SQL está ligado.

      Excluindo um Usuário

      Utilize a seguinte sintaxe para excluir um perfil de usuário do banco de dados:

      • DROP USER IF EXISTS nome_do_usuário;

      Observe que esse comando não excluirá por padrão nenhuma tabela criada pelo usuário excluído, e tentativas de acessar essas tabelas podem resultar em erros.

      Selecionando um Banco de Dados

      Antes de poder criar uma tabela, primeiro você precisa informar ao SGBD o banco de dados no qual você gostaria de criá-la. No MySQL e MariaDB, faça isto com a seguinte sintaxe:

      No PostgreSQL, você deve utilizar o seguinte comando para selecionar seu banco de dados desejado:

      Criando uma Tabela

      A seguinte estrutura de comando cria uma nova tabela com o nome tabela, e inclui duas colunas, cada uma com seu tipo de dado específico:

      • CREATE TABLE tabela ( coluna_1 coluna_1_tipo_de_dado, coluna_2 coluna_2_tipo_de_dado );

      Excluindo uma Tabela

      Para excluir uma tabela inteira, incluindo todos os seus dados, execute o seguinte:

      • DROP TABLE IF EXISTS tabela

      Inserindo Dados em uma Tabela

      Utilize a seguinte sintaxe para popular uma tabela com uma linha de dados:

      • INSERT INTO tabela ( coluna_A, coluna_B, coluna_C ) VALUES ( 'dado_A', 'dado_B', 'dado_C' );

      Você pode também popular uma tabela com várias linhas de dados usando um único comando, assim:

      • INSERT INTO tabela ( coluna_A, coluna_B, coluna_C ) VALUES ( 'dado_1A', 'dado_1B', 'dado_1C' ), ( 'dado_2A', 'dado_2B', 'dado_2C' ), ( 'dado_3A', 'dado_3B', 'dado_3C' );

      Excluindo Dados de uma Tabela

      Para excluir uma linha de dados de uma tabela, utilize a seguinte estrutura de comando. Observe que valor deve ser o valor contido na coluna especificada na linha que você quer excluir:

      • DELETE FROM tabela WHERE coluna='valor';

      Nota: Se você não incluir uma cláusula WHERE em um comando DELETE como no exemplo seguinte, ele excluirá todos os dados contidos em uma tabela, mas não as colunas ou a própria tabela:

      Alterando Dados em uma Tabela

      Use a seguinte sintaxe para atualizar os dados contidos em uma dada linha. Observe que a cláusula WHERE no final do comando informa ao SQL qual linha atualizar. valor é o valor contido na coluna_A que se alinha com a linha que você deseja alterar.

      Nota: Se você deixar de incluir uma cláusula WHERE em um comando UPDATE, o comando substituirá os dados contidos em todas as linhas da tabela.

      • UPDATE tabela SET coluna_1 = valor_1, coluna_2 = valor_2 WHERE coluna_A=valor;

      Inserindo uma Coluna

      A seguinte sintaxe de comando adicionará uma nova coluna a uma tabela:

      • ALTER TABLE tabela ADD COLUMN tipo_de_dado coluna;

      Excluindo uma Coluna

      Um comando seguindo essa estrutura excluirá uma coluna de uma tabela:

      • ALTER TABLE tabela DROP COLUMN coluna;

      Realizando Consultas Básicas

      Para visualizar todos os dados de uma única coluna em uma tabela, use a seguinte sintaxe:

      • SELECT coluna FROM tabela;

      Para consultar várias colunas da mesma tabela, separe os nomes das colunas com uma vírgula:

      • SELECT coluna_1, coluna_2 FROM tabela;

      Você também pode consultar todas as colunas de uma tabela, substituindo os nomes das colunas por um asterisco (*). No SQL, asteriscos agem como um curinga para representar "todos":

      Usando Cláusulas WHERE

      Você pode restringir os resultados de uma consulta adicionando a cláusula WHERE ao comando SELECT, assim:

      • SELECT coluna FROM tabela WHERE condições_que_se_aplicam;

      Por exemplo, você pode consultar todos os dados de uma única linha com uma sintaxe como a seguinte. Observe que valor deve ser um valor contido tanto na coluna especificada quanto na linha que você quer consultar:

      • SELECT * FROM tabela WHERE coluna = valor;

      Um operador de comparação em uma cláusula WHERE define como a coluna especificada deve ser comparada com o valor. Aqui estão alguns operadores comuns de comparação SQL:

      Operador O que ele faz
      = testa a igualdade
      != testa a desigualdade
      < testa menor que
      > testa maior que
      <= testa menor que ou igual a
      >= testa maior que ou igual a
      BETWEEN testa se um valor está dentro de um determinado intervalo
      IN testa se o valor de uma linha está contido em um conjunto de valores especificados
      EXISTS testa se existem linhas, dadas as condições especificadas
      LIKE testa se um valor corresponde a uma string especificada
      IS NULL testa valores NULL
      IS NOT NULL testa todos os valores que não sejam NULL

      O SQL permite o uso de caracteres curinga. Eles são úteis se você estiver tentando encontrar uma entrada específica em uma tabela, mas não tiver certeza de qual é exatamente essa entrada.

      Asteriscos (*) são marcadores que representam “todos”. Isso irá consultar todas as colunas de uma tabela:

      O símbolo de porcentagem (%) representa zero ou mais caracteres desconhecidos.

      • SELECT * FROM tabela WHERE coluna LIKE val%;

      Os underscores (_) são usados para representar um único caractere desconhecido:

      • SELECT * FROM tabela WHERE coluna LIKE v_lue;

      Contando Entradas em uma Coluna

      A função COUNT é utilizada para encontrar o número de entradas em uma determinada coluna. A seguinte sintaxe retornará o número total de valores contidos em coluna:

      • SELECT COUNT(coluna) FROM tabela;

      Você pode restringir os resultados de uma função COUNT adicionando a cláusula WHERE, assim:

      • SELECT COUNT(coluna) FROM table WHERE coluna=valor;

      Encontrando o Valor Médio em uma Coluna

      A função AVG é usada para encontrar o valor médio (nesse caso, a média) entre os valores contidos em uma coluna específica. Observe que a função AVG só funcionará com colunas contendo valores numéricos; quando usada em uma coluna contendo valores de string, pode retornar um erro ou 0:

      • SELECT AVG(coluna) FROM tabela;

      Encontrando a Soma de Valores em uma Coluna

      A função SUM é usado para encontrar a soma total de todos os valores numéricos contidos em uma coluna:

      • SELECT SUM(coluna) FROM tabela;

      Assim como na função AVG, se você executar a função SUM em uma coluna contendo valores de string, ela pode retornar um erro ou apenas 0, dependendo do seu SGBD.

      Encontrando o Maior Valor em uma Coluna

      Para encontrar o maior valor numérico em uma coluna ou o último valor em ordem alfabética, utilize a função MAX:

      • SELECT MAX(coluna) FROM tabela;

      Encontrando o Menor Valor em uma Coluna

      Para encontrar o menor valor numérico em uma coluna ou o primeiro valor em ordem alfabética, use a função MIN:

      • SELECT MIN(coluna) FROM tabela;

      Uma cláusula ORDER BY é usada para ordenar os resultados da consulta. A seguinte sintaxe de consulta retorna os valores de coluna1 e coluna2 e ordena os resultados pelos valores contidos em coluna_1 em ordem crescente ou, para valores de string, em ordem alfabética:

      • SELECT coluna_1, coluna_2 FROM tabela ORDER BY coluna_1;

      Para realizar a mesma ação, mas ordenar os resultados em ordem alfabética decrescente ou reversa, anexe a consulta com DESC:

      • SELECT coluna_1, coluna_2 FROM tabela ORDER BY coluna_1 DESC;

      A cláusula GROUP BY é semelhante à cláusula ORDER BY, mas é usada para ordenar os resultados de uma consulta que inclui uma função de agregação, como COUNT, MAX, MIN, ou SUM. Sozinhas, as funções de agregação descritas na seção anterior retornarão apenas um único valor. No entanto, você pode visualizar os resultados de uma função de agregação executada em cada valor correspondente em uma coluna, ao incluir uma cláusula GROUP BY.

      A seguinte sintaxe contará o número de valores correspondentes em coluna_2 e os agrupará em ordem crescente ou alfabética:

      • SELECT COUNT(coluna_1), coluna_2 FROM tabela GROUP BY coluna_2;

      Para realizar a mesma ação, mas ordenar os resultados em ordem alfabética decrescente ou reversa, adicione DESC à consulta:

      • SELECT COUNT(coluna_1), coluna_2 FROM tabela GROUP BY coluna_2 DESC;

      As cláusulas JOIN são usadas para criar result-sets ou conjuntos de resultados que combinam linhas de duas ou mais tabelas. Uma cláusula JOIN só funcionará se as duas tabelas tiverem uma coluna com nome e tipo de dados idênticos, como neste exemplo:

      • SELECT tabela_1.coluna_1, tabela_2.coluna_2 FROM tabela_1 JOIN tabela_2 ON tabela_1.coluna_comum=tabela_2.coluna_comum;

      Este é um exemplo de uma cláusula INNER JOIN. Um INNER JOIN retornará todos os registros que tiverem valores correspondentes nas duas tabelas, mas não mostrará registros que não tenham valores correspondentes.

      É possível retornar todos os registros de uma das duas tabelas, incluindo valores que não têm ocorrência correspondente na outra tabela, utilizando uma cláusula outer JOIN. As cláusulas outer JOIN são escritas ou como LEFT JOIN ou RIGHT JOIN.

      Uma cláusula LEFT JOIN retorna todos os registros da tabela da "esquerda" e apenas os registros correspondentes da tabela da "direita". No contexto das cláusulas outer JOIN, a tabela da esquerda é aquela referenciada na cláusula FROM, e a tabela da direita é qualquer outra tabela referenciada após a declaração JOIN. A consulta seguinte mostrará todos os registros de tabela_1 e apenas os valores correspondentes de tabela_2. Quaisquer valores que não tenham uma correspondência em tabela_2 aparecerão como NULL no result-set:

      • SELECT tabela_1.coluna_1, tabela_2.coluna_2 FROM tabela_1 LEFT JOIN tabela_2 ON tabela_1.coluna_comum=tabela_2.coluna_comum;

      Uma cláusula RIGHT JOIN funciona da mesma forma que um LEFT JOIN, mas imprime todos os resultados da tabela da direita e apenas os valores correspondentes da tabela da esquerda:

      • SELECT tabela_1.coluna_1, tabela_2.coluna_2 FROM tabela_1 RIGHT JOIN tabela_2 ON tabela_1.coluna_comum=tabela_2.coluna_comum;

      Um operador UNION é útil para combinar os resultados de dois (ou mais) comandos SELECT em um único result-set:

      • SELECT coluna_1 FROM tabela UNION SELECT coluna_2 FROM tabela;

      Além disso, a cláusula UNION pode combinar dois (ou mais) comandos SELECT consultando diferentes tabelas em um mesmo result-set:

      • SELECT coluna FROM tabela_1 UNION SELECT coluna FROM tabela_2;

      Conclusão

      Este guia aborda alguns dos comandos mais comuns no SQL usados para gerenciar bancos de dados, usuários e tabelas e consultar o conteúdo contido nessas tabelas. No entanto, existem muitas combinações de cláusulas e operadores que produzem result-set exclusivos. Se você está procurando um guia mais abrangente para trabalhar com SQL, recomendamos que você confira a Referência de SQL do Banco de Dados Oracle.

      Além disso, se houver comandos SQL comuns que você gostaria de ver neste guia, pergunte ou faça sugestões nos comentários abaixo.

      Por Mark Drake



      Source link

      How Your Online Business Can Nail Customer Service During the Holiday Rush


      The holiday season is upon us once more, and that means many things for your business. On the one hand, you’re about to enter the most lucrative period of the year. However, you’ll also be considerably busier than usual, and will likely need to deal with a much higher number of customer support queries.

      To make sure your support can cope with the holiday rush, you’ll want to plan ahead. Strengthening and preparing your support team is key to helping them provide assistance for a huge influx of stressed customers. If you do that, you’ll be able to reap the benefits of the season more effectively.

      In this article, we’ll discuss why it’s particularly important to provide quality customer service throughout the holidays. We’ll also offer some tips for how you can prepare your business and support team in advance. Let’s get started!

      Why Customer Service Matters Most During the Holidays

      If you’re anything like us, you’re getting busier by the day preparing for the holiday season. However, this isn’t just a time for buying gifts and eating good food. It’s also the most critical period for businesses, as many companies make the bulk of their yearly sales during the last few weeks of the year.

      However, to make sure your business takes full advantage of this period, you’ll need to plan ahead carefully. There are plenty of ways to ensure that you’re ready for the holiday rush, and one of the most crucial is making sure your customer service will function flawlessly.

      Of course, providing high-quality customer support is always necessary. During the holiday rush, however, you will most likely be inundated with even more support queries, questions, and confused customers than at any other time of the year. And because of high stress levels, you’re also more likely to end up dealing with some frustrated and potentially antagonistic customers.

      This might sound intimidating. By preparing in advance and making a solid plan, however, you can ensure that your customer service will remain top-notch even under less-than-ideal circumstances. Not only will this help your customers, but it will be a huge benefit to you and your customer service agents as well.

      10 Ways to Prepare Your Customer Service for the Holiday Rush

      If you’re wondering: “When should I start to prepare for the holidays?”, our answer is right now! It’s never too early to start planning for the year’s final month, but having a plan in place at least before the beginning of December is highly recommended.

      With that in mind, we’re going to guide you through some of the most important steps you’ll want to take. Here are 10 things you can do prepare your customer service before Santa arrives!

      1. Analyze Last Year’s Data

      A perfect place to start your planning is to look back at the previous year. This will involve examining the volume of calls and messages you received, finding out what the most common pain points were, and trying to understand where your service may have been lacking.

      Having this data at hand will be a huge help when formulating a plan for the upcoming rush. You’ll be able to improve in areas where you’ve struggled previously, and you can also preemptively provide information for the most common customer questions. In turn, this will cut down on the number of queries your team has to field.

      How you go about doing this analysis will naturally depend on your toolset. If you’re using software like Zendesk or Awesome Support, you can just view the statistics and queries from previous years. You should also liaise with your support and marketing teams, as they’ll be best equipped to tell you where you need to focus your attention.

      Here are some vital questions you’ll want to be able to answer:

      • How much larger is the volume of support queries you receive during the holiday shopping period, compared with the rest of the year?
      • What are the most common questions customers have?
      • How are most people choosing to contact you — via email, phone, chat, or some other medium?

      Of course, this is by no means an exhaustive list. However, these answers will help you immensely throughout the rest of your preparations.

      2. Decide Which Support Channels to Focus On

      It’s essential that you know where to focus your attention during the holiday season. At first glance, it might seem like the best route to use every conceivable method of contact, but this can lead to spreading yourself too thin.

      Imagine that you have to simultaneously juggle phone lines, live chat, emails, and social media, in addition to updating your content and dealing with orders and shipping. In this scenario, you’ll likely see most — if not all — of those channels suffer in quality. This is especially true if you only have a small support team.

      To avoid this problem, you’ll need to consider which channels of communication to focus on. The best way to start is by looking at which channels are most commonly used by your customers. As we mentioned in the previous section, looking at earlier years’ support queries will give you a good baseline to work from. However, you’ll also want to consider which channels are most popular during the rest of the year.

      For example, if you find that your customers are primarily calling in or using your contact form throughout the year, it’s fair to assume that these will be the busiest channels during the holidays as well. Knowing this will let you assign more people to handle those channels, and avoid keeping customers waiting.

      3. Prepare for Quick Scaling

      The truth is that no matter how well you plan, the holidays are never completely predictable. This means you’ll need to have a contingency plan, in case you need to scale up or down with little notice.

      For example, what if you face twice as many support requests as you anticipated? You’ll need to be able to assign more time and manpower to deal with them, while also keeping the rest of your operations afloat. In this scenario, you might consider hiring remote seasonal workers to help out.

      This is something many companies do to handle the increased volume of work during the holidays. Hiring temporary workers gives you the freedom to change the size of your team at almost a moment’s notice. For example, you could use a service like PartnerHero to outsource some or all of your customer support work during this period.

      Naturally, you’ll need to ensure that these seasonal workers have all the assets and information they need, which is something we’ll discuss later on. With the right preparations in place, they should be able to slot into your normal operations with little friction and help you deal with almost any unexpected situation.

      4. Keep Your Customers Informed

      Arguably the most significant way to avoid customer frustration is to manage their expectations. If your support is changing during the holidays, you need to make that clear as early as possible. They’ll need to be aware of when and how they will be able to contact you.

      It’s also smart to let customers know how your other operations are likely to alter. For example, will returns take longer to process, and will they need to wait a bit for responses to their emails? By letting them know what to expect, you can keep them informed and minimize the risk of frustration or hostility.

      One strategy you can use to your advantage is sometimes referred to as “underpromise and overdeliver.” The idea is that you prepare customers for potential issues that may arise, but then work to avoid those problems anyway. This lets you exceed their expectations.

      Overall, our recommendation is to be honest about what customers can expect and to make any changes clear through as many channels as possible. That includes on your website, social media, and even your email list. This will ensure that the bulk of your customers know what to expect.

      5. Use Automation to Your Advantage

      When the season gets going and you find yourself swamped in tasks, every second will count. To make sure you can use your available time most efficiently, you’ll want to consider automating tasks whenever it’s possible to do so.

      For instance, you can create an automated workflow using software like Help Scout. This can be set up to redirect customer queries to the person or team best suited to deal with them. Not only will this save time on your end, but it will also keep waiting times down for your stressed customers.

      Workflows also let you handle plenty of other tasks automatically, such as tracking products to let you know right away when stocks are low. You can then deal with the potential issue before it becomes a full-blown problem.

      There are plenty of other ways you can use automation during the holidays. One of the best strategies is to set up an AI-driven chatbot that can help you deal with the most common questions. This can dramatically cut down on the amount of time the human members of your team need to spend on customer support requests.

      6. Implement a Triage System for Support Queries

      In addition to automating parts of your support system, you can also optimize it by introducing a triage process. This involves sorting tasks and support queries into categories depending on their urgency. You can then prioritize more urgent matters first, while non-emergency tasks can be dealt with later.

      Implementing triage into your customer service will let you focus your attention on what matters most at any given time. The most pressing and time-sensitive tasks can be dealt with right away, minimizing the risk of making your customers feel frustrated and hostile.

      An easy way to do this is to simply categorize each customer query according to priority. If an issue needs to be dealt with immediately, you might label it as “critical,” while if it needs to be looked at within 1-2 hours it could be labeled “urgent.” Issues that can wait a day or two, on the other hand, can be noted as “low priority.”

      However, you need to remember that you’ll still have to actually deal with all requests. If you find that you’re never getting around to handling low-priority tasks, you may need to consider scaling your team up temporarily by assigning additional personnel.

      7. Update Your Content and Knowledge Base

      Earlier, we discussed the importance of keeping your customers informed. However, this extends beyond just letting them know about changes to your schedule. By making sure that all of your content and assets are up-to-date, you can save both customers and yourself a lot of time and hassle.

      For example, if you provide a knowledge base with information about your products and services, you can use it to answer most of the most commonly asked questions during the holiday period. In many cases, your support team can simply refer customers to relevant knowledge base articles, answering their queries quickly.

      For this to work, you’ll obviously need to ensure that you provide as much documentation and information as possible. It also needs to be thoroughly updated, to ensure that you don’t cause additional confusion among your customers.

      If you need to set up a knowledge base, you can use a plugin such as Heroic Knowledge Base. If you already have one, on the other hand, you should perform a content audit well before the holiday rush kicks in. This can also involve reviewing similar resources, such as your FAQ page.

      8. Learn How to Help Stressed Customers

      The holidays are intended to offer relaxation and fun, but we all know that it can also be a thoroughly stressful period. As such, you’re likely to deal with a few customers who are particularly difficult, frustrated, or even outright antagonistic.

      Naturally, you’ll need to prepare in order to help them out and avoid angering them further. Dealing with difficult customers is a delicate task. The most valuable advice we can offer is to train your support team to stay calm and professional at all times, no matter what a customer might say.

      In addition, here are some ways you can approach particularly challenging customers:

      • Listen. If the customer feels like they’re being deflected or ignored, they’re only going to get angrier and less responsive.
      • Be quick. Naturally, your goal is to be as a fast as possible with all support queries. However, it can be worth prioritizing more stressed customers, to avoid further incident.
      • Treat them like people. We discussed the value of automation earlier, but in tough cases, it’s better to take a personal approach. Make it clear to the customer that you’re handling their issue and care about their frustration, so they don’t feel like they’re being treated as a nuisance.

      In short, by listening to the customer and being prepared to meet them halfway, you can usually solve even the most heated of issues.

      9. Prepare to Provide Compensation to Customers

      In some situations, you may need to compensate customers. Especially in the most volatile or challenging cases, a simple gift can help to smooth things over immensely. Some customers might even demand this kind of treatment.

      Providing compensation can help to soften even the most upset customers. It can also win back some goodwill. Your goal is to ensure that the customer considers using your business again in the future, despite their current grievances.

      Naturally, you’ll want to be very careful about how and when you compensate customers. In some cases, such as when they’ve received a faulty product, you may be legally obligated to provide a new item or a refund.

      However, you can also provide compensation if a customer has had a particularly difficult experience, either with your business or your customer service. This could be in the form of a small gift, a coupon, a discount, or anything else that’s convenient but useful to the customer.

      10. Take Care of Your Support Team

      Finally, while it’s obviously necessary to take care of your customers, you shouldn’t ignore the people on your own front lines. Beginning on Black Friday and Cyber Monday, the holiday rush is a stressful experience for everyone, especially those who have to field questions and requests from wound-up customers.

      Depending on the size of your business, you can take care of your support team in several ways. Naturally, you should make sure they have everything they’ll need to do their jobs without incident.

      However, it’s also nice to reward your support team further, to show your appreciation for all their hard work. Even something as simple as the occasional gift, like seasonally appropriate sweets and drinks, can do a lot to raise morale during this hectic season.

      Holiday Shopping Made Easy

      The holidays are meant to be a time of joy, but it can be hard to feel merry if your customer service is strained. By preparing well in advance, you can put a plan into place, train your team, and inform your customers — providing effective and efficient support as a result.

      Do you have any questions about how to handle customer support during the holiday rush? Find us on social and let’s start the conversation!





      Source link

      Test Salt States Locally with KitchenSalt


      Updated by Linode Written by Linode

      KitchenSalt allows you to use Test Kitchen to test your Salt configurations locally without a Salt master or minions. In this guide you will install KitchenSalt and use Docker to test a Salt state. This guide was created using a system running Ubuntu 18.04.

      Before You Begin

      • You will need root access to your computer, or a user account with sudo privilege. For more information on privileges, see our Users and Groups guide.
      • Install Git on your local computer, if it is not already installed.
      • Update your system packages.

      Install rbenv and Ruby

      Kitchen runs on Ruby. The following commands will install the Ruby version controller rbenv, set rbenv in your PATH, and install Ruby via rbenv.

      1. Install the packages necessary for rbenv:

        sudo apt install libssl-dev libreadline-dev zlib1g-dev bzip2 gcc make git ruby-dev
        
      2. Clone the rbenv git repository and set up your PATH:

        sudo git clone git://github.com/rbenv/rbenv.git /usr/local/rbenv
        sudo mkdir /usr/local/rbenv/plugins
        sudo git clone git://github.com/rbenv/ruby-build.git /usr/local/rbenv/plugins/ruby-build
        sudo tee /etc/profile.d/rbenv.sh <<< 'export PATH="/usr/local/rbenv/plugins/ruby-build/bin:/usr/local/rbenv/bin:$PATH"'
        sudo tee -a /etc/profile.d/rbenv.sh <<< 'source <(rbenv init -)'
        
      3. Reload your system’s profile so that the rbenv commands are added to your PATH:

        source /etc/profile
        

        You can also restart your shell session so the PATH changes take effect.

      4. Install Ruby:

        rbenv install 2.5.1
        

      Install Docker

      These steps install Docker Community Edition (CE) using the official Ubuntu repositories. To install on another distribution, see the official installation page.

      1. Remove any older installations of Docker that may be on your system:

        sudo apt remove docker docker-engine docker.io
        
      2. Make sure you have the necessary packages to allow the use of Docker’s repository:

        sudo apt install apt-transport-https ca-certificates curl software-properties-common
        
      3. Add Docker’s GPG key:

        curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
        
      4. Verify the fingerprint of the GPG key:

        sudo apt-key fingerprint 0EBFCD88
        

        You should see output similar to the following:

        pub   4096R/0EBFCD88 2017-02-22
              Key fingerprint = 9DC8 5822 9FC7 DD38 854A  E2D8 8D81 803C 0EBF CD88
        uid                  Docker Release (CE deb) <docker@docker.com>
        sub   4096R/F273FCD8 2017-02-22
        
      5. Add the stable Docker repository:

        sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
        
      6. Update your package index and install Docker CE:

        sudo apt update
        sudo apt install docker-ce
        
      7. Add your limited Linux user account to the docker group:

        sudo usermod -aG docker exampleuser
        

        You will need to restart your shell session for this change to take effect.

      8. Check that the installation was successful by running the built-in “Hello World” program:

        docker run hello-world
        

      Install KitchenSalt

      1. Install the bundler gem:

        sudo gem install bundler
        
      2. Create a Gemfile in your working directory and add the kitchen-salt, kitchen-docker, and kitchen-sync gems:

        Gemfile
        1
        2
        3
        4
        5
        6
        
        #Gemfile
        source 'https://rubygems.org'
        
        gem 'kitchen-salt'
        gem 'kitchen-docker'
        gem 'kitchen-sync'

        kitchen-sync is used to copy files to Docker containers more quickly.

      3. Install the gems with bundler:

        sudo bundle install
        

      Create a Sample .sls File

      For testing purposes, create a Salt state file that installs NGINX and ensures that it is running. In a text editor, create an nginx.sls file in your working directory and add the following lines:

      nginx.sls
      1
      2
      3
      4
      5
      6
      7
      8
      
      nginx:
        pkg:
          - installed
        service.running:
          - enable: True
          - reload: True
          - watch:
            - pkg: nginx

      Configure kitchen.yml

      1. Now, write the Kitchen configuration file, beginning with the provisioner section. Copy the following lines into a kitchen.yml file in your working directory.

        kitchen.yml
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        
        provisioner:
          name: salt_solo
          salt_install: bootstrap
          is_file_root: true
          require_chef: false
          state_top:
            base:
              "*":
                - nginx
        
        ...

        This section defines salt_solo as the provisioner, which will allow Kitchen to use Salt without a Salt master. In this section Salt is installed via the bootstrap script by setting salt_install: bootstrap, the Salt file root is mapped to the directory where .kitchen.yml is located by setting is_file_root: true, and Chef is disabled by setting require_chef: false. Instead of providing a top file for Salt states, the top file is declared inline. This section is also where Salt pillar files are added. For reference, they are added under the provisioner block:

        kitchen.yml
        1
        2
        3
        4
        5
        6
        7
        8
        9
        
        provisioner:
        ...
          pillars:
            top.sls:
              base:
                "*":
                  - nginx_pillar
          pillars_from_files:
            nginx_pillar.sls: nginx.pillar
      2. Next, configure the driver section:

        kitchen.yml
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        
        ...
        
        driver:
          name: docker
          user_sudo: false
          privileged: true
          forward:
            - 80
        
        ...

        This section declares Docker as the driver, though you could also use Vagrant. Kitchen does not need to use sudo to build the Docker containers, so user_sudo is set to false. privileged is set to true to ensure that the containers run systemd as the exec command. The Docker container will forward traffic to the host on port 80.

      3. Configure the platforms section:

        kitchen.yml
        1
        2
        3
        4
        5
        6
        7
        8
        
        ...
        
        platforms:
          - name: ubuntu
            driver_config:
              run_command: /lib/systemd/systemd
        
        ...

        This section defines which platform Docker will run. By default Docker will run the latest version of that platform. Because different platforms place systemd in different locations, the driver_config section is used to point to the systemd install path of that platform. More than one platform can be defined.

      4. Configure the suites section:

        kitchen.yml
        1
        2
        3
        4
        5
        6
        7
        8
        
        ...
        
        suites:
          - name: oxygen
            provisioner:
              salt_bootstrap_options: -X -p git stable 2018.3
        
        ...

        suites defines which software suite Kitchen will test against. In this context, Kitchen will test against the Oxygen release of Salt. More than one suite can be defined.

      5. Lastly, the transport section allows us to specify the use of kitchen-sync for transferring files:

        kitchen.yml
        1
        2
        3
        4
        
        ...
        
        transport:
          name: sftp
      6. You can now test your Salt configuration with Kitchen. Type the following command to run the test:

        kitchen test
        

        This command will create, converge, and then destroy the test instance. If completed successfully, the final terminal output will be:

          
        -----> Kitchen is finished. (13m32.13s)
        
        

        For a more granular approach to running your test, you can use the individual commands in series:

        kitchen list
        kitchen create
        kitchen converge
        kitchen destroy
        

      Using a Verifier and Next Steps

      Though it is beyond the scope of this article, Kitchen allows for more robust testing than just checking a Salt configuration. You can write tests in bash using Bats, in Ruby using Minitest, Rspec, Serverspec and Inspec, or if you’re more familiar with Python you can use pytest.

      As an example, you can add the following code to your kitchen.yaml to verify your tests using the Inspec gem:

      kitchen.yml
      1
      2
      3
      4
      
      ...
      
      verifier:
        name: inspec

      For more information on writing tests, visit the links in the More Information section below.

      More Information

      You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

      Find answers, ask questions, and help others.

      This guide is published under a CC BY-ND 4.0 license.



      Source link