question stringlengths 11 28.2k | answer stringlengths 26 27.7k | tag stringclasses 130
values | question_id int64 935 78.4M | score int64 10 5.49k |
|---|---|---|---|---|
We've got an application which will be using RabbitMQ and have several different queues for passing messages between tiers.
Initially, I was planning to use multiple direct exchanges, with one for each message type, but it looks like having a single topic exchange with queues using different routing key bindings will a... | Assuming both models are being considered to be implemented using one broker running, there's little difference that I can see.
Option 2 seems more common in the real world for solving this kind of routing problem (at least in my anecdotal experience) and it's exactly the challenge that Topic Exchanges exist to solve.
... | RabbitMQ | 9,704,590 | 62 |
Does anyone know if there's a way to check the number of messages in a RabbitMQ queue from a client application?
I'm using the .NET client library.
| You can actually retrieve this via the client.
When you perform a queue_declare operation, RabbitMQ returns a tuple with three values: (<queue name>, <message count>, <consumer count>). The passive argument to queue_declare allows you to check whether a queue exists without modifying the server state, so you can use qu... | RabbitMQ | 1,038,318 | 62 |
I'm trying to setup my first RabbitMQ dead letter exchange, here are the steps I'm using through the web admin interface:
Create new DIRECT exchange with the name "dead.letter.test"
Create new queue "dead.letter.queue"
Bind "dead.letter.queue" to "dead.letter.test"
Create new queue "test1" with the dead letter exchang... | Gentilissimo Signore was kind enough to answer my question on Twitter. The problem is that if your dead letter exchange is setup as DIRECT you must specify a dead letter routing key. If you just want all your NACKed message to go into a dead letter bucket for later investigation (as I do) then your dead letter exchan... | RabbitMQ | 21,742,232 | 61 |
RabbitMQ in docker lost data after remove container without volume.
My Dockerfile:
FROM rabbitmq:3-management
ENV RABBITMQ_HIPE_COMPILE 1
ENV RABBITMQ_ERLANG_COOKIE "123456"
ENV RABBITMQ_DEFAULT_VHOST "123456"
My run script:
IMAGE_NAME="service-rabbitmq"
TAG="${REGISTRY_ADDRESS}/${IMAGE_NAME}:${VERSION}"
echo $TAG
d... |
Rabbitmq uses the hostname as part of the folder name in the mnesia
directory. Maybe add a --hostname some-rabbit to your docker run?
I had the same issue and I found the answer here.
| RabbitMQ | 41,330,514 | 60 |
I am using django-celery for my django project. Last day I have changed my computer's hostname (I am using Ubuntu 12.04, edited file '/etc/hostname'), and after next restart django-celery was failing with error
Consumer: Connection Error: [Errno 111] Connection refused. Trying again in 4 seconds...
After some researc... | Remove the old installation of RabbitMQ to fix this problem. Here are steps to reinstall RabbitMQ. These commands are run as the root user:
Stop RabbitMQ: rabbitmqctl stop
Change /etc/hosts
Change /etc/hostname
Uninstall old RabbitMQ: dpkg -P rabbitmq-server
Remove RabbitMQ’s database: rm -rf /var/lib/rabbitmq
Find er... | RabbitMQ | 14,659,335 | 60 |
I have thousands of unacked messages in my dev environment which I can't restart.
Is there a way to remove (purge) all messages even if they are unacknowledged?
| Close the channel that the unacked messages reside on, which will nack them back into the queue, then call purge.
| RabbitMQ | 25,114,230 | 59 |
I've created an ASP.NET Core MVC/WebApi site that has a RabbitMQ subscriber based off James Still's blog article Real-World PubSub Messaging with RabbitMQ.
In his article he uses a static class to start the queue subscriber and define the event handler for queued events. This static method then instantiates the event ... | You can avoid the static classes and use Dependency Injection all the way through combined with:
The use of IApplicationLifetime to start/stop the listener whenever the application starts/stops.
The use of IServiceProvider to create instances of the message processors.
First thing, let's move the configuration to its... | RabbitMQ | 40,611,683 | 58 |
Does RabbitMQ have any concept of message priority? I have an issue where some more important messages are being slowed down due to less important messages sitting before them in the queue. I want the high-priority ones to take precedence and move to the front of the queue.
I know I can approximate this using two queue... | The answers on this question are out-of-date. As of RabbitMQ 3.5.0, there is now in-core support for AMQP standard per-message priorities. The documentation has all the gory details, but in short:
You need to define the queue's priority range at the time the queue is created;
Messages without a priority set get a pr... | RabbitMQ | 10,745,084 | 58 |
What is the benefit of building on top of MassTransit compared to building directly on top of RabbitMQ?
I believe one benefit provided by MassTransit is 'type' exchange (publish subscribe by interface / type) so the content of the message is structured, compared to plain RabbitMQ exchanges where the content of the mess... | Things that MT adds on top of just using RabbitMQ:
Optimized, asynchronous multithreaded, concurrent consumers
Message serialization, with support for interfaces, classes, and records, including guidance on versioning message contracts
Automatic exchange bindings, publish conventions
Saga state machines, including per... | RabbitMQ | 12,296,787 | 57 |
I haven't found an existing post asking this but apologize if I missed it.
I'm trying to get my head round microservices and have come across articles where RabbitMQ is used. I'm confused why RabbitMQ is needed. Is the intention that the services will use a web api to communicate with the outside world and RabbitMQ to... | In Microservices architecture you have two ways to communicate between the microservices:
Synchronous - that is, each service calls directly the other microservice , which results in dependency between the services
Asynchronous - you have some central hub (or message queue) where you place all requests between the mic... | RabbitMQ | 45,208,766 | 56 |
I have installed rabbitmq on ubuntu and trying to start it using rabbitmq-server start, however, I'm getting this error:
Activating RabbitMQ plugins ...
0 plugins activated:
node with name "rabbit" already running on "mybox"
diagnostics:
- nodes and their ports on mybox: [{rabbit,38618},
... | Rabbitmq is set to start automatically after it's installed.
I don't think it is configured run with the service command.
To see the status of rabbitmq
sudo rabbitmqctl status
To stop the rabbitmq
sudo rabbitmqctl stop
(Try the status command again to see that it's stopped).
To start it again, the recommended method ... | RabbitMQ | 10,347,751 | 56 |
As a way to learn RabbitMQ and python I'm working on a project that allows me to distribute h264 encodes between a number of computers. The basics are done, I have a daemon that runs on Linux or Mac that attaches to queue, accepts jobs and encodes them using HandBrakeCLI and acks the message once the encode is complet... | Queue browsing is not supported directly, but if you declare a queue with NO auto acknowledgements and do not ACK the messages that you receive, then you can see everything in it. After you have had a look, send a CANCEL on the channel, or disconnect and reconnect to cause all the messages to be requeued. This does inc... | RabbitMQ | 4,700,292 | 55 |
I get a string through a rabbitmq message system. Before sending,
I use json.Marshal, convert the outcome to string and send through
rabbitmq.
The structs that I convert and send can be: (changed the names and the size of the structs but it should not matter)
type Somthing1 struct{
Thing string `json:"thi... | The default types that the json package Unmarshals into are shown in the Unmarshal function documentation
bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null
Since you're unmarshaling into an interface{}, t... | RabbitMQ | 35,583,735 | 54 |
For the company I work for we would like to use RabbitMQ as our main message bus. The idea we have is that every single application uses their own vhost for internal communication and that via the shovel or federation plugin we would make it possible to share certain type of the events across multiple vhosts (maybe ev... | Shovels and queue provide different means to be forward messages from one RabbitMQ node to another.
Federated Exchange
With a federated exchange, queues can be connected to the queue on the upstream(source) node. In addition, an exchange on the downstream(destination) node will receive a copy of messages that are publi... | RabbitMQ | 19,357,272 | 54 |
I've been evaluating messaging technologies for my company but I've become very confused by the conceptual differences between a few terms:
Pub/Sub vs Multicast vs Fan Out
I am working with the following definitions:
Pub/Sub has publishers delivering a separate copy of each message to
each subscriber which means that ... | I'm confused by your choice of three terms to compare. Within RabbitMQ, Fanout and Direct are exchange types. Pub-Sub is a generic messaging pattern but not an exchange type. And you didn't even mention the 3rd and most important Exchange type, namely Topic. In fact, you can implement Fanout behavior on a Topic exchang... | RabbitMQ | 8,261,654 | 54 |
It seems the longer I keep my rabbitmq server running, the more trouble I have with unacknowledged messages. I would love to requeue them. In fact there seems to be an amqp command to do this, but it only applies to the channel that your connection is using. I built a little pika script to at least try it out, but I am... | Unacknowledged messages are those which have been delivered across the network to a consumer but have not yet been ack'ed or rejected -- but that consumer hasn't yet closed the channel or connection over which it originally received them. Therefore the broker can't figure out if the consumer is just taking a long time ... | RabbitMQ | 7,063,224 | 54 |
On my team at work, we use the IBM MQ technology a lot for cross-application communication. I've seen lately on Hacker News and other places about other MQ technologies like RabbitMQ. I have a basic understanding of what it is (a commonly checked area to put and get messages), but what I want to know what exactly is it... | All the explanations so far are accurate and to the point - but might be missing something: one of the main benefits of message queueing: resilience.
Imagine this: you need to communicate with two or three other systems. A common approach these days will be web services which is fine if you need an answers right away.
... | RabbitMQ | 2,868,800 | 53 |
What is the easiest way to create a delay (or parking) queue with Python, Pika and RabbitMQ? I have seen an similar questions, but none for Python.
I find this an useful idea when designing applications, as it allows us to throttle messages that needs to be re-queued again.
There are always the possibility that you wi... | I found this extremely useful when developing my applications. As it gives you an alternative to simply re-queuing your messages. This can easily reduce the complexity of your code, and is one of many powerful hidden features in RabbitMQ.
Steps
First we need to set up two basic channels, one for the main queue, and one... | RabbitMQ | 17,014,584 | 52 |
I'm using rabbitMQ, I take every message from queue with basic_get without automatically acking procedure, which means the message remain in queue until I ack or nack the message.
Sometimes I've messages that can't be processed because of some exception thrown, which prevented them from being fully processed.
Question ... | The basic.nack command is apparently a RabbitMQ extension, which extends the functionality of basic.reject to include a bulk processing mode. Both include a "bit" (i.e. boolean) flag of requeue, so you actually have several choices:
nack/reject with requeue=1: the message will be returned to the queue it came from as ... | RabbitMQ | 28,794,123 | 49 |
How does RabbitMQ compare to Mule, I am going to build an application using message oriented architecture and AMQP (RabbitMQ) provides everything i want, but i am perplexed with so many related technology choice and similar concepts like ESB. I am having a doubt if i am making a choice without considering other alterna... | Mule is an ESB (Enterprise Service Bus). RabbitMQ is a message broker.
An ESB provides added layers atop of a message broker such as routing, transformations and business process management. It is a mediator between applications, integrating Web Services, REST endpoints, database connections, email and ftp servers - yo... | RabbitMQ | 3,280,576 | 49 |
In the RabbitMQ/AMQP Java client, you can create an AMQP.BasicProperties.Builder, and use it to build() an instance of AMQP.BasicProperties. This built properties instance can then be used for all sorts of important things. There are lots of "builder"-style methods available on this builder class:
BasicProperties.Build... | Usually I use very simple approach to memorize something. I will provide all details below, but here is a simple picture of BasicProperties field and values. I've also tried to properly highlight queue/server and application context.
If you want me to enhance it a bit - just drop a small comment. What I really want i... | RabbitMQ | 18,403,623 | 48 |
I need to have a python client that can discover queues on a restarted RabbitMQ server exchange, and then start up a clients to resume consuming messages from each queue. How can I discover queues from some RabbitMQ compatible python api/library?
| There does not seem to be a direct AMQP-way to manage the server but there is a way you can do it from Python. I would recommend using a subprocess module combined with the rabbitmqctl command to check the status of the queues.
I am assuming that you are running this on Linux. From a command line, running:
rabbitmqct... | RabbitMQ | 4,287,941 | 48 |
I'm debugging some Java code that uses Apache POI to pull data out of Microsoft Office documents. Occasionally, it encounter a large document and POI crashes when it runs out of memory. At that point, it tries to publish the error to RabbitMQ, so that other components can know that this step failed and take the appropr... | An AMQP channel is closed on a channel error. Two common things that can cause a channel error:
Trying to publish a message to an exchange that doesn't exist
Trying to publish a message with the immediate flag set that doesn't have a queue with an active consumer set
I would look into setting up a ShutdownListener o... | RabbitMQ | 8,839,094 | 47 |
I want to know how does RabbitMQ store the messages physically in its RAM and Disk?
I know that RabbitMQ tries to keep the messages in memory (But I don't know how the messages are put in the Ram). But the messages can be spilled into disk when the messages are with persistent mode or when the broker has the memory pre... | RabbitMQ uses a custom DB to store the messages, the db is usually located here:
/var/lib/rabbitmq/mnesia/rabbit@hostname/queues
Starting form the version 3.5.5 RabbitMQ introduced the new New Credit Flow
https://www.rabbitmq.com/blog/2015/10/06/new-credit-flow-settings-on-rabbitmq-3-5-5/
Let’s take a look at how Ra... | RabbitMQ | 38,444,425 | 46 |
After the consumer gets a message, consumer/worker does some validations and then call web service. In this phase, if any error occurs or validation fails, we want the message put back to the queue it was originally consumed from.
I have read RabbitMQ documentation. But I am confused about differences between reject, ... | Short answer:
To requeue specific message you can pick both basic.reject or basic.nack with multiple flag set to false.
basic.consume calling may also results to messages redelivering if you are using message acknowledge and there are un-acknowledged message on consumer at specific time and consumer exit without ack-in... | RabbitMQ | 24,107,913 | 46 |
How can I check whether a message Queue already exists or not?
I have 2 different applications, one creating a queue and the other reading from that queue.
So if I run the Client which reads from the queue first, than it crashes.
So to avoid that i would like to check first whether the queue exists or not.
here is the ... | Don't bother checking.
queue.declare is an idempotent operation. So, if you run it once, twice, N times, the result will still be the same.
If you want to ensure that the queue exists, just declare it before using it. Make sure you declare it with the same durability, exclusivity, auto-deleted-ness every time, otherw... | RabbitMQ | 3,457,305 | 45 |
I'm following this guide to learn how to use spring-rabbit with RabbitMQ. However in this guide, the RabbitMQ configuration is as default(localhost server and with credential as guest/guest). What should I do if I want to connect to an remote RabbitMQ with ip address and credential? I don't know where to set these info... | The application for that guide is a Spring Boot Application.
Add a file application.properties to src/main/resources.
You can then configure rabbitmq properties according to the Spring Boot Documentation - scroll down to the rabbitmq properties...
...
spring.rabbitmq.host=localhost # RabbitMQ host.
...
spring.rabbitmq.... | RabbitMQ | 42,200,317 | 44 |
I'm trying to send a python dictionary from a python producer to a python consumer using RabbitMQ. The producer first establishes the connection to local RabbitMQ server. Then it creates a queue to which the message will be delivered, and finally sends the message. The consumer first connects to RabbitMQ server and the... | You can't send native Python types as your payload, you have to serialize them first. I recommend using JSON:
import json
channel.basic_publish(exchange='',
routing_key='task_queue',
body=json.dumps(message),
properties=pika.BasicProperties(
... | RabbitMQ | 34,534,178 | 44 |
What are the differences between those amqp client libraries?
Which one is the most recommended?
What are the major differences?
| I would recommend amqp.node and bramqp over node-amqp. node-amqp has a lot of bugs and is poorly maintained, and it hides the "channel" concept which introduces a lot of problems for rabbitmq servers (because they are never closed).
| RabbitMQ | 20,128,124 | 44 |
I started to use rabbit.js to connect to RabbitMQ from a node.js application.
I'm blocked at:
Error: Channel closed by server: 403 (ACCESS-REFUSED) with message "ACCESS_REFUSED -operation not permitted on the default exchange"
at Channel.C.accept (/.../rabbit.js/node_modules/amqplib/lib/channel.js:398:24)
... | So I never used rabbit.js myself, but after diving into the code, it seems to be using amqplib. The code that parses it can be seen here and it seems it's calling the standard nodejs URL module. So perhaps you can try something like this:
amqp://user:pass@host.com/vhost
Hope it helps!
Cheers.
| RabbitMQ | 24,945,112 | 42 |
Does the RabbitMQ .NET client have any sort of asynchronous support? I'd like to be able to connect and consume messages asynchronously, but haven't found a way to do either so far.
(For consuming messages I can use the EventingBasicConsumer, but that's not a complete solution.)
Just to give some context, this is an ex... | Rabbit supports dispatching to asynchronous message handlers using the AsyncEventingBasicConsumer class. It works similarly to EventingBasicConsumer, but allows you to register a callback which returns a Task. The callback is dispatched to and the returned Task is awaited by the RabbitMQ client.
var factory = new Conne... | RabbitMQ | 31,961,261 | 39 |
I've been trying to figure out which form of connection i should use when using pika, I've got two alternatives as far as I understand.
Either the BlockingConnection or the SelectConnection, however I'm not really sure about the differences between these two (i.e. what is the BlockingConnection blocking? and more)
Th... | The SelectConnection is useful if your application architecture can benefit from an asynchronous design, e.g. doing something else while the RabbitMQ IO completes (e.g. switch to some other IO etc) . This type of connection uses callbacks to indicate when functions return. For example you can declare callbacks for
on_c... | RabbitMQ | 11,987,838 | 39 |
Do you have any pointers how to determine when a subscription problem has occurred so I can reconnect?
My service uses RabbitMQ.Client.MessagePatterns.Subscription for it's subscription. After some time, my client silently stops receiving messages. I suspect network issues as I our VPN connection is not the most reliab... | EDIT: Since I'm sill getting upvotes on this, I should point out that the .NET RabbitMQ client now has this functionality built in: https://www.rabbitmq.com/dotnet-api-guide.html#connection-recovery
Ideally, you should be able to use this and avoid manually implementing reconnection logic.
I recently had to implement ... | RabbitMQ | 12,499,174 | 38 |
I'm ask/answering this question because it hung me up & it's likely someone else will have the same problem.
Install of RabbitMQ x64 v2.8.6 on Windows Server 2008 x64.
After Erlang install using default install location to C:\Program Files\erl5.9.2, I'm attempting to start the server via running the rabbitmq-service.b... | 1- Set environment variable:
Variable name : ERLANG_HOME
Variable value: C:\Program Files (x86)\erl6.4
note: don't include bin on above step.
2- Add %ERLANG_HOME%\bin to the PATH environmental variable:
Variable name : PATH
Variable value: %ERLANG_HOME%\bin
This works well.
| RabbitMQ | 12,323,621 | 38 |
There is a list of PHP clients on the RabbitMQ site. I'm asking this question in hopes that people who have used any of these can share their experiences here. E.g.
Did you have any trouble installing?
Is it stable?
Were there any performance issues?
How is the documentation / support?
Even if you've just used one o... | For reference, PECL AMQP Extension and http://php.net/manual/fa/book.amqp.php are the same thing, one is the package, the other the documentation for the package.
As a maintainer of the official PHP AMQP extension, I am a little biased. Many people use this extension in high volume low latency production environments s... | RabbitMQ | 4,405,992 | 38 |
Web Dynos can handle HTTP Requests
and while Web Dynos handles them Worker Dynos can handle jobs from it.
But I don't know how to make Web Dynos and Worker Dynos to communicate each other.
For example, I want to receive a HTTP request by Web Dynos
, send it to Worker Dynos
, process the job and send back result to Web ... | As the high-level article on background jobs and queuing suggests, your web dynos will need to communicate with your worker dynos via an intermediate mechanism (often a queue).
To accomplish what it sounds like you're hoping to do follow this general approach:
Web request is received by the web dyno
Web dyno adds a jo... | RabbitMQ | 11,429,774 | 37 |
I am using RabbitMQ with Grails, and a problem cropped up this morning. When I run rabbitmqctl status it tells me:
C:\Users\BuildnTest2>rabbitmqctl status
Status of node 'rabbit@BUILDNTEST2-PC' ...
Error: unable to connect to node 'rabbit@BUILDNTEST2-PC': nodedown diagnostics:
- nodes and their ports on BUILDNTEST2-PC... | For what it's worth, in 2018, the docs are WRONG. In windows 10, the default location of the cookie file appears to be:
C:\Windows\System32\config\systemprofile
and NOT
C:\Windows
as the docs say.
The best thing to do is to look at the log file, which is typically located in your user %AppData%\Roaming\RabbitMQ\log... | RabbitMQ | 9,673,172 | 37 |
I am trying to start RMQ inside docker container, with precreated queue qwer.
Prior to this, I was using simple docker-compose.yml file:
rabbit:
image: rabbitmq:management-alpine
environment:
RABBITMQ_DEFAULT_USER: guest
RABBITMQ_DEFAULT_PASS: guest
And it worked fine, except that it has no queues ... | You can predefine queues and exchanges without creating own rabbit-mq docker image.
Your docker-compose should look like this:
rabbit:
container_name: rabbitmq-preload-conf
image: rabbitmq:3-management
volumes:
- ./init/rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf:ro
- ./init/definitions.json:/etc/rabbitmq/definitions... | RabbitMQ | 58,266,688 | 36 |
In our project, we want to use the RabbitMQ in "Task Queues" pattern to pass data.
On the producer side, we build a few TCP server(in node.js) to recv
high concurrent data and send it to MQ without doing anything.
On the consumer side, we use JAVA client to get the task data from
MQ, handle it and then ack.
So the ques... | For best performance in RabbitMQ, follow the advice of its creators. From the RabbitMQ blog:
RabbitMQ's queues are fastest when they're empty. When a queue is
empty, and it has consumers ready to receive messages, then as soon as
a message is received by the queue, it goes straight out to the
consumer. In the c... | RabbitMQ | 10,030,227 | 36 |
I have an ASP.NET Core application where I would like to consume RabbitMQ messages.
I have successfully set up the publishers and consumers in command line applications, but I'm not sure how to set it up properly in a web application.
I was thinking of initializing it in Startup.cs, but of course it dies once startup i... | Use the Singleton pattern for a consumer/listener to preserve it while the application is running. Use the IApplicationLifetime interface to start/stop the consumer on the application start/stop.
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<R... | RabbitMQ | 43,609,345 | 35 |
I am at a loss here so I'm reaching out to the collective knowledge in hope of a miracle.
I have installed RabbitMQ on a Linux box using the defaults.
When I use this code (and the default RabbitMQ installation configuration) everything works nice.
var connectionFactory = new ConnectionFactory();
connectionFactory.Host... | It seems that I have found a solution to my own problem.
The following code works:
ConnectionFactory factory = new ConnectionFactory();
factory.UserName = "user";
factory.Password = "password";
factory.VirtualHost = "/";
factory.Protocol = Protocols.FromEnvironment();
factory.HostName = "192.168.0.12";
factory.Port = A... | RabbitMQ | 4,987,438 | 34 |
I want to run RabbitMQ in one container, and a worker process in another. The worker process needs to access RabbitMQ.
I'd like these to be managed through docker-compose.
This is my docker-compose.yml file so far:
version: "3"
services:
rabbitmq:
image: rabbitmq
command: rabbitmq-server
expose:
-... | Aha! I fixed it. @Ijaz was totally correct - the RabbitMQ service takes a while to start, and my worker tries to connect before it's running.
I tried using a delay, but this failed when the RabbitMQ took longer than usual.
This is also indicative of a larger architectural problem - what happens if the queuing service (... | RabbitMQ | 53,031,439 | 33 |
Why do we need routing key to route messages from exchange to queue? Can't we simply use the queue name to route the message? Also, in case of publishing to multiple queues, we can use multiple queue names. Can anyone point out the scenario where we actually need routing key and queue name won't be suffice?
| There are several types of exchanges. The fanout exchange ignores the routing key and sends messages to all queues. But pretty much all other exchange types use the routing key to determine which queue, if any, will receive a message.
The tutorials on the RabbitMQ website describes several usecases where different exch... | RabbitMQ | 36,302,341 | 33 |
So, this is what I've done:
Installed Erlang on my Windows x64 bit machine
Installed RabbitMQ
Started RabbitMQ service
At this step I have no errors. When, however, I try to enabe rabbitmq-management, I get some error messages in the console. The way I try to enable it is this one:
C:\...\rabbitmq-server-3.5.6\sbin>r... | I faced the same problem and my investigations led me to https://stackoverflow.com/a/34538688 which helped me solve it. After following the steps in that answer, start the service and the problem should be solved.
Basically, the problem is caused by the RabbitMQ installer not registering the service correctly.
| RabbitMQ | 33,951,516 | 33 |
I am using RabbitMQ successfully. However, I have a problem where if I get in the situation where there are lots of messages on the queue then the consumer (a Windows service) tries to get them all and then just holds on to them but never actions or acknowledges them.
When the number of messages in the ready state is l... | A consumer, by default will read as many messages as the bandwidth can handle regardless of actual message processing time by the consumer.
You need to set prefetch values by modifying the Quality of Service (QoS) of the channel to restrict how many messages it will try to pick up at one time. Check out basic.qos here... | RabbitMQ | 19,163,021 | 33 |
I am trying to run the following command
rabbitmq-plugins.bat enable rabbitmq_management
and its giving me an error like this:
11:36:55.464 [error] Failed to create cookie file 'h:/.erlang.cookie': enoent
I am using windows 7, Erlang Version R16B01 and RabbitMQ-Server version 3.1.5
I am using my work PC and our C... | Set the home drive to some dir in the dos shell before executing the cli.
Create a startup file, e.g start-rabbit.bat, with contents below.
set HOMEDRIVE=C:/conf/rabbitmq :: Or your favorite dir
rabbitmq-plugins.bat enable rabbitmq_management
Use a folder in C drive c:/conf/rabbitmq. The rabbitmq system will write t... | RabbitMQ | 18,495,874 | 33 |
At the rabbitMQ web interface at the queue tab I see "Overview" panel where I found these:
Queued messages :
Ready
Unacknowledged
Total
I guess what is the "Total" messages. But what is "Ready" and "Unacknowledged" ?
"Ready" - messages that were delivered to the consumer?
"Unacknowledged" - ?
Message rates:
Pub... | Ready
Is the number of messages that are available to be delivered.
Unacknowledged
Is the number of messages for which the server is waiting for acknowledgement(If a client recieved the message but dont send a acknowledge yet).
Total
Is the sum of Ready and Unacknowledged messages.
About your second question:
Publish
... | RabbitMQ | 18,110,077 | 33 |
We have a PHP app that forwards messages from RabbitMQ to connected devices down a WebSocket connection (PHP AMQP pecl extension v1.7.1 & RabbitMQ 3.6.6).
Messages are consumed from an array of queues (1 per websocket connection), and are acknowledged by the consumer when we receive confirmation over the websocket that... | "PRECONDITION_FAILED - unknown delivery tag" usually happens because of double ack-ing, ack-ing on wrong channels or ack-ing messages that should not be ack-ed.
So in same case you are tying to execute basic.ack two times or basic.ack using another channel
| RabbitMQ | 42,567,689 | 32 |
How to acknowledge the messages manually without using auto acknowledgement.
Is there a way to use this along with the @RabbitListener and @EnableRabbit style of configuration.
Most of the documentation tells us to use SimpleMessageListenerContainer along with ChannelAwareMessageListener.
However using that we lose ... | Add the Channel to the @RabbitListener method...
@RabbitListener(queues = "${eventqueue}")
public void receiveMessage(Order order, Channel channel,
@Header(AmqpHeaders.DELIVERY_TAG) long tag) throws Exception {
...
}
and use the tag in the basicAck, basicReject.
EDIT
@SpringBootApplication
@EnableRabbit
public... | RabbitMQ | 38,728,668 | 32 |
I would like to set a timeout after which a dequeued message is automatically NACKed.
When I dequeue a message I wait until it is transfered over a socket and the other party confirms its reception.
Do I need to keep a list of Timers or can RMQ handle this automatically?
private void Run()
{
_rmqConnection = _queue... | Yes. This is discussed in the official Python tutorial:
A timeout (30 minutes by default) is enforced on consumer delivery acknowledgement. This helps detect buggy (stuck) consumers that never acknowledge deliveries.
You can find more information available on the RabbitMQ documentation for Delivery Acknowledgement Ti... | RabbitMQ | 30,546,977 | 32 |
I couldn't find in RabbitMQ documentation the default x-message-ttl value comes with the installation.
I know how to set it to a desired value but I am curious to know the default value.
| There is no x-message-ttl argument set by default from the broker side, so basically you can interpret default value as infinity.
If you publish message without ttl to queue without ttl set (yupp, there are per-message and per-queue ttl arguments, see note below):
if message published as persistent and queue declared ... | RabbitMQ | 24,946,181 | 32 |
I'm new to RabbitMQ and was wondering of a good approach to this problem I'm mulling over. I want to create a service that subscribes to a queue and only pulls messages that meet a specific criteria; for instance, if a specific subject header is in the message.
I'm still learning about RabbitMQ, and was looking for ti... | RabbitMQ is perfect for this situation. You have a number of options to do what you want. I suggest reading the documentation to get a better understanding. I would suggest that you use a topic or direct exchange. Topic is more flexible. It goes like this.
Producer code connects to the RabbitMQ Broker and creates a... | RabbitMQ | 11,142,071 | 32 |
I installed rabbitmq service on the server and on my system.
I want to use RPC pattern:
var factory = new ConnectionFactory() {
HostName = "158.2.14.42",
Port = Protocols.DefaultProtocol.DefaultPort,
UserName = "Administrator",
Password = "@server@",
VirtualHost = "/"
ContinuationTimeout = new TimeSpa... | As this question mentioned.
After I installed RabbitMQ, I enabled management tools on the server and on my local computer with this:
rabbitmq-plugins enable rabbitmq_management
Then I restarted RabbitMQ service from services.msc
I could see the Rabbitmq management at http://localhost:15672
I logged in to rabbit manage... | RabbitMQ | 47,869,390 | 31 |
If the column in Postgres' table has the name year, how should look INSERT query to set the value for that column?
E.g.: INSERT INTO table (id, name, year) VALUES ( ... ); gives an error near the year word.
| Simply enclose year in double quotes to stop it being interpreted as a keyword:
INSERT INTO table (id, name, "year") VALUES ( ... );
From the documentation:
There is a second kind of identifier: the delimited identifier or
quoted identifier. It is formed by enclosing an arbitrary sequence of
characters in double-... | PostgreSQL | 7,651,417 | 215 |
I'm trying to run psql on my Vagrant machine, but I get this error:
psql: could not connect to server: No such file or directory
Is the server running locally and accepting connections on
Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
Note: Vagrant 1.9.2
Box: ubuntu/trusty64, https://atlas.hashicorp.com/ubu... | I've had this same issue, related to the configuration of my pg_hba.conf file (located in /etc/postgresql/9.6/main). Please note that 9.6 is the postgresql version I am using.
The error itself is related to a misconfiguration of postgresql, which causes the server to crash before it starts.
I would suggest following th... | PostgreSQL | 42,653,690 | 215 |
I came across this post (What is the difference between tinyint, smallint, mediumint, bigint and int in MySQL?) and realized that PostgreSQL does not support unsigned integer.
Can anyone help to explain why is it so?
Most of the time, I use unsigned integer as auto incremented primary key in MySQL. In such design, how ... | It's not in the SQL standard, so the general urge to implement it is lower.
Having too many different integer types makes the type resolution system more fragile, so there is some resistance to adding more types into the mix.
That said, there is no reason why it couldn't be done. It's just a lot of work.
| PostgreSQL | 20,810,134 | 215 |
I'm converting a db from postgres to mysql.
Since i cannot find a tool that does the trick itself, i'm going to convert all postgres sequences to autoincrement ids in mysql with autoincrement value.
So, how can i list all sequences in a Postgres DB (8.1 version) with information about the table in which it's used, the... | The following query gives names of all sequences.
SELECT c.relname FROM pg_class c WHERE c.relkind = 'S' order BY c.relname;
Typically a sequence is named as ${table}_id_seq. Simple regex pattern matching will give you the table name.
To get last value of a sequence use the following query:
SELECT last_value FROM test... | PostgreSQL | 1,493,262 | 214 |
How can I get a list of column names and datatypes of a table in PostgreSQL using a query?
| SELECT
column_name,
data_type
FROM
information_schema.columns
WHERE
table_name = 'table_name';
with the above query you can retrieve columns and its datatype.
| PostgreSQL | 20,194,806 | 211 |
I've tried the following, but I was unsuccessful:
ALTER TABLE person ALTER COLUMN dob POSITION 37;
| "Alter column position" in the PostgreSQL Wiki says:
PostgreSQL currently defines column
order based on the attnum column of
the pg_attribute table. The only way
to change column order is either by
recreating the table, or by adding
columns and rotating data until you
reach the desired layout.
That's pret... | PostgreSQL | 285,733 | 211 |
I have a table on pgsql with names (having more than 1 mio. rows), but I have also many duplicates. I select 3 fields: id, name, metadata.
I want to select them randomly with ORDER BY RANDOM() and LIMIT 1000, so I do this is many steps to save some memory in my PHP script.
But how can I do that so it only gives me a li... | To do a distinct on only one (or n) column(s):
select distinct on (name)
name, col1, col2
from names
This will return any of the rows containing the name. If you want to control which of the rows will be returned you need to order:
select distinct on (name)
name, col1, col2
from names
order by name, col1
Will... | PostgreSQL | 16,913,969 | 209 |
Does anyone know if it's even possible (and how, if yes) to query a database server setting in PostgreSQL (9.1)?
I need to check the max_connections (maximum number of open db connections) setting.
| You can use SHOW:
SHOW max_connections;
This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf in your current session:
RESET max_connection... | PostgreSQL | 8,288,823 | 209 |
I am looking at some PostgreSQL table creation and I stumbled upon this:
CREATE TABLE (
...
) WITH ( OIDS = FALSE );
I read the documentation provided by postgres and I know the concept of object identifier from OOP but still I do not grasp,
why such identifier would be useful in a database?
to make queries shorter... | OIDs basically give you a built-in id for every row, contained in a system column (as opposed to a user-space column). That's handy for tables where you don't have a primary key, have duplicate rows, etc. For example, if you have a table with two identical rows, and you want to delete the oldest of the two, you could... | PostgreSQL | 5,625,585 | 209 |
I want to be able to connect to a PostgreSQL database and find all of the functions for a particular schema.
My thought was that I could make some query to pg_catalog or information_schema and get a list of all functions, but I can't figure out where the names and parameters are stored. I'm looking for a query that wil... | \df <schema>.*
in psql gives the necessary information.
To see the query that's used internally connect to a database with psql and supply an extra "-E" (or "--echo-hidden") option and then execute the above command.
| PostgreSQL | 1,347,282 | 209 |
I want to select sql:
SELECT "year-month" from table group by "year-month" AND order by date, where
year-month - format for date "1978-01","1923-12".
select to_char of couse work, but not "right" order:
to_char(timestamp_column, 'YYYY-MM')
| to_char(timestamp, 'YYYY-MM')
You say that the order is not "right", but I cannot see why it is wrong (at least until year 10000 comes around).
| PostgreSQL | 4,531,577 | 208 |
I would like to "declare" what are effectively multiple TEMP tables using the WITH statement.
The query I am trying to execute is along the lines of:
WITH table_1 AS (
SELECT GENERATE_SERIES('2012-06-29', '2012-07-03', '1 day'::INTERVAL) AS date
)
WITH table_2 AS (
SELECT GENERATE_SERIES('2012-06-30', '2012-07-13', '... | Per the other comments the second Common Table Expression [CTE] is preceded by a comma not a WITH statement so
WITH cte1 AS (SELECT...)
, cte2 AS (SELECT...)
SELECT *
FROM
cte1 c1
INNER JOIN cte2 c2
ON ........
In terms of your actual query this syntax should work in PostgreSql, Oracle, and sql-server, wel... | PostgreSQL | 38,136,854 | 207 |
I am attempting to create a DB for my app and one thing I'd like to find the best way of doing is creating a one-to-many relationship between my Users and Items tables.
I know I can make a third table, ReviewedItems, and have the columns be a User id and an Item id, but I'd like to know if it's possible to make a colum... | It may soon be possible to do this: https://commitfest.postgresql.org/17/1252/ - Mark Rofail has been doing some excellent work on this patch!
The patch will (once complete) allow
CREATE TABLE PKTABLEFORARRAY (
ptest1 float8 PRIMARY KEY,
ptest2 text
);
CREATE TABLE FKTABLEFORARRAY (
ftest1 int[],
FOREIG... | PostgreSQL | 41,054,507 | 206 |
I'm writing a shell script (will become a cronjob) that will:
1: dump my production database
2: import the dump into my development database
Between step 1 and 2, I need to clear the development database (drop all tables?). How is this best accomplished from a shell script? So far, it looks like this:
#!/bin/bash
time=... | I'd just drop the database and then re-create it. On a UNIX or Linux system, that should do it:
$ dropdb development_db_name
$ createdb development_db_name
That's how I do it, actually.
| PostgreSQL | 2,056,876 | 206 |
I recently installed Postgresql 11, during the installation, there's no step to put password and username for Postgres. Now in pgAdmin 4, I wanted to connect the database to server and it's asking me to input password, and I haven't put any in the first place.
Any one knows what's going on?
| The default authentication mode for PostgreSQL is set to ident.
You can access your pgpass.conf via pgAdmin -> Files -> open pgpass.conf
That will give you the path of pgpass.conf at the bottom of the window (official documentation).
After knowing the location, you can open this file and edit it to your liking.
If tha... | PostgreSQL | 55,038,942 | 205 |
The suggested query to list ENUM types is great. But, it merely lists of the schema and the typname. How do I list out the actual ENUM values? For example, in the linked answer above, I would want the following result
schema type values
------------- -------- -------
communication channels 'text_messa... | select n.nspname as enum_schema,
t.typname as enum_name,
e.enumlabel as enum_value
from pg_type t
join pg_enum e on t.oid = e.enumtypid
join pg_catalog.pg_namespace n ON n.oid = t.typnamespace;
| PostgreSQL | 9,540,681 | 205 |
It seems many others have had problems installing the pg gem. None of the solutions posed for others have worked for me.
I have tried to install the pg gem and postgres.app. The pg gem won't install. The first error I get is:
An error occurred while installing pg (0.17.0), and Bundler cannot continue.
Make sure that g... | Same error for me and I didn't experience it until I downloaded OS X 10.9 (Mavericks). Sigh, another OS upgrade headache.
Here's how I fixed it (with homebrew):
Install another build of Xcode Tools (typing brew update in the terminal will prompt you to update the Xcode build tools)
brew update
brew install postgresql
... | PostgreSQL | 19,262,312 | 202 |
I use DBeaver v 5.2.5 on Windows and use it to connect to PostgreSQL databases.
To create a connection, I must specify the database and I have no mean to see other databases on the same server.
A colleague using DBeaver 5.3 on Mac has an option to see all databases, not just the default one.
Is there an equivalent setu... | On the connection, right-click -> Edit connection -> Connection settings -> on the tabbed panel, select PostgreSQL, check the box Show all databases.
UPDATE 19.02.2024
Checkbox is moved to Main Tab. So flow is:
On the connection, right-click -> Edit connection -> Connection settings -> check the box Show all databases.... | PostgreSQL | 54,235,029 | 201 |
Here is an extract of my table:
gid | datepose | pvc
---------+----------------+------------
1 | 1961 | 01
2 | 1949 |
3 | 1990 | 02
1 | 1981 |
1 | | 03
1 | |
I want to fill the PVC column using... | This kind of code perhaps should work for You
SELECT
*,
CASE
WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
ELSE '00'
END AS modifiedpvc
FROM my_tabl... | PostgreSQL | 27,800,119 | 201 |
This question may look like a duplicate of: How to uninstall postgresql on my Mac (running Snow Leopard) however, there are two major differences. I'm running Lion and I'm trying to uninstall PostgreSQL 9.0.4. I've looked at the last question and the link that it referenced, but I did not find a file called "uninstall-... | The following is the un-installation for PostgreSQL 9.1 installed using the EnterpriseDB installer. You most probably have to replace folder /9.1/ with your version number. If /Library/Postgresql/ doesn't exist then you probably installed PostgreSQL with a different method like homebrew or Postgres.app.
To remove the E... | PostgreSQL | 8,037,729 | 201 |
I'm not sure if its standard SQL:
INSERT INTO tblA
(SELECT id, time
FROM tblB
WHERE time > 1000)
What I'm looking for is: what if tblA and tblB are in different DB Servers.
Does PostgreSql gives any utility or has any functionality that will help to use INSERT query with PGresult struct
I mean SELECT ... | As Henrik wrote you can use dblink to connect remote database and fetch result. For example:
psql dbtest
CREATE TABLE tblB (id serial, time integer);
INSERT INTO tblB (time) VALUES (5000), (2000);
psql postgres
CREATE TABLE tblA (id serial, time integer);
INSERT INTO tblA
SELECT id, time
FROM dblink('dbname=... | PostgreSQL | 6,083,132 | 201 |
In MS SQL Server, I create my scripts to use customizable variables:
DECLARE @somevariable int
SELECT @somevariable = -1
INSERT INTO foo VALUES ( @somevariable )
I'll then change the value of @somevariable at runtime, depending on the value that I want in the particular situation. Since it's at the top of the scrip... | Postgres variables are created through the \set command, for example ...
\set myvariable value
... and can then be substituted, for example, as ...
SELECT * FROM :myvariable.table1;
... or ...
SELECT * FROM table1 WHERE :myvariable IS NULL;
edit: As of psql 9.1, variables can be expanded in quotes as in:
\set myvar... | PostgreSQL | 36,959 | 199 |
I have a table:
CREATE TABLE tblproducts
(
productid integer,
product character varying(20)
)
With the rows:
INSERT INTO tblproducts(productid, product) VALUES (1, 'CANDID POWDER 50 GM');
INSERT INTO tblproducts(productid, product) VALUES (2, 'SINAREST P SYP 100 ML');
INSERT INTO tblproducts(productid, product) VALUES... | With postgres 9.0+ you can write:
select string_agg(product,' | ' order by product) from "tblproducts"
Details here.
| PostgreSQL | 24,906,826 | 198 |
I'd like to add a constraint which enforces uniqueness on a column only in a portion of a table.
ALTER TABLE stop ADD CONSTRAINT myc UNIQUE (col_a) WHERE (col_b is null);
The WHERE part above is wishful thinking.
Any way of doing this? Or should I go back to the relational drawing board?
| PostgreSQL doesn't define a partial (i.e. conditional) UNIQUE constraint - however, you can create a partial unique index.
PostgreSQL uses unique indexes to implement unique constraints, so the effect is the same, with an important caveat: you can't perform upserts (ON CONFLICT DO UPDATE) against a unique index like yo... | PostgreSQL | 16,236,365 | 198 |
I want to remove null=True from a TextField:
- footer=models.TextField(null=True, blank=True)
+ footer=models.TextField(blank=True, default='')
I created a schema migration:
manage.py schemamigration fooapp --auto
Since some footer columns contain NULL I get this error if I run the migration:
django.db.utils.I... | Another reason for this maybe because you try to set a column to NOT NULL when it actually already has NULL values.
| PostgreSQL | 12,838,111 | 197 |
I typed psql and I get this:
psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
I used sudo netstat -nlp | grep 5432 to see the status but nothing showed.
And I searched online, somebody... | The error states that the psql utility can't find the socket to connect to your database server. Either you don't have the database service running in the background, or the socket is located elsewhere, or perhaps the pg_hba.conf needs to be fixed.
Step 1: Verify that the database is running
The command may vary depend... | PostgreSQL | 31,645,550 | 195 |
I recently upgraded to OSX 10.7, at which point my rails installation completely borked when trying to connect to the psql server. When I do it from the command line using
psql -U postgres
it works totally fine, but when I try to run the rails server or console with the same username and password, I get this error ... | It's a PATH issue. Mac OSX Lion includes Postgresql in the system now. If you do a which psql you'll likely see usr/bin/psql instead of usr/local/bin/psql which is HomeBrew's correct one. If you run brew doctor you should get a message stating that you need to add usr/local/bin to the head of your PATH env variable.
Ed... | PostgreSQL | 6,770,649 | 195 |
I am working on a Ruby on Rails application and installed PostgreSQL using postgresql-9.1.2-1-osx.dmg. I installed the pg gem.
Then when I executed rake db:create, I got
the following error:
dlopen(/Users/sathishvc/.rvm/gems/ruby-1.9.3-head@knome-vivacious/gems/pg-0.12.2/lib/pg_ext.bundle,
9): Library not loaded: /usr... | If you have upgraded
PostgreSQL with Homebrew (brew update && brew upgrade),
macOS (e.g., from v10.15 (Catalina) to v11 (Big Sur))
Then simply uninstall the pg gem:
gem uninstall pg
bundle install
And the path will be corrected for you. There isn't any need to uninstall the whole PostgreSQL cluster.
| PostgreSQL | 9,023,482 | 194 |
I have two tables with binding primary keys in the database and I want to find a disjoint set between them. For example,
Table1
ID
Name
1
John
2
Peter
3
Mary
Table2
ID
Address
1
address2
2
address2
So how do I create a SQL query so I can fetch the row with ID from table1 that is not in tab... | Try this
SELECT ID, Name
FROM Table1
WHERE ID NOT IN (SELECT ID FROM Table2)
| PostgreSQL | 12,048,633 | 193 |
I have a postgresql function
CREATE OR REPLACE FUNCTION fixMissingFiles() RETURNS VOID AS $$
DECLARE
deletedContactId integer;
BEGIN
SELECT INTO deletedContactId contact_id FROM myContacts WHERE id=206351;
-- print the value of deletedContactId variable to the console
END;
$$ LANGU... | You can raise a notice in Postgres as follows:
RAISE NOTICE 'Value: %', deletedContactId;
Read here for more details.
| PostgreSQL | 23,465,429 | 191 |
I've been looking for a solution for this and could not find a working solution.
I've installed postgres using brew (brew install postgres) in my MacBook and I am currently running it using brew services (brew services list displays postgres as a running service). However, when I try to run psql I get following error... | I had the same error and I fixed it by removing the process pid file:
rm -f /usr/local/var/postgres/postmaster.pid
or for a specific version:
rm -f /usr/local/var/postgresql@16/postmaster.pid
[Updated Answer For Arm-based Chips (Apple M1)]
When you use brew to install postgresql on Apple M1 computers, the postmaster.p... | PostgreSQL | 39,710,384 | 189 |
shopkeeper table has following fields:
id (bigint),amount (numeric(19,2)),createddate (timestamp)
Let's say, I have the above table. I want to get the records for yesterday and
generate a report by having the amount printed to cents.
One way of doing is to perform calculations in my java application and execute a sim... | It depends on a lot of factors - but most crucially:
complexity of calculations (prefer doing complex crunching on an app-server, since that scales out; rather than a db server, which scales up)
volume of data (if you need to access/aggregate a lot of data, doing it at the db server will save bandwidth, and disk io if... | PostgreSQL | 7,510,092 | 189 |
I'm looking for a way to get all rows as INSERT statements from one specific table within a database using pg_dump in PostgreSQL.
E.g., I have table A and all rows in table A I need as INSERT statements, it should also dump those statements to a file.
Is this possible?
| if version < 8.4.0
pg_dump -D -t <table> <database>
Add -a before the -t if you only want the INSERTs, without the CREATE TABLE etc to set up the table in the first place.
version >= 8.4.0
pg_dump --column-inserts --data-only --table=<table> <database>
| PostgreSQL | 2,857,989 | 189 |
I am trying to connect to a Postgresql database, I am getting the following Error:
Error:org.postgresql.util.PSQLException: FATAL: sorry, too many clients already
What does the error mean and how do I fix it?
My server.properties file is following:
serverPortData=9042
serverPortCommand=9078
trackConnectionURL=jdbc:po... | An explanation of the following error:
org.postgresql.util.PSQLException: FATAL: sorry, too many clients already.
Summary:
Your code opened up more than the allowed limit of connections to the postgresql database. It ran something like this: Connection conn = myconn.Open(); inside a loop, and forgot to run conn.close... | PostgreSQL | 2,757,549 | 188 |
John uses CHARACTER VARYING in the places where I use VARCHAR.
I am a beginner, while he is an expert.
This suggests me that there is something which I do not know.
What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?
| VARCHAR is an alias for CHARACTER VARYING, so no difference, see documentation :)
The notations varchar(n) and char(n) are aliases for character varying(n) and character(n), respectively. character without length specifier is equivalent to character(1). If character varying is used without length specifier, the type a... | PostgreSQL | 1,199,468 | 188 |
I'm creating a lot of migrations that have foreign keys in PostgreSQL 9.4.
This is creating a headache because the tables must all be in the exact order expected by the foreign keys when they are migrated. It gets even stickier if I have to run migrations from other packages that my new migrations depend on for a forei... | For migration, it is easier to disable all triggers with:
SET session_replication_role = 'replica';
And after migration reenable all with
SET session_replication_role = 'origin';
| PostgreSQL | 38,112,379 | 187 |
SELECT Table.date FROM Table WHERE date > current_date - 10;
Does this work on PostgreSQL?
| Yes this does work in PostgreSQL (assuming the column "date" is of datatype date)
Why don't you just try it?
The standard ANSI SQL format would be:
SELECT Table.date
FROM Table
WHERE date > current_date - interval '10' day;
I prefer that format as it makes things easier to read (but it is the same as current_date -... | PostgreSQL | 5,465,484 | 187 |
I need to set schema path in Postgres so that I don't every time specify schema dot table e.g. schema2.table.
Set schema path:
SET SCHEMA PATH a,b,c
only seems to work for one query session on mac, after I close query window the path variable sets itself back to default.
How can I make it permanent?
| (And if you have no admin access to the server)
ALTER ROLE <your_login_role> SET search_path TO a,b,c;
Two important things to know about:
When a schema name is not simple, it needs to be wrapped in double quotes.
The order in which you set default schemas a, b, c matters, as it is also the order in which the schemas... | PostgreSQL | 2,875,610 | 187 |
There is DataFrame.to_sql method, but it works only for mysql, sqlite and oracle databases. I cant pass to this method postgres connection or sqlalchemy engine.
| Starting from pandas 0.14 (released end of May 2014), postgresql is supported. The sql module now uses sqlalchemy to support different database flavors. You can pass a sqlalchemy engine for a postgresql database (see docs). E.g.:
from sqlalchemy import create_engine
engine = create_engine('postgresql://username:passwor... | PostgreSQL | 23,103,962 | 186 |
I want to know the principle of "Bitmap heap scan", I know this often happens
when I execute a query with OR in the condition.
Who can explain the principle behind a "Bitmap heap scan"?
| The best explanation comes from Tom Lane, which is the algorithm's author unless I'm mistaking. See also the wikipedia article.
In short, it's a bit like a seq scan. The difference is that, rather than visiting every disk page, a bitmap index scan ANDs and ORs applicable indexes together, and only visits the disk pages... | PostgreSQL | 6,592,626 | 186 |
I have a table in PostgreSQL 8.3 with 2 timestamp columns. I would like to get the difference between these timestamps in seconds. Could you please help me how to get this done?
TableA
(
timestamp_A timestamp,
timestamp_B timestamp
)
I need to get something like (timestamo_B - timestamp_A) in seconds (not just the... | Try:
SELECT EXTRACT(EPOCH FROM (timestamp_B - timestamp_A))
FROM TableA
Details here: EXTRACT.
| PostgreSQL | 14,020,919 | 185 |
I installed PostgreSQL via the graphical install on http://www.postgresql.org/download/macosx/
I see it in my applications and also have the psql terminal in my applications. I need psql to work in the regular terminal for another bash script I'm running for an app.
For some reason, when I run
psql
in the Mac terminal... | You have got the PATH slightly wrong. You need the PATH to "the containing directory", not the actual executable itself.
Your PATH should be set like this:
export PATH=/Library/PostgreSQL/9.5/bin:$PATH
without the extra sql part in it. Also, you must remove the spaces around the equals sign.
| PostgreSQL | 36,155,219 | 184 |
I have a table in a PostgreSQL 8.3.8 database, which has no keys/constraints on it, and has multiple rows with exactly the same values.
I would like to remove all duplicates and keep only 1 copy of each row.
There is one column in particular (named "key") which may be used to identify duplicates, i.e. there should only... | A faster solution is to:
find the first occurence of the duplicate,
then remove all rows that are not the first duplicate occurence.
This looks like the following:
DELETE FROM dups a USING (
SELECT MIN(ctid) as ctid, key
FROM dups
GROUP BY key HAVING COUNT(*) > 1
) b
WHERE a.key = b.key
AND a.ctid <> b.... | PostgreSQL | 6,583,916 | 184 |
I have a database, and I need to know the default encoding for the database. I want to get it from the command line.
| From the command line:
psql my_database -c 'SHOW SERVER_ENCODING'
From within psql, an SQL IDE or an API:
SHOW SERVER_ENCODING;
| PostgreSQL | 6,454,146 | 184 |
I'm trying to make restricted DB users for the app I'm working on, and I want to drop the Postgres database user I'm using for experimenting. Is there any way to drop the user without having to revoke all his rights manually first, or revoke all the grants a user has?
| How about
DROP USER <username>
This is actually an alias for DROP ROLE.
You have to explicity drop any privileges associated with that user, also to move its ownership to other roles (or drop the object).
This is best achieved by
REASSIGN OWNED BY <olduser> TO <newuser>
and
DROP OWNED BY <olduser>
The latter will re... | PostgreSQL | 3,023,583 | 184 |
I have installed postgresql on OSX. When I run psql, I get
$ psql
psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/tmp/.s.PGSQL.5433"?
However, from /etc/services
postgresql 5432/udp # PostgreSQL Database
postgr... | /etc/services is only advisory, it's a listing of well-known ports. It doesn't mean that anything is actually running on that port or that the named service will run on that port.
In PostgreSQL's case it's typical to use port 5432 if it is available. If it isn't, most installers will choose the next free port, usually ... | PostgreSQL | 15,100,368 | 183 |
If I use array_agg to collect names, I get my names separated by commas, but in case there is a null value, that null is also taken as a name in the aggregate. For example :
SELECT g.id,
array_agg(CASE WHEN g.canonical = 'Y' THEN g.users ELSE NULL END) canonical_users,
array_agg(CASE WHEN g.canonical = 'N... | With postgresql-9.3 one can do this;
SELECT g.id,
array_remove(array_agg(CASE WHEN g.canonical = 'Y' THEN g.users ELSE NULL END), NULL) canonical_users,
array_remove(array_agg(CASE WHEN g.canonical = 'N' THEN g.users ELSE NULL END), NULL) non_canonical_users
FROM groups g
GROUP BY g.id;
Update: with postgresql-... | PostgreSQL | 13,122,912 | 183 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.