connection.go 38 KB

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