-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathexpander_test.go
More file actions
455 lines (412 loc) · 12.1 KB
/
expander_test.go
File metadata and controls
455 lines (412 loc) · 12.1 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
package expander
import (
"context"
"database/sql"
"database/sql/driver"
"fmt"
"os"
"testing"
"github.com/go-sql-driver/mysql"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/ncruces/go-sqlite3"
"github.com/sqlc-dev/sqlc/internal/engine/dolphin"
"github.com/sqlc-dev/sqlc/internal/engine/postgresql"
"github.com/sqlc-dev/sqlc/internal/engine/sqlite"
"github.com/sqlc-dev/sqlc/internal/sqltest/docker"
"github.com/sqlc-dev/sqlc/internal/sqltest/native"
)
// PostgreSQLColumnGetter implements ColumnGetter for PostgreSQL using pgxpool.
type PostgreSQLColumnGetter struct {
pool *pgxpool.Pool
}
func (g *PostgreSQLColumnGetter) GetColumnNames(ctx context.Context, query string) ([]string, error) {
conn, err := g.pool.Acquire(ctx)
if err != nil {
return nil, err
}
defer conn.Release()
desc, err := conn.Conn().Prepare(ctx, "", query)
if err != nil {
return nil, err
}
columns := make([]string, len(desc.Fields))
for i, field := range desc.Fields {
columns[i] = field.Name
}
return columns, nil
}
// MySQLColumnGetter implements ColumnGetter for MySQL using the forked driver's StmtMetadata.
type MySQLColumnGetter struct {
db *sql.DB
}
func (g *MySQLColumnGetter) GetColumnNames(ctx context.Context, query string) ([]string, error) {
conn, err := g.db.Conn(ctx)
if err != nil {
return nil, err
}
defer conn.Close()
var columns []string
err = conn.Raw(func(driverConn any) error {
preparer, ok := driverConn.(driver.ConnPrepareContext)
if !ok {
return fmt.Errorf("driver connection does not support PrepareContext")
}
stmt, err := preparer.PrepareContext(ctx, query)
if err != nil {
return err
}
defer stmt.Close()
meta, ok := stmt.(mysql.StmtMetadata)
if !ok {
return fmt.Errorf("prepared statement does not implement StmtMetadata")
}
for _, col := range meta.ColumnMetadata() {
columns = append(columns, col.Name)
}
return nil
})
if err != nil {
return nil, err
}
return columns, nil
}
// SQLiteColumnGetter implements ColumnGetter for SQLite using the native ncruces/go-sqlite3 API.
type SQLiteColumnGetter struct {
conn *sqlite3.Conn
}
func (g *SQLiteColumnGetter) GetColumnNames(ctx context.Context, query string) ([]string, error) {
// Prepare the statement - this gives us column metadata without executing
stmt, _, err := g.conn.Prepare(query)
if err != nil {
return nil, err
}
defer stmt.Close()
// Get column names from the prepared statement
count := stmt.ColumnCount()
columns := make([]string, count)
for i := 0; i < count; i++ {
columns[i] = stmt.ColumnName(i)
}
return columns, nil
}
func TestExpandPostgreSQL(t *testing.T) {
ctx := context.Background()
uri := os.Getenv("POSTGRESQL_SERVER_URI")
if uri == "" {
if err := docker.Installed(); err == nil {
u, err := docker.StartPostgreSQLServer(ctx)
if err != nil {
t.Fatal(err)
}
uri = u
} else if err := native.Supported(); err == nil {
u, err := native.StartPostgreSQLServer(ctx)
if err != nil {
t.Fatal(err)
}
uri = u
} else {
t.Skip("POSTGRESQL_SERVER_URI is empty and neither Docker nor native installation is available")
}
}
pool, err := pgxpool.New(ctx, uri)
if err != nil {
t.Skipf("could not connect to database: %v", err)
}
defer pool.Close()
// Create a test table
_, err = pool.Exec(ctx, `
DROP TABLE IF EXISTS authors;
CREATE TABLE authors (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
bio TEXT
);
`)
if err != nil {
t.Fatalf("failed to create test table: %v", err)
}
defer pool.Exec(ctx, "DROP TABLE IF EXISTS authors")
// Create the parser which also implements format.Dialect
parser := postgresql.NewParser()
// Create the expander
colGetter := &PostgreSQLColumnGetter{pool: pool}
exp := New(colGetter, parser, parser)
tests := []struct {
name string
query string
expected string
}{
{
name: "simple select star",
query: "SELECT * FROM authors",
expected: "SELECT id, name, bio FROM authors;",
},
{
name: "select with no star",
query: "SELECT id, name FROM authors",
expected: "SELECT id, name FROM authors", // No change, returns original
},
{
name: "select star with where clause",
query: "SELECT * FROM authors WHERE id = 1",
expected: "SELECT id, name, bio FROM authors WHERE id = 1;",
},
{
name: "double star",
query: "SELECT *, * FROM authors",
expected: "SELECT id, name, bio, id, name, bio FROM authors;",
},
{
name: "table qualified star",
query: "SELECT authors.* FROM authors",
expected: "SELECT authors.id, authors.name, authors.bio FROM authors;",
},
{
name: "star in middle of columns",
query: "SELECT id, *, name FROM authors",
expected: "SELECT id, id, name, bio, name FROM authors;",
},
{
name: "insert returning star",
query: "INSERT INTO authors (name, bio) VALUES ('John', 'A writer') RETURNING *",
expected: "INSERT INTO authors (name, bio) VALUES ('John', 'A writer') RETURNING id, name, bio;",
},
{
name: "insert returning mixed",
query: "INSERT INTO authors (name, bio) VALUES ('John', 'A writer') RETURNING id, *",
expected: "INSERT INTO authors (name, bio) VALUES ('John', 'A writer') RETURNING id, id, name, bio;",
},
{
name: "update returning star",
query: "UPDATE authors SET name = 'Jane' WHERE id = 1 RETURNING *",
expected: "UPDATE authors SET name = 'Jane' WHERE id = 1 RETURNING id, name, bio;",
},
{
name: "delete returning star",
query: "DELETE FROM authors WHERE id = 1 RETURNING *",
expected: "DELETE FROM authors WHERE id = 1 RETURNING id, name, bio;",
},
{
name: "cte with select star",
query: "WITH a AS (SELECT * FROM authors) SELECT * FROM a",
expected: "WITH a AS (SELECT id, name, bio FROM authors) SELECT id, name, bio FROM a;",
},
{
name: "multiple ctes with dependency",
query: "WITH a AS (SELECT * FROM authors), b AS (SELECT * FROM a) SELECT * FROM b",
expected: "WITH a AS (SELECT id, name, bio FROM authors), b AS (SELECT id, name, bio FROM a) SELECT id, name, bio FROM b;",
},
{
name: "count star not expanded",
query: "SELECT COUNT(*) FROM authors",
expected: "SELECT COUNT(*) FROM authors", // No change - COUNT(*) should not be expanded
},
{
name: "count star with other columns",
query: "SELECT COUNT(*), name FROM authors GROUP BY name",
expected: "SELECT COUNT(*), name FROM authors GROUP BY name", // No change
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
result, err := exp.Expand(ctx, tc.query)
if err != nil {
t.Fatalf("Expand failed: %v", err)
}
if result != tc.expected {
t.Errorf("expected %q, got %q", tc.expected, result)
}
})
}
}
func TestExpandMySQL(t *testing.T) {
ctx := context.Background()
source := os.Getenv("MYSQL_SERVER_URI")
if source == "" {
if err := docker.Installed(); err == nil {
u, err := docker.StartMySQLServer(ctx)
if err != nil {
t.Fatal(err)
}
source = u
} else if err := native.Supported(); err == nil {
u, err := native.StartMySQLServer(ctx)
if err != nil {
t.Fatal(err)
}
source = u
} else {
t.Skip("MYSQL_SERVER_URI is empty and neither Docker nor native installation is available")
}
}
db, err := sql.Open("mysql", source)
if err != nil {
t.Skipf("could not connect to MySQL: %v", err)
}
defer db.Close()
// Verify connection
if err := db.Ping(); err != nil {
t.Skipf("could not ping MySQL: %v", err)
}
// Create a test table
_, err = db.ExecContext(ctx, `DROP TABLE IF EXISTS authors`)
if err != nil {
t.Fatalf("failed to drop test table: %v", err)
}
_, err = db.ExecContext(ctx, `
CREATE TABLE authors (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
bio TEXT
)
`)
if err != nil {
t.Fatalf("failed to create test table: %v", err)
}
defer db.ExecContext(ctx, "DROP TABLE IF EXISTS authors")
// Create the parser which also implements format.Dialect
parser := dolphin.NewParser()
// Create the expander
colGetter := &MySQLColumnGetter{db: db}
exp := New(colGetter, parser, parser)
tests := []struct {
name string
query string
expected string
}{
{
name: "simple select star",
query: "SELECT * FROM authors",
expected: "SELECT id, name, bio FROM authors;",
},
{
name: "select with no star",
query: "SELECT id, name FROM authors",
expected: "SELECT id, name FROM authors", // No change, returns original
},
{
name: "select star with where clause",
query: "SELECT * FROM authors WHERE id = 1",
expected: "SELECT id, name, bio FROM authors WHERE id = 1;",
},
{
name: "table qualified star",
query: "SELECT authors.* FROM authors",
expected: "SELECT authors.id, authors.name, authors.bio FROM authors;",
},
{
name: "double table qualified star",
query: "SELECT authors.*, authors.* FROM authors",
expected: "SELECT authors.id, authors.name, authors.bio, authors.id, authors.name, authors.bio FROM authors;",
},
{
name: "star in middle of columns table qualified",
query: "SELECT id, authors.*, name FROM authors",
expected: "SELECT id, authors.id, authors.name, authors.bio, name FROM authors;",
},
{
name: "count star not expanded",
query: "SELECT COUNT(*) FROM authors",
expected: "SELECT COUNT(*) FROM authors", // No change - COUNT(*) should not be expanded
},
{
name: "count star with other columns",
query: "SELECT COUNT(*), name FROM authors GROUP BY name",
expected: "SELECT COUNT(*), name FROM authors GROUP BY name", // No change
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
result, err := exp.Expand(ctx, tc.query)
if err != nil {
t.Fatalf("Expand failed: %v", err)
}
if result != tc.expected {
t.Errorf("expected %q, got %q", tc.expected, result)
}
})
}
}
func TestExpandSQLite(t *testing.T) {
ctx := context.Background()
// Create an in-memory SQLite database using native API
conn, err := sqlite3.Open(":memory:")
if err != nil {
t.Fatalf("could not open SQLite: %v", err)
}
defer conn.Close()
// Create a test table
err = conn.Exec(`
CREATE TABLE authors (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
bio TEXT
)
`)
if err != nil {
t.Fatalf("failed to create test table: %v", err)
}
// Create the parser which also implements format.Dialect
parser := sqlite.NewParser()
// Create the expander using native SQLite column getter
colGetter := &SQLiteColumnGetter{conn: conn}
exp := New(colGetter, parser, parser)
tests := []struct {
name string
query string
expected string
}{
{
name: "simple select star",
query: "SELECT * FROM authors",
expected: "SELECT id, name, bio FROM authors;",
},
{
name: "select with no star",
query: "SELECT id, name FROM authors",
expected: "SELECT id, name FROM authors", // No change, returns original
},
{
name: "select star with where clause",
query: "SELECT * FROM authors WHERE id = 1",
expected: "SELECT id, name, bio FROM authors WHERE id = 1;",
},
{
name: "double star",
query: "SELECT *, * FROM authors",
expected: "SELECT id, name, bio, id, name, bio FROM authors;",
},
{
name: "table qualified star",
query: "SELECT authors.* FROM authors",
expected: "SELECT authors.id, authors.name, authors.bio FROM authors;",
},
{
name: "star in middle of columns",
query: "SELECT id, *, name FROM authors",
expected: "SELECT id, id, name, bio, name FROM authors;",
},
{
name: "count star not expanded",
query: "SELECT COUNT(*) FROM authors",
expected: "SELECT COUNT(*) FROM authors", // No change - COUNT(*) should not be expanded
},
{
name: "count star with other columns",
query: "SELECT COUNT(*), name FROM authors GROUP BY name",
expected: "SELECT COUNT(*), name FROM authors GROUP BY name", // No change
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
result, err := exp.Expand(ctx, tc.query)
if err != nil {
t.Fatalf("Expand failed: %v", err)
}
if result != tc.expected {
t.Errorf("expected %q, got %q", tc.expected, result)
}
})
}
}