在Android游戏中,用户可以通过Google+,Facebook,Twitter登录:
当应用程序连接到PostgreSQL / PHP后端时,它会发送一个社交ID列表,并将它们存储在sid
表中的social
列中:
create table social (
sid varchar(255) not null,
auth char(32) not null,
social integer not null check (0 <= social and social <= 6),
given varchar(255) not null check (given ~ '\S'),
photo varchar(255) null check (photo ~* '^https?://...'),
stamp timestamp not null,
ip inet not null,
uid integer not null references users on delete cascade,
primary key(sid, social)
);
在名为users
的另一个表格中,我将自动增加的用户ID保留为uid
列,并使用它来跟踪他们的游戏,成就,玩家统计信息:
create table users (
uid serial primary key,
created timestamp not null,
stamp timestamp not null,
banned_until timestamp null,
banned_reason varchar(255) null
);
在PHP登录脚本中,我尽可能合并社交帐户 -
通过接收所有收到的 sids ,找到相应的 uids ,然后取最低找到 uid 并更新social
表中的记录使用最低 uid 。
这在PHP中已经很好用,但现在我试图将合并功能转移到PostgreSQL存储函数中:
CREATE OR REPLACE FUNCTION merge_users(
IN in_users jsonb,
IN in_ip inet,
OUT out_uid integer) AS
$func$
DECLARE
user jsonb;
BEGIN
SELECT MIN(uid) INTO out_uid FROM social
WHERE sid IN (SELECT u->>'sid' FROM JSONB_ARRAY_ELEMENTS(in_users) u);
IF FOUND THEN
UPDATE words_social SET uid=out_uid
WHERE sid IN (SELECT u->>'sid' FROM JSONB_ARRAY_ELEMENTS(in_users) u);
ELSE
INSERT INTO words_users (created, stamp)
VALUES (current_timestamp, current_timestamp)
RETURNING uid INTO out_uid;
END IF;
FOR user IN SELECT * FROM JSONB_ARRAY_ELEMENTS(in_users)
LOOP
RAISE NOTICE 'user sid = %', user->>'sid';
UPDATE social SET
auth = user->'auth',
social = user->'social',
given = user->'given',
photo = user->'photo',
stamp = TO_TIMESTAMP(user->'stamp'),
ip = in_ip,
uid = out_uid
WHERE sid = user->>'sid';
IF NOT FOUND THEN
INSERT INTO social (
sid,
auth,
social,
given,
photo,
stamp,
ip,
uid
) VALUES (
user->'sid',
user->'auth',
user->'social',
user->'given',
user->'photo',
TO_TIMESTAMP(user->'stamp'),
in_ip,
out_uid
);
END IF;
END LOOP;
END
$func$ LANGUAGE plpgsql;
不幸的是,上面的代码会输出语法错误消息:
# select * from merge_users(
'[{"sid":"12345284239407942","auth":"ddddc1808197a1161bc22dc307accccc","social":3,"given":"Alexander1","family":"Farber","photo":"https:\/\/graph.facebook.com\/10154284239407942\/picture?type=large","place":"Bochum, Germany","female":0,"stamp":1450102770},{"sid":"54321284239407942","auth":"ddddc1808197a1161bc22dc307abbbbb","social":4,"given":"Alexander2","family":"Farber","photo":null,"place":"Bochum, Germany","female":0,"stamp":1450102800}]'::jsonb);
NOTICE: min uid = <NULL>
ERROR: operator does not exist: name ->> unknown
LINE 1: SELECT user->>'sid'
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
QUERY: SELECT user->>'sid'
CONTEXT: PL/pgSQL function words_merge_users(jsonb) line 15 at RAISE
我在上面的代码中尝试将::jsonb
附加到u
和user
,但它没有帮助。