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
Running a worker on a different machine results in errors specified below. I have followed the configuration instructions and have sync the dags folder. I would also like to confirm that RabbitMQ and PostgreSQL only needs to be installed on the Airflow core machine and does not need to be installed on the workers (the ...
The ImportError: No module named postgresql error is due to the invalid prefix used in your celery_result_backend. When using a database as a Celery backend, the connection URL must be prefixed with db+. See https://docs.celeryproject.org/en/stable/userguide/configuration.html#conf-database-result-backend So replace: ...
RabbitMQ
37,785,061
22
I've done a ton of research on this, and I'm surprised I haven't found a good answer to this yet anywhere. I'm running a large application on Heroku, and I have certain celery tasks that run for a very long time processing, and at the end of the task save a result. Every time I redeploy on Heroku, it sends SIGTERM (and...
Starting in version >= 4, Celery comes with a special feature, just for Heroku, that supports this functionality out of the box: $ REMAP_SIGTERM=SIGQUIT celery -A proj worker -l info source: https://devcenter.heroku.com/articles/celery-heroku#using-remap_sigterm
RabbitMQ
29,872,998
22
Is there a way to get the size (remaining messages) of a queue in rabbitmq with a simple Curl? Something like curl -xget http://host:1234/api/queue/test/stats Thank you
Finally I did the trick with the following: curl -s -i -u guest:guest http://host:port/api/queues/vhost/queue_name | sed 's/,/\n/g' | grep '"messages"' | sed 's/"messages"://g'
RabbitMQ
24,402,399
22
I am running code on python to send and receive from RabbitMQ queue from another application where I can't allow threading. This is very newbie question but, is there a possibility to just check if there is message and if there are no any then just quit listening ? How should I change basic "Hello world" example for s...
Ok, I found following solution: def receive(): parameters = pika.ConnectionParameters(RabbitMQ_server) connection = pika.BlockingConnection(parameters) channel = connection.channel() channel.queue_declare(queue='toM') method_frame, header_frame, body = channel.basic_get(queue = 'toM') if...
RabbitMQ
9,876,227
22
Is there a way to determine if any task is lost and retry it? I think that the reason for lost can be dispatcher bug or worker thread crash. I was planning to retry them but I'm not sure how to determine which tasks need to be retired? And how to make this process automatically? Can I use my own custom scheduler wh...
What you need is to set CELERY_ACKS_LATE = True Late ack means that the task messages will be acknowledged after the task has been executed, not just before, which is the default behavior. In this way if the worker crashes rabbit MQ will still have the message. Obviously of a total crash (Rabbit + workers) at the same...
RabbitMQ
5,336,645
22
I'm trying to use rabbitmq for a django tutorial but when I want to start the server I get this error: ~$ sudo rabbitmq-server Configuring logger redirection 14:49:57.041 [error] 14:49:57.044 [error] BOOT FAILED BOOT FAILED 14:49:57.044 [error] =========== =========== 14:49:57.044 [error] ERROR: could not bind to di...
Try: sudo lsof -i :25672 sudo kill <PID> sudo rabbitmq-server Where <PID> is the process ID that is occupying port 25672
RabbitMQ
63,263,177
21
When I set permissions to the rabbitmq user, there is output the vhost: [root@ha-node1 my.cnf.d]# rabbitmqctl set_permissions openstack ".*" ".*" ".*" Setting permissions for user "openstack" in vhost "/" ... What is the meaning of the vhost when I set permission, and what function does it have?
In RabbitMQ virtual hosts are logical groups of entities, they are similar to virtual hosts in Apache or server blocks in Nginx. Virtual hosts are created using rabbitmqctl or HTTP API and they provide logical grouping and separation of resources. Every virtual host has a name. When an AMQP 0-9-1 client connects to Rab...
RabbitMQ
45,250,282
21
From spring boot tutorial: https://spring.io/guides/gs/messaging-rabbitmq/ They give an example of creating 1 queue and 1 queue only, but, what if I want to be able to create more then 1 queue? how would it be possible? Obviously, I can't just create the same bean twice: @Bean Queue queue() { return new Queue(queue...
Give the bean definition factory methods different names. Usually, by convention, you would name them the same as the queue, but that's not required... @Bean Queue queue1() { return new Queue(queueNameAAA, false); } @Bean Queue queue2() { return new Queue(queueNameBBB, false); } The method name is the bean n...
RabbitMQ
41,210,688
21
I've done a lot of searching but I cannot fix this issue. I have a basic Rabbitmq container running via this command: docker run -d --hostname rabbitmqhost --name rabbitmq -p 15672:15672 -p 5672:5672 rabbitmq:3-management I am using nameko to create a microservice which connects to this container. Here's a basic micr...
If you're running a service inside a container, then amqp://guest:guest@localhost won't do you any good; localhost refers to the network namespace of the container...so of course you get an ECONNREFUSED, because there's nothing listening there. If you want to connect to a service in another container, you need to use t...
RabbitMQ
40,563,469
21
I want to scale my Node.js Socket application vertically and horizontally and I haven´t found a sophisticated solution yet. My application has two use-cases: Broadcast messages from one user to all others Push messages from one user to a subset of users On one hand, I´ve read that I need Redis for both cases togethe...
I'd say Kafka is a good fit for the horizontal scaling. It is a fairly sophisticated way of distributing a huge amount of events across servers (which at the end is what you want). This is a good read about it: https://engineering.linkedin.com/kafka/running-kafka-scale Regarding the vertical scale, instead of socket.io...
RabbitMQ
37,116,615
21
I've set up RabbitMQ in order to parse some 20.000 requests from an external API but it keeps timing out after a few minutes. It does get to correctly parse about 2000 out of the total 20.000 requests. The log file says: =INFO REPORT==== 16-Feb-2016::17:02:50 === accepting AMQP connection <0.1648.0> (127.0.0.1:33091 ->...
I've just solved a similar problem in python. In my case, it was solved by reducing the prefetch count on the consumer, so that it had fewer messages queued up in its receive buffer. My theory is that the receive buffer on the consumer gets full, and then RMQ tries to write some other message to the consumer's socket a...
RabbitMQ
35,438,843
21
I am trying to create integration test for a Scala / Java application that connects to a RabbitMQ broker. To achieve this I would like an embedded broker that speaks AMQP that I start and stop before each test. Originally I tried to introduce ActiveMQ as an embedded broker with AMQP however the application uses RabbitM...
A completely in-memory solution. Replace the spring.* properties as required. <dependency> <groupId>org.apache.qpid</groupId> <artifactId>qpid-broker</artifactId> <version>6.1.1</version> <scope>test</scope> </dependency> public class EmbeddedBroker { public void start() { Broker broker = new Broker(); ...
RabbitMQ
30,918,557
21
I am using rabbitmctl using pika library. I use the following code to create a Producer #!/usr/bin/env python import pika import time import json import datetime connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost')) channel = connection.channel() channel.queue_declare(queue='he...
Since this seems to be a maintenance procedure, and not something you'll be doing routinely on your code, you should probably be using the RabbitMQ management plugin and delete the queue from there. Anyway, you can delete it from pika with: channel.queue_delete(queue='hello') https://pika.readthedocs.org/en/latest/mo...
RabbitMQ
19,912,344
21
I have Celery running with RabbitMQ broker. Today, I have a failure of a Celery node, it doesn't execute tasks and doesn't respond on service celeryd stop command. After few repeats, the node stopped, but on start I get this message: [WARNING/MainProcess] celery@nodename ready. [WARNING/MainProcess] /home/ubuntu/virtua...
From here http://celery.readthedocs.org/en/latest/userguide/workers.html#starting-the-worker you might need to name each node uniquely. Example: $ celery -A proj worker --loglevel=INFO --concurrency=10 -n worker1.%h In supervisor escape by using %%h.
RabbitMQ
18,673,319
21
I know that there are similar questions to this, such as: https://stackoverflow.com/questions/8232194/pros-and-cons-of-celery-vs-disco-vs-hadoop-vs-other-distributed-computing-packag Differentiate celery, kombu, PyAMQP and RabbitMQ/ironMQ but I'm asking this because I'm looking for a more particular distinction backe...
They are the same in that both can solve the problem that you describe (map-reduce). They are different in that Hadoop is entirely build to solve only that usecase and Celey/RabbitMQ is build to facilitate Task execution on different nodes using message passing. Celery also supports different usecases. Hadoop is solvi...
RabbitMQ
18,521,196
21
It looks like celery does not release memory after task finished. Every time a task finishes, there would be 5m-10m memory leak. So with thousands of tasks, soon it will use up all memory. BROKER_URL = 'amqp://user@localhost:5672/vhost' # CELERY_RESULT_BACKEND = 'amqp://user@localhost:5672/vhost' CELERY_IMPORTS = ( ...
There are two settings which can help you mitigate growing memory consumption of celery workers: Max tasks per child setting (v2.0+): With this option you can configure the maximum number of tasks a worker can execute before it’s replaced by a new process. This is useful if you have memory leaks you have no control...
RabbitMQ
17,541,452
21
I'm trying to get a Django Celery worker to connect to a RabbitMQ server, all running on the same host. However, when I run manage.py celery worker all I get is: [2013-06-11 17:33:41,185: WARNING/MainProcess] celery@localhost has started. [2013-06-11 17:33:44,192: ERROR/MainProcess] Consumer: Connection Error: Socket c...
It looks like you need to grant access to the "/myapp" vhost for the "guest" user. From the docs: set_permissions [-p vhostpath] {user} {conf} {write} {read} So something similar to this will give your guest user unlimited access: rabbitmqctl set_permissions -p /myvhost guest ".*" ".*" ".*"
RabbitMQ
17,054,533
21
I might be misunderstanding how this works (which is why I'm asking), but I think when a celery worker consumes a task from RabbitMQ it puts a lock on it -- so to speak -- and then must acknowledge it completed that task onces it's done. So say I have 4 workers which all have the prefetch setting at 1 and queue of 6 ta...
This is mentioned in the FAQ, but I can't blame you for not finding it: http://docs.celeryproject.org/en/latest/faq.html#should-i-use-retry-or-acks-late The default behavior of early ack is there because we don't want to enforce users to write idempotent tasks.
RabbitMQ
12,594,802
21
I am using Celery with RabbitMQ. Lately, I have noticed that a large number of temporary queues are getting made. So, I experimented and found that when a task fails (that is a tasks raises an Exception), then a temporary queue with a random name (like c76861943b0a4f3aaa6a99a6db06952c) is formed and the queue remains. ...
It sounds like you're using the amqp as the results backend. From the docs here are the pitfalls of using that particular setup: Every new task creates a new queue on the server, with thousands of tasks the broker may be overloaded with queues and this will affect performance in negative ways. If you’re using Rab...
RabbitMQ
7,144,025
21
I send the following message with content type application/json: However whene i get messages from the same RabbitMQ Web console, it shows the payload as String. What am I doing wrong? Or am I fundamentally misunderstanding and the Payload is always of type String?
From the official docs: AMQP messages also have a payload (the data that they carry), which AMQP brokers treat as an opaque byte array. The broker will not inspect or modify the payload. It is possible for messages to contain only attributes and no payload. It is common to use serialisation formats like JSON, Thrift, ...
RabbitMQ
49,788,162
20
Is it possible to use a different message broker with celery? For example: I would like to use PostgreSQL instead of RabbitMQ. AFAIK it is only supported in the result backend: http://docs.celeryproject.org/en/latest/userguide/configuration.html#database-backend-settings Since PostgreSQL 9.5 there is SKIP LOCKED which ...
Yes, you can use postgres as broker instead of rabbitmq. Here is a simple example to demonstrate it. from celery import Celery broker = 'sqla+postgresql://user:pass@host/dbname' app = Celery(broker=broker) @app.task def add(x, y): return x + y Queuing tasks In [1]: from demo import add In [2]: add.delay(1,2...
RabbitMQ
47,473,583
20
I have configured the RabbitMQ rabbitmq.config file with new port number i.e. 5671 with SSL. Now I want to disable the default port i.e. 5672. Config file as below :- [ {rabbit, [ {ssl_listeners, [5671]}, {ssl_options, [{cacertfile,"/ay/app/xxx/softwares/rabbitmq_server-3.1.1/etc/ssl/cacert.pem"}, ...
To disable standart RabbitMQ 5672 port add {tcp_listeners, []} to your rabbitmq.conf: [ {rabbit, [ {tcp_listeners, []}, {ssl_listeners, [5671]}, {ssl_options, [{cacertfile,"/ay/app/xxx/softwares/rabbitmq_server-3.1.1/etc/ssl/cacert.pem"}, {certfile,"/ay/app/xxx/softwares/rabbitmq_se...
RabbitMQ
19,806,313
20
When I route a task to a particular queue it works: task.apply_async(queue='beetroot') But if I create a chain: chain = task | task And then I write chain.apply_async(queue='beetroot') It seems to ignore the queue keyword and assigns to the default 'celery' queue. It would be nice if celery supported routing in chai...
I do it like this: subtask = task.s(*myargs, **mykwargs).set(queue=myqueue) mychain = celery.chain(subtask, subtask2, ...) mychain.apply_async()
RabbitMQ
14,953,521
20
I am using celery with a rabbitmq backend. It is producing thousands of queues with 0 or 1 items in them in rabbitmq like this: $ sudo rabbitmqctl list_queues Listing queues ... c2e9b4beefc7468ea7c9005009a57e1d 1 1162a89dd72840b19fbe9151c63a4eaa 0 07638a97896744a190f8131c3ba063de 0 b34f8d6d7402408c...
Celery with the AMQP backend will store task tombstones (results) in an AMQP queue named with the task ID that produced the result. These queues will persist even after the results are drained. A couple recommendations: Apply ignore_result=True to every task you can. Don't depend on results from other tasks. Switch ...
RabbitMQ
14,636,534
20
I have tried to use Rabbitmq server for some reason the connection closes abruptly even though I passed the correct username and password. Rabbitmq server is running on port 5672 and telneting to my server at port 5672 says its running fine. I have installed rabbitmq server in CentOS and my rabbitmq server log are as ...
connection_closed_abruptly means the client closed the TCP connection without going through the proper AMQP connection termination process. Is your rabbit server behind a load balancer? A common cause for connections being abruptly closed as soon as they're started is a TCP load balancer's heartbeat. If this is the cas...
RabbitMQ
13,946,153
20
When using RabbitMQ for sending messages you basically have exchanges, queues and bindings. I've understood their idea and how they relate to each other, but I am not quite sure who sets up what. Basically, I have three scenarios in my application. Scenario 1: One publisher, several worker processes What I want to achi...
I think what you say is right except on Scenario 3. If messages should not be lost if a consumer goes offline then you need durable queues and the queues can't be auto_delete'd. Everything else seems right to me. In the case of scenario 2 you could also let RabbitMQ auto-generate queue names for you and then let those...
RabbitMQ
12,597,006
20
I'm just looking in to the config details of RabbitMQ and came across [{rabbit, [{vm_memory_high_watermark, 0}, {disk_free_limit, {mem_relative, 1.0}} ] }] What does this config mean? vm_memory_high_watermark set to 0 means => Block all publishers immediately the rabbitmq app starts? But we still...
The vm_memory_high_watermark is a percentage value is related to memory flow control in RabbitMQ. If you take a look at Memory flow control you will see that it says, under "Memory-Based Flow Control" heading: The RabbitMQ server detects the total amount of RAM installed in the computer on startup and when rabbitmqctl...
RabbitMQ
12,175,156
20
I'm trying to install the RabbitMQ PECL extension but after running sudo pecl install amqp I get the following cryptic error message, which extensive googling hasn't helped resolve. I have these packages installed: librabbitmq - RabbitMQ C client itself) librabbitmq-dev - dev headers etc. and RabbitMQ runnin...
I had to install it applying following steps found here: # Download the rabbitmq-c library @ version 0-9-1 git clone git://github.com/alanxz/rabbitmq-c.git cd rabbitmq-c # Enable and update the codegen git submodule git submodule init git submodule update # Configure, compile and install autoreconf -i && ./conf...
RabbitMQ
9,520,914
20
I have a RabbitMQ cluster with two nodes in production and the cluster is breaking with these error messages: =ERROR REPORT==== 23-Dec-2011::04:21:34 === ** Node rabbit@rabbitmq02 not responding ** ** Removing (timedout) connection ** =INFO REPORT==== 23-Dec-2011::04:21:35 === node rabbit@rabbitmq02 lost 'rabbit' =ER...
RabbitMQ Clusters do not work well on unreliable networks (part of RabbitMQ documentation). So when the network failure happens (in a two node cluster) each node thinks that it is the master and the only node in the cluster. Two master nodes don't automatically reconnect, because their states are not automatically sync...
RabbitMQ
8,654,053
20
I am new to Spring AMQP. I am having an application which is a producer sending messages to the other application which is a consumer. Once the consumer receives the message, we will do validation of the data. If the data is proper we have to ACK and message should be removed from the Queue. If the data is improper we...
See the documentation. By default, (with defaultRequeueRejected=true) the container will ack the message (causing it to be removed) if the listener exits normally or reject (and requeue) it if the listener throws an exception. If the listener (or error handler) throws an AmqpRejectAndDontRequeueException, the default b...
RabbitMQ
39,530,787
19
I have a Spring AMQP message listener running. public class ConsumerService implements MessageListener { @Autowired RabbitTemplate rabbitTemplate; @Override public void onMessage(Message message) { try { testService.process(message); //This process method can throw Business Excepti...
Since onMessage() doesn't allow to throw checked exceptions you can wrap the exception in a RuntimeException and re-throw it. try { testService.process(message); } catch (BusinessException e) { throw new RuntimeException(e); } Note however that this may result in the message to be re-delivered indefinitely. He...
RabbitMQ
36,979,840
19
I have a RabbitMQ 3.4.2 instance with a web management plugin installed. When I push to the message {'operationId': 194} to the queue using Python's kombu queue package, the message is read on the other end as a dictionary. However, when I send the message using the web console: I get the following error on the receiv...
I had to use content_type instead of content-type (an underscore instead of a hyphen). This is a pretty questionable design decision, because the standard everybody knows is content-type.
RabbitMQ
34,200,756
19
I need to limit the rate of consuming messages from rabbitmq queue. I have found many suggestions, but most of them offer to use prefetch option. But this option doesn't do what I need. Even if I set prefetch to 1 the rate is about 6000 messages/sec. This is too many for consumer. I need to limit for example about 70 t...
Implementing a token bucket might help: https://en.wikipedia.org/wiki/Token_bucket You can write a producer that produces to the "token bucket queue" at a fixed rate with a TTL on the message (maybe expires after a second?) or just set a maximum queue size equal to your rate per second. Consumers that receive a "normal...
RabbitMQ
29,226,590
19
I've been learning RabbitMQ various topologies, however, I couldn't find any reference to dynamic queue creation (aka Declare Queue) emitted from a producer. The idea would be to create queues dynamically depending on a particular event (e.g a HTTP request). The queue would be temporary with a TTL set and named after t...
Essentially, what you want to do is use RabbitMQ to buffer messages waiting in a set of queues (which is what a message queuing system does by definition). :) Assuming you know what your queues are from the consuming side, you won't have any issues. There is no constraint that a producer can't create a queue. As a cav...
RabbitMQ
21,265,242
19
I have create a simple publisher and a consumer which subscribes on the queue using basic.consume. My consumer acknowledges the messages when the job runs without an exception. Whenever I run into an exception I don´t ack the message and return early. Only the acknowledged messages disappear from the queue, so that´s ...
If message was not acknowledged and application fails, it will be redelivered automatically and redelivered property on envelope will be set to true (unless you consume them with no-ack = true flag). UPD: You have to nack message with redelivery flag in your catch block try { //Do some business logic } ...
RabbitMQ
17,654,475
19
How can I use two different celery project which consumes messages from single RabbitMQ installation. Generally, these scripts work fine if I use different rabbitmq for them. But on production machine, I need to share the same RabbitMQ backend for them. Note: Due to some constraint, I cannot merge new projects in exist...
RabbitMQ has the ability to create virtual message brokers called virtual hosts or vhosts. Each one is essentially a mini-RabbitMQ server with its own queues. This lets you safely use one RabbitMQ server for multiple applications. rabbitmqctl add_vhost command creates a vhost. By default Celery uses the / default vhost...
RabbitMQ
12,209,652
19
I just switched from ForkPool to gevent with concurrency (5) as the pool method for Celery workers running in Kubernetes pods. After the switch I've been getting a non recoverable erro in the worker: amqp.exceptions.PreconditionFailed: (0, 0): (406) PRECONDITION_FAILED - delivery acknowledgement on channel 1 timed out....
The accepted answer is the correct answer. However, if you have an existing RabbitMQ server running and do not want to restart it, you can dynamically set the configuration value by running the following command on the RabbitMQ server: rabbitmqctl eval 'application:set_env(rabbit, consumer_timeout, 36000000).' This wil...
RabbitMQ
69,828,547
18
I have a .net micro-service receiving messages using RabbitMQ client, I need to test the following: 1- consumer is successfully connected to rabbitMq host. 2- consumer is listening to queue. 3- consumer is receiving messages successfully. To achieve the above, I have created a sample application that sends messages and...
I have built many such tests. I have thrown up some basic code on GitHub here with .NET Core 2.0. You will need a RabbitMQ cluster for these automated tests. Each test starts by eliminating the queue to ensure that no messages already exist. Pre existing messages from another test will break the current test. I have a ...
RabbitMQ
50,176,793
18
I am trying to build my airflow using docker and rabbitMQ. I am using rabbitmq:3-management image. And I am able to access rabbitMQ UI, and API. In airflow I am building airflow webserver, airflow scheduler, airflow worker and airflow flower. Airflow.cfg file is used to config airflow. Where I am using broker_url = amq...
From within your airflow containers, you should be able to connect to the service rabbit1. So all you need to do is to change amqp://user:**@localhost:5672//: to amqp://user:**@rabbit1:5672//: and it should work. Docker compose creates a default network and attaches services that do not explicitly define a network to i...
RabbitMQ
44,710,248
18
I'm working on a personnal project which is to transform a monolithic web application into microservices (each service has its own database). At this moment the monolithic backend is made with NodeJS and is able to reply REST request. When I began to split the application into multiple services I faced the next probl...
Tom suggested a pretty good link, where the top-voted answer with its reasoning and solution is the one you can rely on. Your specific problem may be rooted in the fact that Register Service and User Service are separate. Maybe they should not be? Ideally, Register service should publish "UserRegistered" event to a bu...
RabbitMQ
41,636,566
18
We have a wrapper library around RabbitMQ at my workplace, created by someone who no longer works here. I'm designing a new system using Rabbit, and am working out the best approach for declaring queues, exchanges and bindings. Our Rabbit architecture has a few federated global zones, and each zone has multiple Rabbit ...
Is re-declaring the queues and exchanges a significant performance hit it can be for a very large volume of messages Is re-declaring on each use a good approach because it handles queues/exchanges disappearing due to broker restarts or explicit deletion? "good approach" - no. "effective" at preventing disappeared e...
RabbitMQ
35,445,391
18
RabbitMQ allows you to "heartbeat" a connection, i.e. from time to time the client and the server check (using empty messages) that the other party is still there and available. So far, so good. Unfortunately, I was not able to find a place in the documentation where a suggestion is made what a reasonable value for thi...
This answer if for RabbitMQ < 3.5.5, for newer versions see the answer from @bmaupin. It depends on your application needs. Out of the box it is 10 min for RabbitMQ. If you fail to ack heartbeat twice (20min of inactivity), connection will be closed immediately without sending any connection.close method or any error f...
RabbitMQ
25,984,602
18
Ok here is an overview of what's going on: M <-- Message with unique id of 1234 | +-Start Queue | | | <-- Exchange /|\ / | \ / | \ <-- bind to multiple queues Q1 Q2 Q3 \ | / <-- start of the problem is here \ | / \ | / \|/ | Q4 <-- Queues 1,2 and 3 must finish firs...
You need to implement this: http://www.eaipatterns.com/Aggregator.html but the RabbitMQBundle for Symfony doesn't support that so you would have to use the underlying php-amqplib. A normal consumer callback from the bundle will get an AMQPMessage. From there you can access the channel and manually publish to whatever e...
RabbitMQ
13,861,459
18
I've got rabbitmq 2.8.2 set up with the web management interface running. The Queues and Exchanges show no data. rabbitmqctl list_queues works and shows my queues. I've done rabbitmqctl stop_app, start_app.. and also service rabbitmq-server restart. Any idea how to get the queue & exchange details to populate?
I had removed the guest user and created a new user for myself. My new user did not have permission to access the / vhost. Adding that permission fixed my issue.
RabbitMQ
10,939,545
18
This is probably a very simple answer, but I'm not seeing an obvious solution in the MassTransit docs or forums. When you have some messages that have been moved over to the error queue in RabbitMQ, what's the best mechanism for getting them back into the processing queue? Also, is there any built-in logging of why the...
Enable logging with the right plugin (NLog, log4net, etc) and failures should be in the log, assuming the right log level is enabled. There is no great way to move messages back. Dru has worked on a busdriver tool https://github.com/MassTransit/MassTransit/tree/master/src/Tools/BusDriver. This, I believe, will allow y...
RabbitMQ
10,502,905
18
I know that we can do this to list queue in a rabbitmq: rabbitmqctl list_queues but how can I do this via pika?
No. Pika is an AMQP library. If you want to manage an MQ Broker, then you need an MQ Broker management tool. Fortunately, RabbitMQ comes with such a tool if you install a recent version of RabbitMQ such as 2.7.1 and you install the RabbitMQ management plugins. That gives you a web GUI as well as a RESTful API that you ...
RabbitMQ
9,652,295
18
Does RabbitMQ call the callback function for a consumer when it has some message for it, or does the consumer have to poll the RabbitMQ client? So on the consumer side, if there is a PHP script, can RabbitMQ call it and pass the message/parameters to it. e.g. if rating is submitted on shard 1 and the aggregateRating ta...
The AMQPQueue::consume method is now a "proper" implementation of basic.consume as of version 1.0 of the PHP AMQP library (http://www.php.net/manual/en/amqpqueue.consume.php). Unfortunately, since PHP is a single threaded language, you cant do other things while waiting for a message in the same process space. If you c...
RabbitMQ
9,151,698
18
Just upgraded to a new version of RabbitMQ -- 2.3.1 -- and now the following error occurs: PRECONDITION_FAILED unknown delivery tag 1 ...followed by the channel closing. This worked on an older RabbitMQ with no client-side changes. In terms of application behavior: When App A wants to send an async message to App b...
The only codepath that can cause that exception is through the broker handling a 'basic.ack', so this sounds like a client issue; check the client code. In particular, check that you aren't ack'ing messages more than once. Doing so is in violation of the AMQP 0-9-1 spec: A message MUST not be acknowledged more than o...
RabbitMQ
5,075,694
18
I'm a little confused as to which one I should use. I think either will work, but is one better or more appropriate than the other? http://github.com/ask/carrot/tree/master http://github.com/ask/celery/tree/master
If you need to send/receive messages to/from AMQP message queues, use carrot. If you want to run scheduled tasks on a number of machines, use celery. If you're making soup, use both ;-)
RabbitMQ
1,102,254
18
I want to set message header while sending a message to rabbit. I am using below code, but confused how to set message header in it. public static <T> void sendMessage(String routingKey,final Object message,Class<T> type){ DefaultClassMapper typeMapper = new DefaultClassMapper(); typeMapper.setDefaultType(typ...
Java 8: template.convertAndSend(routingKey, message, m -> { m.getMessageProperties().getHeaders().put("foo", "bar"); m.getMessageProperties().setPriority(priority); return m; }); Java 6,7: template.convertAndSend(routingKey, message, new MessagePostProcessor() { @Override public Message po...
RabbitMQ
39,853,393
17
I have two, separate RabbitMQ instances. I'm trying to find the best way to listen to events from both. For example, I can consume events on one with the following: credentials = pika.PlainCredentials(user, pass) connection = pika.BlockingConnection(pika.ConnectionParameters(host="host1", credentials=credentials)) cha...
The answer to "what is the best way" depends heavily on your usage pattern of queues and what you mean by "best". Since I can't comment on questions yet, I'll just try to suggest some possible solutions. In each example I'm going to assume exchange is already declared. Threads You can consume messages from two queues o...
RabbitMQ
28,550,140
17
I have a set up to send messages to durable queues from server (NodeJS) and the client (android app) listens to messages on their respective queues (each android device listens to its corresponding queue which is unique). As per the RabbitMQ document, when we try to connect to a queue with empty name (i.e "") then Rabb...
If you are creating queue with blank name a random queue name amq.gen-* will be generated. If you are connecting to queue with blank name then, depending of method, last declared on this channel queue name will be used. If no queue was declared or method doesn't support blank queue name error will be thrown. See queue....
RabbitMQ
22,194,675
17
It seems PostgreSQL does not allow to create a database table named 'user'. But MySQL will allow to create such a table. Is that because it is a key word? But Hibernate cannot identify any issue (even if we set the PostgreSQLDialect).
user is a reserved word and it's usually not a good idea use reserved words for identifiers (tables, columns). If you insist on doing that you have to put the table name in double quotes: create table "user" (...); But then you always need to use double quotes when referencing the table. Additionally the table name is...
PostgreSQL
22,256,124
157
I've just got myself a little bit stuck with some SQL. I don't think I can phrase the question brilliantly - so let me show you. I have two tables, one called person, one called appointment. I'm trying to return the number of appointments a person has (including if they have zero). Appointment contains the person_id an...
You want an outer join for this (and you need to use person as the "driving" table) SELECT person.person_id, COUNT(appointment.person_id) AS "number_of_appointments" FROM person LEFT JOIN appointment ON person.person_id = appointment.person_id GROUP BY person.person_id; The reason why this is working, is that the o...
PostgreSQL
14,793,057
157
Ok I have a table with a indexed key and a non indexed field. I need to find all records with a certain value and return the row. I would like to know if I can order by multiple values. Example: id x_field -- ----- 123 a 124 a 125 a 126 b 127 f 128 b 129 a 130 x 131 x 132 b 133 ...
... WHERE x_field IN ('f', 'p', 'i', 'a') ... ORDER BY CASE x_field WHEN 'f' THEN 1 WHEN 'p' THEN 2 WHEN 'i' THEN 3 WHEN 'a' THEN 4 ELSE 5 -- fallback for values not inside the IN clause. eg : x_field = 'b' END, id
PostgreSQL
6,332,043
157
How do you view a stored function or procedure? Say I have an old function without the original definition - I want to see what it is doing in pg/psql but I can't seem to figure out a way to do that. using Postgres version 8.4.1
\df+ <function_name> in psql.
PostgreSQL
3,524,859
157
I am running my development on Ubuntu 11.10, and RubyMine Here is my development settings for the database.yml: which RubyMine created for me development: adapter: postgresql encoding: unicode database: mydb_development pool: 5 username: myuser password: when I try to run the app, I get this error below, i...
If you installed postresql on your server then just host: localhost to database.yml, I usually throw it in around where it says pool: 5. Otherwise if it's not localhost definitely tell that app where to find its database. development: adapter: postgresql encoding: unicode database: kickrstack_development host:...
PostgreSQL
9,987,171
155
myCol ------ true true true false false null In the above table, if I do : select count(*), count(myCol); I get 6, 5 I get 5 as it doesn't count the null entry. How do I also count the number of true values (3 in the example)? (This is a simplification and I'm actually using a much more complicated expression w...
SELECT COALESCE(sum(CASE WHEN myCol THEN 1 ELSE 0 END),0) FROM <table name> or, as you found out for yourself: SELECT count(CASE WHEN myCol THEN 1 END) FROM <table name>
PostgreSQL
5,396,498
155
I would like to list all tables in the liferay database in my PostgreSQL install. How do I do that? I would like to execute SELECT * FROM applications; in the liferay database. applications is a table in my liferay db. How is this done? Here's a list of all my databases: postgres=# \list ...
If you wish to list all tables, you must use: \dt *.* to indicate that you want all tables in all schemas. This will include tables in pg_catalog, the system tables, and those in information_schema. There's no built-in way to say "all tables in all user-defined schemas"; you can, however, set your search_path to a lis...
PostgreSQL
12,445,608
154
I have a two tables Student -------- Id Name 1 John 2 David 3 Will Grade --------- Student_id Mark 1 A 2 B 2 B+ 3 C 3 A Is it possible to make native Postgresql SELECT to get results like below: Name Array of marks ----------------------- 'John', {'...
Use array_agg: http://www.sqlfiddle.com/#!1/5099e/1 SELECT s.name, array_agg(g.Mark) as marks FROM student s LEFT JOIN Grade g ON g.Student_id = s.Id GROUP BY s.Id By the way, if you are using Postgres 9.1, you don't need to repeat the columns on SELECT to GROUP BY, e.g. you don't need to repeat the student n...
PostgreSQL
10,928,210
154
If I have a docker-compose file like: version: "3" services: postgres: image: postgres:9.4 volumes: - db-data:/var/lib/db volumes: db-data: ... then doing docker-compose up creates a named volume for db-data. Is there a way to remove this volume via docker-compose? If it were an anonymous volume, the...
docker-compose down -v removes all volumes attached. See the docs
PostgreSQL
45,511,956
153
I'm looking to write a postgresql query to do the following : if(field1 > 0, field2 / field1 , 0) I've tried this query, but it's not working if (field1 > 0) then return field2 / field1 as field3 else return 0 as field3 thank youu
As stated in PostgreSQL docs here: The SQL CASE expression is a generic conditional expression, similar to if/else statements in other programming languages. Code snippet specifically answering your question: SELECT field1, field2, CASE WHEN field1>0 THEN field2/field1 ELSE 0 END AS field3 FROM test
PostgreSQL
19,029,842
153
I have a small table (~30 rows) in my Postgres 9.0 database with an integer ID field (the primary key) which currently contains unique sequential integers starting at 1, but which was not created using the 'serial' keyword. How can I alter this table such that from now on inserts to this table will cause this field to ...
Look at the following commands (especially the commented block). DROP TABLE foo; DROP TABLE bar; CREATE TABLE foo (a int, b text); CREATE TABLE bar (a serial, b text); INSERT INTO foo (a, b) SELECT i, 'foo ' || i::text FROM generate_series(1, 5) i; INSERT INTO bar (b) SELECT 'bar ' || i::text FROM generate_series(1, ...
PostgreSQL
9,490,014
153
Does Postgres have any way to say ALTER TABLE foo ADD CONSTRAINT bar ... which will just ignore the command if the constraint already exists, so that it doesn't raise an error?
A possible solution is to simply use DROP IF EXISTS before creating the new constraint. ALTER TABLE foo DROP CONSTRAINT IF EXISTS bar; ALTER TABLE foo ADD CONSTRAINT bar ...; Seems easier than trying to query information_schema or catalogs, but might be slow on huge tables since it always recreates the constraint. Edi...
PostgreSQL
6,801,919
153
We use copy command to copy data of one table to a file outside database. Is it possible to copy data of one table to another table using command. If yes can anyone please share the query. Or is there any better approach like we can use pg_dump or something like that.
You cannot easily do that, but there's also no need to do so. CREATE TABLE mycopy AS SELECT * FROM mytable; or CREATE TABLE mycopy (LIKE mytable INCLUDING ALL); INSERT INTO mycopy SELECT * FROM mytable; If you need to select only some columns or reorder them, you can do this: INSERT INTO mycopy(colA, colB) SELECT co...
PostgreSQL
31,284,514
152
I have this query I have written in PostgreSQL that returns an error saying: [Err] ERROR: LINE 3: FROM (SELECT DISTINCT (identifiant) AS made_only_recharge This is the whole query: SELECT COUNT (made_only_recharge) AS made_only_recharge FROM ( SELECT DISTINCT (identifiant) AS made_only_recharge FROM cdr_dat...
Add an ALIAS onto the subquery, SELECT COUNT(made_only_recharge) AS made_only_recharge FROM ( SELECT DISTINCT (identifiant) AS made_only_recharge FROM cdr_data WHERE CALLEDNUMBER = '0130' EXCEPT SELECT DISTINCT (identifiant) AS made_only_recharge FROM cdr_data ...
PostgreSQL
14,767,209
152
I have a query like this that nicely generates a series of dates between 2 given dates: select date '2004-03-07' + j - i as AllDate from generate_series(0, extract(doy from date '2004-03-07')::int - 1) as i, generate_series(0, extract(doy from date '2004-08-16')::int - 1) as j It generates 162 dates between 2004...
Can be done without conversion to/from int (but to/from timestamp instead) SELECT date_trunc('day', dd):: date FROM generate_series ( '2007-02-01'::timestamp , '2008-04-01'::timestamp , '1 day'::interval) dd ;
PostgreSQL
14,113,469
152
I would like to take a look at the PostgreSQL log files to see what my app writes to them but I can't find them. Any ideas?
On OSX Homebrew installation the log can be found at: Latest Homebrew: /opt/homebrew/var/log/postgres.log or older: /usr/local/var/log/postgres.log or for older version of postgres (< 9.6) /usr/local/var/postgres/server.log Bonus - check if PostgreSQL is running using Homebrew: brew services info --all
PostgreSQL
2,563,494
152
I am working with a fresh postgresql install, with 'postgres' super user. Logged in via: sudo -u postgres psql postgres=# createdb database postgres-# \list List of databases Name | Owner | Encoding | Collation | Ctype | Access privileges -----------+----------+...
createdb is a command line utility which you can run from bash and not from psql. To create a database from psql, use the create database statement like so: create database [databasename]; Note: be sure to always end your SQL statements with ;
PostgreSQL
13,321,005
151
I have a json array stored in my postgres database. The json looks like this: [ { "operation": "U", "taxCode": "1000", "description": "iva description", "tax": "12" }, { "operation": "U", "taxCode": "1001", "description": "iva description", "ta...
I post the answer originally written by pozs in the comment section. unnest() is for PostgreSQL's array types. Instead one of the following function can be used: json_array_elements(json) (9.3+) jsonb_array_elements(jsonb) (9.4+) json[b]_array_elements_text(json[b]) (9.4+) Example: select * from json_array_elements...
PostgreSQL
36,174,881
150
I would like to delete rows which contain a foreign key, but when I try something like this: DELETE FROM osoby WHERE id_osoby='1' I get this statement: ERROR: update or delete on table "osoby" violates foreign key constraint "kontakty_ibfk_1" on table "kontakty" DETAIL: Key (id_osoby)=(1) is still referenced from...
To automate this, you could define the foreign key constraint with ON DELETE CASCADE. I quote the the manual for foreign key constraints: CASCADE specifies that when a referenced row is deleted, row(s) referencing it should be automatically deleted as well. Look up the current FK definition like this: SELECT pg_get_c...
PostgreSQL
14,182,079
150
I'm trying to do something like this in postgres: UPDATE table1 SET (col1, col2) = (SELECT col2, col3 FROM othertable WHERE othertable.col1 = 123); INSERT INTO table1 (col1, col2) VALUES (SELECT col1, col2 FROM othertable) But point 1 is not possible even with postgres 9.0 as mentioned in the docs (http://www.postgre...
For the UPDATE Use: UPDATE table1 SET col1 = othertable.col2, col2 = othertable.col3 FROM othertable WHERE othertable.col1 = 123; For the INSERT Use: INSERT INTO table1 (col1, col2) SELECT col1, col2 FROM othertable You don't need the VALUES syntax if you are using a SELECT to populate the INSERT ...
PostgreSQL
3,736,732
150
I cannot understand the syntax error in creating a composite key. It may be a logic error, because I have tested many varieties. How do you create composite keys in Postgres? CREATE TABLE tags ( (question_id, tag_id) NOT NULL, question_id INTEGER NOT NULL, tag_id SERIAL NO...
Your compound PRIMARY KEY specification already does what you want. Omit the line that's giving you a syntax error, and omit the redundant CONSTRAINT (already implied), too: CREATE TABLE tags ( question_id INTEGER NOT NULL, tag_id SERIAL NOT NULL, tag1 VARCHAR(20), ...
PostgreSQL
1,285,967
150
I have just install Postgres 9.3 on Windows 7. The installation completed successfully. It has never asked me to provide the password for postgres user. The service postgresql-x64-9.3 is up and running. However, I cannot connect: I do not not know the password. I've found the following answer, but it did not help: simi...
[WINDOWS] https://stackoverflow.com/a/27108276/1087499 [LINUX] might work for windows too After installing postgres follow following steps in order to setup password for default system account of Linux execute following in terminal: user:~$ sudo -i -u postgres postgres@user:~$ psql after executing above two commands y...
PostgreSQL
27,107,557
149
I'd like to perform division in a SELECT clause. When I join some tables and use aggregate function I often have either null or zero values as the dividers. As for now I only come up with this method of avoiding the division by zero and null values. (CASE(COALESCE(COUNT(column_name),1)) WHEN 0 THEN 1 ELSE (COALESCE(CO...
You can use NULLIF function e.g. something/NULLIF(column_name,0) If the value of column_name is 0 - result of entire expression will be NULL
PostgreSQL
17,681,375
149
How can I add comment to column in PostgreSQL? create table session_log ( UserId int index not null, PhoneNumber int index);
Comments are attached to a column using the comment statement: create table session_log ( userid int not null, phonenumber int ); comment on column session_log.userid is 'The user ID'; comment on column session_log.phonenumber is 'The phone number including the area code'; You can also add a comment to the ...
PostgreSQL
32,070,876
148
MySQL's explain output is pretty straightforward. PostgreSQL's is a little more complicated. I haven't been able to find a good resource that explains it either. Can you describe what exactly explain is saying or at least point me in the direction of a good resource?
The part I always found confusing is the startup cost vs total cost. I Google this every time I forget about it, which brings me back to here, which doesn't explain the difference, which is why I'm writing this answer. This is what I have gleaned from the Postgres EXPLAIN documentation, explained as I understand it. H...
PostgreSQL
117,262
148
Before anything, please note that I have found several similar questions on Stack Overflow and articles all over the web, but none of those helped me fix my issue: PG Error could not connect to server: Connection refused Is the server running on port 5432? PG::ConnectionBad - could not connect to server: Connection re...
run postgres -D /usr/local/var/postgres and you should see something like: FATAL: lock file "postmaster.pid" already exists HINT: Is another postmaster (PID 379) running in data directory "/usr/local/var/postgres"? Then run kill -9 PID in HINT And you should be good to go.
PostgreSQL
37,307,346
147
I have a query that returns avg(price) select avg(price) from( select *, cume_dist() OVER (ORDER BY price desc) from web_price_scan where listing_Type='AARM' and u_kbalikepartnumbers_id = 1000307 and (EXTRACT(Day FROM (Now()-dateEnded)))*24 < 48 and price>( select avg(price)* 0.5...
use coalesce COALESCE(value [, ...]) The COALESCE function returns the first of its arguments that is not null. Null is returned only if all arguments are null. It is often used to substitute a default value for null values when data is retrieved for display. Edit Here's an example of COALESCE with your query: SE...
PostgreSQL
11,007,009
147
I need to remove some attributes from a json type column. The Table: CREATE TABLE my_table( id VARCHAR(80), data json); INSERT INTO my_table (id, data) VALUES ( 'A', '{"attrA":1,"attrB":true,"attrC":["a", "b", "c"]}' ); Now, I need to remove attrB from column data. Something like alter table my_table drop column ...
Update: for 9.5+, there are explicit operators you can use with jsonb (if you have a json typed column, you can use casts to apply a modification): Deleting a key (or an index) from a JSON object (or, from an array) can be done with the - operator: SELECT jsonb '{"a":1,"b":2}' - 'a', -- will yield jsonb '{"b":2}' ...
PostgreSQL
23,490,965
146
I am looking for a way to implement the SQLServer-function datediff in PostgreSQL. That is, this function returns the count (as a signed integer value) of the specified datepart boundaries crossed between the specified start date and end date. datediff(dd, '2010-04-01', '2012-03-05') = 704 // 704 changes of day in this...
Simply subtract them: SELECT ('2015-01-12'::date - '2015-01-01'::date) AS days; The result: days ------ 11
PostgreSQL
17,833,176
146
I have been migrating a MySQL db to Pg (9.1), and have been emulating MySQL ENUM data types by creating a new data type in Pg, and then using that as the column definition. My question -- could I, and would it be better to, use a CHECK CONSTRAINT instead? The MySQL ENUM types are implemented to enforce specific values ...
Based on the comments and answers here, and some rudimentary research, I have the following summary to offer for comments from the Postgres-erati. Will really appreciate your input. There are three ways to restrict entries in a Postgres database table column. Consider a table to store "colors" where you want only 'red'...
PostgreSQL
10,923,213
145
How can I tell if my Postgresql server is running or not? I'm getting this message: [~/dev/working/sw] sudo bundle exec rake db:migrate rake aborted! could not connect to server: Connection refused Is the server running on host "localhost" and accepting TCP/IP connections on port 5432? Update: > which postgre...
The simplest way to to check running processes: ps auxwww | grep postgres And look for a command that looks something like this (your version may not be 8.3): /Library/PostgreSQL/8.3/bin/postgres -D /Library/PostgreSQL/8.3/data To start the server, execute something like this: /Library/PostgreSQL/8.3/bin/pg_ctl start...
PostgreSQL
7,975,414
145
Is there a way with PostgreSQL to sort rows with NULL values in fields to the end of the selected table? Like: SELECT * FROM table ORDER BY somevalue, PUT_NULL_TO_END
NULL values are sorted last in default ascending order. You don't have to do anything extra. The issue applies to descending order, which is the perfect inverse and thus sorts NULL values on top. PostgreSQL 8.3 introduced NULLS LAST: ORDER BY somevalue DESC NULLS LAST For PostgreSQL 8.2 and older or other RDBMS withou...
PostgreSQL
7,621,205
145
This is a summary of what I am trying to do: $array[0] = 1; $array[1] = 2; $sql = "SELECT * FROM table WHERE some_id = $array" Obviously, there are some syntax issues, but this is what I want to do, and I haven't found anything yet that shows how to do it. Currently, my plan is to do something along these lines: fore...
SELECT * FROM table WHERE some_id = ANY(ARRAY[1, 2]) or ANSI-compatible: SELECT * FROM table WHERE some_id IN (1, 2) The ANY syntax is preferred because the array as a whole can be passed in a bound variable: SELECT * FROM table WHERE some_id = ANY(?::INT[]) You would need to pass a string represen...
PostgreSQL
10,738,446
143
I am using following query: ALTER TABLE presales ALTER COLUMN code TYPE numeric(10,0); to change the datatype of a column from character(20) to numeric(10,0) but I am getting the error: column "code" cannot be cast to type numeric
You can try using USING: The optional USING clause specifies how to compute the new column value from the old; if omitted, the default conversion is the same as an assignment cast from old data type to new. A USING clause must be provided if there is no implicit or assignment cast from old to new type. So this might ...
PostgreSQL
7,683,359
143
I have a somewhat detailed query in a script that uses ? placeholders. I wanted to test this same query directly from the psql command line (outside the script). I want to avoid going in and replacing all the ? with actual values, instead I'd like to pass the arguments after the query. Example: SELECT * FROM foo...
You can use the -v option e.g: $ psql -v v1=12 -v v2="'Hello World'" -v v3="'2010-11-12'" and then refer to the variables in SQL as :v1, :v2 etc: select * from table_1 where id = :v1; Please pay attention to how we pass string/date values using two quotes " '...' " But this way of interpolation is prone to SQL inject...
PostgreSQL
7,389,416
143
Attempting to insert an escape character into a table results in a warning. For example: create table EscapeTest (text varchar(50)); insert into EscapeTest (text) values ('This is the first part \n And this is the second'); Produces the warning: WARNING: nonstandard use of escape in a string literal (Using PSQL 8....
Partially. The text is inserted, but the warning is still generated. I found a discussion that indicated the text needed to be preceded with 'E', as such: insert into EscapeTest (text) values (E'This is the first part \n And this is the second'); This suppressed the warning, but the text was still not being returned c...
PostgreSQL
935
143
I am trying to configure ssl certificate for PostgreSQL server. I have created a certificate file (server.crt) and key (server.key) in data directory and update the parameter SSL to "on" to enable secure connection. I just want only the server to be authenticated with server certificates on the client side and don't re...
psql below 9.2 does not accept this URL-like syntax for options. The use of SSL can be driven by the sslmode=value option on the command line or the PGSSLMODE environment variable, but the default being prefer, SSL connections will be tried first automatically without specifying anything. Example with a conninfo stri...
PostgreSQL
14,021,998
142
I have the following table projects. id title created_at claim_window 1 Project One 2012-05-08 13:50:09.924 5 2 Project Two 2012-06-01 13:50:09.924 10 A) I want to find the deadline with the calculation deadline = created_at + claim_window, where claim_window is the number of days. Something...
This will give you the deadline : select id, title, created_at + interval '1' day * claim_window as deadline from projects Alternatively the function make_interval can be used: select id, title, created_at + make_interval(days => claim_window) as deadline from projects To get all proje...
PostgreSQL
10,909,902
142
I am trying to create table with Postgis. I do it by this page. But when I import postgis.sql file, I get a lot of errors: ERROR: type "geometry" does not exist Does anybody know how can I fix it?
I had the same problem, but it was fixed by running following code CREATE EXTENSION postgis; In detail, open pgAdmin select (click) your database click "SQL" icon on the bar run "CREATE EXTENSION postgis;" code
PostgreSQL
6,850,500
142
Did a new install of postgres 8.4 on mint ubuntu. How do I create a user for postgres and login using psql? When I type psql, it just tells me psql: FATAL: Ident authentication failed for user "my-ubuntu-username"
There are two methods you can use. Both require creating a user and a database. By default psql connects to the database with the same name as the user. So there is a convention to make that the "user's database". And there is no reason to break that convention if your user only needs one database. We'll be using mydat...
PostgreSQL
2,172,569
142
When I have a column with separated values, I can use the unnest() function: myTable id | elements ---+------------ 1 |ab,cd,efg,hi 2 |jk,lm,no,pq 3 |rstuv,wxyz select id, unnest(string_to_array(elements, ',')) AS elem from myTable id | elem ---+----- 1 | ab 1 | cd 1 | efg 1 | hi 2 | jk ... How can I include...
Postgres 14 or later Use string_to_table() instead of unnest(string_to_array()) for a comma-separated string: SELECT t.id, a.elem, a.nr FROM tbl t LEFT JOIN LATERAL string_to_table(t.elements, ',') WITH ORDINALITY AS a(elem, nr) ON true; fiddle Related: Split column into multiple rows in Postg...
PostgreSQL
8,760,419
141
I'd like to make a random string for use in session verification using PostgreSQL. I know I can get a random number with SELECT random(), so I tried SELECT md5(random()), but that doesn't work. How can I do this?
You can fix your initial attempt like this: SELECT md5(random()::text); Much simpler than some of the other suggestions. :-)
PostgreSQL
3,970,795
141
I have pgAdmin version 1.16.1 installed on my machine. For exporting a table dump, I do: Right click on the table => Choose backup => Set Format to Plain => Save the file as some_name.sql Then I remove the table. Ok, now I need to import the backup I just created from some_name.sql into the database. How am I supposed ...
In pgAdmin, select the required target schema in object tree (databases ->your_db_name -> schemas -> your_target_schema) Click on Plugins/PSQL Console (in top-bar) Write \i /path/to/yourfile.sql Press enter
PostgreSQL
18,736,345
140
For development I'm using SQLite database with production in PostgreSQL. I updated my local database with data and need to transfer a specific table to the production database. Running sqlite database .dump > /the/path/to/sqlite-dumpfile.sql, SQLite outputs a table dump in the following format: BEGIN TRANSACTION; CREAT...
You should be able to feed that dump file straight into psql: /path/to/psql -d database -U username -W < /the/path/to/sqlite-dumpfile.sql If you want the id column to "auto increment" then change its type from "int" to "serial" in the table creation line. PostgreSQL will then attach a sequence to that column so that I...
PostgreSQL
4,581,727
140
I have an application using hibernate 3.1 and JPA annotations. It has a few objects with byte[] attributes (1k - 200k in size). It uses the JPA @Lob annotation, and hibernate 3.1 can read these just fine on all major databases -- it seems to hide the JDBC Blob vendor peculiarities (as it should do). @Entity public cl...
What is the portable way to annotate a byte[] property? It depends on what you want. JPA can persist a non annotated byte[]. From the JPA 2.0 spec: 11.1.6 Basic Annotation The Basic annotation is the simplest type of mapping to a database column. The Basic annotation can be applied to a persistent property or...
PostgreSQL
3,677,380
140
Is it possible to change the constraint name in Postgres? I have a PK added with: ALTER TABLE contractor_contractor ADD CONSTRAINT commerce_contractor_pkey PRIMARY KEY(id); And I want to to have different name for it, to be consistent with the rest of the system. Shall I delete the existing PK constraint and create a ...
To rename an existing constraint in PostgreSQL 9.2 or newer, you can use ALTER TABLE: ALTER TABLE name RENAME CONSTRAINT constraint_name TO new_constraint_name;
PostgreSQL
971,786
140
I am trying to do a like query like so def self.search(search, page = 1 ) paginate :per_page => 5, :page => page, :conditions => ["name LIKE '%?%' OR postal_code like '%?%'", search, search], order => 'name' end But when it is run something is adding quotes which causes the sql statement to come out like so SE...
Your placeholder is replaced by a string and you're not handling it right. Replace "name LIKE '%?%' OR postal_code LIKE '%?%'", search, search with "name LIKE ? OR postal_code LIKE ?", "%#{search}%", "%#{search}%"
PostgreSQL
19,105,706
139
I'll need to invoke REFRESH MATERIALIZED VIEW on each change to the tables involved, right? I'm surprised to not find much discussion of this on the web. How should I go about doing this? I think the top half of the answer here is what I'm looking for: https://stackoverflow.com/a/23963969/168143 Are there any dangers t...
I'll need to invoke REFRESH MATERIALIZED VIEW on each change to the tables involved, right? Yes, PostgreSQL by itself will never call it automatically, you need to do it some way. How should I go about doing this? Many ways to achieve this. Before giving some examples, keep in mind that REFRESH MATERIALIZED VIEW co...
PostgreSQL
29,437,650
138