MaGnezij
03/24/2023, 1:23 PMRuben
03/24/2023, 2:47 PMraoxnei
03/24/2023, 2:52 PMAlexander24
03/24/2023, 3:00 PMJoshTheNerd
03/24/2023, 3:02 PMMorpheus
03/24/2023, 3:10 PMNetail
03/24/2023, 3:26 PMjson
[
{
"id": 1,
"name": "Awesome project",
"team": {
"lead": [1],
"frontend": [2, 3],
"backend": [4]
}
}
]
This is because it is a key-array type, with the key being dynamic.
json
{
"<role>: <user id>[]
}
Members are currently saved in a different table as such:
json
[
{
"id": 1,
"email": "user1@gmail.com",
},
{
"id": 2,
"email": "user2@gmail.com",
},
{
"id": 3,
"email": "user3@gmail.com",
},
{
"id": 4,
"email": "user4@gmail.com",
}
]
The next would be to fetch each user object with the id given in the role array, resulting in:
json
[
{
"id": 1,
"name": "Awesome project",
"team": {
"lead": [
{
"id": 1,
"email": "user1@gmail.com",
},
],
"frontend": [
{
"id": 2,
"email": "user2@gmail.com",
},
{
"id": 3,
"email": "user3@gmail.com",
},
],
"backend": [
{
"id": 4,
"email": "user4@gmail.com",
}
]
}
}
]
For now I thought of fetching the project object first and the looping through each array and fetching the corresponding user object. But I feel like there would be an easier way, e.g. through a queryimagio
03/24/2023, 3:30 PMmy_column=eq.foo
but the docs and code lack any example of how you might have a realtime filter condition such as my_column=eq.foo AND other_column=lte.30
.
Relevant code is here https://github.com/supabase/realtime-js/blob/master/src/RealtimeChannel.ts
and here https://github.com/supabase/realtime/blob/a4f740004508164745470063f62453a5610bd677/lib/extensions/postgres_cdc_rls/repo/migrations/20211116213934_create_realtime_is_visible_through_filters_function.ex#L8
The postgresql functions seem to suggest that multiple conditions are possible but the JS code is pretty unclear.
Can anybody point me toward how to assign multiple conditions to a postgres changes listener filter?ccssmnn
03/24/2023, 3:58 PMeloahsam
03/24/2023, 4:08 PMWil | The🐐.eth
03/24/2023, 4:13 PMguard let userId = supabase.auth.user()?.id as? String else {
import Foundation
import SwiftUI
import Combine
import Supabase
class HomeViewModel: ObservableObject {
@Published var username: String = ""
private var cancellables = Set<AnyCancellable>()
private let userDataAccess: UserDataAccess
private let supabase = SupabaseClient(supabaseURL: URL(string: Config.supabaseURL)!, supabaseKey: Config.supabaseKey)
init() {
userDataAccess = UserDataAccess(supabase: supabase)
fetchUserData()
}
private func fetchUserData() {
guard let userId = supabase.auth.user()?.id as? String else {
return
}
userDataAccess.retrieveUserData(user_id: userId) { [weak self] result in
DispatchQueue.main.async {
switch result {
case .success(let userData):
self?.username = userData.display_name
case .failure(let error):
print("Failed to fetch user data: \(error)")
}
}
}
}
}
Here is the UserDataAccess file the HomeViewModel is referencing.
import Supabase
import Foundation
class UserDataAccess {
private let supabase: SupabaseClient
init(supabase: SupabaseClient) {
self.supabase = supabase
}
func retrieveUserData(user_id: String, completion: @escaping (Result<UserData, Error>) -> Void) {
let query = supabase.database
.from("user_data")
.select(columns: "*")
.filter(column: "user_id", operator: .eq, value: user_id)
.single()
Task {
do {
let response: UserData = try await query.execute().value
completion(.success(response))
} catch {
completion(.failure(error))
}
}
}
func insertUserData(userData: UserData, completion: @escaping (Result<UserData, Error>) -> Void) {
do {
let encoder = JSONEncoder()
let jsonData = try encoder.encode(userData)
if let jsonObject = try JSONSerialization.jsonObject(with: jsonData) as? [String: Any] {
let encodableObject = jsonObject.mapValues { AnyEncodable($0) }
let query = supabase.database
.from("user_data")
.insert(values: encodableObject, returning: .representation)
.single()
Task {
do {
let response: UserData = try await query.execute().value
completion(.success(response))
} catch {
completion(.failure(error))
}
}
} else {
completion(.failure(NSError(domain: "InsertUserDataError", code: -1, userInfo: [NSLocalizedDescriptionKey: "Failed to convert userData to JSON"])))
}
} catch {
completion(.failure(error))
}
}
}
And the UserData.swift file
import Foundation
struct UserData: Codable {
let user_id: String
let display_name: String
let age: Int
let gender: String
let height: Double?
let weight: Double?
let fitness_goal: String
enum CodingKeys: String, CodingKey {
case user_id = "user_id"
case display_name = "display_name"
case age = "age"
case gender = "gender"
case height = "height"
case weight = "weight"
case fitness_goal = "fitness_goal"
}
}
Any help would greatly appreciated. Thank you very much.Kenbak
04/13/2023, 3:03 PMLoSantos_YT👑
04/13/2023, 3:13 PMgurps
04/13/2023, 3:48 PMuseSessionContext
doesn't seem to refresh when the user logs in. I tried it on other browsers and saw the session hydrating, but it doesn't on Safari. I am using MacBook Pro M1 2021 14 Inch and Safari version 16.3, this also happens on mobile Safari as well.DonQ
04/13/2023, 4:03 PMjar
04/13/2023, 4:04 PMkevlust
04/13/2023, 4:07 PMsupafloh
04/13/2023, 5:33 PMjs
const { data: updateData, error: updateError } = await supabase
.from("profiles")
.update({
provider_token: refreshData.access_token,
provider_refresh_token: refreshData.refreshToken,
provider_token_expires_at: new Date(refreshData.newAccess.expires_in + now).toISOString(),
})
.eq("id", user.id)
.select("*");
if (updateError) {
console.log(updateError);
return;
}
console.log(updateData);
I'm sure the values being passed in are different as I am printing them right before running the query
There are no errors in logs from what I can see
What are some steps I can take to debug this?christer
04/13/2023, 6:04 PMhttps://cdn.discordapp.com/attachments/1096133946187710545/1096133946414207147/Screenshot_2023-04-13_at_20.03.04.png▾
H1GHG2M3R
04/13/2023, 7:18 PMimport { supabase } from "./supabaseClient";
retrieving the session:
const { data: sessionData, error: sessionErr } = await supabase.auth.getSession();
and then updating the users row like this:
const { data, error } = await supabase
.from("profiles")
.update({ steam_id: profile.id })
.eq('id', sessionData.session?.user.id)
I am getting a error: invalid input syntax for type uuid: "undefined". which makes me think that maybe the "getSession" method is not working?
but even if i just use my own uuid as a string instead of sessionData.session?.user.id for testing i still get a error" duplicate key value violates unique constraint "profiles_pkey" " as it already exists.
Cant figure out what am i doing wrongGlennMarcus
04/13/2023, 10:00 PMhello-world
example from https://supabase.com/docs/guides/functions/quickstart After substituting my project-ref and ANON_KEY the curl command is showing a 502 Bad Gateway
. I can see the errors on the supabase dashboard, so I can confirm calls are making it out to the network.1voy
04/13/2023, 10:00 PMMidas
04/13/2023, 10:59 PMjsx
import { supabaseClient } from "../utils/supabaseClient";
import { Navigate } from "react-router-dom";
import React, { useState, useEffect } from "react";
import { Auth } from "@supabase/auth-ui-react";
import { ThemeSupa } from "@supabase/auth-ui-shared";
function Login() {
const [logged, setLogged] = useState(false);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchData() {
const result = await supabaseClient.auth.getSession();
if (result.data.session !== null) setLogged(true);
console.log(result);
setLoading(false);
}
fetchData();
}, []);
return <>{loading ? <div>Loading...</div> : logged ? <Navigate to="/logged" /> : <Auth supabaseClient={supabaseClient} theme={{ ThemeSupa }} providers={["google"]} />}</>;
}
export default Login;
https://cdn.discordapp.com/attachments/1096208151310770247/1096208151591796848/image.png▾
Lorenium
04/13/2023, 11:35 PMPL/pgSQL function public.handle_update_user() line 3 at SQL statement
here are my triggers/functions:
postgres
CREATE OR REPLACE FUNCTION public.handle_new_user()
RETURNS TRIGGER AS $$
BEGIN
INSERT INTO public.profile (id, email, username)
VALUES (NEW.id, NEW.email, NEW.raw_user_meta_data->>'username');
RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
DROP TRIGGER IF EXISTS on_auth_user_created ON auth.users;
CREATE TRIGGER on_auth_user_created
AFTER INSERT ON auth.users
FOR EACH ROW EXECUTE PROCEDURE public.handle_new_user();
-- Function and trigger to update user
CREATE OR REPLACE FUNCTION public.handle_update_user() RETURNS TRIGGER AS $$
BEGIN
UPDATE public.profie
SET email = NEW.email, username = NEW.username, updated_at = NEW.updated_at
WHERE id = NEW.id;
RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY definer;
DROP TRIGGER IF EXISTS on_auth_user_updated ON auth.users;
CREATE TRIGGER on_auth_user_updated AFTER UPDATE ON auth.users
FOR EACH ROW EXECUTE FUNCTION public.handle_update_user();
-- Function and trigger to delete user
CREATE OR REPLACE FUNCTION public.handle_delete_user() RETURNS TRIGGER AS $$
BEGIN
DELETE FROM public.profile
WHERE id = OLD.id;
RETURN OLD;
END;
$$ LANGUAGE plpgsql SECURITY definer;
DROP TRIGGER IF EXISTS on_auth_user_deleted ON auth.users;
CREATE TRIGGER on_auth_user_deleted AFTER DELETE ON auth.users
FOR EACH ROW EXECUTE FUNCTION public.handle_delete_user();
What am I doing wrong? Also why was handle_update_user
triggered even though I'm inserting into the table?
https://cdn.discordapp.com/attachments/1096217125904994424/1096217126055972904/image.png▾
landfight
04/13/2023, 11:50 PMERROR Error uploading image to bucket: {"error": "", "message": "new row violates row-level security policy for table \"objects\"", "statusCode": "403"}
here is the code with expo image picker and im trying to use this with an authenticated user
const pickImage = async () => {
// Pick an image
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
// Get user ID and file extension
const { data, error } = await supabase.auth.getSession();
const user = data?.session?.user;
const userId = user?.id;
const fileExtension = result.assets[0].uri.split(".").pop();
// Create unique file name and get image blob
const fileName = `profile_picture_${userId}.${fileExtension}`;
const response = await fetch(result.assets[0].uri);
const fileBlob = await response.blob();
// Upload image to bucket
if (!result.canceled) {
setProfileImage(result.assets[0].uri);
const { data, error } = await supabase.storage
.from("profile_pictures")
.upload(fileName, fileBlob, {
cacheControl: "3600",
upsert: true,
});
if (error) {
console.error("Error uploading image to bucket:", error);
}
}
};
i used the default templates for the bucket policies
https://cdn.discordapp.com/attachments/1096220910589067395/1096220911281131550/CleanShot_2023-04-13_at_19.49.57.png▾
pusha007
04/13/2023, 11:54 PMconst pool = new Pool({
host: 'xxxo',
user: 'xxx',
database: db_name ?? 'postgres',
password: 'xxx',
ssl: { rejectUnauthorized: false },
port: 22163,
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 10000,
});
return pool;
}
export var connectors = {
'defaultdb': construct_pool('defaultdb'),
'tenant_db1': construct_pool('tenant_db1'),
'tenant_db2': construct_pool('tenant_db2')
}
Vik
04/14/2023, 12:19 AMDwarfNinja
04/14/2023, 12:36 AMAuth.Users Table {
id PK
email
//etc. etc. Supabase Auth
}
Public.Friends table {
id PK
created_at
user FK Auth.Users.Id
friend FK Auth.Users.Id
}
Public.Timeline table {
id PK
created_at
user FK Auth.Users.Id
message
}
Josiah
04/14/2023, 12:56 AMdonga
04/14/2023, 1:52 AM