<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Banco de dados &#8211; Rafael Bernard Araujo</title>
	<atom:link href="https://rafael.bernard-araujo.com/categoria/technology/banco-de-dados/feed" rel="self" type="application/rss+xml" />
	<link>https://rafael.bernard-araujo.com</link>
	<description>desenvolvendo... while(!success){  try(); }</description>
	<lastBuildDate>Sat, 10 May 2025 23:56:33 +0000</lastBuildDate>
	<language>pt-BR</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
<site xmlns="com-wordpress:feed-additions:1">21941730</site>	<item>
		<title>Recover and replace win1252 content to utf-8 for a PostgreSQL database</title>
		<link>https://rafael.bernard-araujo.com/recover-and-replace-win1252-content-to-utf-8-for-a-postgresql-database.php</link>
					<comments>https://rafael.bernard-araujo.com/recover-and-replace-win1252-content-to-utf-8-for-a-postgresql-database.php#respond</comments>
		
		<dc:creator><![CDATA[rafael]]></dc:creator>
		<pubDate>Mon, 10 Oct 2022 23:32:00 +0000</pubDate>
				<category><![CDATA[Banco de dados]]></category>
		<category><![CDATA[PostGreSQL]]></category>
		<category><![CDATA[database]]></category>
		<guid isPermaLink="false">https://rafael.bernard-araujo.com/?p=1651</guid>

					<description><![CDATA[I shouldn't be the first to need to export data from a PostgreSQL database installed on Windows with a win1252 code to a database with UTF-8 code (in my case, on a Linux server). It is not enough to transform the transfer file to UTF-8, as the characters of win1252 (left double quote, right double [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>I shouldn't be the first to need to export data from a PostgreSQL database installed on Windows with a win1252 code to a database with UTF-8 code (in my case, on a Linux server).</p>
<p>It is not enough to transform the transfer file to UTF-8, as the characters of win1252 (left double quote, right double quote, single quote and dash) will be there, with a weird value in your database.</p>
<p>In my experience, I had to import data as-is and afterwards perform an update using the function to rewrite data for UTF-8 characters correctly.</p>
<p>The following code examples are for: 1 - transform to HTML characters; 2 - transform to single characters.</p>
<p>HTML:</p>
<pre><code class="language-plpgsql">-- DROP FUNCTION substitui_win1252_html(texto);

CREATE OR REPLACE FUNCTION substitui_win1252_html(texto text)
    RETURNS text AS
$$
BEGIN

    texto := replace(replace(replace(replace(replace(texto, &#039;&#039;, &#039;&amp;#8217;&#039;), &#039;&#039;, &#039;&amp;#8220;&#039;), &#039;&#039;, &#039;&amp;#8221;&#039;), &#039;&#039;,&#039;&amp;#8226;&#039;), &#039;&#039;, &#039;&amp;#8211;&#039;)::text; 
    RETURN texto;

END;
$$
LANGUAGE plpgsql;</code></pre>
<p>Simple:</p>
<pre><code class="language-plpgsql">-- DROP FUNCTION substitui_win1252(texto);

CREATE OR REPLACE FUNCTION substitui_win1252(texto text)
    RETURNS text AS
$$
BEGIN

    texto := replace(replace(replace(replace(replace(texto, &#039;&#039;, &#039;&#039;&#039;&#039;), &#039;&#039;, &#039;&quot;&#039;), &#039;&#039;, &#039;&quot;&#039;), &#039;&#039;,&#039;&amp;#8226;&#039;), &#039;&#039;, &#039;-&#039;)::text;  
    RETURN texto;

END;
$$
LANGUAGE plpgsql;</code></pre>
<p>Don't worry about the squares that you might see. If you copy it to a good text editor, you will their actual value.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://rafael.bernard-araujo.com/recover-and-replace-win1252-content-to-utf-8-for-a-postgresql-database.php/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1651</post-id>	</item>
		<item>
		<title>PostgreSQL &#8211; pg_upgrade from 10 to 12</title>
		<link>https://rafael.bernard-araujo.com/postgresql-pg_upgrade-from-10-to-12.php</link>
					<comments>https://rafael.bernard-araujo.com/postgresql-pg_upgrade-from-10-to-12.php#respond</comments>
		
		<dc:creator><![CDATA[rafael]]></dc:creator>
		<pubDate>Tue, 31 Mar 2020 14:20:19 +0000</pubDate>
				<category><![CDATA[PostGreSQL]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[infrastructure]]></category>
		<guid isPermaLink="false">https://rafael.bernard-araujo.com/?p=1344</guid>

					<description><![CDATA[I have some PostgreSQL databases running pretty well but we need to keep our software updated. This is a mandatory practice for a high-quality service. Those servers are running version 10 and they need to be upgraded to version 12. I have used pg_dump / pg_restore strategy for a long time, but this time I [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>I have some PostgreSQL databases running pretty well but we need to keep our software updated. This is a mandatory practice for a high-quality service. Those servers are running version 10 and they need to be upgraded to version 12. I have used <code>pg_dump</code> / <code>pg_restore</code> strategy for a long time, but this time I would rather use <code>pg_upgrade</code>.</p>
<p>Let's dive into how to do it.</p>
<p>Table of contents:</p>
<ol>
<li>Install</li>
<li>InitDB</li>
<li>Check upgrade consistency</li>
<li>Set locale</li>
<li>Upgrade</li>
<li>Configurations</li>
</ol>
<h2>Install</h2>
<p>The package <code>postgresql12-server</code> contains everything needed to run the server, but my databases use some extensions [1], then I will add <code>postgresql12-devel</code> and <code>postgresql12-contrib</code> to be able to compile and to install the extensions.</p>
<pre><code class="language-sh">yum install postgresql12-server postgresql12-devel postgresql12-contrib</code></pre>
<h2>InitDB</h2>
<p>After installation we need to setup new server with initdb:</p>
<pre><code class="language-sh">~% /usr/pgsql-12/bin/postgresql-12-setup initdb
Initializing database … OK</code></pre>
<h2>Check upgrade consistency</h2>
<p>We need to check compatibility. Turn to postgres user (<code>su - postgres</code>) and run the command:</p>
<pre><code class="language-sh">~% /usr/pgsql-12/bin/pg_upgrade --old-bindir=/usr/pgsql-10/bin --new-bindir=/usr/pgsql-12/bin --old-datadir=/var/lib/pgsql/10/data --new-datadir=/var/lib/pgsql/12/data --check

Performing Consistency Checks on Old Live Server
------------------------------------------------
Checking cluster versions                                   ok
Checking database user is the install user                  ok
Checking database connection settings                       ok
Checking for prepared transactions                          ok
Checking for reg* data types in user tables                 ok
Checking for contrib/isn with bigint-passing mismatch       ok
Checking for tables WITH OIDS                               fatal

Your installation contains tables declared WITH OIDS, which is not supported
anymore. Consider removing the oid column using
    ALTER TABLE ... SET WITHOUT OIDS;
A list of tables with the problem is in the file:
    tables_with_oids.txt

Failure, exiting</code></pre>
<p>As you may see, I got a fatal error, indicating that the upgrade is not possible. In my case, tables with OIDs are the culprit. In your case could be something else. In any case, we need to fix before upgrading.</p>
<p>I fixed tables removing OIDs on mentioned tables. And ran check again:</p>
<pre><code class="language-sh">Performing Consistency Checks on Old Live Server
------------------------------------------------
Checking cluster versions                                   ok
Checking database user is the install user                  ok
Checking database connection settings                       ok
Checking for prepared transactions                          ok
Checking for reg* data types in user tables                 ok
Checking for contrib/isn with bigint-passing mismatch       ok
Checking for tables WITH OIDS                               ok
Checking for invalid &quot;sql_identifier&quot; user columns          ok
Checking for presence of required libraries                 ok
Checking database user is the install user                  ok
Checking for prepared transactions                          ok

*Clusters are compatible*</code></pre>
<p>Yay!</p>
<h2>Set locale</h2>
<p>There is a tricky configuration that is not detected by <code>pg_upgrade check</code> but it is very important to me. I use <code>C</code> locale on my databases [2], then I need to perform an extra step. If this is your case, you may follow the same steps applying yours.</p>
<p>I need to stop postgresql10 and start postgresql12:</p>
<pre><code class="language-sh">systemctl stop postgresql-10.service
systemctl start postgresql-12.service</code></pre>
<p>Then I run locale change at my template1 then locale will be enabled when my database will be upgraded.</p>
<pre><code class="language-sql">UPDATE pg_database SET datcollate=&#039;C&#039;, datctype=&#039;C&#039; WHERE datname=&#039;template1&#039;;</code></pre>
<p>And stop again: <code>systemctl stop postgresql-12.service</code> to be ready to upgrade.</p>
<h2>Upgrade</h2>
<p>Upgrade command is the same that we run before, without <code>--check</code> flag.</p>
<pre><code class="language-sh">~% /usr/pgsql-12/bin/pg_upgrade --old-bindir=/usr/pgsql-10/bin --new-bindir=/usr/pgsql-12/bin --old-datadir=/var/lib/pgsql/10/data --new-datadir=/var/lib/pgsql/12/data

Performing Consistency Checks
-----------------------------
Checking cluster versions                                   ok
Checking database user is the install user                  ok
Checking database connection settings                       ok
Checking for prepared transactions                          ok
Checking for reg* data types in user tables                 ok
Checking for contrib/isn with bigint-passing mismatch       ok
Checking for tables WITH OIDS                               ok
Checking for invalid &quot;sql_identifier&quot; user columns          ok
Creating dump of global objects                             ok
Creating dump of database schemas
                                                            ok
Checking for presence of required libraries                 ok
Checking database user is the install user                  ok
Checking for prepared transactions                          ok

If pg_upgrade fails after this point, you must re-initdb the
new cluster before continuing.

Performing Upgrade
------------------
Analyzing all rows in the new cluster                       ok
Freezing all rows in the new cluster                        ok
Deleting files from new pg_xact                             ok
Copying old pg_xact to new server                           ok
Setting next transaction ID and epoch for new cluster       ok
Deleting files from new pg_multixact/offsets                ok
Copying old pg_multixact/offsets to new server              ok
Deleting files from new pg_multixact/members                ok
Copying old pg_multixact/members to new server              ok
Setting next multixact ID and offset for new cluster        ok
Resetting WAL archives                                      ok
Setting frozenxid and minmxid counters in new cluster       ok
Restoring global objects in the new cluster                 ok
Restoring database schemas in the new cluster
                                                            ok
Copying user relation files
                                                            ok
Setting next OID for new cluster                            ok
Sync data directory to disk                                 ok
Creating script to analyze new cluster                      ok
Creating script to delete old cluster                       ok

Upgrade Complete
----------------
Optimizer statistics are not transferred by pg_upgrade so,
once you start the new server, consider running:
    ./analyze_new_cluster.sh

Running this script will delete the old cluster&#039;s data files:
    ./delete_old_cluster.sh</code></pre>
<p>Consider running analyze_new_cluster. Optional but nice to have.</p>
<pre><code class="language-sh">vacuumdb: processing database &quot;mydb&quot;: Generating minimal optimizer statistics (1 target)
vacuumdb: processing database &quot;postgres&quot;: Generating minimal optimizer statistics (1 target)
vacuumdb: processing database &quot;template1&quot;: Generating minimal optimizer statistics (1 target)
vacuumdb: processing database &quot;mydb&quot;: Generating medium optimizer statistics (10 targets)
vacuumdb: processing database &quot;postgres&quot;: Generating medium optimizer statistics (10 targets)
vacuumdb: processing database &quot;template1&quot;: Generating medium optimizer statistics (10 targets)
vacuumdb: processing database &quot;mydb&quot;: Generating default (full) optimizer statistics
vacuumdb: processing database &quot;postgres&quot;: Generating default (full) optimizer statistics
vacuumdb: processing database &quot;template1&quot;: Generating default (full) optimizer statistics

Done</code></pre>
<h2>Configurations</h2>
<p>Before deleting your old cluster, remember to get some of your configurations.</p>
<pre><code class="language-sh">mv /var/lib/pgsql/12/data/pg_hba.conf /var/lib/pgsql/12/data/pg_hba.conf.new
cp /var/lib/pgsql/10/data/pg_hba.conf /var/lib/pgsql/12/data/</code></pre>
<p>I am not a big fan of writing directly to <code>postgresql.conf</code> file. Instead, I keep configuration files under version control and include the directory where those files are deployed. I treat them as code, then it becomes easier to maintain and manage.</p>
<p>Another advantage is that I don't have any mess about config file differences when a new version arises. I am automatically using new default configurations, my customized setting are loaded and I can quickly address any incompatibility caused by migration without touching the original conf file.</p>
<p>Let's go for it:</p>
<pre><code># Add settings for extensions here
include_dir = &#039;/var/lib/pgsql/conf.d&#039;   # include files ending in &#039;.conf&#039; from</code></pre>
<p>Then you may delete your old cluster. <img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>Links:</p>
<ol>
<li>Extensions: <a href="https://www.postgresql.org/docs/current/contrib.html">https://www.postgresql.org/docs/current/contrib.html</a></li>
<li>Locale: <a href="https://www.postgresql.org/docs/current/locale.html">https://www.postgresql.org/docs/current/locale.html</a></li>
</ol>
]]></content:encoded>
					
					<wfw:commentRss>https://rafael.bernard-araujo.com/postgresql-pg_upgrade-from-10-to-12.php/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1344</post-id>	</item>
		<item>
		<title>Precisamos de apoio das ferramentas para a paginação por conjunto de chaves</title>
		<link>https://rafael.bernard-araujo.com/precisamos-de-apoio-das-ferramentas-para-a-paginacao-por-conjunto-de-chaves.php</link>
					<comments>https://rafael.bernard-araujo.com/precisamos-de-apoio-das-ferramentas-para-a-paginacao-por-conjunto-de-chaves.php#respond</comments>
		
		<dc:creator><![CDATA[rafael]]></dc:creator>
		<pubDate>Tue, 13 Oct 2015 11:57:55 +0000</pubDate>
				<category><![CDATA[Banco de dados]]></category>
		<category><![CDATA[sql]]></category>
		<guid isPermaLink="false">http://rafael.bernard-araujo.com/?p=1157</guid>

					<description><![CDATA[(Traduzido de We need tool support for keyset pagination) Você sabia que a paginação via offset é muito problemática, mas fácil de evitar? offset instrui os bancos de dados a pular os primeiros N resultados N de uma consulta. No entanto, o banco de dados ainda deve buscar essas linhas a partir do disco e [&#8230;]]]></description>
										<content:encoded><![CDATA[<blockquote><p>(Traduzido de <a href="http://use-the-index-luke.com/no-offset" target="_blank" rel="noopener noreferrer">We need tool support for keyset pagination</a>)</p></blockquote>
<p>Você sabia que a paginação via <code>offset</code> é muito problemática, mas fácil de evitar?</p>
<p><code>offset</code> instrui os bancos de dados a pular os primeiros N resultados N de uma consulta. No entanto, o banco de dados ainda deve buscar essas linhas a partir do disco e trazê-los em ordem antes de ele pode enviar os seguintes.</p>
<p>Isto não é um problema de implementação, é a maneira na qual <code>offset</code> foi desenhado:</p>
<p style="padding-left: 30px;">... As linhas são primeiro classificadas de acordo com a &lt;cláusula order by&gt; e, em seguida, limitada retirando-se o número de linhas especificadas na &lt;cláusula offset&gt; desde o início ...</p>
<p>— <a class="ulink" href="https://web.archive.org/web/20230525220603/https://www.wiscorp.com/sql20nn.zip" target="_blank" rel="noopener noreferrer">SQL:2011, Part 2, §4.15.3 Derived tables</a></p>
<p>Em outras palavras, grandes <code>offset</code>s impõe um grande trabalho para o banco de dados, não importa se SQL ou NoSQL.</p>
<p>Mas o problema com <code>offset</code> não pára aqui: já pensou sobre o que acontece se uma nova linha é inserida entre duas páginas buscadas?</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/use-the-index-luke.com//img/offset-drifting.png?w=580" alt="offset-drifting" /></p>
<p>Quando <span class="command"><strong>offset</strong></span>➌ é usado para ignorar as entradas❶ anteriores, você terá duplicações no caso de existirem novas linhas inseridas entre as duas páginas➋. Há outras anomalias possíveis também, este é apenas o caso mais comum.</p>
<p>Este nem é um problema de banco de dados, é a maneira como os <em>frameworks</em> implementam paginação: eles apenas dizem qual é o número da página a ser recuperada ou quantas linhas devem ser ignoradas. Com estas informações apenas, nenhum banco de dados pode fazer melhor.</p>
<h2>Vida sem OFFSET</h2>
<p>Agora imagine um mundo sem estes problemas. Como se constata, viver sem <span class="command">offset</span> é bem simples: apenas utilize uma cláusula <span class="command">where</span> que selecione apenas os dados que você ainda não viu.</p>
<p>Para isso, exploraremos o fato de que trabalhamos com um conjunto ordenado - você tem uma cláusula <span class="command">order by</span>, não é? Uma vez que há uma ordenação definida, podemos usar um filtro simples para somente selecionar o que é posterior a entrada que vimos anteriormente.</p>
<pre><code class="language-sql">SELECT ...
FROM ...
WHERE ...
AND id &lt; ?last_seen_id
ORDER BY id DESC
FETCH FIRST 10 ROWS ONLY</code></pre>
<p>Esta é a receita básica. Ele fica mais interessante quando a classificação é por várias colunas, mas a idéia é a mesma. Esta receita também é aplicável a muitos sistemas <a class="ulink" href="https://stackoverflow.com/questions/20960815/range-query-for-mongodb-pagination/21040304#21040304" target="_blank" rel="noopener noreferrer">N</a><a class="ulink" href="http://tugdualgrall.blogspot.co.at/2013/10/pagination-with-couchbase.html" target="_blank" rel="noopener noreferrer">o</a><a class="ulink" href="https://github.com/orientechnologies/orientdb/wiki/Pagination#use-the-rid-limit" target="_blank" rel="noopener noreferrer">S</a><a class="ulink" href="http://guide.couchdb.org/draft/recipes.html#pagination" target="_blank" rel="noopener noreferrer">Q</a><a class="ulink" href="https://web.archive.org/web/20140901104426/http://heliosearch.org/solr/paging-and-deep-paging/" target="_blank" rel="noopener noreferrer">L</a>.</p>
<p>Esta abordagem - chamada <em>seek method</em> ou <em>keyset pagination</em> - resolve o problema de derivação de resultados como ilustrado acima e é ainda mais rápido do que <span class="command">offset</span>. Se você quer saber o que acontece dentro do banco de dados ao usar <span class="command">offset</span> ou <em>keyset pagination</em>, dê uma olhada nestes slides (benchmarks, benchmarks!):</p>
<p><iframe style="border: 1px solid #CCC; border-width: 1px 1px 0; margin-bottom: 1.5em;" src="https://www.slideshare.net/slideshow/embed_code/22210863" width="512" height="421" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe></p>
<p>No <a class="ulink" href="https://www.slideshare.net/MarkusWinand/p2d2-pagination-done-the-postgresql-way/43" target="_blank" rel="noopener noreferrer">slide 43</a> você também pode ver que <em>keyset pagination</em> tem algumas limitações: mais notavelmente que você não pode navegar diretamente para páginas arbitrariamente. No entanto, isto não é um problema quando se utiliza rolagem infinita. Mostrar o número de páginas para serem clicadas é uma interface de navegação pobre, na minha humilde opinião.</p>
<p>Se você quiser ler mais sobre como implementar corretamente <em>keyset pagination</em> em SQL, por favor <a href="http://use-the-index-luke.com/sql/partial-results/fetch-next-page" target="_blank" rel="noopener noreferrer">fetch-next-page</a>. Mesmo que você não esteja envolvido com o SQL, vale a pena ler <a href="http://use-the-index-luke.com/sql/partial-results/fetch-next-page" target="_blank" rel="noopener noreferrer">fetch-next-page</a> antes de começar a implementar qualquer coisa.</p>
<h2>No entando, os frameworks</h2>
<p>A principal razão para preferir <span class="command">offset</span> a paginação por conjunto de chaves (<em>keyset pagination</em>) é a falta de suporte. A maioria das ferramentas de paginação são baseadas em <span class="command">offset</span>, mas não oferecem nenhuma maneira conveniente para a utilização de paginação por conjunto de chaves.</p>
<p>Por favor, note que a paginação por conjunto de chaves afeta toda a tecnologia envolvida na execução de JavaScript do navegador que esteja fazendo a requisição AJAX para rolagem infinita: ao invés de simplesmente passar um número de página para o servidor, você deve passar o conjunto de chaves completo (geralmente múltiplas colunas) para o servidor.</p>
<p>O hall da fama de frameworks que suportam paginação por conjunto de chaves é ainda pequeno:</p>
<div class="itemizedlist">
<ul class="itemizedlist">
<li class="listitem">
<p class="short"><a class="ulink" href="http://jooq.org/" target="_blank" rel="noopener noreferrer">jOOQ</a> — Java Object Oriented Querying. <a class="ulink" href="http://www.jooq.org/doc/3.4/manual/sql-building/sql-statements/select-statement/seek-clause/" target="_blank" rel="noopener noreferrer">Docs</a>.</p>
</li>
<li class="listitem">
<p class="short"><a class="ulink" href="https://pypi.python.org/pypi/django-infinite-scroll-pagination" target="_blank" rel="noopener noreferrer">Django Infinite Scroll Pagination</a>.</p>
</li>
<li class="listitem">
<p class="short">Ruby <a class="ulink" href="https://github.com/glebm/order_query" target="_blank" rel="noopener noreferrer">order_query</a></p>
</li>
<li class="listitem">
<p class="short">Django (Python) <a class="ulink" href="https://github.com/novafloss/django-chunkator" target="_blank" rel="noopener noreferrer">chunkator</a></p>
</li>
<li class="listitem"><a class="ulink" href="https://github.com/Blazebit/blaze-persistence" target="_blank" rel="noopener noreferrer">blaze-persistence</a> — a rich Criteria API for JPA providers (started in July 2014)</li>
</ul>
</div>
<p>É por isto que preciso da sua ajuda. Se você estiver mantendo um framework que tem algum envolvimento com paginação, eu peço, eu imploro, que você construa um suporte nativo para navegação por conjunto de chaves também. Se você tiver quaisquer perguntas sobre detalhes, ficarei feliz em ajudar (<a class="ulink" href="http://ask.use-the-index-luke.com/" target="_blank" rel="noopener noreferrer">forum</a>, <a class="ulink" href="http://use-the-index-luke.com/contact">contact form</a>, <a class="ulink" href="https://x.com/MarkusWinand" target="_blank" rel="noopener noreferrer">Twitter</a>)!</p>
<p>Mesmo que você esteja apenas utilizando um software que deveria suportar paginação por conjunto de chaves, como um gerenciador de conteúdos ou uma loja virtual, faça os mantenedores saberem sobre isso. Você poderia fazer uma requisitação da funcionalidade (link a esta página) ou, se possível, desenvolva um <em>patch</em>. Novamente, ficarei feliz em ajudar a ter todos os devidos detalhes.</p>
<p>Tome <a class="ulink" href="https://github.com/david-binda/no-offset-pagination-for-wordpress" target="_blank" rel="noopener noreferrer">WordPress como um exemplo</a>.</p>
<h2>Espalhe a palavra</h2>
<p>O problema com a paginação de conjunto de chaves não é técnico. O problema é que é pouquíssimo conhecido no meio e não há suporte das ferramentas. Se você gosta da idéia de evitar o uso de paginação por offset, por favor, ajude a <em>espalhar a palavra</em>. <a class="ulink" href="https://x.com/intent/post?source=webclient&amp;text=I%27m%20supporting%20%23NoOffset%3APlease%20help%20spreading%20the%20word%20that%20SQLs%20OFFSET%20is%20bad.Use%20keyset%20pagination%20instead%3Ahttp%3A%2F%2Fuse-the-index-luke.com%2Fno-offset" target="_blank" rel="noopener noreferrer">Use o Twitter</a>, compartilhe, <a class="ulink" href="mailto:?subject=Paging%20without%20row%20counts&amp;body=Hi%21%0A%0AI%27ve%20just%20read%20an%20article%20that%20says%20using%20row%20counts%20to%20do%20pagination%20is%20a%20bad%20idea%20and%20we%20should%20instead%20fetch%20subsequent%20pages%20using%20the%20last%20fetched%20row%20to%20basically%20load%20everything%20after%20that.%0A%0AI%20though%20that%20might%20be%20interesting%20to%20you%3A%0A%20%20%20http%3A%2F%2Fuse-the-index-luke.com%2Fno-offset">envie por e-mail</a>, você pode até reproduzir este post (<a class="ulink" href="https://creativecommons.org/licenses/by-nc-nd/3.0/" target="_blank" rel="noopener noreferrer">CC-BY-NC-ND</a>). Traduções são também bem-vindas, apenas faça um contato prévio - eu também incluirei o link da tradução a esta página.</p>
<p>Ah, e se você estiver em um blog, você também pode acrescentar um banner para que seus leitores fiquem alertas a isto. Eu preparei uma a <a class="ulink" href="http://use-the-index-luke.com/no-offset/banner">galeria de banner NoOffset</a> com alguns formatos comuns. Escolha o que ficar melhor.</p>
<div class="banner-gallery center"><a href="http://use-the-index-luke.com/no-offset"> <img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/use-the-index-luke.com/img/no-offset-banner-468x60.white.png?resize=468%2C60" alt="Do not use offset in SQL. Learn why." width="468" height="60" /> </a></div>
]]></content:encoded>
					
					<wfw:commentRss>https://rafael.bernard-araujo.com/precisamos-de-apoio-das-ferramentas-para-a-paginacao-por-conjunto-de-chaves.php/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1157</post-id>	</item>
		<item>
		<title>Backup de todos os bancos do servidor PostgreSQL</title>
		<link>https://rafael.bernard-araujo.com/backup-de-todos-os-bancos-do-servidor-postgresql.php</link>
					<comments>https://rafael.bernard-araujo.com/backup-de-todos-os-bancos-do-servidor-postgresql.php#respond</comments>
		
		<dc:creator><![CDATA[rafael]]></dc:creator>
		<pubDate>Thu, 21 Jun 2012 14:34:24 +0000</pubDate>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[PostGreSQL]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[shell script]]></category>
		<guid isPermaLink="false">http://rafael.bernard-araujo.com/?p=997</guid>

					<description><![CDATA[Extremamente útil, ainda mais quando há possibilidade de criação de banco de dados de forma automatizada (servidores de hospedagem, por exemplo). Download]]></description>
										<content:encoded><![CDATA[<p>Extremamente útil, ainda mais quando há possibilidade de criação de banco de dados de forma automatizada (servidores de hospedagem, por exemplo).</p>
<p><script src="https://gist.github.com/rafaelbernard/2966026.js"></script></p>
<p><a href="https://gist.github.com/rafaelbernard/2966026/raw/b3711c06976d90f8d46394c32277dbe871147dc2/bac_all_db_pg.sh" title="GIST - Backup de todos os bancos do servidor PostgreSQL">Download</a></p>
<p><!--


<pre class="bash shell">#!/bin/bash
# Baseado em http://mig5.net/content/mysql-postgresql-all-databases-backup-script
# Rafael Bernard Rodrigues Araujo - 14/06/2012

today=$(date +%y%m%d)

# local dir where the backups go
myDir='/disk2/backup/pg'

# this is for PostgreSQL. If you don't need it, you
# could leave it here, but remove the 'backup_pgsql'
# function call at the end of the script

CMD_PSQL=/usr/local/pgsql/bin/psql
CMD_DUMP=/usr/local/pgsql/bin/pg_dump
arq_tar=''

function backup_pgsql {
        #Seleciona os bancos a serem copiados, eliminando os bancos de sistema
        for db in `psql -U postgres -tq -d template1 -c "select datname from pg_database where datname not in ('template1','template0','postgres')"`; do
echo 'Iniciando o backup de '${db};
                arq_tar="${myDir}/${db}-${today}.tar";
                pg_dump -U postgres -F tar -f $arq_tar $db;
                gzip $arq_tar;
                echo 'Backup concluido';
        done;
}

backup_pgsql</pre>

--></p>
]]></content:encoded>
					
					<wfw:commentRss>https://rafael.bernard-araujo.com/backup-de-todos-os-bancos-do-servidor-postgresql.php/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">997</post-id>	</item>
		<item>
		<title>Gerando 1000 linhas de dados aleatórios &#8211; PostgreSQL</title>
		<link>https://rafael.bernard-araujo.com/gerando-1000-linhas-de-dados-aleatorios-postgresql.php</link>
					<comments>https://rafael.bernard-araujo.com/gerando-1000-linhas-de-dados-aleatorios-postgresql.php#comments</comments>
		
		<dc:creator><![CDATA[rafael]]></dc:creator>
		<pubDate>Thu, 19 Apr 2012 18:50:47 +0000</pubDate>
				<category><![CDATA[PostGreSQL]]></category>
		<guid isPermaLink="false">http://rafael.bernard-araujo.com/?p=977</guid>

					<description><![CDATA[Muito útil! SELECT i, clock_timestamp() t1, random() r1, random() r2, random() r3, clock_timestamp() + (round(random()*1000)::text &#124;&#124; &#039; days&#039;)::interval d1 from generate_series(1,1000) i(i);]]></description>
										<content:encoded><![CDATA[<p>Muito útil!</p>
<p><script src="https://gist.github.com/2422955.js?file=pg_random_1000_rows_table.sql"></script></p>
<pre><code class="language-sql">SELECT i, clock_timestamp() t1, random() r1, random() r2, random() r3, clock_timestamp() + (round(random()*1000)::text || &#039; days&#039;)::interval d1 
from generate_series(1,1000) i(i);</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://rafael.bernard-araujo.com/gerando-1000-linhas-de-dados-aleatorios-postgresql.php/feed</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">977</post-id>	</item>
		<item>
		<title>Substituir conteúdo win1252 para utf-8</title>
		<link>https://rafael.bernard-araujo.com/substituir-conteudo-win1252-para-utf-8.php</link>
					<comments>https://rafael.bernard-araujo.com/substituir-conteudo-win1252-para-utf-8.php#comments</comments>
		
		<dc:creator><![CDATA[rafael]]></dc:creator>
		<pubDate>Thu, 16 Jun 2011 15:19:40 +0000</pubDate>
				<category><![CDATA[PostGreSQL]]></category>
		<category><![CDATA[codificação]]></category>
		<category><![CDATA[encoding]]></category>
		<guid isPermaLink="false">http://rafael.bernard-araujo.com/?p=771</guid>

					<description><![CDATA[Não devo ser o primeiro a precisar exportar dados de um banco PostGreSQL instalado em Windows com codificação win1252 para um banco com codificação em utf-8 (no meu caso, em servidor Linux). Não basta transformar o arquivo de importação para utf-8, pois os caracteres do win1252 (aspas duplas à esquerda, aspas duplas à direita, aspa [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Não devo ser o primeiro a precisar exportar dados de um banco PostGreSQL instalado em Windows com codificação win1252 para um banco com codificação em utf-8 (no meu caso, em servidor Linux).</p>
<p>Não basta transformar o arquivo de importação para utf-8, pois os caracteres do win1252 (aspas duplas à esquerda, aspas duplas à direita, aspa simples e travessão) estarão lá, com um valor esquisito no seu banco. A minha solução foi importar assim mesmo e depois realizar um update usando uma função para corrigir.</p>
<p>Os exemplos de código a seguir são para: 1 - transformar para caracteres HTML; 2 - transformar para os caracteres simples.</p>
<p>HTML:</p>
<p><script src="https://gist.github.com/1029869.js"> </script></p>
<p>Simples:</p>
<p><script src="https://gist.github.com/1029899.js"> </script></p>
<p>Não se preocupe com os quadrados que aparecem. Se você copiar para um bom editor de texto, verá que possuem valores diferentes.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://rafael.bernard-araujo.com/substituir-conteudo-win1252-para-utf-8.php/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">771</post-id>	</item>
		<item>
		<title>Aonde você deseja se conectar hoje?</title>
		<link>https://rafael.bernard-araujo.com/aonde-voce-deseja-se-conectar-hoje.php</link>
					<comments>https://rafael.bernard-araujo.com/aonde-voce-deseja-se-conectar-hoje.php#respond</comments>
		
		<dc:creator><![CDATA[rafael]]></dc:creator>
		<pubDate>Fri, 21 Nov 2008 17:35:12 +0000</pubDate>
				<category><![CDATA[Banco de dados]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[asp]]></category>
		<category><![CDATA[firebird]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[paradoxx]]></category>
		<category><![CDATA[PostGreSQL]]></category>
		<guid isPermaLink="false">http://rafael.bernard-araujo.com/?p=107</guid>

					<description><![CDATA[O site ConnectionString vem com uma proposta simples e muito útil: fornecer linhas de conexão. Tem conexão para tudo. Há conexões bancos de dados (SQL Server, Informix, MySQL, Progress, Paradox, Firebird etc), arquivos de dados (Excel, TXT, SQL Lite etc) e também para outros tipos (MS Project, Active Directory, Exchange, DNS etc). A idéia de [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>O site <a href="https://www.connectionstrings.com/" title="ConnectionString" target="_blank" rel="noopener">ConnectionString</a> vem com uma proposta simples e muito útil: fornecer linhas de conexão. Tem conexão para tudo. Há conexões bancos de dados (SQL Server, Informix, MySQL, Progress, Paradox, Firebird etc), arquivos de dados (Excel, TXT, SQL Lite etc) e também para outros tipos (MS Project, Active Directory, Exchange, DNS etc).</p>
<blockquote><p> A idéia de ConnectionString é fornecer uma fácil referência para linhas de conexão.</p>
<p>Hoje, existem 213 linhas de conexão no banco de dados coletadas a partir de outros sites da internet, livros, arquivos de ajuda, msdn ou que tenham sido submetidos pelos colegas desenvolvedores de todo o mundo.</p></blockquote>
<p>Se alguém conhecer algum projeto semelhante para outras linguagens, não deixe de colocar nos comentários, por favor.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://rafael.bernard-araujo.com/aonde-voce-deseja-se-conectar-hoje.php/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">107</post-id>	</item>
		<item>
		<title>Consultas case-insensitive e accent-insensitive no MySQL</title>
		<link>https://rafael.bernard-araujo.com/consultas-case-insensitive-e-accent-insensitive-no-mysql.php</link>
					<comments>https://rafael.bernard-araujo.com/consultas-case-insensitive-e-accent-insensitive-no-mysql.php#comments</comments>
		
		<dc:creator><![CDATA[rafael]]></dc:creator>
		<pubDate>Tue, 21 Oct 2008 13:51:15 +0000</pubDate>
				<category><![CDATA[Banco de dados]]></category>
		<category><![CDATA[MySQL]]></category>
		<guid isPermaLink="false">http://rafael.bernard-araujo.com/?p=12</guid>

					<description><![CDATA[Uma necessidade comum com dados em língua portuguesa são as buscas no bancos de dados insensível a caso e insensível a acentos. No MySQL, até a versão 4.0, as consultas eram por padrão insensível ao caso (case-insensitive) e insensível ao acento (accent-insensitive). Isso mudou, porém, a partir da versão 4.1, que introduziu um suporte melhorado [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Uma necessidade comum com dados em língua portuguesa são as buscas no bancos de dados insensível a caso e insensível a acentos.</p>
<p>No MySQL, até a versão 4.0, as consultas eram por padrão insensível ao caso (<em>case-insensitive</em>) e insensível ao acento (<em>accent-insensitive</em>). Isso mudou, porém, a partir da versão 4.1, que introduziu um suporte melhorado a comparações (<em>collations</em>) e definições de caracteres (<em>charsets</em>). Alguns desenvolvedores devem ter ficado surpresos com suas buscas que antes ignoravam acentos e maiúsculas e agora já exigiam que se colocasse.</p>
<p>A partir dessa versão, a sintaxe para uma consulta que ignora acentos e o caso seria a seguinte:</p>
<pre><code class="language-sql">SELECT *
FROM `tab_municipios`
WHERE `NomeMunic` = _utf8 &#039;SAO PAULO&#039; COLLATE utf8_unicode_ci</code></pre>
<p>Adaptado de <a target="_blank" href="http://web.archive.org/web/20160811164006/http://dicas-l.com.br/arquivo/consultas_case-insensitive_no_postgresql_e_no_mysql.php" rel="noopener">Consultas case-insensitive no PostgreSQL e no MySQL</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://rafael.bernard-araujo.com/consultas-case-insensitive-e-accent-insensitive-no-mysql.php/feed</wfw:commentRss>
			<slash:comments>18</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">12</post-id>	</item>
	</channel>
</rss>
