https://supabase.com/ logo
Join Discord
Powered by
# help-and-questions
  • Prevent duplicates in a table
    m

    moxdisboss

    03/14/2023, 6:07 PM
    I have a table where users can favorite a movie. But how do I make it so that if the movie is already in their favorites list it won’t append the movie to the table?
    g
    • 2
    • 1
  • Don't return array from foreign key select
    n

    nbert

    03/14/2023, 8:14 PM
    Using supabase-js with the
    npx supabase gen types typescript ...
    types.
    The following:
    Copy code
    ts
    let { data } = await supabase
                .from('table')
                .select(`*, tool ( id, category, name )`);
    returns a data object with for
    data.tool
    the type:
    Copy code
    ts
    tool: (number & {
            id: unknown;
            category: unknown;
            name: unknown;
        }) | (number & {
            id: unknown;
            category: unknown;
            name: unknown;
        }[]);
    with
    data.tool
    being either an object or an array... But returning an array shouldn't be possible since the foreign key is a unique key, so it can only be a single object. Is there a way to make supabase only select the first result, or know that it cannot be an array?
    g
    • 2
    • 7
  • Insert into Dynamic Column
    t

    tsnakejake

    03/14/2023, 8:30 PM
    Hello! Is there a way (in SQL) to insert into a column based on a variable?
    g
    • 2
    • 14
  • BigQuery foreign data wrapper does not get all rows
    r

    Ruben

    03/14/2023, 8:45 PM
    https://github.com/supabase/wrappers/issues/73 It appears that the BigQuery foreign data wrapper is not bringing all rows over to postgres in all situations. As suggested in the blog post I am using the FWD for a very simple etl sync job. Just getting any new data from bigquery into postgres. But it appears that only an arbitrarily cut off number (35000 on view 17500 on single table) of rows are being considered for the input. I'm using version 0.1.1 according to ReadMe. Has anyone else run into this BigQuery wrapper problem ?
  • Error response could use column and value properties
    a

    AlesVaupotic

    03/14/2023, 9:24 PM
    For example, if I receive the following:
    Copy code
    js
    {
      "error": {
        "code": "23505",
        "details": "Key (id)=(1) already exists.",
        "hint": null,
        "message": "duplicate key value violates unique constraint \"countries_pkey\""
      },
      "status": 409,
      "statusText": "Conflict"
    }
    I need to parse the
    details
    to extract the column on which the value violates constraints to translate into local language and format accordingly. Simply adding
    column
    and
    value
    to
    error
    would help a lot. Any thoughts about it? Am I missing something and could simply access those properties already?
    g
    • 2
    • 13
  • Error while user trying to login
    o

    ostoto

    03/14/2023, 9:52 PM
    I'm using the react auth helpers library and am getting this error when users are tyring to login. Unhandled server error: ERROR: constraint "mfa_amr_claims_session_id_authentication_method_pkey" for table "mfa_amr_claims" does not exist (SQLSTATE 42704)
    g
    • 2
    • 4
  • Suddenly JS library not executing update
    d

    dmayo2

    03/14/2023, 9:56 PM
    Hello All. Pretty new to supabase. Kinda' like writing queries this way. I'm working in SolidJS/js and on free tier of supabase while in development. No changes to code that updates db record. Doesn't even look like the library is sending the request out to my supabase.co server URI. The GETs in the same code work fine. Any suggestions on where to start looking? Thanks.
    g
    • 2
    • 9
  • How to check postgrest version?
    d

    DYELbrah

    03/15/2023, 12:09 AM
    Not sure what version I'm running in my local db, anyone know how to check? Thanks!
    g
    s
    • 3
    • 14
  • Troubleshooting Empty Results from Storage API Call in Edge-Function in Local Env
    j

    jarnold

    03/15/2023, 12:15 AM
    Background: I am currently setting up my local environment and working on getting everything up and running. Context: Currently focusing on creating an edge-function that interacts with the storage API to retrieve the list of storage buckets. I set up three storage buckets locally to test this functionality. Problem: However, I'm running into some issues with the API call. Although I'm receiving a 200 status code, I'm not getting any data or results. Instead, I'm getting an empty array. Questions / Notes: Could it be a policy issue? I've tried multiple policy configurations with no success. Supabase Version: "@supabase/supabase-js": "https://esm.sh/@supabase/supabase-js@2.7.1", Lmk if you need more info..
  • Set urls and templates with SQL?
    e

    ejkreboot

    03/15/2023, 12:32 AM
    I am creating an initialization script for configuring my supabase project when my app deploys. I create buckets, tables, function, triggers, and permissions via SQL. Is it possible to set the app and redirect url, and email templates via SQL, or do I have to do that via the dashboard or CLI?
    g
    • 2
    • 1
  • After updating Supabase CLI, how do make sure docker image is up to date?
    d

    DYELbrah

    03/15/2023, 12:39 AM
    We have just updated the supabase cli version, we now want to make sure that the docker image is up to date too. Not sure if we should delete the old container and start a new one?
    s
    • 2
    • 3
  • Is the spread operator functional on remote / local database?
    d

    DYELbrah

    03/15/2023, 1:08 AM
    I'm attempting to run the following query:
    Copy code
    const {
            data: transactionLineItemsData2,
            error: transactionLineItemsError2,
            status,
            statusText,
          } = await ctx.supabase
            .from("customer_transaction_line_item")
            .select(`id, ...product ( material )`)
            .eq("customer_transaction_id", id);
    I just get error:
    Copy code
    failed to parse select parameter (id,...product(material))
    Looking at article: https://supabase.com/blog/postgrest-11-prerelease
    g
    n
    • 3
    • 23
  • RLS Issues when using api call in pages/api from app directory in next13
    d

    Dontblink

    03/15/2023, 1:45 AM
    I'm currently trying to enable RLS, however I have an issue when it runs from an api I have set up, here's my api function
    Copy code
    // Next.js API route support: https://nextjs.org/docs/api-routes/introduction
    import type { NextApiRequest, NextApiResponse } from "next";
    import { createClient } from "@supabase/supabase-js";
    
    type Data = {
      name: string;
    };
    
    const supabase = createClient(
      process.env.NEXT_PUBLIC_SUPABASE_URL,
      process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
    );
    
    export default async function handler(
      req: NextApiRequest,
      res: NextApiResponse
    ) {
      const authHeader = req.headers.authorization;
      if (!authHeader || !authHeader.startsWith("Bearer ")) {
        return res.status(401).json({ error: "Unauthorized" });
      }
    
      const token = authHeader.split(" ")[1];
      const { data: user, error } = await supabase.auth.getUser(token);
      if (error || !user) {
        return res.status(401).json({ error: "Unauthorized" });
      }
    
      let { data: user_jobs, errorFetch } = await supabase
        .from("user_jobs")
        .select("*");
      if (errorFetch) {
        console.log(errorFetch);
        return res.status(500).json({ error: "Internal server error" });
      }
    
      // Handle authenticated user
      return res.status(200).json({ user_jobs });
    }
    Now I've verified that the user != null and I've consoled logged it out to validate that the user matches where it's being sent from. When I turn on RLS and make a policy where only authenticated can read, it returns an empty array, and when I take off RLS it returns the full array of the jobs for the user. Do I have to do something with next cookies or headers in this case?
  • signInWithPassword not making a valid session for the user
    m

    Mohamed Yasser

    03/15/2023, 2:12 AM
    I decided to make my own UI instead of using supabase Auth UI. So in the new UI , If the user clicked signin it will call the following function const loginUser = async (email: string, password: string) => { const { data, error } = await supabaseAdmin.auth.signInWithPassword({ email: email, password: password, }) if (error) throw error; else{ const res = await supabaseAdmin.auth.getSession() console.log(res) } } The session was logged in the console, however, the user is still not signed in, as I tried to do the following const user = useSupaUser(); console.log(user); "user" was logged as null value,. And the same goes for session in const { session, isLoading: isLoadingUser, supabaseClient: supabase} = useSessionContext(); Can anyone help me know if there' s something that I am missing. As I am new to supabase and that's my first project using it.
    s
    l
    • 3
    • 12
  • role "supabase_admin" does not exist
    d

    Derock

    03/15/2023, 2:15 AM
    I'm trying to set up the supabase database inside of easypanel using docker. I have copied over all of the configuration options from supabase's docker-compose.yml for the db service. Image:
    supabase/postgres:15.1.0.54-rc0
    Env:
    Copy code
    POSTGRES_HOST=/var/run/postgresql
    PGPORT=5432
    POSTGRES_PORT=5432
    PGPASSWORD=verysecurepassword
    POSTGRES_PASSWORD=verysecurepassword
    PGDATABASE=postgres
    POSTGRES_DB=postgres
    /docker-entrypoint-initdb.d/99-realtime.sql
    mounted with the contents:
    Copy code
    sql
    \set pguser `echo "$POSTGRES_USER"`
    
    create schema if not exists _realtime;
    alter schema _realtime owner to :pguser;
    /docker-entrypoint-initdb.d/98-webhooks.sql
    mounted with the contents:
    /docker-entrypoint-initdb.d/99-roles.sql
    mounted with the contents:
    Copy code
    sql
    -- NOTE: change to your own passwords for production environments
    \set pgpass `echo "$POSTGRES_PASSWORD"`
    
    ALTER USER authenticator WITH PASSWORD :'pgpass';
    ALTER USER pgbouncer WITH PASSWORD :'pgpass';
    ALTER USER supabase_auth_admin WITH PASSWORD :'pgpass';
    ALTER USER supabase_functions_admin WITH PASSWORD :'pgpass';
    ALTER USER supabase_storage_admin WITH PASSWORD :'pgpass';
    startup command:
    docker-entrypoint.sh -c config_file=/etc/postgresql/postgresql.conf -c log_min_messages=fatal
    logs:
    Copy code
    The database cluster will be initialized with this locale configuration:
      provider:    libc
      LC_COLLATE:  en_US.utf8
      LC_CTYPE:    C.UTF-8
      LC_MESSAGES: en_US.utf8
      LC_MONETARY: en_US.utf8
      LC_NUMERIC:  en_US.utf8
      LC_TIME:     en_US.utf8
    The default database encoding has accordingly been set to "UTF8".
    The default text search configuration will be set to "english".
    
    Data page checksums are disabled.
    
    fixing permissions on existing directory /var/lib/postgresql/data ... ok
    creating subdirectories ... ok
    selecting dynamic shared memory implementation ... posix
    selecting default max_connections ... 100
    selecting default shared_buffers ... 128MB
    selecting default time zone ... Etc/UTC
    creating configuration files ... ok
    running bootstrap script ... ok
    performing post-bootstrap initialization ... ok
    initdb: warning: enabling "trust" authentication for local connections
    syncing data to disk ... ok
    initdb: hint: You can change this by editing pg_hba.conf or using the option -A, or --auth-local and --auth-host, the next time you run initdb.
    
    
    Success. You can now start the database server using:
    
        pg_ctl -D /var/lib/postgresql/data -l logfile start
    
    waiting for server to start.... done
    server started
    
    /usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/98-webhooks.sql
    BEGIN
    psql:/docker-entrypoint-initdb.d/98-webhooks.sql:3: ERROR:  role "supabase_admin" does not exist
    • 1
    • 1
  • Uploading image files to storage
    j

    JulesCoast

    03/15/2023, 2:44 AM
    I'm trying to upload files to my bucket from a next.js api. It's uploading successfully, but the content type is incorrect. If the
    contentType
    option blank, it defaults to text. I've tried
    Blob
    ,
    FormData
    , and
    File
    . None seem to work. Any ideas? Thank you!
    Copy code
    js
    const { data, error } = await db.storage
      .from("gallery")
      .upload("qqqq-asdf", image, {
        contentType: "FormData",
       });
    g
    • 2
    • 5
  • anyone how to query jsonb with graphql?
    r

    richardoreo

    03/15/2023, 3:09 AM
    can't find much online, if at all. i looked at my collections and it looks like all of the table collections were generated automatically except for the one that has the jsonb column data
    • 1
    • 1
  • Local dev setup guide
    s

    supermario

    03/15/2023, 3:17 AM
    I've spent some time going over the local dev setup of the supabase studio. The guide which I followed was https://supabase.com/docs/guides/cli/local-development. The idea was to create a local supabase project & connect your studio dev server to the same by putting in respective .env vars. But seems like it's not that simple. Do we have a step by step guide/instructions for connecting a local studio dev server to a locally set-up supabase project? Its not clear which parameters to should you set in apps/studio/.env. This is the same question I've asked in the GH discussions: https://github.com/supabase/supabase/discussions/13004
    ł
    • 2
    • 5
  • Is it okay to have an indefinitely running function?
    p

    Peanut

    03/15/2023, 3:36 AM
    I read your simple Discord bot article (https://supabase.com/docs/guides/functions/examples/discord-bot) and it implies you would run your bot using a Supabase function. Cloud functions are supposed to be tiny, single-usage that should do 1 job then spin down. Is it suitable to deploy my indefinitely running Discord bot on Supabase functions? What are the implications of it running forever?
    • 1
    • 1
  • Approaches to Integrate Supabase <> ChatGPT
    n

    nkeating

    03/15/2023, 4:38 AM
    Looking for guidance on the best paths to integrate GPT to be able to query my Supabase DB. I saw the Clippy post, but its pretty basic and geared towards more static data / not constantly changing data like say a CRM. For context, looking to build something similar to this https://chatspot.ai/ (best single example of leveraging ChatGPT with internal database ive seen btw). The most common suggestion ive seen is LlamaIndex/IndexGPT (https://gpt-index.readthedocs.io/en/latest/index.html), but wanted to check with the community first to see any perspectives on this path. Any thoughts / resources / ideas are greatly appreciated!
    e
    n
    • 3
    • 10
  • When you use .select() at the end of a query to return the changed data, does that count as a query?
    v

    Vik

    03/15/2023, 6:17 AM
    Pretty much as the title says. I'm curious if this counts as a query if the data is returned this way.
    g
    • 2
    • 2
  • Combining RLS policies for custom claims
    ł

    ŁukaszW.

    03/15/2023, 8:36 AM
    I have a situation like this. Have a column with flag is_public which should mean than anyone can access the row that's simple Have an owner_id which mean that this row is owned by some user I have a custom claim "owner" , and when owner logs in, he has access only to the dashboard, when he can manage only his "things" How I can combine policies, any user and anon without custom claim have access to any public row, and the user with claim "owner" can see only rows with his owner_id value. For now I manage to have a policy for anon using (is_public = true) and for owner ( get_my_claim('role) = '"owner"' and owner_id = auth_uid()) This gives owner access to his rows, but also to any public rows from other owners. Please help me out how to combine these to work as expected
    g
    • 2
    • 4
  • Self-hosting on a new Rootserver
    l

    Limuz

    03/15/2023, 9:01 AM
    Hello, did anyone try to host selfhost supabase on your own rootserver any exp with that or is it a bad idea to beginn with ? thank you for your time Limuz
    ł
    d
    • 3
    • 3
  • Failed to update pg.tables with the given id must be owner of table supabase
    k

    kvnfo

    03/15/2023, 9:12 AM
    Getting this error when trying to update the users table, I used the nextjs supabase stripe starter. Looked around and unable to solve this, does anyone have any suggestions? Thank you
  • Authentication API issue
    s

    Siddharth

    03/15/2023, 9:19 AM
    So I am using the Auth API and when I use the magic link the user will be redirected to my site abc.com The url I am getting is https://abc.com/#acess_token= something But I want that # be replaced with ? Or & Because using that hashtag my system does not recognise the parameter, so I can't use token
    g
    • 2
    • 2
  • Trying to upload a file from Supabase UI: The object exceeded the maximum allowed size
    l

    lumen

    03/15/2023, 9:42 AM
    Hi! I'm trying to upload a file from Supabase UI, and getting the following error: > The object exceeded the maximum allowed size How can I modify the maximum allowed upload size?
    • 1
    • 1
  • How can I show an error for an expired magic link?
    l

    lumen

    03/15/2023, 9:50 AM
    When the user clicks on a magic link for the second time, they're redirected to a url that looks like this (indicating that the link has expired):
    Copy code
    http://localhost:3000/#error=unauthorized_client&error_code=401&error_description=Email+link+is+invalid+or+has+expired
    And then supabase automatically redirects them back to my home page (
    /
    ). So the user fails to log in, and they don't see any information explaining the issue. How can I "see" this error on the client, so I could show the user an appropriate message? I can't simply do something like:
    Copy code
    javascript
    if (location.hash.includes("error")) {
      showErrorMessage()
    }
    Because the user is immediately automatically redirected to
    /
    .
  • How can I get the Discord roles of users that authenticated with Discord?
    t

    Torwent

    03/15/2023, 10:06 AM
    My webapp has login exclusively through discord, so every user logged in through it. How could I fetch a user roles in a certain guild at any time if possible? From my understanding from reading discord documentation, I would probably need to make my own auth implementation from scratch but I was wondering if it could be done through supabase since I'm already using it and it works wonders!
    g
    • 2
    • 4
  • Best practice websocket connection across multiple pages NextJS?
    r

    rnnyrk

    03/15/2023, 10:12 AM
    Hi there. I'm trying to build a NextJS app with a websocket connection. Although it works I run into the "tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance" constantly. I want a websocket/presence connection to be alive across multiple pages. For this I've made a React context wrapper around every page (based on this tutorial

    https://www.youtube.com/watch?v=BelYEMJ2N00▾

    ) Trying to subscribe to broadcast messages, but not sure how/when to subscribe. Currently doing it in the useEffect of the context wrapper, so every page can is subscribed on mount. Any tips and tricks?
    Copy code
    typescript
    export const RoomContext = React.createContext<RoomContextType | null>(null);
    
    export const RoomContextWrapper = ({ children, currentUser }: RoomContextProps) => {
      const router = useRouter<{ roomCode: string }>();
      const { roomCode } = router.query;
    
      const [isSubscribed, setSubscribed] = useState(false);
    
      const { users, roomId } = useRoomSubscriber({ roomCode, userId: currentUser });
      const { roomChannel, roomState, onSetRoomStatus } = useRoomStatus({
        roomId: roomCode,
        isPlayingUser: true,
        username: currentUser,
      });
    
      useEffect(() => {
        console.log('MOUNT', { roomChannel, isSubscribed });
    
        if (roomChannel && !isSubscribed) {
          roomChannel.subscribe((status: `${REALTIME_SUBSCRIBE_STATES}`) => {
            if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) {
              setSubscribed(true);
            }
          });
        }
      }, [roomChannel, isSubscribed]);
    
      useEffect(() => {
        return () => {
          console.log('UNMOUNT', { roomChannel });
    
          if (roomChannel) {
            setSubscribed(false);
            roomChannel.unsubscribe();
          }
        };
      }, [roomChannel]);
    
      const values = {
        roomState,
        onSetRoomStatus,
        isSubscribed,
        users,
        username: user?.name,
      };
    
      return <RoomContext.Provider value={values}>{children(values)}</RoomContext.Provider>;
    };
  • When did bucket ids stop supporting "_"? Now I can't even delete my old buckets.
    k

    kilterskjalg

    03/15/2023, 11:41 AM
    I've got underscores "_" in most of my bucket ids and names. Amongst others - one called "profile_imgs" that I'm pretty sure is a name i got from a tutorial on supabase.com sometime in august/september. Hmm.. Shouldn't there be a check when bucket is created that would prevent me from having this problem? Any tips as to how I can get these buckets removed?
    g
    • 2
    • 1
1...167168169...230Latest