connection.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  1. package pgserver
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/binary"
  6. "encoding/hex"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "log"
  11. "net"
  12. "regexp"
  13. "sort"
  14. "strconv"
  15. "strings"
  16. "github.com/danfragoso/pizzasql-next/pkg/executor"
  17. "github.com/danfragoso/pizzasql-next/pkg/lexer"
  18. "github.com/danfragoso/pizzasql-next/pkg/parser"
  19. "github.com/danfragoso/pizzasql-next/pkg/storage"
  20. "github.com/danfragoso/pizzasql-next/pkg/version"
  21. )
  22. // Connection represents a client connection
  23. type Connection struct {
  24. conn net.Conn
  25. reader *bufio.Reader
  26. writer *bufio.Writer
  27. executor *executor.Executor
  28. schema *storage.SchemaManager
  29. dbManager *storage.DatabaseManager
  30. database string
  31. params map[string]string
  32. txStatus byte
  33. quiet bool // Disable query logging
  34. statements map[string]*preparedStatement
  35. portals map[string]*portal
  36. extendedFailed bool
  37. }
  38. type preparedStatement struct {
  39. query string
  40. paramOIDs []int32
  41. }
  42. type portal struct {
  43. query string
  44. executed bool
  45. }
  46. // NewConnection creates a new connection handler
  47. func NewConnection(conn net.Conn, dbManager *storage.DatabaseManager, quiet bool) *Connection {
  48. return &Connection{
  49. conn: conn,
  50. reader: bufio.NewReader(conn),
  51. writer: bufio.NewWriter(conn),
  52. dbManager: dbManager,
  53. params: make(map[string]string),
  54. statements: make(map[string]*preparedStatement),
  55. portals: make(map[string]*portal),
  56. txStatus: TxStatusIdle,
  57. quiet: quiet,
  58. }
  59. }
  60. // Handle processes the connection
  61. func (c *Connection) Handle() error {
  62. defer func() {
  63. if c.executor != nil {
  64. if err := c.executor.RollbackActive(); err != nil && !c.quiet {
  65. log.Printf("failed to roll back disconnected transaction: %v", err)
  66. }
  67. }
  68. c.conn.Close()
  69. }()
  70. // First, check for SSL request (sent before startup message)
  71. // SSL request is 8 bytes: length(4) + code(4) where code = 80877103
  72. firstBytes := make([]byte, 8)
  73. n, err := io.ReadFull(c.reader, firstBytes)
  74. if err != nil {
  75. return fmt.Errorf("failed to read initial bytes: %w", err)
  76. }
  77. // Check if it's an SSL request (code 80877103 = 0x04D2162F)
  78. if n == 8 {
  79. length := binary.BigEndian.Uint32(firstBytes[0:4])
  80. code := binary.BigEndian.Uint32(firstBytes[4:8])
  81. if length == 8 && code == 80877103 {
  82. // SSL request - we don't support SSL, send 'N'
  83. if !c.quiet {
  84. log.Printf("Client requested SSL, sending rejection")
  85. }
  86. if _, err := c.conn.Write([]byte{'N'}); err != nil {
  87. return fmt.Errorf("failed to send SSL rejection: %w", err)
  88. }
  89. // Now read the actual startup message
  90. } else {
  91. // Not SSL request, this is part of startup message
  92. // We need to prepend these bytes back for ReadStartupMessage
  93. // Create a multi-reader that first reads our buffered bytes, then continues with the reader
  94. c.reader = bufio.NewReader(io.MultiReader(bytes.NewReader(firstBytes), c.reader))
  95. }
  96. }
  97. // Read startup message
  98. if !c.quiet {
  99. log.Printf("Reading startup message...")
  100. }
  101. params, err := ReadStartupMessage(c.reader)
  102. if err != nil {
  103. return fmt.Errorf("failed to read startup message: %w", err)
  104. }
  105. c.params = params
  106. if !c.quiet {
  107. log.Printf("Startup params: %+v", params)
  108. }
  109. // Get database name from params (default to "pizzasql")
  110. dbName := params["database"]
  111. if dbName == "" {
  112. dbName = "pizzasql"
  113. }
  114. c.database = dbName
  115. if !c.quiet {
  116. log.Printf("New connection: user=%s database=%s", params["user"], dbName)
  117. }
  118. // Initialize database
  119. if err := c.initDatabase(dbName); err != nil {
  120. c.sendError("FATAL", ErrCodeConnectionFailure, fmt.Sprintf("Failed to initialize database: %v", err))
  121. return err
  122. }
  123. // Send authentication OK (no auth for now)
  124. if err := c.sendAuthenticationOk(); err != nil {
  125. return err
  126. }
  127. // Send parameter status messages
  128. if err := c.sendParameterStatus("server_version", version.PostgreSQLCompatVersion+" (PizzaSQL)"); err != nil {
  129. return err
  130. }
  131. // Build identity is a separate, custom ParameterStatus so the PostgreSQL
  132. // compatibility string above stays stable for version-sniffing drivers.
  133. if err := c.sendParameterStatus("pizzasql.version", version.String()); err != nil {
  134. return err
  135. }
  136. if err := c.sendParameterStatus("pizzasql.commit", version.Commit); err != nil {
  137. return err
  138. }
  139. if err := c.sendParameterStatus("server_encoding", "UTF8"); err != nil {
  140. return err
  141. }
  142. if err := c.sendParameterStatus("client_encoding", "UTF8"); err != nil {
  143. return err
  144. }
  145. if err := c.sendParameterStatus("DateStyle", "ISO, MDY"); err != nil {
  146. return err
  147. }
  148. if err := c.sendParameterStatus("TimeZone", "UTC"); err != nil {
  149. return err
  150. }
  151. // Send backend key data (for cancellation - we don't implement this yet)
  152. if err := c.sendBackendKeyData(12345, 67890); err != nil {
  153. return err
  154. }
  155. // Send ready for query
  156. if err := c.sendReadyForQuery(); err != nil {
  157. return err
  158. }
  159. // Message loop
  160. for {
  161. msg, err := ReadMessage(c.reader)
  162. if err != nil {
  163. if err == io.EOF {
  164. log.Printf("Connection closed by client")
  165. return nil
  166. }
  167. return fmt.Errorf("failed to read message: %w", err)
  168. }
  169. if err := c.handleMessage(msg); err != nil {
  170. if err == io.EOF {
  171. // Normal termination
  172. log.Printf("Connection closed normally")
  173. return nil
  174. }
  175. log.Printf("Error handling message: %v", err)
  176. return err
  177. }
  178. }
  179. }
  180. // initDatabase initializes the database connection
  181. func (c *Connection) initDatabase(dbName string) error {
  182. db, err := c.dbManager.GetDatabase(dbName)
  183. if err != nil {
  184. return err
  185. }
  186. c.schema = db.Schema
  187. c.executor = executor.New(db.Schema, db.Table)
  188. c.executor.SyncCatalog()
  189. return nil
  190. }
  191. // handleMessage processes a client message
  192. func (c *Connection) handleMessage(msg *Message) error {
  193. switch msg.Type {
  194. case MsgQuery:
  195. return c.handleQuery(msg)
  196. case MsgTerminate:
  197. log.Printf("Client requested termination")
  198. return io.EOF
  199. case MsgParse:
  200. return c.handleParse(msg)
  201. case MsgBind:
  202. return c.handleBind(msg)
  203. case MsgDescribe:
  204. return c.handleDescribe(msg)
  205. case MsgExecute:
  206. return c.handleExecute(msg)
  207. case MsgClose:
  208. return c.handleClose(msg)
  209. case MsgFlush:
  210. return c.writer.Flush()
  211. case MsgSync:
  212. c.extendedFailed = false
  213. return c.sendReadyForQuery()
  214. default:
  215. log.Printf("Unknown message type: %c (%d)", msg.Type, msg.Type)
  216. c.sendError("ERROR", ErrCodeProtocolViolation, fmt.Sprintf("Unknown message type: %c", msg.Type))
  217. return c.sendReadyForQuery()
  218. }
  219. }
  220. // handleQuery processes a simple query
  221. func (c *Connection) handleQuery(msg *Message) error {
  222. // A Query message carries a single NUL-terminated query string.
  223. if len(msg.Data) == 0 || msg.Data[len(msg.Data)-1] != 0 {
  224. c.sendError("ERROR", ErrCodeProtocolViolation, "invalid Query message: missing null terminator")
  225. return c.sendReadyForQuery()
  226. }
  227. sql := string(msg.Data[:len(msg.Data)-1])
  228. if !c.quiet {
  229. log.Printf("Query: %s", sql)
  230. }
  231. // Handle empty query
  232. sqlTrimmed := strings.TrimSpace(sql)
  233. if sqlTrimmed == "" || sqlTrimmed == ";" {
  234. if err := c.sendEmptyQueryResponse(); err != nil {
  235. return err
  236. }
  237. return c.sendReadyForQuery()
  238. }
  239. // Handle special PostgreSQL system queries that drivers send
  240. sqlUpper := strings.ToUpper(strings.TrimSpace(sql))
  241. singleStatement := isSingleStatementSQL(sql)
  242. // In a failed transaction only ROLLBACK (or ROLLBACK TO SAVEPOINT) is
  243. // accepted. Gate before honoring the special driver queries below so they
  244. // return 25P02 instead of a result. Multi-statement batches are gated
  245. // per statement in the execution loop below.
  246. if c.txStatus == TxStatusFailed && singleStatement && !isRollbackStatement(sql) {
  247. c.sendError("ERROR", ErrCodeTransactionAborted, "current transaction is aborted, commands ignored until end of transaction block")
  248. return c.sendReadyForQuery()
  249. }
  250. // lib/pq and other drivers query these for connection validation
  251. if singleStatement && strings.Contains(sqlUpper, "SELECT VERSION()") {
  252. // Return a fake PostgreSQL version
  253. return c.handleVersionQuery()
  254. }
  255. if singleStatement && strings.Contains(sqlUpper, "SELECT CURRENT_USER") {
  256. // Return the current user
  257. return c.handleCurrentUserQuery()
  258. }
  259. if singleStatement && strings.Contains(sqlUpper, "SHOW") && (strings.Contains(sqlUpper, "SERVER_VERSION") ||
  260. strings.Contains(sqlUpper, "SERVER_ENCODING") ||
  261. strings.Contains(sqlUpper, "CLIENT_ENCODING")) {
  262. // Handle SHOW commands
  263. return c.handleShowCommand(sqlUpper)
  264. }
  265. if result, handled, err := c.catalogResult(sql); handled {
  266. if err != nil {
  267. c.sendError("ERROR", ErrCodeInternalError, err.Error())
  268. return c.sendReadyForQuery()
  269. }
  270. if err := c.sendTabularResult(result, "SELECT"); err != nil {
  271. return err
  272. }
  273. return c.sendReadyForQuery()
  274. }
  275. // Parse the complete batch before executing its first statement. This keeps
  276. // unsupported trailing clauses from turning into committed writes.
  277. l := lexer.New(sql)
  278. p := parser.New(l)
  279. stmts, err := p.ParseMultiple()
  280. if err != nil {
  281. c.sendError("ERROR", ErrCodeSyntaxError, fmt.Sprintf("Syntax error: %v", err))
  282. return c.sendReadyForQuery()
  283. }
  284. for _, stmt := range stmts {
  285. if c.txStatus == TxStatusFailed {
  286. if _, rollback := stmt.(*parser.RollbackStmt); !rollback {
  287. c.sendError("ERROR", ErrCodeTransactionAborted, "current transaction is aborted, commands ignored until end of transaction block")
  288. return c.sendReadyForQuery()
  289. }
  290. }
  291. result, err := c.executor.Execute(stmt)
  292. if err != nil {
  293. code := ErrCodeInternalError
  294. if errors.Is(err, storage.ErrSerialization) {
  295. code = ErrCodeSerializationFailure
  296. c.txStatus = TxStatusIdle
  297. } else if c.txStatus == TxStatusInBlock {
  298. c.txStatus = TxStatusFailed
  299. }
  300. c.sendError("ERROR", code, fmt.Sprintf("Execution error: %v", err))
  301. return c.sendReadyForQuery()
  302. }
  303. if err := c.sendResult(result, stmt); err != nil {
  304. return err
  305. }
  306. }
  307. return c.sendReadyForQuery()
  308. }
  309. func (c *Connection) handleParse(msg *Message) error {
  310. if c.extendedFailed {
  311. return nil
  312. }
  313. name, pos, err := readCString(msg.Data, 0)
  314. if err != nil {
  315. return c.failExtended(ErrCodeProtocolViolation, err)
  316. }
  317. query, pos, err := readCString(msg.Data, pos)
  318. if err != nil || pos+2 > len(msg.Data) {
  319. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Parse message"))
  320. }
  321. count := int(binary.BigEndian.Uint16(msg.Data[pos : pos+2]))
  322. pos += 2
  323. if pos+count*4 != len(msg.Data) {
  324. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Parse parameter list"))
  325. }
  326. oids := make([]int32, count)
  327. for i := range oids {
  328. oids[i] = int32(binary.BigEndian.Uint32(msg.Data[pos : pos+4]))
  329. pos += 4
  330. }
  331. c.statements[name] = &preparedStatement{query: query, paramOIDs: oids}
  332. return c.writeMessage(MsgParseComplete, nil)
  333. }
  334. func (c *Connection) handleBind(msg *Message) error {
  335. if c.extendedFailed {
  336. return nil
  337. }
  338. portalName, pos, err := readCString(msg.Data, 0)
  339. if err != nil {
  340. return c.failExtended(ErrCodeProtocolViolation, err)
  341. }
  342. statementName, pos, err := readCString(msg.Data, pos)
  343. if err != nil {
  344. return c.failExtended(ErrCodeProtocolViolation, err)
  345. }
  346. statement, ok := c.statements[statementName]
  347. if !ok {
  348. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("prepared statement %q does not exist", statementName))
  349. }
  350. formats, pos, err := readInt16List(msg.Data, pos)
  351. if err != nil || pos+2 > len(msg.Data) {
  352. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind format list"))
  353. }
  354. paramCount := int(binary.BigEndian.Uint16(msg.Data[pos : pos+2]))
  355. pos += 2
  356. params := make([]boundParameter, paramCount)
  357. for i := range params {
  358. if pos+4 > len(msg.Data) {
  359. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind parameter"))
  360. }
  361. length := int32(binary.BigEndian.Uint32(msg.Data[pos : pos+4]))
  362. pos += 4
  363. params[i].oid = parameterOID(statement.paramOIDs, i)
  364. params[i].format = parameterFormat(formats, i)
  365. if length == -1 {
  366. params[i].null = true
  367. continue
  368. }
  369. if length < 0 || pos+int(length) > len(msg.Data) {
  370. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind parameter length"))
  371. }
  372. params[i].value = append([]byte(nil), msg.Data[pos:pos+int(length)]...)
  373. pos += int(length)
  374. }
  375. _, pos, err = readInt16List(msg.Data, pos) // result formats; text output is currently used
  376. if err != nil || pos != len(msg.Data) {
  377. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind result format list"))
  378. }
  379. query, err := bindQuery(statement.query, params)
  380. if err != nil {
  381. return c.failExtended(ErrCodeInvalidParameter, err)
  382. }
  383. c.portals[portalName] = &portal{query: query}
  384. return c.writeMessage(MsgBindComplete, nil)
  385. }
  386. func (c *Connection) handleDescribe(msg *Message) error {
  387. if c.extendedFailed {
  388. return nil
  389. }
  390. if len(msg.Data) < 2 {
  391. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Describe message"))
  392. }
  393. name, pos, err := readCString(msg.Data, 1)
  394. if err != nil || pos != len(msg.Data) {
  395. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Describe name"))
  396. }
  397. switch msg.Data[0] {
  398. case 'S':
  399. statement, ok := c.statements[name]
  400. if !ok {
  401. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("prepared statement %q does not exist", name))
  402. }
  403. mb := NewMessageBuilder()
  404. mb.WriteInt16(int16(len(statement.paramOIDs)))
  405. for _, oid := range statement.paramOIDs {
  406. mb.WriteInt32(oid)
  407. }
  408. if err := c.writeMessage(MsgParameterDescription, mb.Bytes()); err != nil {
  409. return err
  410. }
  411. case 'P':
  412. if _, ok := c.portals[name]; !ok {
  413. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("portal %q does not exist", name))
  414. }
  415. default:
  416. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Describe target"))
  417. }
  418. // Execute sends the row description once the bound statement has been
  419. // analyzed, avoiding side effects during Describe.
  420. return c.writeMessage(MsgNoData, nil)
  421. }
  422. func (c *Connection) handleExecute(msg *Message) error {
  423. if c.extendedFailed {
  424. return nil
  425. }
  426. name, pos, err := readCString(msg.Data, 0)
  427. if err != nil || pos+4 != len(msg.Data) {
  428. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Execute message"))
  429. }
  430. portal, ok := c.portals[name]
  431. if !ok {
  432. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("portal %q does not exist", name))
  433. }
  434. if portal.executed {
  435. return c.failExtended(ErrCodeFeatureNotSupported, fmt.Errorf("portal can only be executed once"))
  436. }
  437. portal.executed = true
  438. // Check the transaction state before catalog emulation. Catalog queries do
  439. // not all parse as regular PizzaSQL statements, but must still return 25P02
  440. // while the transaction is aborted.
  441. if c.txStatus == TxStatusFailed && !isRollbackStatement(portal.query) {
  442. return c.failExtended(ErrCodeTransactionAborted, fmt.Errorf("current transaction is aborted, commands ignored until end of transaction block"))
  443. }
  444. if result, handled, catalogErr := c.catalogResult(portal.query); handled {
  445. if catalogErr != nil {
  446. return c.failExtended(ErrCodeInternalError, catalogErr)
  447. }
  448. return c.sendTabularResult(result, "SELECT")
  449. }
  450. l := lexer.New(portal.query)
  451. stmt, err := parser.New(l).Parse()
  452. if err != nil {
  453. return c.failExtended(ErrCodeSyntaxError, fmt.Errorf("syntax error: %w", err))
  454. }
  455. result, err := c.executor.Execute(stmt)
  456. if err != nil {
  457. code := ErrCodeInternalError
  458. if errors.Is(err, storage.ErrSerialization) {
  459. code = ErrCodeSerializationFailure
  460. c.txStatus = TxStatusIdle
  461. } else if c.txStatus == TxStatusInBlock {
  462. c.txStatus = TxStatusFailed
  463. }
  464. return c.failExtended(code, fmt.Errorf("execution error: %w", err))
  465. }
  466. return c.sendResult(result, stmt)
  467. }
  468. var catalogFilterPattern = regexp.MustCompile(`(?i)\b(table_name|tablename|table_schema|schemaname|constraint_name|indexname)\s*=\s*'((?:''|[^'])*)'`)
  469. func (c *Connection) catalogResult(sql string) (*executor.Result, bool, error) {
  470. if !isSingleStatementSQL(sql) {
  471. return nil, false, nil
  472. }
  473. upper := strings.ToUpper(sql)
  474. var source string
  475. for _, candidate := range []string{
  476. "INFORMATION_SCHEMA.TABLES", "INFORMATION_SCHEMA.COLUMNS",
  477. "INFORMATION_SCHEMA.TABLE_CONSTRAINTS", "INFORMATION_SCHEMA.KEY_COLUMN_USAGE",
  478. "PG_TABLES", "PG_INDEXES",
  479. } {
  480. if strings.Contains(upper, "FROM "+candidate) {
  481. source = candidate
  482. break
  483. }
  484. }
  485. if source == "" {
  486. return nil, false, nil
  487. }
  488. if c.txStatus == TxStatusIdle {
  489. c.schema.LockStatement()
  490. defer c.schema.UnlockStatement()
  491. }
  492. tables, err := c.schema.ListTables()
  493. if err != nil {
  494. return nil, true, err
  495. }
  496. rows := make([]map[string]interface{}, 0)
  497. switch source {
  498. case "INFORMATION_SCHEMA.TABLES":
  499. for _, table := range tables {
  500. rows = append(rows, map[string]interface{}{
  501. "table_catalog": c.database, "table_schema": "public", "table_name": table, "table_type": "BASE TABLE",
  502. })
  503. }
  504. case "PG_TABLES":
  505. for _, table := range tables {
  506. indexes, _ := c.schema.ListTableIndexes(table)
  507. rows = append(rows, map[string]interface{}{
  508. "schemaname": "public", "tablename": table, "tableowner": c.params["user"], "tablespace": nil,
  509. "hasindexes": len(indexes) > 0, "hasrules": false, "hastriggers": false, "rowsecurity": false,
  510. })
  511. }
  512. case "INFORMATION_SCHEMA.COLUMNS":
  513. for _, table := range tables {
  514. schema, schemaErr := c.schema.GetSchema(table)
  515. if schemaErr != nil {
  516. continue
  517. }
  518. for i, column := range schema.Columns {
  519. rows = append(rows, map[string]interface{}{
  520. "table_catalog": c.database, "table_schema": "public", "table_name": table,
  521. "column_name": column.Name, "ordinal_position": int64(i + 1), "column_default": column.Default,
  522. "is_nullable": yesNo(column.Nullable), "data_type": strings.ToLower(column.Type),
  523. })
  524. }
  525. }
  526. case "INFORMATION_SCHEMA.TABLE_CONSTRAINTS", "INFORMATION_SCHEMA.KEY_COLUMN_USAGE":
  527. for _, table := range tables {
  528. schema, schemaErr := c.schema.GetSchema(table)
  529. if schemaErr != nil || schema.PrimaryKey == "" || schema.PrimaryKey == "_rowid_" {
  530. continue
  531. }
  532. row := map[string]interface{}{
  533. "constraint_catalog": c.database, "constraint_schema": "public", "constraint_name": table + "_pkey",
  534. "table_catalog": c.database, "table_schema": "public", "table_name": table,
  535. }
  536. if source == "INFORMATION_SCHEMA.TABLE_CONSTRAINTS" {
  537. row["constraint_type"] = "PRIMARY KEY"
  538. row["is_deferrable"] = "NO"
  539. row["initially_deferred"] = "NO"
  540. } else {
  541. row["column_name"] = schema.PrimaryKey
  542. row["ordinal_position"] = int64(1)
  543. }
  544. rows = append(rows, row)
  545. }
  546. case "PG_INDEXES":
  547. for _, table := range tables {
  548. indexes, _ := c.schema.ListTableIndexes(table)
  549. for _, index := range indexes {
  550. columns := make([]string, len(index.Columns))
  551. for i, column := range index.Columns {
  552. columns[i] = column.Name
  553. }
  554. unique := ""
  555. if index.Unique {
  556. unique = "UNIQUE "
  557. }
  558. rows = append(rows, map[string]interface{}{
  559. "schemaname": "public", "tablename": table, "indexname": index.Name, "tablespace": nil,
  560. "indexdef": fmt.Sprintf("CREATE %sINDEX %s ON %s (%s)", unique, index.Name, table, strings.Join(columns, ", ")),
  561. })
  562. }
  563. }
  564. }
  565. for _, match := range catalogFilterPattern.FindAllStringSubmatch(sql, -1) {
  566. column, expected := strings.ToLower(match[1]), strings.ReplaceAll(match[2], "''", "'")
  567. filtered := rows[:0]
  568. for _, row := range rows {
  569. if value, ok := row[column]; ok && strings.EqualFold(fmt.Sprintf("%v", value), expected) {
  570. filtered = append(filtered, row)
  571. }
  572. }
  573. rows = filtered
  574. }
  575. columns := catalogProjection(sql, rows)
  576. result := executor.NewResult("SELECT")
  577. if len(columns) == 1 && columns[0] == "count(*)" {
  578. result.AddColumnWithType("count", "INTEGER")
  579. result.AddRow(int64(len(rows)))
  580. return result, true, nil
  581. }
  582. for _, column := range columns {
  583. columnType := "TEXT"
  584. if column == "ordinal_position" {
  585. columnType = "INTEGER"
  586. } else if strings.HasPrefix(column, "has") || column == "rowsecurity" {
  587. columnType = "BOOLEAN"
  588. }
  589. result.AddColumnWithType(column, columnType)
  590. }
  591. for _, row := range rows {
  592. values := make([]interface{}, len(columns))
  593. for i, column := range columns {
  594. values[i] = row[column]
  595. }
  596. result.AddRow(values...)
  597. }
  598. return result, true, nil
  599. }
  600. func isSingleStatementSQL(sql string) bool {
  601. trimmed := strings.TrimSpace(sql)
  602. if strings.HasSuffix(trimmed, ";") {
  603. trimmed = strings.TrimSpace(strings.TrimSuffix(trimmed, ";"))
  604. }
  605. inString, inIdent := false, false
  606. for i := 0; i < len(trimmed); i++ {
  607. switch trimmed[i] {
  608. case '\'':
  609. if !inIdent {
  610. if inString && i+1 < len(trimmed) && trimmed[i+1] == '\'' {
  611. i++
  612. continue
  613. }
  614. inString = !inString
  615. }
  616. case '"':
  617. if !inString {
  618. inIdent = !inIdent
  619. }
  620. case ';':
  621. if !inString && !inIdent {
  622. return false
  623. }
  624. }
  625. }
  626. return true
  627. }
  628. // isRollbackStatement reports whether sql parses as a single ROLLBACK
  629. // statement, including ROLLBACK TO SAVEPOINT.
  630. func isRollbackStatement(sql string) bool {
  631. stmt, err := parser.New(lexer.New(sql)).Parse()
  632. if err != nil {
  633. return false
  634. }
  635. _, ok := stmt.(*parser.RollbackStmt)
  636. return ok
  637. }
  638. func catalogProjection(sql string, rows []map[string]interface{}) []string {
  639. upper := strings.ToUpper(sql)
  640. selectPos, fromPos := strings.Index(upper, "SELECT"), strings.Index(upper, " FROM ")
  641. if selectPos < 0 || fromPos < 0 || fromPos <= selectPos+6 {
  642. return nil
  643. }
  644. projection := strings.TrimSpace(sql[selectPos+6 : fromPos])
  645. projection = strings.TrimSpace(strings.TrimPrefix(strings.ToUpper(projection), "DISTINCT "))
  646. if projection == "*" && len(rows) > 0 {
  647. columns := make([]string, 0, len(rows[0]))
  648. for column := range rows[0] {
  649. columns = append(columns, column)
  650. }
  651. sort.Strings(columns)
  652. return columns
  653. }
  654. parts := strings.Split(projection, ",")
  655. columns := make([]string, 0, len(parts))
  656. for _, part := range parts {
  657. column := strings.TrimSpace(part)
  658. if index := strings.Index(strings.ToUpper(column), " AS "); index >= 0 {
  659. column = strings.TrimSpace(column[:index])
  660. }
  661. if index := strings.LastIndex(column, "."); index >= 0 {
  662. column = column[index+1:]
  663. }
  664. columns = append(columns, strings.ToLower(strings.Trim(column, `"`)))
  665. }
  666. return columns
  667. }
  668. func yesNo(value bool) string {
  669. if value {
  670. return "YES"
  671. }
  672. return "NO"
  673. }
  674. func (c *Connection) sendTabularResult(result *executor.Result, tag string) error {
  675. if err := c.sendRowDescription(result.Columns, result.ColumnTypes); err != nil {
  676. return err
  677. }
  678. for _, row := range result.Rows {
  679. if err := c.sendDataRow(row, result.Columns); err != nil {
  680. return err
  681. }
  682. }
  683. return c.sendCommandComplete(fmt.Sprintf("%s %d", tag, len(result.Rows)))
  684. }
  685. func (c *Connection) handleClose(msg *Message) error {
  686. if c.extendedFailed {
  687. return nil
  688. }
  689. if len(msg.Data) < 2 {
  690. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Close message"))
  691. }
  692. name, pos, err := readCString(msg.Data, 1)
  693. if err != nil || pos != len(msg.Data) {
  694. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Close name"))
  695. }
  696. if msg.Data[0] == 'S' {
  697. delete(c.statements, name)
  698. } else if msg.Data[0] == 'P' {
  699. delete(c.portals, name)
  700. } else {
  701. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Close target"))
  702. }
  703. return c.writeMessage(MsgCloseComplete, nil)
  704. }
  705. func (c *Connection) failExtended(code string, err error) error {
  706. c.extendedFailed = true
  707. return c.sendError("ERROR", code, err.Error())
  708. }
  709. type boundParameter struct {
  710. value []byte
  711. oid int32
  712. format int16
  713. null bool
  714. }
  715. func readCString(data []byte, pos int) (string, int, error) {
  716. if pos < 0 || pos >= len(data) {
  717. return "", pos, fmt.Errorf("missing null-terminated string")
  718. }
  719. end := bytes.IndexByte(data[pos:], 0)
  720. if end < 0 {
  721. return "", pos, fmt.Errorf("unterminated string")
  722. }
  723. return string(data[pos : pos+end]), pos + end + 1, nil
  724. }
  725. func readInt16List(data []byte, pos int) ([]int16, int, error) {
  726. if pos+2 > len(data) {
  727. return nil, pos, fmt.Errorf("missing list length")
  728. }
  729. count := int(binary.BigEndian.Uint16(data[pos : pos+2]))
  730. pos += 2
  731. if pos+count*2 > len(data) {
  732. return nil, pos, fmt.Errorf("truncated list")
  733. }
  734. result := make([]int16, count)
  735. for i := range result {
  736. result[i] = int16(binary.BigEndian.Uint16(data[pos : pos+2]))
  737. pos += 2
  738. }
  739. return result, pos, nil
  740. }
  741. func parameterOID(oids []int32, index int) int32 {
  742. if index < len(oids) {
  743. return oids[index]
  744. }
  745. return 0
  746. }
  747. func parameterFormat(formats []int16, index int) int16 {
  748. if len(formats) == 1 {
  749. return formats[0]
  750. }
  751. if index < len(formats) {
  752. return formats[index]
  753. }
  754. return 0
  755. }
  756. func bindQuery(query string, params []boundParameter) (string, error) {
  757. var result strings.Builder
  758. inString, inIdent := false, false
  759. for i := 0; i < len(query); {
  760. ch := query[i]
  761. if ch == '\'' && !inIdent {
  762. result.WriteByte(ch)
  763. if inString && i+1 < len(query) && query[i+1] == '\'' {
  764. result.WriteByte(query[i+1])
  765. i += 2
  766. continue
  767. }
  768. inString = !inString
  769. i++
  770. continue
  771. }
  772. if ch == '"' && !inString {
  773. inIdent = !inIdent
  774. result.WriteByte(ch)
  775. i++
  776. continue
  777. }
  778. if ch == '$' && !inString && !inIdent && i+1 < len(query) && query[i+1] >= '0' && query[i+1] <= '9' {
  779. end := i + 1
  780. for end < len(query) && query[end] >= '0' && query[end] <= '9' {
  781. end++
  782. }
  783. n, _ := strconv.Atoi(query[i+1 : end])
  784. if n < 1 || n > len(params) {
  785. return "", fmt.Errorf("parameter $%d was not provided", n)
  786. }
  787. literal, err := parameterLiteral(params[n-1])
  788. if err != nil {
  789. return "", fmt.Errorf("parameter $%d: %w", n, err)
  790. }
  791. result.WriteString(literal)
  792. i = end
  793. continue
  794. }
  795. result.WriteByte(ch)
  796. i++
  797. }
  798. return result.String(), nil
  799. }
  800. func parameterLiteral(param boundParameter) (string, error) {
  801. if param.null {
  802. return "NULL", nil
  803. }
  804. if param.format == 1 {
  805. switch param.oid {
  806. case 16:
  807. if len(param.value) != 1 {
  808. return "", fmt.Errorf("invalid binary boolean")
  809. }
  810. if param.value[0] == 0 {
  811. return "FALSE", nil
  812. }
  813. return "TRUE", nil
  814. case 21:
  815. if len(param.value) != 2 {
  816. return "", fmt.Errorf("invalid binary int2")
  817. }
  818. return strconv.FormatInt(int64(int16(binary.BigEndian.Uint16(param.value))), 10), nil
  819. case 23:
  820. if len(param.value) != 4 {
  821. return "", fmt.Errorf("invalid binary int4")
  822. }
  823. return strconv.FormatInt(int64(int32(binary.BigEndian.Uint32(param.value))), 10), nil
  824. case 20:
  825. if len(param.value) != 8 {
  826. return "", fmt.Errorf("invalid binary int8")
  827. }
  828. return strconv.FormatInt(int64(binary.BigEndian.Uint64(param.value)), 10), nil
  829. default:
  830. return "", fmt.Errorf("binary format is unsupported for OID %d", param.oid)
  831. }
  832. }
  833. value := string(param.value)
  834. switch param.oid {
  835. case 0:
  836. if strings.EqualFold(value, "true") || strings.EqualFold(value, "false") {
  837. return strings.ToUpper(value), nil
  838. }
  839. if _, err := strconv.ParseFloat(value, 64); err == nil && value != "" {
  840. return value, nil
  841. }
  842. return "'" + strings.ReplaceAll(value, "'", "''") + "'", nil
  843. case 16:
  844. if strings.EqualFold(value, "true") || value == "1" || value == "t" {
  845. return "TRUE", nil
  846. }
  847. return "FALSE", nil
  848. case 20, 21, 23, 26, 700, 701, 1700:
  849. if _, err := strconv.ParseFloat(value, 64); err != nil {
  850. return "", fmt.Errorf("invalid numeric value")
  851. }
  852. return value, nil
  853. default:
  854. return "'" + strings.ReplaceAll(value, "'", "''") + "'", nil
  855. }
  856. }
  857. // sendResult sends query results
  858. func (c *Connection) sendResult(result *executor.Result, stmt parser.Statement) error {
  859. // Any statement that produced a row set (SELECT, or INSERT/UPDATE/DELETE
  860. // with RETURNING) sends a row description and its data rows. Other
  861. // statements only send the command completion tag.
  862. if len(result.Columns) > 0 {
  863. if err := c.sendRowDescription(result.Columns, wireColumnTypes(result)); err != nil {
  864. return err
  865. }
  866. for _, row := range result.Rows {
  867. if err := c.sendDataRow(row, result.Columns); err != nil {
  868. return err
  869. }
  870. }
  871. return c.sendCommandComplete(c.getCommandTag(stmt, result))
  872. }
  873. // For other statements, just send command complete
  874. tag := c.getCommandTag(stmt, result)
  875. return c.sendCommandComplete(tag)
  876. }
  877. // wireColumnTypes corrects declared-affinity metadata when SQLite has stored a
  878. // value of another type. In particular, binding []byte to a VARCHAR column is
  879. // still a BLOB in SQLite; advertising TEXT while encoding PostgreSQL bytea text
  880. // would make clients receive the literal "\\x..." instead of the original
  881. // bytes.
  882. func wireColumnTypes(result *executor.Result) []string {
  883. types := append([]string(nil), result.ColumnTypes...)
  884. if len(types) < len(result.Columns) {
  885. types = append(types, make([]string, len(result.Columns)-len(types))...)
  886. }
  887. for _, row := range result.Rows {
  888. for i, value := range row {
  889. if i >= len(types) {
  890. break
  891. }
  892. if _, ok := value.([]byte); ok {
  893. types[i] = "BLOB"
  894. }
  895. }
  896. }
  897. return types
  898. }
  899. // getCommandTag returns the command completion tag
  900. func (c *Connection) getCommandTag(stmt parser.Statement, result *executor.Result) string {
  901. switch s := stmt.(type) {
  902. case *parser.SelectStmt:
  903. return fmt.Sprintf("SELECT %d", len(result.Rows))
  904. case *parser.CreateTableStmt:
  905. return "CREATE TABLE"
  906. case *parser.DropTableStmt:
  907. return "DROP TABLE"
  908. case *parser.CreateIndexStmt:
  909. return "CREATE INDEX"
  910. case *parser.DropIndexStmt:
  911. return "DROP INDEX"
  912. case *parser.AlterTableStmt:
  913. return "ALTER TABLE"
  914. case *parser.InsertStmt:
  915. return fmt.Sprintf("INSERT 0 %d", result.RowsAffected)
  916. case *parser.UpdateStmt:
  917. return fmt.Sprintf("UPDATE %d", result.RowsAffected)
  918. case *parser.DeleteStmt:
  919. return fmt.Sprintf("DELETE %d", result.RowsAffected)
  920. case *parser.BeginStmt:
  921. c.txStatus = TxStatusInBlock
  922. return "BEGIN"
  923. case *parser.CommitStmt:
  924. c.txStatus = TxStatusIdle
  925. return "COMMIT"
  926. case *parser.RollbackStmt:
  927. if s.Savepoint != "" {
  928. c.txStatus = TxStatusInBlock
  929. return "ROLLBACK"
  930. }
  931. c.txStatus = TxStatusIdle
  932. return "ROLLBACK"
  933. case *parser.SavepointStmt:
  934. c.txStatus = TxStatusInBlock
  935. return "SAVEPOINT"
  936. case *parser.ReleaseStmt:
  937. c.txStatus = TxStatusInBlock
  938. return "RELEASE"
  939. default:
  940. return "OK"
  941. }
  942. }
  943. // sendAuthenticationOk sends authentication OK message
  944. func (c *Connection) sendAuthenticationOk() error {
  945. mb := NewMessageBuilder()
  946. mb.WriteInt32(0) // Auth OK
  947. return c.writeMessage(MsgAuthenticationOk, mb.Bytes())
  948. }
  949. // sendParameterStatus sends a parameter status message
  950. func (c *Connection) sendParameterStatus(name, value string) error {
  951. mb := NewMessageBuilder()
  952. mb.WriteString(name)
  953. mb.WriteString(value)
  954. return c.writeMessage(MsgParameterStatus, mb.Bytes())
  955. }
  956. // sendBackendKeyData sends backend key data
  957. func (c *Connection) sendBackendKeyData(processID, secretKey int32) error {
  958. mb := NewMessageBuilder()
  959. mb.WriteInt32(processID)
  960. mb.WriteInt32(secretKey)
  961. return c.writeMessage(MsgBackendKeyData, mb.Bytes())
  962. }
  963. // sendReadyForQuery sends ready for query message
  964. func (c *Connection) sendReadyForQuery() error {
  965. mb := NewMessageBuilder()
  966. mb.AppendByte(c.txStatus)
  967. if err := c.writeMessage(MsgReadyForQuery, mb.Bytes()); err != nil {
  968. return err
  969. }
  970. // ReadyForQuery closes out a response cycle, so flush everything buffered
  971. // so far. This is what makes simple-query results and Sync responses
  972. // visible to the client.
  973. return c.writer.Flush()
  974. }
  975. // sendEmptyQueryResponse sends empty query response
  976. func (c *Connection) sendEmptyQueryResponse() error {
  977. return c.writeMessage(MsgEmptyQueryResponse, []byte{})
  978. }
  979. // sendRowDescription sends row description (column metadata)
  980. func (c *Connection) sendRowDescription(columns []string, columnTypes []string) error {
  981. mb := NewMessageBuilder()
  982. mb.WriteInt16(int16(len(columns)))
  983. for i, col := range columns {
  984. colType := ""
  985. if i < len(columnTypes) {
  986. colType = columnTypes[i]
  987. }
  988. mb.WriteString(col)
  989. mb.WriteInt32(0) // table OID
  990. mb.WriteInt16(0) // column attribute number
  991. mb.WriteInt32(c.getOIDForType(colType)) // type OID
  992. mb.WriteInt16(c.getTypeSizeForType(colType)) // type size
  993. mb.WriteInt32(-1) // type modifier
  994. mb.WriteInt16(0) // format code (text)
  995. }
  996. return c.writeMessage(MsgRowDescription, mb.Bytes())
  997. }
  998. // sendDataRow sends a data row
  999. func (c *Connection) sendDataRow(row []interface{}, columns []string) error {
  1000. mb := NewMessageBuilder()
  1001. mb.WriteInt16(int16(len(row)))
  1002. for _, value := range row {
  1003. if value == nil {
  1004. mb.WriteInt32(-1) // NULL indicator
  1005. continue
  1006. }
  1007. // Convert value to string
  1008. strValue := c.valueToString(value)
  1009. mb.WriteInt32(int32(len(strValue)))
  1010. mb.WriteBytes([]byte(strValue))
  1011. }
  1012. return c.writeMessage(MsgDataRow, mb.Bytes())
  1013. }
  1014. // sendCommandComplete sends command complete message
  1015. func (c *Connection) sendCommandComplete(tag string) error {
  1016. mb := NewMessageBuilder()
  1017. mb.WriteString(tag)
  1018. return c.writeMessage(MsgCommandComplete, mb.Bytes())
  1019. }
  1020. // sendError sends an error response
  1021. func (c *Connection) sendError(severity, code, message string) error {
  1022. mb := NewMessageBuilder()
  1023. mb.AppendByte(ErrorFieldSeverity)
  1024. mb.WriteString(severity)
  1025. mb.AppendByte(ErrorFieldCode)
  1026. mb.WriteString(code)
  1027. mb.AppendByte(ErrorFieldMessage)
  1028. mb.WriteString(message)
  1029. mb.AppendByte(0) // Terminator
  1030. if err := c.writeMessage(MsgErrorResponse, mb.Bytes()); err != nil {
  1031. return err
  1032. }
  1033. // Errors must be visible promptly, including FATAL startup failures that
  1034. // are not followed by a ReadyForQuery before the connection closes.
  1035. return c.writer.Flush()
  1036. }
  1037. // writeMessage buffers a message for the connection. It does not flush, so
  1038. // callers that need to make a response visible to the client must flush at the
  1039. // appropriate protocol boundary (ReadyForQuery, an explicit Flush message, or
  1040. // an error response). Buffering amortizes the per-message syscalls that a
  1041. // result set would otherwise incur; the underlying bufio.Writer bounds memory
  1042. // use so large result sets cannot grow the buffer without limit.
  1043. func (c *Connection) writeMessage(msgType byte, data []byte) error {
  1044. if !c.quiet {
  1045. log.Printf("Sending message type=%c length=%d", msgType, len(data)+4)
  1046. }
  1047. return WriteMessage(c.writer, msgType, data)
  1048. }
  1049. // getOIDForType returns PostgreSQL OID for type
  1050. func (c *Connection) getOIDForType(typeName string) int32 {
  1051. switch strings.ToUpper(typeName) {
  1052. case "INTEGER", "INT":
  1053. return 23 // INT4OID
  1054. case "BIGINT":
  1055. return 20 // INT8OID
  1056. case "TEXT", "VARCHAR", "CHAR", "UUID":
  1057. // UUID is stored as text (SQLite-style), so it reports TEXTOID rather
  1058. // than the native PG UUID OID.
  1059. return 25 // TEXTOID
  1060. case "REAL", "FLOAT":
  1061. return 700 // FLOAT4OID
  1062. case "DOUBLE":
  1063. return 701 // FLOAT8OID
  1064. case "BOOLEAN", "BOOL":
  1065. return 16 // BOOLOID
  1066. case "BLOB":
  1067. return 17 // BYTEAOID
  1068. case "DATETIME", "TIMESTAMP":
  1069. // Datetime values are exchanged as UTC RFC3339 (ISO8601 with a timezone
  1070. // offset), which timestamptz decodes directly.
  1071. return 1184 // TIMESTAMPTZOID
  1072. case "DATE":
  1073. return 1082 // DATEOID
  1074. default:
  1075. return 25 // Default to TEXT
  1076. }
  1077. }
  1078. // getTypeSizeForType returns type size
  1079. func (c *Connection) getTypeSizeForType(typeName string) int16 {
  1080. switch strings.ToUpper(typeName) {
  1081. case "INTEGER", "INT":
  1082. return 4
  1083. case "BIGINT":
  1084. return 8
  1085. case "REAL", "FLOAT":
  1086. return 4
  1087. case "DOUBLE":
  1088. return 8
  1089. case "BOOLEAN", "BOOL":
  1090. return 1
  1091. case "DATETIME", "TIMESTAMP":
  1092. return 8
  1093. case "DATE":
  1094. return 4
  1095. default:
  1096. return -1 // Variable length
  1097. }
  1098. }
  1099. // valueToString converts a value to string
  1100. func (c *Connection) valueToString(value interface{}) string {
  1101. if value == nil {
  1102. return ""
  1103. }
  1104. // PostgreSQL's text format for bytea is \x followed by hex. Emitting that
  1105. // lets libpq/pgx decode a BLOB column (OID 17) losslessly.
  1106. if b, ok := value.([]byte); ok {
  1107. return `\x` + hex.EncodeToString(b)
  1108. }
  1109. return fmt.Sprintf("%v", value)
  1110. }
  1111. // handleVersionQuery handles SELECT version()
  1112. func (c *Connection) handleVersionQuery() error {
  1113. columns := []string{"version"}
  1114. columnTypes := []string{"TEXT"}
  1115. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1116. return err
  1117. }
  1118. row := []interface{}{"PostgreSQL " + version.PostgreSQLCompatVersion + " (PizzaSQL)"}
  1119. if err := c.sendDataRow(row, columns); err != nil {
  1120. return err
  1121. }
  1122. if err := c.sendCommandComplete("SELECT 1"); err != nil {
  1123. return err
  1124. }
  1125. return c.sendReadyForQuery()
  1126. }
  1127. // handleCurrentUserQuery handles SELECT current_user
  1128. func (c *Connection) handleCurrentUserQuery() error {
  1129. columns := []string{"current_user"}
  1130. columnTypes := []string{"TEXT"}
  1131. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1132. return err
  1133. }
  1134. user := c.params["user"]
  1135. if user == "" {
  1136. user = "pizzasql"
  1137. }
  1138. row := []interface{}{user}
  1139. if err := c.sendDataRow(row, columns); err != nil {
  1140. return err
  1141. }
  1142. if err := c.sendCommandComplete("SELECT 1"); err != nil {
  1143. return err
  1144. }
  1145. return c.sendReadyForQuery()
  1146. }
  1147. // handleShowCommand handles SHOW commands
  1148. func (c *Connection) handleShowCommand(sqlUpper string) error {
  1149. var value string
  1150. var name string
  1151. if strings.Contains(sqlUpper, "SERVER_VERSION") {
  1152. name = "server_version"
  1153. value = version.PostgreSQLCompatVersion
  1154. } else if strings.Contains(sqlUpper, "SERVER_ENCODING") {
  1155. name = "server_encoding"
  1156. value = "UTF8"
  1157. } else if strings.Contains(sqlUpper, "CLIENT_ENCODING") {
  1158. name = "client_encoding"
  1159. value = "UTF8"
  1160. } else {
  1161. // Unknown SHOW command
  1162. c.sendError("ERROR", ErrCodeFeatureNotSupported, "SHOW command not supported")
  1163. return c.sendReadyForQuery()
  1164. }
  1165. columns := []string{name}
  1166. columnTypes := []string{"TEXT"}
  1167. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1168. return err
  1169. }
  1170. row := []interface{}{value}
  1171. if err := c.sendDataRow(row, columns); err != nil {
  1172. return err
  1173. }
  1174. if err := c.sendCommandComplete("SHOW"); err != nil {
  1175. return err
  1176. }
  1177. return c.sendReadyForQuery()
  1178. }