|
| 1 | +//go:build all || integration |
| 2 | +// +build all integration |
| 3 | + |
| 4 | +package gocql |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "fmt" |
| 9 | + "testing" |
| 10 | +) |
| 11 | + |
| 12 | +// Keyspace_table checks if Query.Keyspace() is updated based on prepared statement |
| 13 | +func TestKeyspaceTable(t *testing.T) { |
| 14 | + cluster := createCluster() |
| 15 | + |
| 16 | + fallback := RoundRobinHostPolicy() |
| 17 | + cluster.PoolConfig.HostSelectionPolicy = TokenAwareHostPolicy(fallback) |
| 18 | + |
| 19 | + session, err := cluster.CreateSession() |
| 20 | + if err != nil { |
| 21 | + t.Fatal("createSession:", err) |
| 22 | + } |
| 23 | + |
| 24 | + cluster.Keyspace = "wrong_keyspace" |
| 25 | + |
| 26 | + keyspace := "test1" |
| 27 | + table := "table1" |
| 28 | + |
| 29 | + err = createTable(session, `DROP KEYSPACE IF EXISTS `+keyspace) |
| 30 | + if err != nil { |
| 31 | + t.Fatal("unable to drop keyspace:", err) |
| 32 | + } |
| 33 | + |
| 34 | + err = createTable(session, fmt.Sprintf(`CREATE KEYSPACE %s |
| 35 | + WITH replication = { |
| 36 | + 'class' : 'SimpleStrategy', |
| 37 | + 'replication_factor' : 1 |
| 38 | + }`, keyspace)) |
| 39 | + |
| 40 | + if err != nil { |
| 41 | + t.Fatal("unable to create keyspace:", err) |
| 42 | + } |
| 43 | + |
| 44 | + if err := session.control.awaitSchemaAgreement(); err != nil { |
| 45 | + t.Fatal(err) |
| 46 | + } |
| 47 | + |
| 48 | + err = createTable(session, fmt.Sprintf(`CREATE TABLE %s.%s (pk int, ck int, v int, PRIMARY KEY (pk, ck)); |
| 49 | + `, keyspace, table)) |
| 50 | + |
| 51 | + if err != nil { |
| 52 | + t.Fatal("unable to create table:", err) |
| 53 | + } |
| 54 | + |
| 55 | + if err := session.control.awaitSchemaAgreement(); err != nil { |
| 56 | + t.Fatal(err) |
| 57 | + } |
| 58 | + |
| 59 | + ctx := context.Background() |
| 60 | + |
| 61 | + // insert a row |
| 62 | + if err := session.Query(`INSERT INTO test1.table1(pk, ck, v) VALUES (?, ?, ?)`, |
| 63 | + 1, 2, 3).WithContext(ctx).Consistency(One).Exec(); err != nil { |
| 64 | + t.Fatal(err) |
| 65 | + } |
| 66 | + |
| 67 | + var pk int |
| 68 | + |
| 69 | + /* Search for a specific set of records whose 'pk' column matches |
| 70 | + * the value of inserted row. */ |
| 71 | + qry := session.Query(`SELECT pk FROM test1.table1 WHERE pk = ? LIMIT 1`, |
| 72 | + 1).WithContext(ctx).Consistency(One) |
| 73 | + if err := qry.Scan(&pk); err != nil { |
| 74 | + t.Fatal(err) |
| 75 | + } |
| 76 | + |
| 77 | + // cluster.Keyspace was set to "wrong_keyspace", but during prepering statement |
| 78 | + // Keyspace in Query should be changed to "test" and Table should be changed to table1 |
| 79 | + assertEqual(t, "qry.Keyspace()", "test1", qry.Keyspace()) |
| 80 | + assertEqual(t, "qry.Table()", "table1", qry.Table()) |
| 81 | +} |
0 commit comments