Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions src/export/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,57 @@ describe('Database Operations Module', () => {
])
})

it('should quote table names that require identifiers in data queries', async () => {
vi.mocked(executeTransaction)
.mockResolvedValueOnce([{ name: "kid's profiles" }])
.mockResolvedValueOnce([{ id: 1, name: 'Alice' }])

const result = await getTableData(
"kid's profiles",
mockDataSource,
mockConfig
)

expect(executeTransaction).toHaveBeenNthCalledWith(1, {
queries: [
{
sql: "SELECT name FROM sqlite_master WHERE type='table' AND name=?;",
params: ["kid's profiles"],
},
],
isRaw: false,
dataSource: mockDataSource,
config: mockConfig,
})
expect(executeTransaction).toHaveBeenNthCalledWith(2, {
queries: [{ sql: 'SELECT * FROM "kid\'s profiles";' }],
isRaw: false,
dataSource: mockDataSource,
config: mockConfig,
})
expect(result).toEqual([{ id: 1, name: 'Alice' }])
})

it('should quote reserved table names in data queries', async () => {
vi.mocked(executeTransaction)
.mockResolvedValueOnce([{ name: 'order' }])
.mockResolvedValueOnce([{ id: 1 }])

const result = await getTableData(
'order',
mockDataSource,
mockConfig
)

expect(executeTransaction).toHaveBeenNthCalledWith(2, {
queries: [{ sql: 'SELECT * FROM "order";' }],
isRaw: false,
dataSource: mockDataSource,
config: mockConfig,
})
expect(result).toEqual([{ id: 1 }])
})

it('should return null if table does not exist', async () => {
vi.mocked(executeTransaction).mockResolvedValueOnce([])

Expand Down
32 changes: 31 additions & 1 deletion src/export/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,36 @@ import { DataSource } from '../types'
import { executeTransaction } from '../operation'
import { StarbaseDBConfiguration } from '../handler'

const sqliteKeywords = new Set([
'select',
'from',
'where',
'table',
'index',
'insert',
'values',
'order',
'group',
'by',
'limit',
'offset',
'join',
'on',
'and',
'or',
])

function formatIdentifier(identifier: string) {
if (
/^[A-Za-z_][A-Za-z0-9_]*$/.test(identifier) &&
!sqliteKeywords.has(identifier.toLowerCase())
) {
return identifier
}

return `"${identifier.replace(/"/g, '""')}"`
}

export async function executeOperation(
queries: { sql: string; params?: any[] }[],
dataSource: DataSource,
Expand Down Expand Up @@ -43,7 +73,7 @@ export async function getTableData(

// Get table data
const dataResult = await executeOperation(
[{ sql: `SELECT * FROM ${tableName};` }],
[{ sql: `SELECT * FROM ${formatIdentifier(tableName)};` }],
dataSource,
config
)
Expand Down