-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathAccountInfoQueries.java
More file actions
1299 lines (1159 loc) · 71.8 KB
/
AccountInfoQueries.java
File metadata and controls
1299 lines (1159 loc) · 71.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2025, VRAI Labs and/or its affiliates. All rights reserved.
*
* This software is licensed under the Apache License, Version 2.0 (the
* "License") as published by the Apache Software Foundation.
*
* You may not use this file except in compliance with the License. You may
* obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.supertokens.storage.postgresql.queries;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.postgresql.util.PSQLException;
import org.postgresql.util.ServerErrorMessage;
import io.supertokens.pluginInterface.authRecipe.ACCOUNT_INFO_TYPE;
import io.supertokens.pluginInterface.authRecipe.AuthRecipeUserInfo;
import io.supertokens.pluginInterface.authRecipe.CanBecomePrimaryResult;
import io.supertokens.pluginInterface.authRecipe.CanLinkAccountsResult;
import io.supertokens.pluginInterface.authRecipe.exceptions.AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException;
import io.supertokens.pluginInterface.authRecipe.exceptions.AnotherPrimaryUserWithEmailAlreadyExistsException;
import io.supertokens.pluginInterface.authRecipe.exceptions.AnotherPrimaryUserWithPhoneNumberAlreadyExistsException;
import io.supertokens.pluginInterface.authRecipe.exceptions.AnotherPrimaryUserWithThirdPartyInfoAlreadyExistsException;
import io.supertokens.pluginInterface.authRecipe.exceptions.CannotBecomePrimarySinceRecipeUserIdAlreadyLinkedWithPrimaryUserIdException;
import io.supertokens.pluginInterface.authRecipe.exceptions.CannotLinkSinceRecipeUserIdAlreadyLinkedWithAnotherPrimaryUserIdException;
import io.supertokens.pluginInterface.authRecipe.exceptions.EmailChangeNotAllowedException;
import io.supertokens.pluginInterface.authRecipe.exceptions.InputUserIdIsNotAPrimaryUserException;
import io.supertokens.pluginInterface.authRecipe.exceptions.PhoneNumberChangeNotAllowedException;
import io.supertokens.pluginInterface.authRecipe.exceptions.UnknownUserIdException;
import io.supertokens.pluginInterface.bulkimport.PrimaryUser;
import io.supertokens.pluginInterface.emailpassword.exceptions.DuplicateEmailException;
import io.supertokens.pluginInterface.exceptions.StorageQueryException;
import io.supertokens.pluginInterface.exceptions.StorageTransactionLogicException;
import io.supertokens.pluginInterface.multitenancy.AppIdentifier;
import io.supertokens.pluginInterface.multitenancy.TenantIdentifier;
import io.supertokens.pluginInterface.passwordless.exception.DuplicatePhoneNumberException;
import io.supertokens.pluginInterface.sqlStorage.TransactionConnection;
import io.supertokens.pluginInterface.thirdparty.exception.DuplicateThirdPartyUserException;
import io.supertokens.storage.postgresql.PreparedStatementValueSetter;
import static io.supertokens.storage.postgresql.QueryExecutorTemplate.execute;
import static io.supertokens.storage.postgresql.QueryExecutorTemplate.executeBatch;
import static io.supertokens.storage.postgresql.QueryExecutorTemplate.update;
import io.supertokens.storage.postgresql.Start;
import io.supertokens.storage.postgresql.config.Config;
import static io.supertokens.storage.postgresql.config.Config.getConfig;
import io.supertokens.storage.postgresql.utils.Utils;
public class AccountInfoQueries {
static String getQueryToCreateRecipeUserAccountInfosTable(Start start) {
String schema = Config.getConfig(start).getTableSchema();
String tableName = Config.getConfig(start).getRecipeUserAccountInfosTable();
// @formatter:off
return "CREATE TABLE IF NOT EXISTS " + tableName + " ("
+ "app_id VARCHAR(64) NOT NULL,"
+ "recipe_user_id CHAR(36) NOT NULL,"
+ "recipe_id VARCHAR(128) NOT NULL,"
+ "account_info_type VARCHAR(8) NOT NULL,"
+ "account_info_value TEXT NOT NULL,"
+ "third_party_id VARCHAR(28),"
+ "third_party_user_id VARCHAR(256),"
+ "primary_user_id CHAR(36) NULL,"
+ "CONSTRAINT " + Utils.getConstraintName(schema, tableName, null, "pkey")
+ " PRIMARY KEY (app_id, recipe_id, recipe_user_id, account_info_type, third_party_id, third_party_user_id),"
+ "CONSTRAINT " + Utils.getConstraintName(schema, tableName, "tenant_id", "fkey")
+ " FOREIGN KEY(app_id)"
+ " REFERENCES " + Config.getConfig(start).getAppsTable() + " (app_id) ON DELETE CASCADE"
+ ");";
// @formatter:on
}
static String getQueryToCreateRecipeUserTenantsTable(Start start) {
String schema = Config.getConfig(start).getTableSchema();
String tableName = Config.getConfig(start).getRecipeUserTenantsTable();
// @formatter:off
return "CREATE TABLE IF NOT EXISTS " + tableName + " ("
+ "app_id VARCHAR(64) NOT NULL,"
+ "recipe_user_id CHAR(36) NOT NULL,"
+ "tenant_id VARCHAR(64) NOT NULL,"
+ "recipe_id VARCHAR(128) NOT NULL,"
+ "account_info_type VARCHAR(8) NOT NULL,"
+ "account_info_value TEXT NOT NULL,"
+ "third_party_id VARCHAR(28),"
+ "third_party_user_id VARCHAR(256),"
+ "CONSTRAINT " + Utils.getConstraintName(schema, tableName, null, "pkey")
+ " PRIMARY KEY (app_id, tenant_id, recipe_id, account_info_type, third_party_id, third_party_user_id, account_info_value),"
+ "CONSTRAINT " + Utils.getConstraintName(schema, tableName, "tenant_id", "fkey")
+ " FOREIGN KEY(app_id, tenant_id)"
+ " REFERENCES " + Config.getConfig(start).getTenantsTable() + " (app_id, tenant_id) ON DELETE CASCADE"
+ ");";
// @formatter:on
}
static String getQueryToCreatePrimaryUserTenantsTable(Start start) {
String schema = Config.getConfig(start).getTableSchema();
String tableName = Config.getConfig(start).getPrimaryUserTenantsTable();
// @formatter:off
return "CREATE TABLE IF NOT EXISTS " + tableName + " ("
+ "app_id VARCHAR(64) NOT NULL,"
+ "tenant_id VARCHAR(64) NOT NULL,"
+ "account_info_type VARCHAR(8) NOT NULL,"
+ "account_info_value TEXT NOT NULL,"
+ "primary_user_id CHAR(36) NOT NULL,"
+ "CONSTRAINT " + Utils.getConstraintName(schema, tableName, null, "pkey")
+ " PRIMARY KEY (app_id, tenant_id, account_info_type, account_info_value),"
+ "CONSTRAINT " + Utils.getConstraintName(schema, tableName, "app_id", "fkey")
+ " FOREIGN KEY(app_id, tenant_id)"
+ " REFERENCES " + Config.getConfig(start).getTenantsTable() + " (app_id, tenant_id) ON DELETE CASCADE"
+ ");";
// @formatter:on
}
static String getQueryToCreateTenantIndexForRecipeUserTenantsTable(Start start) {
return "CREATE INDEX IF NOT EXISTS idx_recipe_user_tenants_tenant ON "
+ Config.getConfig(start).getRecipeUserTenantsTable() + "(app_id, tenant_id);";
}
static String getQueryToCreateRecipeUserIdIndexForRecipeUserTenantsTable(Start start) {
return "CREATE INDEX IF NOT EXISTS idx_recipe_user_tenants_recipe_user_id ON "
+ Config.getConfig(start).getRecipeUserTenantsTable() + "(recipe_user_id);";
}
static String getQueryToCreateAccountInfoIndexForRecipeUserTenantsTable(Start start) {
return "CREATE INDEX IF NOT EXISTS idx_recipe_user_tenants_account_info ON "
+ Config.getConfig(start).getRecipeUserTenantsTable()
+ "(app_id, tenant_id, account_info_type, third_party_id, account_info_value);";
}
static String getQueryToCreatePrimaryUserIndexForPrimaryUserTenantsTable(Start start) {
return "CREATE INDEX IF NOT EXISTS idx_primary_user_tenants_primary ON "
+ Config.getConfig(start).getPrimaryUserTenantsTable() + "(primary_user_id);";
}
private static boolean isPrimaryKeyError(ServerErrorMessage serverMessage, String tableName) {
if (serverMessage == null || tableName == null) {
return false;
}
String[] tableNameParts = tableName.split("\\.");
tableName = tableNameParts[tableNameParts.length - 1];
return "23505".equals(serverMessage.getSQLState()) && serverMessage.getConstraint() != null
&& serverMessage.getConstraint().equals(tableName + "_pkey");
}
private static void throwAccountInfoChangeNotAllowed(ACCOUNT_INFO_TYPE accountInfoType)
throws EmailChangeNotAllowedException, PhoneNumberChangeNotAllowedException {
if (ACCOUNT_INFO_TYPE.EMAIL.equals(accountInfoType)) {
throw new EmailChangeNotAllowedException();
}
if (ACCOUNT_INFO_TYPE.PHONE_NUMBER.equals(accountInfoType)) {
throw new PhoneNumberChangeNotAllowedException();
}
throw new IllegalArgumentException(
"updateAccountInfo_Transaction should only be called with accountInfoType EMAIL or PHONE_NUMBER");
}
private static void throwPrimaryUserTenantsConflict(String[] conflict)
throws AnotherPrimaryUserWithPhoneNumberAlreadyExistsException,
AnotherPrimaryUserWithEmailAlreadyExistsException,
AnotherPrimaryUserWithThirdPartyInfoAlreadyExistsException {
if (conflict == null) {
return;
}
String conflictingPrimaryUserId = conflict[0];
String accountInfoType = conflict[1];
if (ACCOUNT_INFO_TYPE.THIRD_PARTY.toString().equals(accountInfoType)) {
throw new AnotherPrimaryUserWithThirdPartyInfoAlreadyExistsException(conflictingPrimaryUserId);
}
if (ACCOUNT_INFO_TYPE.EMAIL.toString().equals(accountInfoType)) {
throw new AnotherPrimaryUserWithEmailAlreadyExistsException(conflictingPrimaryUserId);
}
if (ACCOUNT_INFO_TYPE.PHONE_NUMBER.toString().equals(accountInfoType)) {
throw new AnotherPrimaryUserWithPhoneNumberAlreadyExistsException(conflictingPrimaryUserId);
}
}
private static void throwRecipeUserTenantsConflict(String accountInfoType, boolean shouldThrowChangeNotAllowedExceptions)
throws DuplicateEmailException, DuplicatePhoneNumberException, DuplicateThirdPartyUserException,
EmailChangeNotAllowedException, PhoneNumberChangeNotAllowedException {
if (accountInfoType == null) {
return;
}
// this can never be updating
if (ACCOUNT_INFO_TYPE.THIRD_PARTY.toString().equals(accountInfoType)) {
throw new DuplicateThirdPartyUserException();
}
if (shouldThrowChangeNotAllowedExceptions) {
if (ACCOUNT_INFO_TYPE.EMAIL.toString().equals(accountInfoType)) {
throw new EmailChangeNotAllowedException();
}
if (ACCOUNT_INFO_TYPE.PHONE_NUMBER.toString().equals(accountInfoType)) {
throw new PhoneNumberChangeNotAllowedException();
}
} else {
if (ACCOUNT_INFO_TYPE.EMAIL.toString().equals(accountInfoType)) {
throw new DuplicateEmailException();
}
if (ACCOUNT_INFO_TYPE.PHONE_NUMBER.toString().equals(accountInfoType)) {
throw new DuplicatePhoneNumberException();
}
}
}
public static void addRecipeUserAccountInfo_Transaction(Start start, Connection sqlCon,
TenantIdentifier tenantIdentifier, String userId,
String recipeId, ACCOUNT_INFO_TYPE accountInfoType,
String thirdPartyId, String thirdPartyUserId,
String accountInfoValue)
throws SQLException {
{
String QUERY = "INSERT INTO " + getConfig(start).getRecipeUserAccountInfosTable()
+ "(app_id, recipe_user_id, recipe_id, account_info_type, third_party_id, third_party_user_id, account_info_value, primary_user_id)"
+ " VALUES(?, ?, ?, ?, ?, ?, ?, ?)";
update(sqlCon, QUERY, pst -> {
pst.setString(1, tenantIdentifier.getAppId());
pst.setString(2, userId);
pst.setString(3, recipeId);
pst.setString(4, accountInfoType.toString());
pst.setString(5, thirdPartyId);
pst.setString(6, thirdPartyUserId);
pst.setString(7, accountInfoValue);
pst.setObject(8, null); // primary_user_id is NULL initially
});
}
{
String QUERY = "INSERT INTO " + getConfig(start).getRecipeUserTenantsTable()
+ "(app_id, recipe_user_id, tenant_id, recipe_id, account_info_type, third_party_id, third_party_user_id, account_info_value)"
+ " VALUES(?, ?, ?, ?, ?, ?, ?, ?)";
update(sqlCon, QUERY, pst -> {
pst.setString(1, tenantIdentifier.getAppId());
pst.setString(2, userId);
pst.setString(3, tenantIdentifier.getTenantId());
pst.setString(4, recipeId);
pst.setString(5, accountInfoType.toString());
pst.setString(6, thirdPartyId);
pst.setString(7, thirdPartyUserId);
pst.setString(8, accountInfoValue);
});
}
}
public static boolean addPrimaryUserAccountInfo_Transaction(Start start, Connection sqlCon, AppIdentifier appIdentifier, String userId) throws
StorageQueryException, AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException,
CannotBecomePrimarySinceRecipeUserIdAlreadyLinkedWithPrimaryUserIdException, UnknownUserIdException {
try {
String schema = Config.getConfig(start).getTableSchema();
String primaryUserTenantsTable = getConfig(start).getPrimaryUserTenantsTable();
String recipeUserTenantsTable = getConfig(start).getRecipeUserTenantsTable();
String recipeUserAccountInfosTable = getConfig(start).getRecipeUserAccountInfosTable();
// Ensure same user doesn't become primary in parallel
io.supertokens.storage.postgresql.queries.Utils.takeAdvisoryLock(sqlCon, appIdentifier.getAppId() + "~" + userId);
// Insert with ON CONFLICT to catch primary key violations
String QUERY = "INSERT INTO " + primaryUserTenantsTable
+ " (app_id, tenant_id, account_info_type, account_info_value, primary_user_id)"
+ " SELECT r.app_id, r.tenant_id, r.account_info_type, r.account_info_value, ?"
+ " FROM " + recipeUserTenantsTable + " r"
+ " INNER JOIN " + recipeUserAccountInfosTable + " ai"
+ " ON r.app_id = ai.app_id"
+ " AND r.recipe_user_id = ai.recipe_user_id"
+ " AND r.recipe_id = ai.recipe_id"
+ " AND r.account_info_type = ai.account_info_type"
+ " AND r.account_info_value = ai.account_info_value"
+ " WHERE r.app_id = ? AND r.recipe_user_id = ? AND ai.primary_user_id IS NULL"
+ " ON CONFLICT ON CONSTRAINT " + Utils.getConstraintName(schema, primaryUserTenantsTable, null, "pkey")
+ " DO UPDATE SET account_info_type = EXCLUDED.account_info_type"
+ " RETURNING primary_user_id, account_info_type";
String[] conflict = execute(sqlCon, QUERY, pst -> {
pst.setString(1, userId); // primary_user_id
pst.setString(2, appIdentifier.getAppId());
pst.setString(3, userId); // recipe_user_id
}, rs -> {
String[] firstConflict = null;
while (rs.next()) {
String returnedPrimaryUserId = rs.getString("primary_user_id");
String accountInfoType = rs.getString("account_info_type");
// Check if the returned primary_user_id is different from the userId
if (!userId.equals(returnedPrimaryUserId)) {
if (firstConflict == null) {
firstConflict = new String[]{returnedPrimaryUserId, accountInfoType};
}
// Prioritize THIRD_PARTY conflicts
if (ACCOUNT_INFO_TYPE.THIRD_PARTY.toString().equals(accountInfoType)) {
return new String[]{returnedPrimaryUserId, accountInfoType};
}
}
}
return firstConflict;
});
// Throw conflict if any row had a different primary_user_id
if (conflict != null) {
assert conflict.length == 2;
String conflictingPrimaryUserId = conflict[0];
String accountInfoType = conflict[1];
String message;
if (ACCOUNT_INFO_TYPE.EMAIL.toString().equals(accountInfoType)) {
message = "This user's email is already associated with another user ID";
} else if (ACCOUNT_INFO_TYPE.PHONE_NUMBER.toString().equals(accountInfoType)) {
message = "This user's phone number is already associated with another user ID";
} else if (ACCOUNT_INFO_TYPE.THIRD_PARTY.toString().equals(accountInfoType)) {
message = "This user's third party login is already associated with another user ID";
} else {
message = "Account info is already associated with another user ID";
}
throw new AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException(conflictingPrimaryUserId, message);
}
// Update primary_user_id in recipe_user_account_infos to recipe_user_id (making it primary)
// Return both old and new primary_user_id values
String UPDATE_QUERY = "WITH old_values AS ("
+ " SELECT primary_user_id FROM " + recipeUserAccountInfosTable
+ " WHERE app_id = ? AND recipe_user_id = ?"
+ " LIMIT 1"
+ ")"
+ " UPDATE " + recipeUserAccountInfosTable
+ " SET primary_user_id = recipe_user_id"
+ " WHERE app_id = ? AND recipe_user_id = ?"
+ " RETURNING (SELECT primary_user_id FROM old_values) AS old_primary_user_id, primary_user_id AS new_primary_user_id";
String[] result = execute(sqlCon, UPDATE_QUERY, pst -> {
pst.setString(1, appIdentifier.getAppId());
pst.setString(2, userId);
pst.setString(3, appIdentifier.getAppId());
pst.setString(4, userId);
}, rs -> {
String[] res = null;
while (rs.next()) {
String oldPrimaryUserId = rs.getString("old_primary_user_id");
String newPrimaryUserId = rs.getString("new_primary_user_id");
res = new String[]{oldPrimaryUserId, newPrimaryUserId};
}
return res;
});
if (result == null) {
throw new UnknownUserIdException();
}
{
String oldPrimaryUserId = result[0];
String newPrimaryUserId = result[1];
if (oldPrimaryUserId != null) {
if (oldPrimaryUserId.equals(newPrimaryUserId)) {
return false; // was already primary
} else {
throw new CannotBecomePrimarySinceRecipeUserIdAlreadyLinkedWithPrimaryUserIdException(oldPrimaryUserId, "This user ID is already linked to another user ID");
}
}
}
// all okay
return true; // now became primary
} catch (SQLException e) {
throw new StorageQueryException(e);
}
}
public static CanBecomePrimaryResult checkIfLoginMethodCanBecomePrimary(Start start, AppIdentifier appIdentifier, String recipeUserId)
throws StorageQueryException, UnknownUserIdException {
try {
return start.startTransaction(con -> {
Connection sqlCon = (Connection) con.getConnection();
String QUERY = "SELECT primary_user_id FROM " + getConfig(start).getRecipeUserAccountInfosTable()
+ " WHERE app_id = ? AND recipe_user_id = ? LIMIT 1";
String[] primaryUserId = execute(sqlCon, QUERY, pst -> {
pst.setString(1, appIdentifier.getAppId());
pst.setString(2, recipeUserId);
}, rs -> {
if (rs.next()) {
return new String[]{rs.getString("primary_user_id")};
}
return new String[]{};
});
if (primaryUserId.length == 0) {
throw new StorageTransactionLogicException(new UnknownUserIdException());
}
assert primaryUserId.length == 1;
if (primaryUserId[0] != null) {
if (primaryUserId[0].equals(recipeUserId)) {
return CanBecomePrimaryResult.wasAlreadyAPrimeryUserResult();
} else {
return CanBecomePrimaryResult.linkedWithAnotherPrimaryUserResult(primaryUserId[0]);
}
}
// now we need to check if the user can become primary by checking if there are conflicting account info
// Get all tenant IDs and account info for this recipe user
String recipeUserTenantsTable = getConfig(start).getRecipeUserTenantsTable();
String primaryUserTenantsTable = getConfig(start).getPrimaryUserTenantsTable();
// Query to find conflicts: check if any account info of this recipe user
// is already associated with a different primary_user_id in primary_user_tenants
String CONFLICT_QUERY = "SELECT p.primary_user_id, p.account_info_type"
+ " FROM " + primaryUserTenantsTable + " p"
+ " INNER JOIN " + recipeUserTenantsTable + " r"
+ " ON p.app_id = r.app_id"
+ " AND p.tenant_id = r.tenant_id"
+ " AND p.account_info_type = r.account_info_type"
+ " AND p.account_info_value = r.account_info_value"
+ " WHERE r.app_id = ?"
+ " AND r.recipe_user_id = ?"
+ " AND p.primary_user_id != ?"
+ " LIMIT 1";
String[] conflict = execute(sqlCon, CONFLICT_QUERY, pst -> {
pst.setString(1, appIdentifier.getAppId());
pst.setString(2, recipeUserId);
pst.setString(3, recipeUserId);
}, rs -> {
if (rs.next()) {
return new String[]{
rs.getString("primary_user_id"),
rs.getString("account_info_type")
};
}
return null;
});
if (conflict != null) {
String conflictingPrimaryUserId = conflict[0];
String accountInfoType = conflict[1];
String message;
if (ACCOUNT_INFO_TYPE.EMAIL.toString().equals(accountInfoType)) {
message = "This user's email is already associated with another user ID";
} else if (ACCOUNT_INFO_TYPE.PHONE_NUMBER.toString().equals(accountInfoType)) {
message = "This user's phone number is already associated with another user ID";
} else if (ACCOUNT_INFO_TYPE.THIRD_PARTY.toString().equals(accountInfoType)) {
message = "This user's third party login is already associated with another user ID";
} else {
message = "Account info is already associated with another primary user";
}
return CanBecomePrimaryResult.conflictingAccountInfoResult(conflictingPrimaryUserId, message);
}
return CanBecomePrimaryResult.okResult();
});
} catch (StorageTransactionLogicException e) {
Exception cause = e.actualException;
if (cause instanceof UnknownUserIdException) {
throw (UnknownUserIdException) cause;
}
throw new StorageQueryException(cause);
}
}
public static CanLinkAccountsResult checkIfLoginMethodsCanBeLinked(Start start,
AppIdentifier appIdentifier,
String _primaryUserId,
String recipeUserId)
throws StorageQueryException, UnknownUserIdException {
try {
return start.startTransaction(con -> {
String primaryUserId;
Connection sqlCon = (Connection) con.getConnection();
{
String QUERY = "SELECT primary_user_id FROM " + getConfig(start).getRecipeUserAccountInfosTable()
+ " WHERE app_id = ? AND recipe_user_id = ? LIMIT 1";
String[] result = execute(sqlCon, QUERY, pst -> {
pst.setString(1, appIdentifier.getAppId());
pst.setString(2, _primaryUserId);
}, rs -> {
if (rs.next()) {
return new String[]{rs.getString("primary_user_id")};
}
return new String[]{};
});
if (result.length == 0) {
throw new StorageTransactionLogicException(new UnknownUserIdException());
}
assert result.length == 1;
if (result[0] == null) {
return CanLinkAccountsResult.inputUserIsNotPrimaryUserResult();
}
primaryUserId = result[0];
}
{
String QUERY = "SELECT primary_user_id FROM " + getConfig(start).getRecipeUserAccountInfosTable()
+ " WHERE app_id = ? AND recipe_user_id = ? LIMIT 1";
String[] result = execute(sqlCon, QUERY, pst -> {
pst.setString(1, appIdentifier.getAppId());
pst.setString(2, recipeUserId);
}, rs -> {
if (rs.next()) {
return new String[]{rs.getString("primary_user_id")};
}
return new String[]{};
});
if (result.length == 0) {
throw new StorageTransactionLogicException(new UnknownUserIdException());
}
assert result.length == 1;
if (result[0] != null) {
if (result[0].equals(primaryUserId)) {
return CanLinkAccountsResult.wasAlreadyLinkedToPrimaryUserResult();
} else {
return CanLinkAccountsResult.recipeUserLinkedToAnotherPrimaryUserResult(result[0]);
}
}
}
String QUERY = "SELECT primary_user_id, account_info_type " +
"FROM " + getConfig(start).getPrimaryUserTenantsTable() + " " +
"WHERE app_id = ? AND ((account_info_type, account_info_value) IN (" +
" (SELECT account_info_type, account_info_value " +
" FROM " + getConfig(start).getPrimaryUserTenantsTable() + " " +
" WHERE app_id = ? AND primary_user_id = ?) " +
" UNION " +
" (SELECT account_info_type, account_info_value " +
" FROM " + getConfig(start).getRecipeUserAccountInfosTable() + " " +
" WHERE app_id = ? AND recipe_user_id = ?)" +
")) AND ((tenant_id) IN (" +
" (SELECT tenant_id " +
" FROM " + getConfig(start).getPrimaryUserTenantsTable() + " " +
" WHERE app_id = ? AND primary_user_id = ?) " +
" UNION " +
" (SELECT tenant_id " +
" FROM " + getConfig(start).getRecipeUserTenantsTable() + " " +
" WHERE app_id = ? AND recipe_user_id = ?)" +
")) AND primary_user_id != ? LIMIT 1;";
String[] result = execute(sqlCon, QUERY, pst -> {
pst.setString(1, appIdentifier.getAppId()); // primary_user_tenants.app_id (main)
pst.setString(2, appIdentifier.getAppId()); // subquery 1: primary_user_tenants.app_id
pst.setString(3, primaryUserId); // subquery 1: primary_user_tenants.primary_user_id
pst.setString(4, appIdentifier.getAppId()); // subquery 2: recipe_user_account_infos.app_id
pst.setString(5, recipeUserId); // subquery 2: recipe_user_account_infos.recipe_user_id
pst.setString(6, appIdentifier.getAppId()); // tenant from primary_user_tenants
pst.setString(7, primaryUserId); // tenant from primary_user_tenants.primary_user_id
pst.setString(8, appIdentifier.getAppId()); // tenant from recipe_user_tenants.app_id
pst.setString(9, recipeUserId); // tenant from recipe_user_tenants.recipe_user_id
pst.setString(10, primaryUserId); // primary user id that's not matching
}, rs -> {
if (rs.next()) {
// Return conflicting primary_user_id and account_info_type
return new String[]{rs.getString("primary_user_id"), rs.getString("account_info_type")};
}
return null;
});
if (result != null && !result[0].equals(primaryUserId)) {
String conflictingPrimaryUserId = result[0];
String accountInfoType = result[1];
String message;
if (ACCOUNT_INFO_TYPE.EMAIL.toString().equals(accountInfoType)) {
message = "This user's email is already associated with another user ID";
} else if (ACCOUNT_INFO_TYPE.PHONE_NUMBER.toString().equals(accountInfoType)) {
message = "This user's phone number is already associated with another user ID";
} else if (ACCOUNT_INFO_TYPE.THIRD_PARTY.toString().equals(accountInfoType)) {
message = "This user's third party login is already associated with another user ID";
} else {
message = "Account info is already associated with another primary user";
}
return CanLinkAccountsResult.notOkResult(conflictingPrimaryUserId, message);
}
return CanLinkAccountsResult.okResult();
});
} catch (StorageTransactionLogicException e) {
Exception cause = e.actualException;
if (cause instanceof UnknownUserIdException) {
throw (UnknownUserIdException) cause;
}
throw new StorageQueryException(cause);
}
}
public static boolean reserveAccountInfoForLinking_Transaction(Start start, Connection sqlCon, AppIdentifier appIdentifier,
String recipeUserId, String _primaryUserId)
throws StorageQueryException, UnknownUserIdException,
InputUserIdIsNotAPrimaryUserException, CannotLinkSinceRecipeUserIdAlreadyLinkedWithAnotherPrimaryUserIdException,
AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException {
try {
String schema = Config.getConfig(start).getTableSchema();
String primaryUserTenantsTable = getConfig(start).getPrimaryUserTenantsTable();
String recipeUserTenantsTable = getConfig(start).getRecipeUserTenantsTable();
String recipeUserAccountInfosTable = getConfig(start).getRecipeUserAccountInfosTable();
// Step 1: Fetch the actual primaryUserId for _primaryUserId
String primaryUserId;
String fetchPrimaryUserIdQuery = "SELECT primary_user_id FROM " + recipeUserAccountInfosTable + " WHERE app_id = ? AND recipe_user_id = ? LIMIT 1";
String[] primaryUserIds = execute(sqlCon, fetchPrimaryUserIdQuery, pst -> {
pst.setString(1, appIdentifier.getAppId());
pst.setString(2, _primaryUserId);
}, rs -> {
if (rs.next()) {
return new String[]{rs.getString("primary_user_id")};
}
return null;
});
if (primaryUserIds == null) {
throw new UnknownUserIdException();
}
if (primaryUserIds[0] == null) {
// if the mapping doesn't show this as a primary user, it means this user is not a primary user
throw new InputUserIdIsNotAPrimaryUserException(_primaryUserId);
}
primaryUserId = primaryUserIds[0];
// Ensure no linking to same user in parallel
io.supertokens.storage.postgresql.queries.Utils.takeAdvisoryLock(sqlCon, appIdentifier.getAppId() + "~" + primaryUserId);
// Step 2: Find all target tenant_ids to write for (union of tenants for the primary user and for the recipe user)
// and find all (account_info_type, account_info_value) for this user (union from both primary and recipe user)
// The select/join/insert operations will now use the retrieved primaryUserId value directly
String QUERY = "INSERT INTO " + primaryUserTenantsTable
+ " (app_id, tenant_id, account_info_type, account_info_value, primary_user_id)"
+ " SELECT ?, all_tenants.tenant_id, all_accounts.account_info_type, all_accounts.account_info_value, ?"
+ " FROM ("
+ " SELECT tenant_id FROM " + primaryUserTenantsTable
+ " WHERE app_id = ? AND primary_user_id = ?"
+ " UNION"
+ " SELECT tenant_id FROM " + recipeUserTenantsTable + " WHERE app_id = ? AND recipe_user_id = ?"
+ " ) all_tenants CROSS JOIN ("
+ " SELECT account_info_type, account_info_value FROM " + primaryUserTenantsTable
+ " WHERE app_id = ? AND primary_user_id = ?"
+ " UNION"
+ " SELECT account_info_type, account_info_value FROM " + recipeUserAccountInfosTable + " WHERE app_id = ? AND recipe_user_id = ? AND primary_user_id is NULL"
+ " ) all_accounts"
+ " ON CONFLICT ON CONSTRAINT " + Utils.getConstraintName(schema, primaryUserTenantsTable, null, "pkey")
+ " DO UPDATE SET account_info_type = EXCLUDED.account_info_type"
+ " RETURNING primary_user_id, account_info_type";
String[] conflict = execute(sqlCon, QUERY, pst -> {
pst.setString(1, appIdentifier.getAppId()); // app_id for INSERT
pst.setString(2, primaryUserId); // primary_user_id for INSERT
pst.setString(3, appIdentifier.getAppId()); // tenant subquery 1: primary_user_tenants.app_id
pst.setString(4, primaryUserId); // tenant subquery 1: primary_user_id
pst.setString(5, appIdentifier.getAppId()); // tenant subquery 2: recipe_user_tenants.app_id
pst.setString(6, recipeUserId); // tenant subquery 2: recipe_user_tenants.recipe_user_id
pst.setString(7, appIdentifier.getAppId()); // account subquery 1: primary_user_tenants.app_id
pst.setString(8, primaryUserId); // account subquery 1: primary_user_id
pst.setString(9, appIdentifier.getAppId()); // account subquery 2: recipe_user_account_infos.app_id
pst.setString(10, recipeUserId); // account subquery 2: recipe_user_account_infos.recipe_user_id
}, rs -> {
String[] firstConflict = null;
while (rs.next()) {
String returnedPrimaryUserId = rs.getString("primary_user_id");
String accountInfoType = rs.getString("account_info_type");
// Check if the returned primary_user_id is different from the expected primaryUserId
if (!primaryUserId.equals(returnedPrimaryUserId)) {
if (firstConflict == null) {
firstConflict = new String[]{returnedPrimaryUserId, accountInfoType};
}
// Prioritize THIRD_PARTY conflicts
if (ACCOUNT_INFO_TYPE.THIRD_PARTY.toString().equals(accountInfoType)) {
return new String[]{returnedPrimaryUserId, accountInfoType};
}
}
}
return firstConflict;
});
// Throw conflict if any row had a different primary_user_id
if (conflict != null && conflict[0] != null) {
String conflictingPrimaryUserId = conflict[0].trim();
String accountInfoType = conflict[1];
String message;
if (ACCOUNT_INFO_TYPE.EMAIL.toString().equals(accountInfoType)) {
message = "This user's email is already associated with another user ID";
} else if (ACCOUNT_INFO_TYPE.PHONE_NUMBER.toString().equals(accountInfoType)) {
message = "This user's phone number is already associated with another user ID";
} else if (ACCOUNT_INFO_TYPE.THIRD_PARTY.toString().equals(accountInfoType)) {
message = "This user's third party login is already associated with another user ID";
} else {
message = "Account info is already associated with another user ID";
}
throw new AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException(conflictingPrimaryUserId, message);
}
// Update primary_user_id in recipe_user_account_infos to link the recipe user to the primary user
String UPDATE_QUERY = "WITH old_values AS ("
+ " SELECT primary_user_id FROM " + recipeUserAccountInfosTable
+ " WHERE app_id = ? AND recipe_user_id = ?"
+ " LIMIT 1"
+ ")"
+ " UPDATE " + recipeUserAccountInfosTable
+ " SET primary_user_id = ?"
+ " WHERE app_id = ? AND recipe_user_id = ?"
+ " RETURNING (SELECT primary_user_id FROM old_values) AS old_primary_user_id, primary_user_id AS new_primary_user_id";
String[] result = execute(sqlCon, UPDATE_QUERY, pst -> {
pst.setString(1, appIdentifier.getAppId());
pst.setString(2, recipeUserId);
pst.setString(3, primaryUserId);
pst.setString(4, appIdentifier.getAppId());
pst.setString(5, recipeUserId);
}, rs -> {
String[] res = null;
while (rs.next()) {
String oldPrimaryUserId = rs.getString("old_primary_user_id");
String newPrimaryUserId = rs.getString("new_primary_user_id");
res = new String[]{oldPrimaryUserId, newPrimaryUserId};
}
return res;
});
if (result == null) {
throw new UnknownUserIdException();
}
{
String oldPrimaryUserId = result[0];
String newPrimaryUserId = result[1];
// If newPrimaryUserId is NULL, it means something went wrong
if (newPrimaryUserId == null) {
throw new InputUserIdIsNotAPrimaryUserException(primaryUserId);
}
if (oldPrimaryUserId != null) {
if (oldPrimaryUserId.equals(newPrimaryUserId)) {
return false; // was already linked to this primary user
} else {
// Fetch the recipe user info to include in the exception
AuthRecipeUserInfo recipeUserInfo = GeneralQueries.getPrimaryUserInfoForUserId_Transaction(
start, sqlCon, appIdentifier, recipeUserId);
if (recipeUserInfo == null) {
throw new UnknownUserIdException();
}
throw new CannotLinkSinceRecipeUserIdAlreadyLinkedWithAnotherPrimaryUserIdException(
recipeUserInfo);
}
}
}
// all okay
return true;
} catch (SQLException e) {
throw new StorageQueryException(e);
}
}
public static void addTenantIdToRecipeUser_Transaction(Start start, Connection sqlCon, TenantIdentifier tenantIdentifier, String userId)
throws StorageQueryException, DuplicateEmailException, DuplicateThirdPartyUserException, DuplicatePhoneNumberException {
String schema = Config.getConfig(start).getTableSchema();
String recipeUserTenantsTable = getConfig(start).getRecipeUserTenantsTable();
String recipeUserAccountInfosTable = getConfig(start).getRecipeUserAccountInfosTable();
String QUERY = "INSERT INTO " + recipeUserTenantsTable
+ " (app_id, recipe_user_id, tenant_id, recipe_id, account_info_type, third_party_id, third_party_user_id, account_info_value)"
+ " SELECT DISTINCT r.app_id, r.recipe_user_id, ?, r.recipe_id, r.account_info_type, r.third_party_id, r.third_party_user_id, r.account_info_value"
+ " FROM " + recipeUserAccountInfosTable + " r"
+ " WHERE r.app_id = ? AND r.recipe_user_id = ?"
+ " ON CONFLICT ON CONSTRAINT " + Utils.getConstraintName(schema, recipeUserTenantsTable, null, "pkey")
+ " DO UPDATE SET account_info_type = EXCLUDED.account_info_type "
+ " RETURNING recipe_user_id, account_info_type";
try {
String conflictAccountInfoType = execute(sqlCon, QUERY, pst -> {
pst.setString(1, tenantIdentifier.getTenantId());
pst.setString(2, tenantIdentifier.getAppId());
pst.setString(3, userId);
}, rs -> {
String firstConflictType = null;
while (rs.next()) {
String returnedRecipeUserId = rs.getString("recipe_user_id");
String accountInfoType = rs.getString("account_info_type");
// Check if the returned recipe_user_id is different from the userId
if (!userId.equals(returnedRecipeUserId)) {
if (firstConflictType == null) {
firstConflictType = accountInfoType;
}
// Prioritize THIRD_PARTY conflicts
if (ACCOUNT_INFO_TYPE.THIRD_PARTY.toString().equals(accountInfoType)) {
return accountInfoType;
}
}
}
return firstConflictType;
});
// Throw conflict if any row had a different recipe_user_id
throwRecipeUserTenantsConflict(conflictAccountInfoType, false);
} catch (EmailChangeNotAllowedException | PhoneNumberChangeNotAllowedException e) {
throw new IllegalStateException("should never happen", e);
} catch (SQLException e) {
throw new StorageQueryException(e);
}
}
public static void addTenantIdToPrimaryUser_Transaction(Start start, TransactionConnection con, TenantIdentifier tenantIdentifier, String supertokensUserId)
throws StorageQueryException,
AnotherPrimaryUserWithPhoneNumberAlreadyExistsException,
AnotherPrimaryUserWithEmailAlreadyExistsException,
AnotherPrimaryUserWithThirdPartyInfoAlreadyExistsException {
Connection sqlCon = (Connection) con.getConnection();
String schema = Config.getConfig(start).getTableSchema();
String primaryUserTenantsTable = getConfig(start).getPrimaryUserTenantsTable();
String recipeUserAccountInfosTable = getConfig(start).getRecipeUserAccountInfosTable();
String QUERY = "INSERT INTO " + primaryUserTenantsTable
+ " (app_id, tenant_id, account_info_type, account_info_value, primary_user_id)"
+ " SELECT rac.app_id, ?, rac.account_info_type, rac.account_info_value, rac.primary_user_id"
+ " FROM " + recipeUserAccountInfosTable + " rac"
+ " WHERE rac.app_id = ? AND rac.recipe_user_id = ?"
+ " ON CONFLICT ON CONSTRAINT " + Utils.getConstraintName(schema, primaryUserTenantsTable, null, "pkey")
+ " DO UPDATE SET account_info_type = EXCLUDED.account_info_type "
+ " RETURNING primary_user_id, account_info_type";
try {
String[] conflict = execute(sqlCon, QUERY, pst -> {
pst.setString(1, tenantIdentifier.getTenantId());
pst.setString(2, tenantIdentifier.getAppId());
pst.setString(3, supertokensUserId);
}, rs -> {
String[] firstConflict = null;
while (rs.next()) {
String returnedPrimaryUserId = rs.getString("primary_user_id");
String accountInfoType = rs.getString("account_info_type");
// Check if the returned primary_user_id is different from the supertokensUserId
if (!supertokensUserId.equals(returnedPrimaryUserId)) {
if (firstConflict == null) {
firstConflict = new String[]{returnedPrimaryUserId, accountInfoType};
}
// Prioritize THIRD_PARTY conflicts
if (ACCOUNT_INFO_TYPE.THIRD_PARTY.toString().equals(accountInfoType)) {
return new String[]{returnedPrimaryUserId, accountInfoType};
}
}
}
return firstConflict;
});
// Throw conflict if any row had a different primary_user_id
throwPrimaryUserTenantsConflict(conflict);
} catch (SQLException e) {
throw new StorageQueryException(e);
}
}
public static void removeAccountInfoForRecipeUserWhileRemovingTenant_Transaction(Start start, Connection sqlCon, TenantIdentifier tenantIdentifier, String userId) throws StorageQueryException {
try {
String QUERY = "DELETE FROM " + getConfig(start).getRecipeUserTenantsTable()
+ " WHERE app_id = ? AND tenant_id = ? AND recipe_user_id = ?";
update(sqlCon, QUERY, pst -> {
pst.setString(1, tenantIdentifier.getAppId());
pst.setString(2, tenantIdentifier.getTenantId());
pst.setString(3, userId);
});
} catch (SQLException e) {
throw new StorageQueryException(e);
}
}
public static void removeAccountInfoReservationForPrimaryUserWhileRemovingTenant_Transaction(Start start, Connection sqlCon, TenantIdentifier tenantIdentifier, String userId) throws StorageQueryException {
try {
String primaryUserTenantsTable = getConfig(start).getPrimaryUserTenantsTable();
String recipeUserAccountInfosTable = getConfig(start).getRecipeUserAccountInfosTable();
String recipeUserTenantsTable = getConfig(start).getRecipeUserTenantsTable();
// This query removes rows from the primary_user_tenants table for the given primary user (identified by the passed-in userId),
// but only for those tenants that the user is no longer associated with after a tenant removal operation.
// It does so by:
// 1. Identifying the primary_user_id linked to the given recipe_user (by userId).
// 2. Deleting only those primary_user_tenants rows (for this app and primary_user_id) whose tenant_id is NOT present
// in the list of tenants remaining for any of the primary user's linked recipe users,
// except for the tenant/user combination being removed (i.e., tenant_id != removed tenant).
// 3. Effectively, this ensures that account info reservations in primary_user_tenants only remain on tenants
// where the primary user (or any linked user) is still active after this tenant of user is removed.
String QUERY = "DELETE FROM " + primaryUserTenantsTable
+ " WHERE app_id = ? AND primary_user_id IN ("
+ " SELECT primary_user_id FROM " + recipeUserAccountInfosTable + " WHERE recipe_user_id = ? LIMIT 1"
+ " ) AND (tenant_id) NOT IN ("
+ " SELECT DISTINCT tenant_id"
+ " FROM " + recipeUserTenantsTable
+ " WHERE recipe_user_id IN ("
+ " SELECT recipe_user_id"
+ " FROM " + recipeUserAccountInfosTable
+ " WHERE primary_user_id IN ("
+ " SELECT primary_user_id FROM " + recipeUserAccountInfosTable
+ " WHERE recipe_user_id = ? LIMIT 1"
+ " ) AND ((recipe_user_id = ? AND tenant_id != ?) OR recipe_user_id != ?)"
+ " )"
+ " )";
update(sqlCon, QUERY, pst -> {
pst.setString(1, tenantIdentifier.getAppId());
pst.setString(2, userId);
pst.setString(3, userId);
pst.setString(4, userId);
pst.setString(5, tenantIdentifier.getTenantId());
pst.setString(6, userId);
});
} catch (SQLException e) {
throw new StorageQueryException(e);
}
}
public static void removeAccountInfoReservationForPrimaryUserForUnlinking_Transaction(Start start, Connection sqlCon, AppIdentifier tenantIdentifier, String userId) throws StorageQueryException {
try {
String primaryUserTenantsTable = getConfig(start).getPrimaryUserTenantsTable();
String recipeUserAccountInfosTable = getConfig(start).getRecipeUserAccountInfosTable();
String recipeUserTenantsTable = getConfig(start).getRecipeUserTenantsTable();
// This query removes rows from the primary_user_tenants table for the given primary user (identified by the passed-in userId),
// but only for those account info and tenant combinations that the user is no longer associated with after an unlinking operation.
// It does so by:
// 1. Identifying the primary_user_id linked to the given recipe_user (by userId).
// 2. Deleting only those primary_user_tenants rows (for this app and primary_user_id) where:
// a) The (account_info_type, account_info_value) combination is NOT present in any other linked recipe user's
// recipe_user_tenants, OR
// b) The tenant_id is NOT present in any other linked recipe user's recipe_user_tenants.
// 3. Effectively, this ensures that account info reservations in primary_user_tenants only remain where
// the primary user (or any other linked user) still has that account info or tenant after this user is unlinked.
String QUERY = "DELETE FROM " + primaryUserTenantsTable
+ " WHERE app_id = ? AND primary_user_id IN ("
+ " SELECT primary_user_id FROM " + recipeUserAccountInfosTable + " WHERE app_id = ? AND recipe_user_id = ? LIMIT 1"
+ " ) AND ("
+ " (account_info_type, account_info_value) NOT IN ("
+ " SELECT DISTINCT account_info_type, account_info_value"
+ " FROM " + recipeUserAccountInfosTable
+ " WHERE app_id = ? AND primary_user_id IN ("
+ " SELECT primary_user_id FROM " + recipeUserAccountInfosTable
+ " WHERE app_id = ? AND recipe_user_id = ? LIMIT 1"
+ " ) AND recipe_user_id <> ?"
+ " )"
+ " OR tenant_id NOT IN ("
+ " SELECT DISTINCT tenant_id"
+ " FROM " + recipeUserTenantsTable
+ " WHERE app_id = ? AND recipe_user_id IN ("
+ " SELECT recipe_user_id"
+ " FROM " + recipeUserAccountInfosTable
+ " WHERE app_id = ? AND primary_user_id IN ("
+ " SELECT primary_user_id FROM " + recipeUserAccountInfosTable
+ " WHERE app_id = ? AND recipe_user_id = ? LIMIT 1"
+ " ) AND recipe_user_id <> ?"
+ " )"
+ " )"
+ " )";
update(sqlCon, QUERY, pst -> {
pst.setString(1, tenantIdentifier.getAppId()); // WHERE app_id = ?
pst.setString(2, tenantIdentifier.getAppId()); // SELECT ... WHERE app_id = ?
pst.setString(3, userId); // ... AND recipe_user_id = ?
pst.setString(4, tenantIdentifier.getAppId()); // WHERE app_id = ? (NOT IN clause)
pst.setString(5, tenantIdentifier.getAppId()); // SELECT ... WHERE app_id = ? (nested)
pst.setString(6, userId); // ... AND recipe_user_id = ? (nested)
pst.setString(7, userId); // ... AND recipe_user_id <> ?
pst.setString(8, tenantIdentifier.getAppId()); // WHERE app_id = ? (tenant_id NOT IN)
pst.setString(9, tenantIdentifier.getAppId()); // WHERE app_id = ? (nested in tenant_id NOT IN)
pst.setString(10, tenantIdentifier.getAppId()); // SELECT ... WHERE app_id = ? (deeply nested)